简体   繁体   English

使用C#by Handle获取Excel应用程序的实例

[英]Get instance of Excel application with C# by Handle

I have ac# simple application that have to write some values in a excel ranges of a specific worksheet. 我有一个简单的应用程序,必须在特定工作表的excel范围内写入一些值。 I create an instance of Excel application if not exist, but if exist i want to set active it and take an instance if it to use in my code. 如果不存在,我创建一个Excel应用程序的实例,但如果存在,我想设置它的活动并获取一个实例,如果它在我的代码中使用。

I use this code to create a new application: 我使用此代码创建一个新的应用程序:

Microsoft.Office.Interop.Excel app = 
   new Microsoft.Office.Interop.Excel.Application();
app.Visible = true;

To get the handle of active excel window i use this api 要获取活动excel窗口的句柄,我使用此api

[DllImportAttribute("User32.dll")]
private static extern int FindWindow(String ClassName, String WindowName);

How can i get an instance of excel application by an handle? 如何通过句柄获取excel应用程序的实例?

int hWnd = FindWindow(null, "Microsoft Excel - MySheet.xlsx");
Microsoft.Office.Interop.Excel app = ....(hWnd)

Use the following code to get the first running instance of Excel: 使用以下代码获取Excel的第一个运行实例:

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

Example

public Excel.Application StartExcel()
{
    Excel.Application instance = null;
    try
    {
       instance = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
    }
    catch (System.Runtime.InteropServices.COMException ex)
    {
       instance = new Excel.ApplicationClass();
    }

    return instance;
}

There might be more than one Excel instance running. 可能有多个Excel实例在运行。

GetActiveObject(...) looks in the Running Object Table (ROT) and would give you the last Excel instance that was opened - not necessarily the one corresponding with the window handle you have. GetActiveObject(...)在运行对象表(ROT)中查找,并为您提供最后打开的Excel实例 - 不一定是与您拥有的窗口句柄相对应的实例。

You're looking for AccessibleObjectFromWindow(..). 您正在寻找AccessibleObjectFromWindow(..)。 The Andrew Whitechapel post linked to in the other answer shows how to use this function. 在另一个答案中链接的Andrew Whitechapel帖子显示了如何使用此功能。

Another link - http://blogs.officezealot.com/whitechapel/archive/2005/04/10/4514.aspx . 另一个链接 - http://blogs.officezealot.com/whitechapel/archive/2005/04/10/4514.aspx

You can use Marshal.GetActiveObject, see this blog post for details: 您可以使用Marshal.GetActiveObject,有关详细信息,请参阅此博客文章:

http://blogs.msdn.com/andreww/archive/2008/11/30/starting-or-connecting-to-office-apps.aspx http://blogs.msdn.com/andreww/archive/2008/11/30/starting-or-connecting-to-office-apps.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM