为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
慕村9548890 2019-12-27 15:11:34
我有一种情况,我必须检查用户是否已经打开了Microsoft Word。如果他有,那么我必须终止winword.exe进程并继续执行我的代码。是否有任何简单的代码可以使用vb.net或c#杀死进程?
查看完整描述

3 回答

?
胡子哥哥

TA贡献1825条经验 获得超6个赞

您将要使用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,这表明该过程是远程的。


查看完整回答
反对 回复 2019-12-27
?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

 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;

    }


查看完整回答
反对 回复 2019-12-27
  • 3 回答
  • 0 关注
  • 628 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信