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

时间:2016-02-12 15:46:12

标签: c# .net excel-interop

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

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

所以这启动了一个Excel应用程序。如何使用进程ID& amp;来引用此特定Excel实例?主窗把手?

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

我基本上想要下面的内容。

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

请不要使用Process.Start方法启动Excel应用程序,如果是buts或maybe则不能。

2 个答案:

答案 0 :(得分:4)

您可以使用以下代码访问所有正在运行的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);
    }
}

答案 1 :(得分:0)

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

var letter_counts = function(txt) {
    var res = {};
    for (var i=0;i<txt.length;i++) {
        var c = txt[i].toLowerCase();
        res[c] = ( res[c] ? res[c] : 0 ) + 1;
    };
    return res;
};

var letter_cnts = letter_counts("Abba");
// Object {a: 2, b: 2}

letter_cnts["a"]; // == 2
letter_cnts["b"]; // == 2