终止运行应用程序C#的一个特定会话



我过去常常这样杀死进程:

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

我怎么能只杀死runnug进程的一个会话呢
有可能吗?

如果我理解得对,这里是我的代码:

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();

用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();
    }
}

编辑:获取进程SessionID进程。Start返回进程的实例

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

相关内容

最新更新