考虑以下代码:
using Microsoft.Office.Interop.Word;
ApplicationClass _application = new ApplicationClass();
Run Code Online (Sandbox Code Playgroud)
我可以从_application启动的Winword.exe进程中获取PID吗?
我需要PID因为文件损坏,我只是不能退出ApplicationClass,即使使用这段代码:
_application.Quit(ref saveFile, ref missing, ref missing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(_application);
GC.Collect();
GC.WaitForPendingFinalizers();
Run Code Online (Sandbox Code Playgroud)
我无法搜索winword.exe进程并将其杀死,因为我会有几个,而且我不知道要杀哪个.如果我可以为每个ApplicationClass获取一个PID,我可能会杀死正确的winword.exe进程,这会给我带来麻烦.
这是怎么做的.
//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;
while (GetProcessIdByWindowTitle(AppId) == Int32.MaxValue) //Loop till u get
{
Thread.Sleep(5);
}
///Get the pid by for word application
this.WordPid = GetProcessIdByWindowTitle(AppId);
///You canh hide the application afterward
this.oWordApp.Application.Visible = false;
/// <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;
}
Run Code Online (Sandbox Code Playgroud)
Word 文件中可能存在一些错误。因此,当您使用方法打开文件时Word.ApplicationClass.Documents.Open(),将显示一个对话框,并且进程将挂起。
Word.ApplicationClass.Documents.OpenNoRepairDialog()代替使用。我发现它解决了问题。