views:

397

answers:

1

I'm busy writing a BHO(Browser Helper Object) in C# and I need to attach events handlers to all onclick events on Input Elements. I'm NOT using the built in webbrowser provided by visual studio, instead I am launching a new instance of the Internet Explorer installed on the clients PC. The problem comes in when using different versions of IE.

In IE7 and IE8 I can do it like this:

public void attachEventHandler(HTMLDocument doc)
{
  IHTMLElementCollection els = doc.all;
  foreach (IHTMLElement el in els)
  {
    if(el.tagName == "INPUT")
    {
      HTMLInputElementClass inputElement = el as HTMLInputElementClass;
      if (inputElement.IHTMLInputElement_type != "text" && InputElement.IHTMLInputElement_type != "password")
      {
        inputElement.HTMLButtonElementEvents_Event_onclick += new HTMLButtonElementEvents_onclickEventHandler(buttonElement_HTMLButtonElementEvents_Event_onclick);
      }
    }
  }
}

That works perfectly, the thing is, IE6 throws an error when casting to HTMLInputElementClass, so you are forced to cast to DispHTMLInputElement:

public void attachEventHandler(HTMLDocument doc)
{
  IHTMLElementCollection els = doc.all;
  foreach (IHTMLElement el in els)
  {
    if(el.tagName == "INPUT")
    {
      DispHTMLInputElement inputElement = el as DispHTMLInputElement;
      if (inputElement.type != "text" && inputElement.type != "password")
      {
        //attach onclick event handler here
      }
    }
  }
}

The problem is, I cant seem to find a way to attach the event to the DispHTMLInputElement object. Any ideas?

+1  A: 

So it turns out that once you have cast from a System_ComObject to a DispHTMLInputElement object you can interact with the mshtml.[events] interface. So the code to add an event handler for IE6 will be:

public void attachEventHandler(HTMLDocument doc)
{
  IHTMLElementCollection els = doc.all;
  foreach (IHTMLElement el in els)
  {
    if(el.tagName == "INPUT")
    {
      DispHTMLInputElement inputElement = el as DispHTMLInputElement;
      if (inputElement.type != "text" && inputElement.type != "password")
      {
        HTMLButtonElementEvents_Event htmlButtonEvent = inputElement as HTMLButtonElementEvents_Event;
        htmlButtonEvent.onclick += new HTMLButtonElementEvents_onclickEventHandler(buttonElement_HTMLButtonElementEvents_Event_onclick);
      }
    }
  }
 }

You can however interface directly into the event handler, but I wanted to exclude some types like passwaord and text fields, therefore I had to cast to DispHTMLInputElement first

Yo Momma