如何使用Vb.NET或C#终止进程?

我有一种情况,我必须检查用户是否已经打开了Microsoft Word。如果他有,那么我必须终止winword.exe进程并继续执行我的代码。

是否有任何简单的代码可以使用vb.net或c#杀死进程?



慕村9548890
浏览 630回答 3
3回答

胡子哥哥

您将要使用System.Diagnostics.Process.Kill方法。您可以使用System.Diagnostics.Proccess.GetProcessesByName获得所需的进程 。示例已经在此处发布,但是我发现non.exe版本的效果更好,所以类似: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     }}您可能不必处理NotSupportedException,这表明该过程是远程的。

Smart猫小萌

 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;    }
打开App,查看更多内容
随时随地看视频慕课网APP