2009-12-10 96 views
3

我忙于在C#中编写BHO(浏览器帮助对象),我需要将事件处理程序附加到输入元素上的所有onclick事件。我不使用Visual Studio提供的内置web浏览器,而是使用安装在客户端PC上的Internet Explorer的新实例。使用不同版本的IE时出现问题。将事件处理程序附加到mshtml.DispHTMLInputElement

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

这铸造HTMLInputElementClass的时候,所以你不得不转换为DispHTMLInputElement完美的作品,问题是,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") 
     { 
     //attach onclick event handler here 
     } 
    } 
    } 
} 

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

回答

5

所以事实证明,一旦你从System_ComObject转换到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和文本字段,因此我不得不投以DispHTMLInputElement第一个

相关问题