我在我的应用程序中使用Microsoft.Office.Interop.PowerPoint来控制演示文稿SlideShow。我可以使用代码连接到PowerPoint
PowerPointApp = Marshal.GetActiveObject("PowerPoint.Application") as Microsoft.Office.Interop.PowerPoint.Application;
并且一切正常,但是我无法发布引用(在SlideShow结束并且PowerPoint被关闭后)
Marshal.FinalReleaseComObject(PowerPointApp);
此调用仍会引发异常:
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)).
我尝试将两个方法(GetActiveObject和FinalReleaseComObject)包装成:
App.Current.Dispatcher.Invoke((MethodInvoker)delegate{ ... });`
确保从同一个线程调用这两个方法,但我得到了同样的异常。
我还试图在PowerPoint仍然运行时发布引用 - 在这种情况下,对RCW的引用毫无例外地发布(但我需要在PowerPoint关闭后发布这些引用)
答案 0 :(得分:0)
使用ReleaseComObject而不是FinalReleaseComObject方法。 Systematically Releasing Objects文章声明如下:
完成使用后,使用System.Runtime.InteropServices.Marshal.ReleaseComObject释放Office / PowerPoint对象。然后在Visual Basic中将变量设置为Nothing(C#中为null)以释放对该对象的引用。
它与Outlook有关,但相同的原则可以应用于任何Office应用程序。