In this code, we track for "notepad" and "calc". If you try to track ALL the processes, you'll have problems with process that are "restricted". The error is catched and will throw something in the console.
I'd like to point out that I inspired myself from various sources but none worked as I liked. This one is an modified version of the code here:
http://www.mycsharpcorner.com/Post.aspx?postID=24[
^].
struct ProcessInfo
{
public String Name;
public DateTime StartTime;
}
ArrayList watchedProcesses = new ArrayList();
ArrayList processesBook = new ArrayList();
private void timerScan_Tick(object sender, EventArgs e)
{
watchedProcesses.Add("notepad");
watchedProcesses.Add("calc");
ArrayList currentlyRunningProcessNames = new ArrayList();
Process[] currentlyRunning = Process.GetProcesses();
foreach(Process process in currentlyRunning)
{
if(watchedProcesses.Contains(process.ProcessName))
{
try
{
ProcessInfo currentProcess = new ProcessInfo();
currentProcess.Name = process.ProcessName;
currentProcess.StartTime = process.StartTime;
if(!processesBook.Contains(currentProcess))
{
System.Diagnostics.Debug.WriteLine(currentProcess.StartTime + " | Process Started: " + currentProcess.Name + " | Running: " + new TimeSpan(DateTime.Now.Ticks - currentProcess.StartTime.Ticks).ToString());
processesBook.Add(currentProcess);
}
currentlyRunningProcessNames.Add(currentProcess);
}
catch(System.ComponentModel.Win32Exception err)
{
System.Diagnostics.Debug.WriteLine(process.ProcessName + " cannot be scanned. " + err.Message);
}
}
}
foreach(ProcessInfo bookKeptProcess in processesBook)
{
if(!currentlyRunningProcessNames.Contains(bookKeptProcess))
{
System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + " | Process Ended: " + bookKeptProcess.Name + " | Running: " + new TimeSpan(DateTime.Now.Ticks - bookKeptProcess.StartTime.Ticks).ToString());
}
}
processesBook = currentlyRunningProcessNames;
}
I have a three years technical education in computer science (June 2006) and a four years bachelor's degree in Software Engineering from the École de Technologie Supérieure (August 2010). I worked as a Web Developper at the beginning of my career before being recruited as a .NET Analyst-Programer at SNC-Lavalin in Montreal. I worked there until they outsourced all development to CGI. I worked there since.