Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I kill a process using Vb.NET or C#?

I have a scenario where I have to check whether user has already opened Microsoft Word. If he has, then I have to kill the winword.exe process and continue to execute my code.

Does any one have any straight-forward code for killing a process using vb.net or c#?

like image 929
bugBurger Avatar asked Sep 22 '08 16:09

bugBurger


People also ask

How do you stop a process in VB net?

Diagnostics. Process. Kill method. You can obtain the process you want using System.

How do I kill a process in Visual Studio?

In Task Manager, if you go to the applications tab, you can right click on the instance you want to kill based on the name, then click on "Go to process". It should select the process you want to kill. Show activity on this post.


1 Answers

You'll want to use the System.Diagnostics.Process.Kill method. You can obtain the process you want using System.Diagnostics.Proccess.GetProcessesByName.

Examples have already been posted here, but I found that the non-.exe version worked better, so something like:

foreach ( Process p in System.Diagnostics.Process.GetProcessesByName("winword") ) {     try     {         p.Kill();         p.WaitForExit(); // possibly with a timeout     }     catch ( Win32Exception winException )     {         // process was terminating or can't be terminated - deal with it     }     catch ( InvalidOperationException invalidException )     {         // process has already exited - might be able to let this one go      } } 

You probably don't have to deal with NotSupportedException, which suggests that the process is remote.

like image 177
Blair Conrad Avatar answered Sep 24 '22 07:09

Blair Conrad