Bla*_*rad 94
您将需要使用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
}
}
Run Code Online (Sandbox Code Playgroud)
您可能没有必要处理NotSupportedException
,这表明该过程是远程的.
mdb*_*mdb 25
彻底杀死Word进程是可能的(参见其他一些回复),但是直接粗鲁和危险:如果用户在打开的文档中有重要的未保存更改,该怎么办?更不用说这将留下的陈旧临时文件......
这可能就这方面而言(VB.NET):
Dim proc = Process.GetProcessesByName("winword")
For i As Integer = 0 To proc.Count - 1
proc(i).CloseMainWindow()
Next i
Run Code Online (Sandbox Code Playgroud)
这将以有序的方式关闭所有打开的Word窗口(如果适用,提示用户保存他/她的工作).当然,用户总是可以在这种情况下单击"取消",因此您也应该能够处理这种情况(最好是通过设置"请关闭所有Word实例,否则我们无法继续"对话框... )
Nic*_*rdi 15
这是一个如何杀死所有Word进程的简单示例.
Process[] procs = Process.GetProcessesByName("winword");
foreach (Process proc in procs)
proc.Kill();
Run Code Online (Sandbox Code Playgroud)
您可以绕过安全问题,只需检查Word进程是否正在运行,并要求用户关闭它,然后单击应用程序中的"继续"按钮,即可创建更多politer应用程序.这是许多安装人员采用的方法.
private bool isWordRunning()
{
return System.Diagnostics.Process.GetProcessesByName("winword").Length > 0;
}
Run Code Online (Sandbox Code Playgroud)
当然,只有当您的应用程序具有GUI时,您才能执行此操作
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, i.e: 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;
}
Run Code Online (Sandbox Code Playgroud)