杀死一个运行应用程序C#的特定会话

时间:2014-09-03 09:40:23

标签: c# process

我曾经杀过这样的过程:

Process []GetPArry = Process.GetProcesses();
foreach(Process testProcess in GetPArry)  
        {
        string ProcessName = testProcess .ProcessName;              
        ProcessName  = ProcessName .ToLower();
        if (ProcessName.CompareTo("winword") == 0)
        testProcess.Kill();
        }  

如何只杀死runnug进程的一个会话 有可能吗?

2 个答案:

答案 0 :(得分:3)

如果我理解你的话,这是我的代码:

Process []GetPArry = Process.GetProcesses();
foreach(Process testProcess in GetPArry)  
{
    string ProcessName = testProcess.ProcessName;              
    ProcessName  = ProcessName.ToLower();
    if (ProcessName.CompareTo("winword") == 0)
    {
        testProcess.Kill();
        break;
    }
}

这会杀掉第一次出现的" winword"名。

但是如果要杀死特定的进程实例,则需要首先获取PID:

int pid = process.Id;

然后,您可以在以后轻松杀死它:

Process []GetPArry = Process.GetProcesses();
foreach(Process testProcess in GetPArry)  
{
    if (testProcess.Id == pid)
    {
        testProcess.Kill();
        break;
    }
}

使用Linq(因为我非常喜欢):

Process.GetProcesses().Where(process => process.Id == pid).First().Kill();

答案 1 :(得分:2)

使用SessionID

尝试此操作
Process []GetPArry = Process.GetProcesses();
foreach(Process testProcess in GetPArry)  
{
    string ProcessName = testProcess .ProcessName;              
    ProcessName  = ProcessName .ToLower();
    if (ProcessName.CompareTo("winword") == 0 && testProcess.SessionId == <SessionID>)
    {
        testProcess.Kill();
    }
}

编辑: get process-SessionID Process.Start返回Process的实例

ProcessStartInfo processInfo = new ProcessStartInfo(eaInstallationPath);
processInfo.Verb = "runas";
var myProcess = Process.Start(processInfo);
var mySessionID = myProcess.SessionId;