views:

560

answers:

1

I'm working on an extension (BHO) for Internet Explorer, and having trouble attaching a .NET delegate to the mshtml objects to catch DOM events.

I've tried using the events published by the IHTMLElementEvents2_Event, ... interfaces, and that works, but only if I specify the correct type for the DOM element whose events I want to catch. I also need to specify in code the type of the element, and this technique doesn't allow for catching custom DOM events.

I've also tried using the HtmlEventProxy class, which attaches IDispatch objects to the DOM elements via the IHTMLElement2.attachEvent method, but that isn't working for me at all. When I try to access the event object as described in this thread, I get a hang when accessing the DOM element's document property.

So how can I attach event handlers to DOM elements without needing to special case every kind of element and every kind of event?

Thanks.

+1  A: 

You can try this code:

[ComVisible(true)]
public class Foo
{
  public Foo(HtmlDocument doc) 
  {
    IHTMLDocument2 doc2 = (IHTMLDocument2)doc.DomDocument;
    doc2.onkeydown = this;
  }

  [System.Runtime.InteropServices.DispId(0)]
  public void EventHandler()
  {
    IHTMLWindow2 win2 = (IHTMLWindow2)_doc.Window.DomWindow;
    IHTMLEventObj e = win2.@event;

    if (e.keyCode == (int)Keys.F5)
    {
      // ...
    }
  }
}
alex2k8