2014-09-03 94 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