如何获取隐藏的Excel应用程序实例的ProcessID(PID) [英] How can I get the ProcessID (PID) for a hidden Excel Application instance
问题描述
我有一个 Microsoft.Office.Interop.Excel.Application
的实例.为了确保 EXCEL.EXE
进程及时消失,我需要找到在创建 Application
对象时实例化的ProcessID.
I have an instance of Microsoft.Office.Interop.Excel.Application
. In order to ensure that the EXCEL.EXE
process dies in time I need to find the ProcessID that was instantiated when I created the Application
object.
当Excel Application
时,我为此找到了样本.>有一个窗口.
I found samples for this when the Excel Application
has a window.
是否有一种方法可以对隐藏"实例执行此操作,即当没有窗口绑定到 EXCEL.EXE
进程时,即当没有 excelApp.Hwnd
时,设置吗?
Is there a way to do that for a "hidden" instance i.e. when there is no window bound to the EXCEL.EXE
process i.e. when excelApp.Hwnd
is not set?
推荐答案
Application.Hwnd
具有有效的窗口句柄,即使该应用程序具有没有可见的工作簿窗口.
Application.Hwnd
has a valid window handle that you can use to get the process for the associated Excel application even when the application has no visible workbook window.
[DllImport("user32.dll")]
static extern int GetWindowThreadProcessId(int hWnd, out int lpdwProcessId);
Process GetExcelProcess(Microsoft.Office.Interop.Excel.Application excelApp)
{
int id;
GetWindowThreadProcessId(excelApp.Hwnd, out id);
return Process.GetProcessById(id);
}
void TerminateExcelProcess(Microsoft.Office.Interop.Excel.Application excelApp)
{
var process = GetExcelProcess(excelApp);
if (process != null)
{
process.Kill();
}
}
private void button1_Click(object sender, EventArgs e)
{
// Create Instance of Excel
Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
try
{
// Work with oXL
}
finally
{
TerminateExcelProcess(oXL);
}
}
注意:此问题具有一些答案,这些答案解释了为什么在您使用完Excel进程后Excel进程不会终止的原因通过自动化从C#中获取(除非您对确保释放对您显式使用的任何对象的每个引用都非常着迷).
Note: This question has some answers that explain why the Excel process will not terminate when you are finished working with it from C# via automation (unless you are very pedantic about making sure you release every reference to any object you use explicitly).
这篇关于如何获取隐藏的Excel应用程序实例的ProcessID(PID)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!