COMException in C# when hooking into event

2019-04-29 02:07发布

I am receiving a COM Exception when trying to hook into an event on a COM Object. Here is the code I am trying to execute.

COMClass a = IComClass as ComClass;
a.SomeEvent += new SomeEvent_EventHandler(MethodNameHere);

Line two throws an exception of type COMException with the following information:

System.Runtime.InteropServices.COMException was caught

Message="Exception from HRESULT: 0x80040202"

Source="mscorlib"

ErrorCode=-2147220990

StackTrace: at System.Runtime.InteropServices.ComTypes.IConnectionPoint.Advise(Object pUnkSink, Int32& pdwCookie)

Does anyone have any ideas why I am unable to hook into a COM event or if there is a workaround for hooking into COM events?

Chris

2条回答
不美不萌又怎样
2楼-- · 2019-04-29 02:45

The error code you got is CONNECT_E_CANNOTCONNECT, something that Googles well. It indicates that the COM server isn't happy about your attempt to subscribe an event handler. Why it is not is something you'll need to find out. Getting help from the component author or vendor is almost always required.

One thing you can try is to look at the type library with Oleview.exe and find out if the event you're trying to subscribe to is on a dispinterface that's marked as the default source interface. If it is not, try casting the object to the dispinterface type, then subscribe to its event.

查看更多
走好不送
3楼-- · 2019-04-29 02:46

The problem was the interface for the events was no registered. Once I added the registry key for the Events Interface, this resolved the problem. I was able to get the interface id information using OLEViewer.exe

查看更多
登录 后发表回答