How do I add an event listener using MSHTML's addEventListener in IE9?

余生颓废 提交于 2019-11-30 21:24:08

After some research, I learned that these COM connection points (event handlers) are specified with DispId(0). Callback functions are represented by instances of classes like:

// These attributes may be optional, depending on the project configuration.
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.AutoDispatch)]
public class EventListener
{
    [DispId(0)]
    // The "target" parameter is an implementation detail.
    public void NameDoesNotMatter(object target, IDOMEvent evt) { ... }
}

Since DispId(0) specifies the default method to invoke, the actual name of the method doesn't matter. However, the method parameters certainly do matter. For example, IHTMLElement.onclick must be assigned a callback with no arguments, while IHTMLElement2.attachEvent takes a callback with one parameter of type IHTMLEventObj (or IHTMLEventObj2, ..., 6 , or even just object).

In summary, COM IDispatch callbacks can be implemented in C# using a COM-visible class with a method that accepts the correct arguments and is annotated with [DispId(0)].


Despite all of this, solutions that avoid the W3C DOM Events API may be more appropriate, as IE9 DOM objects do not support this method when the browser is using a lower document mode for compatibility. For example, an extension that uses addEventListener will fail on a page like Bing, which is rendered in IE7 mode.

It also doesn't seem possible to set the document mode used by an IWebBrowser2 instance aside from manually doing it through the F12 developer tools.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!