如何使用Vb.NET或C#终止进程?

如何使用Vb.NET或C#终止进程?,c#,vb.net,process,kill,C#,Vb.net,Process,Kill,我有一个场景,我必须检查用户是否已经打开了Microsoft Word。如果他有,那么我必须终止winword.exe进程并继续执行我的代码 是否有人使用vb.net或c#直接编写了终止进程的代码?您将要使用该方法。您可以使用 这里已经发布了一些示例,但我发现非.exe版本工作得更好,所以类似于: foreach ( Process p in System.Diagnostics.Process.GetProcessesByName("winword") ) { try {

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

是否有人使用vb.net或c#直接编写了终止进程的代码?

您将要使用该方法。您可以使用

这里已经发布了一些示例,但我发现非.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进程

Process[] procs = Process.GetProcessesByName("winword");

foreach (Process proc in procs)
    proc.Kill();

类似这样的方法会奏效:

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

完全终止Word进程是可能的(请参阅其他一些答复),但绝对是粗鲁和危险的:如果用户在打开的文档中有重要的未保存更改,该怎么办?更不用说这会留下陈旧的临时文件

这可能是您在这方面所能做到的(VB.NET):


这将有序地关闭所有打开的Word窗口(如果适用,提示用户保存其工作)。当然,在这种情况下,用户始终可以单击“取消”,因此您也应该能够处理这种情况(最好通过弹出“请关闭所有Word实例,否则我们无法继续”对话框…

您可以绕过安全问题,通过简单地检查Word进程是否正在运行,创建一个更礼貌的应用程序,并要求用户关闭它,然后单击应用程序中的“继续”按钮。这是许多安装人员采用的方法

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

当然,只有当你的应用程序有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;
    }
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;
    }
公共部分类表单1:表单
{
[ThreadStatic()]
静态Microsoft.Office.Interop.Word.Application wordObj=null;
公共表格1()
{
初始化组件();
}
公共bool OpenDoc(字符串documentName)
{
bool-bSuccss=false;
System.Threading.Thread newThread;
int iRetryCount;
国际iWait;
int-pid=0;
int iMaxRetry=3;
尝试
{
iRetryCount=1;
尝试打开文档:
iWait=0;
newThread=newThread(()=>OpenDocument(documentName,pid));
newThread.Start();
等待单词:
睡眠(1000);
iWait=iWait+1;
if(iWait<60)//1分钟等待
去等你的话;
其他的
{
iRetryCount=iRetryCount+1;
newThread.Abort();
//'-----------------------------------------
//'杀死无响应的word实例
如果((wordObj!=null))
{
尝试
{
Process.GetProcessById(pid.Kill();
Marshal.ReleaseComObject(wordObj);
wordObj=null;
}
捕获(例外情况除外)
{
}
}
//'----------------------------------------
如果(iMaxRetry>=iRetryCount)
转到尝试打开文档;
其他的
后藤成功;
}
}
捕获(例外情况除外)
{
bSuccss=false;
}
成功的话:
返回bSuccss;
}
私有bool OpenDocument(字符串docName,int-pid)
{
bool bsucces=假;
Microsoft.Office.Interop.Word.Application tWord;
日期时间时间;
日期时间;
尝试
{
tWord=新的Microsoft.Office.Interop.Word.Application();
sTime=DateTime.Now;
wordObj=新的Microsoft.Office.Interop.Word.Application();
eTime=DateTime.Now;
第二,退出(错误);
发布对象元帅(第二);
tWord=null;
wordObj.Visible=false;
pid=GETPID(时间、时间);
//现在做些事情
wordObj.Documents.OpenNoRepairDialog(docName);
//其他代码
if(wordObj!=null)
{
wordObj.Quit(false);
Marshal.ReleaseComObject(wordObj);
wordObj=null;
}
b成功=真;
}
抓住
{ }
返回b成功;
}
private int GETPID(System.DateTime开始时间,System.DateTime结束时间)
{
int-pid=0;
尝试
{
foreach(Process.getProcessByName(“WINWORD”)中的进程p)
{

如果在我的托盘应用程序中(string.IsNullOrEmpty(string.Empty+p.MainWindowTitle)&p.HasExited==false&&(p.StartTime.Ticks>=StartTime.Ticks&p.StartTime.Ticks),我需要清理Excel和Word互操作。因此,这个简单的方法通常会终止进程

这使用了一个通用的异常处理程序,但可以很容易地为多个异常拆分,如在其他答案中所述。如果我的日志记录产生大量误报(即无法杀死已杀死的),我可能会这样做。但到目前为止,guid(工作笑话)

//
///按名称终止进程
/// 
///进程名称列表
私有进程(列表名称)
{
var进程=新列表();
foreach(名称中的变量名称)
processs.AddRange(Process.getProcessByName(name.ToList());
foreach(进程中的进程p)
{
尝试
{
p、 杀死();
p、 WaitForExit();
}
捕获(例外情况除外)
{
//伐木
insertFeedback(“清理进程失败”,ex);
}
}
}
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;
    }
/// <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" }));