从进程 ID 检索 Excel 应用程序

本文关键字:Excel 应用程序 检索 ID 进程 | 更新日期: 2023-09-27 18:34:19

我正在使用Process类启动Excel应用程序。我能够使用以下代码获取进程 ID 和主窗口句柄。

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

因此,这将启动一个 Excel 应用程序。如何使用进程 ID 和主窗口句柄引用此特定 Excel 实例?

我在这里看到了类似的问题,但答案是指向不再存在的网页的链接。

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

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

请不要使用Process.Start方法启动Excel应用程序,没有如果但是或可能。

从进程 ID 检索 Excel 应用程序

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

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