C# 将事件处理程序附加到mshtml.DispHTMLInputElement

C# 将事件处理程序附加到mshtml.DispHTMLInputElement,c#,mshtml,bho,event-handling,C#,Mshtml,Bho,Event Handling,我正忙着用C#编写一个BHO(浏览器助手对象),我需要将事件处理程序附加到输入元素上的所有onclick事件。我没有使用visual studio提供的内置webbrowser,而是在客户端PC上安装了一个新的Internet Explorer实例。使用不同版本的IE时会出现问题 在IE7和IE8中,我可以这样做: public void attachEventHandler(HTMLDocument doc) { IHTMLElementCollection els = doc.all;

我正忙着用C#编写一个BHO(浏览器助手对象),我需要将事件处理程序附加到输入元素上的所有onclick事件。我没有使用visual studio提供的内置webbrowser,而是在客户端PC上安装了一个新的Internet Explorer实例。使用不同版本的IE时会出现问题

在IE7和IE8中,我可以这样做:

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);
      }
    }
  }
}
这非常有效,问题是,IE6在转换到HTMLInputElementClass时抛出一个错误,因此您必须转换到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
      }
    }
  }
}

问题是,我似乎找不到将事件附加到DispHTMLInputElement对象的方法。有什么想法吗?

因此,一旦您将系统对象转换为DispHTMLInputElement对象,就可以与mshtml。[events]接口交互。因此,为IE6添加事件处理程序的代码如下:

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);
      }
    }
  }
 }

但是,您可以直接连接到事件处理程序,但我想排除一些类型,如passwaord和text字段,因此我必须首先转换到DispHTMLInputElement

我需要感谢Yo Momma。对
HTMLButtonElementEvents\u事件的强制转换产生了所有的不同。花几个小时在这上面。