我有一种情况,我必须检查用户是否已经打开了Microsoft Word。如果他有,那么我必须终止winword.exe进程并继续执行我的代码。
是否有任何简单的代码可以使用vb.net或c#杀死进程?
Answers:
您将要使用System.Diagnostics.Process.Kill方法。您可以使用System.Diagnostics.Proccess.GetProcessesByName获得所需的进程 。
示例已经在这里发布,但是我发现non.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
这将以有序的方式关闭所有打开的Word窗口(如果适用,将提示用户保存其工作)。当然,在这种情况下,用户始终可以单击“取消”,因此您也应该能够处理这种情况(最好通过放置“请关闭所有Word实例,否则我们将无法继续”对话框)... )
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;
}
在任务栏应用程序中,我需要清理Excel和Word Interop。因此,这种简单的方法通常会杀死进程。
这使用了通用的异常处理程序,但是可以很容易地拆分为多个异常,如其他答案中所述。如果我的日志记录产生大量误报(即无法杀死已经被杀死的),我可以这样做。但到目前为止,还算这样(工作笑话)。
/// <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" }));
clean Excel and Word Interops
连什么意思?
CloseMainWindow
。我只是希望他们有一天会开始弃用这种有害的API,这显然是内核级别的,对于任何用户空间应用程序都不可能实现
请看下面的例子
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;
}