如何杀死使用Vb.NET或C#的进程?

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

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

您将需要使用System.Diagnostics.Process.Kill方法。 您可以使用System.Diagnostics.Proccess.GetProcessesByName获取所需的进程。

例子已经发布在这里,但我发现非。exe版本更好地工作,所以像这样:

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 ,这表明该过程是远程的。

彻底杀死Word的过程是可能的(见其他一些答复),但彻底的粗鲁和危险:如果用户在一个打开的文档中有重要的未保存的变化呢? 更不用提陈旧的临时文件,这将留下…

这可能是你可以去这方面(VB.NET):

  Dim proc = Process.GetProcessesByName("winword") For i As Integer = 0 To proc.Count - 1 proc(i).CloseMainWindow() Next i 

这将以有序的方式closures所有打开的Word窗口(如果适用的话,提示用户保存他/她的工作)。 当然,在这种情况下,用户总是可以点击“取消”,所以你应该也可以处理这种情况(最好通过提出一个“请closures所有Word实例,否则我们不能继续”对话框… )

这是如何杀死所有Word进程的简单例子。

 Process[] procs = Process.GetProcessesByName("winword"); foreach (Process proc in procs) proc.Kill(); 
  public bool FindAndKillProcess(string name) { //here we're going to get a list of all running processes on //the computer foreach (Process clsProcess in Process.GetProcesses()) { //now we're going to see if any of the running processes //match the currently running processes by using the StartsWith Method, //this prevents us from incluing the .EXE for the process we're looking for. //. Be sure to not //add the .exe to the name you provide, ie: NOTEPAD, //not NOTEPAD.EXE or false is always returned even if //notepad is running if (clsProcess.ProcessName.StartsWith(name)) { //since we found the proccess we now need to use the //Kill Method to kill the process. Remember, if you have //the process running more than once, say IE open 4 //times the loop thr way it is now will close all 4, //if you want it to just close the first one it finds //then add a return; after the Kill try { clsProcess.Kill(); } catch { return false; } //process killed, return true return true; } } //process not found, return false return false; } 

您可以绕过安全考虑,通过简单地检查Word进程是否正在运行,并要求用户closures它,然后单击应用程序中的“继续”button来创build一个更好的politer应用程序。 这是许多安装人员采取的方法。

 private bool isWordRunning() { return System.Diagnostics.Process.GetProcessesByName("winword").Length > 0; } 

当然,如果你的应用程序有一个GUI,你只能这样做

在我的托盘应用程序中,我需要清理Excel和Word Interops。 所以这个简单的方法一般杀死进程。

这使用了一个通用的exception处理程序,但可以很容易地拆分多个exception,如其他答案中所述。 我可以这样做,如果我的日志logging产生大量的误报(即不能杀死已经死亡)。 但迄今如此guid(工作笑话)。

 /// <summary> /// Kills Processes By Name /// </summary> /// <param name="names">List of Process Names</param> private void killProcesses(List<string> names) { var processes = new List<Process>(); foreach (var name in names) processes.AddRange(Process.GetProcessesByName(name).ToList()); foreach (Process p in processes) { try { p.Kill(); p.WaitForExit(); } catch (Exception ex) { // Logging RunProcess.insertFeedback("Clean Processes Failed", ex); } } } 

这就是我如何称呼它:

 killProcesses((new List<string>() { "winword", "excel" })); 

像这样的东西将工作:

 foreach ( Process process in Process.GetProcessesByName( "winword.exe" ) ) { process.Kill(); process.WaitForExit(); } 

更好的做法是,更安全,更有礼貌地检测进程是否在运行,并告诉用户手动closures进程。 当然,你也可以添加一个超时时间,如果它们消失,就杀掉这个进程。

请看下面的例子

 public partial class Form1 : Form { [ThreadStatic()] static Microsoft.Office.Interop.Word.Application wordObj = null; public Form1() { InitializeComponent(); } public bool OpenDoc(string documentName) { bool bSuccss = false; System.Threading.Thread newThread; int iRetryCount; int iWait; int pid = 0; int iMaxRetry = 3; try { iRetryCount = 1; TRY_OPEN_DOCUMENT: iWait = 0; newThread = new Thread(() => OpenDocument(documentName, pid)); newThread.Start(); WAIT_FOR_WORD: Thread.Sleep(1000); iWait = iWait + 1; if (iWait < 60) //1 minute wait goto WAIT_FOR_WORD; else { iRetryCount = iRetryCount + 1; newThread.Abort(); //'----------------------------------------- //'killing unresponsive word instance if ((wordObj != null)) { try { Process.GetProcessById(pid).Kill(); Marshal.ReleaseComObject(wordObj); wordObj = null; } catch (Exception ex) { } } //'---------------------------------------- if (iMaxRetry >= iRetryCount) goto TRY_OPEN_DOCUMENT; else goto WORD_SUCCESS; } } catch (Exception ex) { bSuccss = false; } WORD_SUCCESS: return bSuccss; } private bool OpenDocument(string docName, int pid) { bool bSuccess = false; Microsoft.Office.Interop.Word.Application tWord; DateTime sTime; DateTime eTime; try { tWord = new Microsoft.Office.Interop.Word.Application(); sTime = DateTime.Now; wordObj = new Microsoft.Office.Interop.Word.Application(); eTime = DateTime.Now; tWord.Quit(false); Marshal.ReleaseComObject(tWord); tWord = null; wordObj.Visible = false; pid = GETPID(sTime, eTime); //now do stuff wordObj.Documents.OpenNoRepairDialog(docName); //other code if (wordObj != null) { wordObj.Quit(false); Marshal.ReleaseComObject(wordObj); wordObj = null; } bSuccess = true; } catch { } return bSuccess; } private int GETPID(System.DateTime startTime, System.DateTime endTime) { int pid = 0; try { foreach (Process p in Process.GetProcessesByName("WINWORD")) { if (string.IsNullOrEmpty(string.Empty + p.MainWindowTitle) & p.HasExited == false && (p.StartTime.Ticks >= startTime.Ticks & p.StartTime.Ticks <= endTime.Ticks)) { pid = p.Id; break; } } } catch { } return pid; }