从进程 ID 中检索 Excel 应用程序

Retrieve Excel application from process id

我正在使用 Process class 启动一个 Excel 应用程序。我可以使用下面的代码获取进程 ID 和主 window 句柄。

  Process xlP = Process.Start("excel.exe");
  int id = xlP.Id;
  int hwnd = (int)Process.GetCurrentProcess().MainWindowHandle;

所以这会启动一个 Excel 应用程序。如何使用进程 ID 和主 window 句柄引用 Excel 的这个特定实例?

我在这里看到过类似的问题,但答案是 link 一个不再存在的网页。

我基本上想要下面这样的东西。

oExcelApp =  (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");

请注意,Excel 应用程序必须使用 Process.Start 方法启动,没有 if buts 或 maybes。

您可以使用以下代码访问所有 运行 Excel 个实例并显示它们使用的 Window 句柄:

[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);
    }
}

添加对Microsoft.Office.Interop.Excel的引用并使用以下代码:

        Process xlP = Process.Start("excel.exe");
        int id = xlP.Id;
        int hwnd = (int)Process.GetCurrentProcess().MainWindowHandle;

        Excel.Application oExcelApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");

        if(xlP.MainWindowTitle.Contains( oExcelApp.ActiveWorkbook.Name)   )
        {
            //Proceed further
        }