Using late binding to get a specific instance of Excel in C #

Just after a little help with late binding.

I am trying to belate bind excel and I have no problems. Only when I have multiple excel instances where I run into some problems.

I would like to be able to determine which excel instance is bound to (and link events, etc.). The main reason is that I have an application that opens an Excel document from a third-party tool and events are not processed. I want to be able to use a specific excel instance that I know is open to catch events. The only problem is that excel is already open by the user (no matter how).

If excel opens after binding, obviously I have no problem. Only when excel is already open.

It seems that the binding is done with the first open, open.

Here is the actual code:

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

Any ideas?

Greetings

Dale.

+3
source share
1 answer

Retrieving a specific instance of Excel requires the use of the API to access object>.

This is well explained in the article Getting an Application Object in an Auto-Tuning Add-in by Andrew Whitechapel.

, . divo : excel.

+4

Source: https://habr.com/ru/post/1719943/


All Articles