从进程ID检索Excel应用程序 [英] Retrieve Excel application from process id
问题描述
我正在使用Process
类启动Excel应用程序.我可以获取进程ID&带有以下代码的主窗口句柄.
I am starting an Excel application using the Process
class. I am able to get the process id & the main window handle with the code below.
Process xlP = Process.Start("excel.exe");
int id = xlP.Id;
int hwnd = (int)Process.GetCurrentProcess().MainWindowHandle;
因此,这将启动Excel应用程序.如何使用进程ID&引用这个特定的Excel实例.主窗把手?
So this starts an Excel application. How do I reference this particular instance of Excel with the process id & main window handle?
我在这里看到了类似的问题,但是答案是一个不再存在的网页的链接.
I have seen similar questions on here but the answer was a link to a webpage that no longer exists.
我基本上想要下面的东西.
I basically want something like below.
oExcelApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
请不必使用Process.Start
方法来启动Excel应用程序,而是不要启动.
Please not the Excel application has to be started using the Process.Start
method, no if buts or maybes.
推荐答案
您可以使用以下代码访问所有正在运行的Excel实例并显示其使用的窗口句柄:
You can use the following code to access all running Excel instances and display the Window Handle they use:
[DllImport("ole32.dll")]
private static extern int GetRunningObjectTable(int reserved, out IRunningObjectTable prot);
private void button1_Click(object sender, EventArgs e)
{
IRunningObjectTable lRunningObjectTable = null;
IEnumMoniker lMonikerList = null;
try
{
// Query Running Object Table
if (GetRunningObjectTable(0, out lRunningObjectTable) != 0 || lRunningObjectTable == null)
{
return;
}
// List Monikers
lRunningObjectTable.EnumRunning(out lMonikerList);
// Start Enumeration
lMonikerList.Reset();
// Array used for enumerating Monikers
IMoniker[] lMonikerContainer = new IMoniker[1];
IntPtr lPointerFetchedMonikers = IntPtr.Zero;
// foreach Moniker
while (lMonikerList.Next(1, lMonikerContainer, lPointerFetchedMonikers) == 0)
{
object lComObject;
lRunningObjectTable.GetObject(lMonikerContainer[0], out lComObject);
// Check the object is an Excel workbook
if (lComObject is Microsoft.Office.Interop.Excel.Workbook)
{
Microsoft.Office.Interop.Excel.Workbook lExcelWorkbook = (Microsoft.Office.Interop.Excel.Workbook)lComObject;
// Show the Window Handle
MessageBox.Show("Found Excel Application with Window Handle " + lExcelWorkbook.Application.Hwnd);
}
}
}
finally
{
// Release ressources
if (lRunningObjectTable != null) Marshal.ReleaseComObject(lRunningObjectTable);
if (lMonikerList != null) Marshal.ReleaseComObject(lMonikerList);
}
}
这篇关于从进程ID检索Excel应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!