通过Handle获取C#的Excel应用程序实例 [英] Get instance of Excel application with C# by Handle

查看:352
本文介绍了通过Handle获取C#的Excel应用程序实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个c#简单的应用程序,必须在特定工作表的excel范围内编写一些值。
如果不存在,我创建一个Excel应用程序的实例,但如果存在我想要设置活动它,并采取一个实例,如果它在我的代码中使用。



我使用这段代码创建一个新的应用程序:

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

要获得Active Excel窗口的句柄,我使用这个api

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

如何通过句柄获取excel应用程序的实例?

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


解决方案

使用以下代码获取第一个运行的Excel实例:

  oExcelApp =(Excel 。应用)System.Runtime.InteropServices.Marshal.GetActiveObject( Excel.Application); 

示例

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

返回实例;
}


I have a c# simple application that have to write some values in a excel ranges of a specific worksheet. 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.

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

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

How can i get an instance of excel application by an handle?

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:

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

这篇关于通过Handle获取C#的Excel应用程序实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆