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

169,902

Solution 1

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.

Solution 2

Killing the Word process outright is possible (see some of the other replies), but outright rude and dangerous: what if the user has important unsaved changes in an open document? Not to mention the stale temporary files this will leave behind...

This is probably as far as you can go in this regard (VB.NET):

    Dim proc = Process.GetProcessesByName("winword")
    For i As Integer = 0 To proc.Count - 1
        proc(i).CloseMainWindow()
    Next i

This will close all open Word windows in an orderly fashion (prompting the user to save his/her work if applicable). Of course, the user can always click 'Cancel' in this scenario, so you should be able to handle this case as well (preferably by putting up a "please close all Word instances, otherwise we can't continue" dialog...)

Solution 3

Here is an easy example of how to kill all Word Processes.

Process[] procs = Process.GetProcessesByName("winword");

foreach (Process proc in procs)
    proc.Kill();

Solution 4

    public bool FindAndKillProcess(string name)
    {
        //here we're going to get a list of all running processes on
        //the computer
        foreach (Process clsProcess in Process.GetProcesses()) {
            //now we're going to see if any of the running processes
            //match the currently running processes by using the StartsWith Method,
            //this prevents us from incluing the .EXE for the process we're looking for.
            //. Be sure to not
            //add the .exe to the name you provide, i.e: NOTEPAD,
            //not NOTEPAD.EXE or false is always returned even if
            //notepad is running
            if (clsProcess.ProcessName.StartsWith(name))
            {
                //since we found the proccess we now need to use the
                //Kill Method to kill the process. Remember, if you have
                //the process running more than once, say IE open 4
                //times the loop thr way it is now will close all 4,
                //if you want it to just close the first one it finds
                //then add a return; after the Kill
                try 
                {
                    clsProcess.Kill();
                }
                catch
                {
                    return false;
                }
                //process killed, return true
                return true;
            }
        }
        //process not found, return false
        return false;
    }

Solution 5

You can bypass the security concerns, and create a much politer application by simply checking if the Word process is running, and asking the user to close it, then click a 'Continue' button in your app. This is the approach taken by many installers.

private bool isWordRunning() 
{
    return System.Diagnostics.Process.GetProcessesByName("winword").Length > 0;
}

Of course, you can only do this if your app has a GUI

Share:
169,902
bugBurger
Author by

bugBurger

Updated on July 05, 2022

Comments

  • bugBurger
    bugBurger almost 2 years

    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#?

  • Rami
    Rami over 15 years
    One comment - use "winword" instead of "winword.exe"
  • Marc Stober
    Marc Stober over 15 years
    I don't find the processes when there's a .exe given to GetProcessesByName, although winword workd fine.
  • specializt
    specializt over 5 years
    it also wont work in a lot of other cases (if the process has shielded itself with ACLs, for instance) - actually killing a process is a horrible idea and will only generate problems in the long run. Processes should always be closed instead of killed so that they can shutdown properly. This answer is a typical beginners' mistake.
  • specializt
    specializt over 5 years
    what is clean Excel and Word Interops even supposed to mean?
  • tyler_mitchell
    tyler_mitchell over 5 years
    as in clean up, if i didn't use this process i would have hundreds of instances of word and excel which would end up hanging my machine.
  • specializt
    specializt over 5 years
    killing live processes might also make your machine hang - and you might lose important data and you might corrupt the installation entirely, forcing the user to repair or reinstall. So, to summarize : your clean algorithm will actually will pretty much destroy the system one shiny day; one should be very careful about process control, especially if it comes to microsoft processes because these are tighly woven into the OS and cause a whole truckload of problems if not handled carefully. But nowadays, microsoft has learned from their mistakes and shields them against sabotage.
  • specializt
    specializt over 5 years
    so ... you got lucky this time. But please learn from your mistake and stop killing processes. Have a look at CloseMainWindow. I just hope they start deprecating harmful API like this one someday, this is clearly kernel-level and should not be possible for any userspace app
  • tyler_mitchell
    tyler_mitchell over 5 years
    your going off on a very small snippet of code, with no context of how its used...
  • specializt
    specializt over 5 years
    thats ... a blatant lie
  • Nathan
    Nathan about 4 years
    I agree with this approach. Killing a process should be the last possible resort. There could be unintended consequences.