简体   繁体   English

使用C#.net在Windows中检测进程已在运行

[英]Detecting a Process is already running in windows using C# .net

How do I detect if a process is already running under the Windows Task Manager? 如何检测进程是否已在Windows任务管理器下运行? I'd like to get the memory and cpu usage as well. 我也想获得内存和CPU使用率。

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. :) (我将留下从方法中获取数据的机制 - 这是17:15,我准备回家了。:)

您是否查看了System.Diagnostics.Process类。

You can use System.Diagnostics.Process Class. 您可以使用System.Diagnostics.Process类。
There is a GetProcesses() and a GetProcessesByName() method that will get a list of all the existing processes in an array. 有一个GetProcesses()和一个GetProcessesByName()方法,它将获取数组中所有现有进程的列表。

The Process object has all the information you need to detect if a process is running. Process对象具有检测进程是否正在运行所需的所有信息。

If you wanted to find out about the IE Processes that are running: 如果您想了解正在运行的IE进程:

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();                      
   }
}

You could use WMI to query something along the lines of 您可以使用WMI查询某些内容

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

Especially processor usage is a bit tricky with WMI, though. 但是,尤其是WMI处理器的使用有点棘手。 You are probably better off with System.Diagnostics.Process, as Ian Jacobs suggested. 正如Ian Jacobs建议的那样,你最好使用System.Diagnostics.Process。

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); 
    } 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM