将事件处理程序附加到mshtml.disphtmlinputelement
-
18-09-2019 - |
题
我正忙于在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对象的方法。有任何想法吗?
解决方案
因此,事实证明,一旦您将System_comobject施放到DISPHTMLINPUTEMENT对象,就可以与MSHTML进行交互。[事件]接口。因此,添加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
不隶属于 StackOverflow