Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# check if a process exists then close it

Tags:

c#

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 ) {...}
like image 290
Eric Fortis Avatar asked Dec 15 '10 19:12

Eric Fortis


1 Answers

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();
        }
like image 149
Llermerr Avatar answered Nov 15 '22 18:11

Llermerr