[英]Using late binding to get a specific instance of Excel in C#
在稍后帮助后期绑定。
我试图晚绑定excel,我没有任何问题这样做。 只有当我有多个excel实例打开时才遇到一些问题。
我希望能够确定要绑定到哪个excel实例(以及链接事件等)。 主要原因是我有一个应用程序从第三方工具打开excel文档,并且不处理事件。 我希望能够利用我知道可以捕获事件的特定excel实例。 唯一的问题是如果用户已经打开了excel(无论如何)。
如果在绑定后打开excel,显然,我没有遇到问题。 只有当excel已经打开时才会这样。
似乎绑定是在第一个打开的实例中完成的。
这是实际的代码:
Type excelType = Type.GetTypeFromProgID("Excel.Application");
// Throw exception if the type wasn't found
if (excelType == null)
throw new Exception(error);
//Get the Excel.Application Type by creating a new type instance
excelApplication = Marshal.GetActiveObject("Excel.Application");
//Throw exception if the object couldn't be created
if (excelApplication == null)
throw new Exception(error);
this.withEvents = withEvents;
//Create link between the Word.Applications events and the ApplicationEvents2_WordEvents class
if (this.withEvents)
{
excelEvents = new ExcelApplicationEvents();
//holds the connection point references of the Word.Application object
IConnectionPointContainer connectionPointContainer = excelApplication as IConnectionPointContainer;
//Find the connection point of the GUID found from Red Gate's .Net Reflector
Guid guid = new Guid("00024413-0000-0000-C000-000000000046");
connectionPointContainer.FindConnectionPoint(ref guid, out connectionPoint);
//Advise the Word.Application to send events to the event handler
connectionPoint.Advise(excelEvents, out sinkCookie);
excelEvents.WorkbookBeforeSaveEvent += new EventHandler<WorkbookEventArgs>(ExcelEventsWorkbookBeforeSaveEvent);
}
有任何想法吗?
干杯,
戴尔。
获取Excel的特定实例需要您使用AccessibleObjectFromWindow API 。
在 Andrew Whitechapel的文章“在Shimmed Automation Add-in中获取应用程序对象”中对此进行了解释 。
但是,你想要的是使用后期绑定来执行它。 这里有divo详细介绍: 如何使用后期绑定来获取excel实例 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.