I'm using Microsoft.Office.Interop.PowerPoint in my app to control presentation SlideShow. I can connect to PowerPoint using code
PowerPointApp = Marshal.GetActiveObject("PowerPoint.Application") as Microsoft.Office.Interop.PowerPoint.Application;
and all works ok, but I can't release refereces (after SlideShow ends and PowerPoint was CLOSED) using
Marshal.FinalReleaseComObject(PowerPointApp);
This call still throws an exception:
A first chance exception of type 'System.InvalidCastException' occurred in mscorlib.dll
Additional information: Unable to cast COM object of type 'System.__ComObject' to interface type 'System.Runtime.InteropServices.ComTypes.IConnectionPoint'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{B196B286-BAB4-101A-B69C-00AA00341D07}' failed due to the following error: The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD)).
I tried to wrap both methods (GetActiveObject and FinalReleaseComObject) into:
App.Current.Dispatcher.Invoke((MethodInvoker)delegate{ ... });`
to ensure that both methods are called from same thread, but I got same exception.
I also tried to release references when PowerPoint is still runnig - in this case, references to RCW are released without exception (but I need to release these referencers after PowerPoint is closed)
Use the ReleaseComObject instead of the FinalReleaseComObject method. The Systematically Releasing Objects article states the following:
Use System.Runtime.InteropServices.Marshal.ReleaseComObject to release an Office/PowerPoint object when you have finished using it. Then set a variable to Nothing in Visual Basic (null in C#) to release the reference to the object.
It is related to Outlook, but the same principles can be applied to any Office application.
User contributions licensed under CC BY-SA 3.0