从MS-Word中ApplicationClass获取PID? [英] Get PID from MS-Word ApplicationClass?

查看:290
本文介绍了从MS-Word中ApplicationClass获取PID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个code:

using Microsoft.Office.Interop.Word;

ApplicationClass _application = new ApplicationClass();

我可以从被_Application推出Winword.exe进程得到PID?

Can I get the PID from the Winword.exe process that was launched by the _application?

我需要的PID因为损坏的文件,我不能退出ApplicationClass,即使使用这种code:

I need the PID because with corrupted files, I just can't quit the ApplicationClass, even using this code:

_application.Quit(ref saveFile, ref missing, ref missing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(_application);
GC.Collect();
GC.WaitForPendingFinalizers();

我不能搜索Winword.exe进程和杀死它,因为我有几个,我不知道杀了哪一个。如果我能得到一个PID为每个ApplicationClass,我可以只杀那是给我的烦恼退出正确Winword.exe进程。

I can't search for the winword.exe process and kill it, because I will have several, and I don't know which one to kill. If I can get a PID for each ApplicationClass, I could just kill the correct winword.exe process that is giving me troubles to quit.

推荐答案

下面是如何做到这一点。

Here is how to do it.

//Set the AppId
string AppId = ""+DateTime.Now.Ticks(); //A random title

//Create an identity for the app

this.oWordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
this.oWordApp.Application.Caption = AppId;
this.oWordApp.Application.Visible = true;

///Get the pid by for word application
this.WordPid = StaticMethods.GetProcessIdByWindowTitle(AppId);

while ( StaticMethods.GetProcessIdByWindowTitle(AppId) == Int32.MaxValue) //Loop till u get
{
    Thread.Sleep(5);
}

this.WordPid = StaticMethods.GetProcessIdByWindowTitle(AppId);


///You canh hide the application afterward            
this.oWordApp.Application.Visible = false;

string this.oWordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
this.oWordApp.Application.Caption = AppId;
this.oWordApp.Application.Visible = true;
///Get the pid by 
this.WordPid = StaticMethods.GetProcessIdByWindowTitle(AppId);

while ( StaticMethods.GetProcessIdByWindowTitle(AppId) == Int32.MaxValue)
{
    Thread.Sleep(5);
}

this.WordPid = StaticMethods.GetProcessIdByWindowTitle(AppId);

this.oWordApp.Application.Visible = false; //You Can hide the application now

/// <summary>
/// Returns the name of that process given by that title
/// </summary>
/// <param name="AppId">Int32MaxValue returned if it cant be found.</param>
/// <returns></returns>
public static int GetProcessIdByWindowTitle(string AppId)
{
   Process[] P_CESSES = Process.GetProcesses();
   for (int p_count = 0; p_count < P_CESSES.Length; p_count++)
   {
        if (P_CESSES[p_count].MainWindowTitle.Equals(AppId))
        {
                    return P_CESSES[p_count].Id;
        }
   }

    return Int32.MaxValue;
}

这篇关于从MS-Word中ApplicationClass获取PID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆