gpt4 book ai didi

c# - 从 MS-Word ApplicationClass 获取 PID?

转载 作者:可可西里 更新时间:2023-11-01 07:56:18 25 4
gpt4 key购买 nike

考虑这段代码:

using Microsoft.Office.Interop.Word;

ApplicationClass _application = new ApplicationClass();

我能否从 _application 启动的 Winword.exe 进程中获取 PID?

我需要 PID,因为文件已损坏,我无法退出 ApplicationClass,即使使用以下代码也是如此:

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

我不能搜索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;
}

关于c# - 从 MS-Word ApplicationClass 获取 PID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/814936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com