2014-09-03 60 views
0

的一个特定的会话:杀我杀死进程是这样​​运行的应用程序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过程中只有一个会话。
可能吗?

+1

你会杀进程的实例只是第一个进程或特定的? – 2014-09-03 09:45:33

+0

如果你正在关闭Microsoft Word,那么使用COM挂钩它会不会是一个更好的想法,并要求它很好地退出? – 2014-09-03 09:51:58

+0

@ LasseV.Karlsen,谢谢,The Word就是这个例子。 – user3165438 2014-09-03 11:11:34

回答

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

谢谢,好主意!如果我喜欢杀死一个特定的实例呢? – user3165438 2014-09-03 11:12:49

+0

@ user3165438我已经更新了我的答案,请看一看。 – 2014-09-03 11:28:51

+0

看起来不错!我怎样才能得到我已经编程启动的进程的ID,使用'processInfo'? – user3165438 2014-09-03 11:40:35

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

编辑:获取过程的SessionID的Process.Start返回

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

谢谢,我该如何获得我编程启动的进程的'':ProcessStartInfo processInfo = \t new ProcessStartInfo(eaInstallationPath); processInfo.Verb =“runas”; Process.Start(processInfo);'? – user3165438 2014-09-03 11:38:08

+0

我已经更新了我的答案 – 2014-09-03 11:45:45

+1

非常感谢! upvoted :) – user3165438 2014-09-03 11:59:34