8

How do I detect if a process is already running under the Windows Task Manager? I'd like to get the memory and cpu usage as well.

jinsungy
  • 10,717
  • 24
  • 71
  • 79

6 Answers6

28

Simple example...

bool processIsRunning(string process)
{
    return (System.Diagnostics.Process.GetProcessesByName(process).Length != 0);
}

Oops... forgot the mem usage, etc...

bool processIsRunning(string process)
{
System.Diagnostics.Process[] processes = 
    System.Diagnostics.Process.GetProcessesByName(process);
foreach (System.Diagnostics.Process proc in processes)
{
    Console.WriteLine("Current physical memory : " + proc.WorkingSet64.ToString());
    Console.WriteLine("Total processor time : " + proc.TotalProcessorTime.ToString());
    Console.WriteLine("Virtual memory size : " + proc.VirtualMemorySize64.ToString());
}
return (processes.Length != 0);
}

(I'll leave the mechanics of getting the data out of the method to you - it's 17:15 here, and I'm ready to go home. :)

ZombieSheep
  • 29,603
  • 12
  • 67
  • 114
7

Have you looked into the System.Diagnostics.Process Class.

Jimi
  • 29,621
  • 8
  • 43
  • 61
Ian Jacobs
  • 5,456
  • 1
  • 23
  • 38
3

You can use System.Diagnostics.Process Class.
There is a GetProcesses() and a GetProcessesByName() method that will get a list of all the existing processes in an array.

The Process object has all the information you need to detect if a process is running.

Jimi
  • 29,621
  • 8
  • 43
  • 61
StubbornMule
  • 2,720
  • 5
  • 20
  • 19
3

If you wanted to find out about the IE Processes that are running:

System.Diagnostics.Process[] ieProcs = Process.GetProcessesByName("IEXPLORE");

if (ieProcs.Length > 0)
{
   foreach (System.Diagnostics.Process p in ieProcs)
   {                        
      String virtualMem = p.VirtualMemorySize64.ToString();
      String physicalMem = p.WorkingSet64.ToString();
      String cpu = p.TotalProcessorTime.ToString();                      
   }
}
Ralph Willgoss
  • 11,750
  • 4
  • 64
  • 67
Millhouse
  • 732
  • 1
  • 8
  • 17
1

You could use WMI to query something along the lines of

"SELECT * FROM Win32_Process WHERE Name = '<your process name here>'"

Especially processor usage is a bit tricky with WMI, though. You are probably better off with System.Diagnostics.Process, as Ian Jacobs suggested.

Community
  • 1
  • 1
Tomalak
  • 332,285
  • 67
  • 532
  • 628
0

Something like this:

foreach ( WindowsProcess in Process.GetProcesses) 
{ 
    if (WindowsProcess.ProcessName == nameOfProcess) { 
        Console.WriteLine(WindowsProcess.WorkingSet64.ToString); 
        Console.WriteLine(WindowsProcess.UserProcessorTime.ToString); 
        Console.WriteLine(WindowsProcess.TotalProcessorTime.ToString); 
    } 
} 
Jimi
  • 29,621
  • 8
  • 43
  • 61
Mike L
  • 4,693
  • 5
  • 33
  • 52