Yo *_*mma 3 c# bho mshtml event-handling
我正忙于在C#中编写BHO(浏览器助手对象),我需要将事件处理程序附加到输入元素上的所有onclick事件.我没有使用visual studio提供的内置web浏览器,而是启动了客户端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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这很有效,事实是,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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,我似乎找不到将事件附加到DispHTMLInputElement对象的方法.有任何想法吗?
事实证明,一旦你从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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是你可以直接连接到事件处理程序,但是我想要排除某些类型,如passwaord和text字段,因此我必须首先强制转换为DispHTMLInputElement