如何使用 Vb.NET 或 C# 终止进程? [英] How do I kill a process using Vb.NET or C#?

查看:33
本文介绍了如何使用 Vb.NET 或 C# 终止进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,我必须检查用户是否已经打开了 Microsoft Word.如果他有,那么我必须杀死 winword.exe 进程并继续执行我的代码.

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.

有没有人有使用 vb.net 或 c# 杀死进程的直接代码?

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

推荐答案

您需要使用 System.Diagnostics.Process.Kill 方法.您可以获得您想要使用的过程System.Diagnostics.Proccess.GetProcessesByName.

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

这里已经发布了示例,但我发现非 .exe 版本效果更好,因此类似于:

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
     }
}

您可能不必处理 NotSupportedException,这表明该过程是远程的.

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

这篇关于如何使用 Vb.NET 或 C# 终止进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆