开发者

C# check if a process exists then close it

I'm trying to Close a process within C# but how do I check if is open first? Users asked for this feature and some of them will be still using the close button of the other process.

So, right now works fine:

Process.GetProcessesByName("ProcessName")[0].CloseMainWindow();

Now, how do I check first that it exists, this doesn't work:

if ( Process.GetProcessesByName("ProcessName")[0] !=开发者_运维技巧 null ) {...}


Try this to avoid the race condition in which a process closes after the first call to GetProcessesByName:

Process[] processes = Process.GetProcessesByName("ProcessName");
if (processes.Length > 0)
    processes[0].CloseMainWindow();


If you're planning to deploy this application on a wide range of machines, you will want to know that this code can sometimes fail.

The Process class in .NET is based on Windows performance counters, which on some machines can be disabled through the registry. When this happens, the call to the Process.GetProcessesByName method will throw an exception.

I think this situation is typical for machines with various "clean up / performance tuning" applications which, among other stuff, disable the performance counters in order to supposedly improve the machine's performance.

In the past this has repeatedly caused me pain with some percentage of my customers' client machines, which led me to explore other (if somewhat limited or cumbersome) alternatives, like making calls to Win API directly using PInvoke to iterate over the processes.

Another possible solution would be to ensure that your installer or application enables performance counters, or at least knows how to deal with them being disabled.


How about

if (Process.GetProcessesByName("ProcessName").Length > 0) {...}


You could also just loop, which works fine if there aren't any.

foreach(Process p in Process.GetProcessesByName("ProcessName"))
{
    p.CloseMainWindow();
}


Process.GetProcessesByName("ProcessName").FirstOrDefault() != null


You could use GetProcessesByName like so:

foreach(var application in Process.GetProcessesByName("ApplicationName"))
        {
            application.CloseMainWindow();
        }

If you meant to kill the application, then you could do this instead:

foreach(var application in Process.GetProcessesByName("ApplicationName"))
        {
            application.Kill();
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜