WPF WebBrowser: How to set element click event?
I've figured out how to make everything red as soon as the page is finished loading:
private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
{
var doc = (IHTMLDocument2)webBrowser1.Document;
foreach (IHTMLElement elem in doc.all)
{
elem.style.backgroundColor = "#ff0000";
}
}
Now what if I want to make the element only change color when it's clicked? I see that elem
has an onclick
property, but it's type is dynamic
so I don't know what to do with it. The documentatio开发者_如何学运维n is pretty useless.
You could do it by using the HTMLDocumentClass
instead of the IHTMLDocument2
interface:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
{
mshtml.HTMLDocumentClass doc = (mshtml.HTMLDocumentClass)webBrowser1.Document;
doc.HTMLDocumentEvents_Event_onclick += new mshtml.HTMLDocumentEvents_onclickEventHandler(OnClickHandler);
}
bool OnClickHandler()
{
mshtml.HTMLDocumentClass doc = (mshtml.HTMLDocumentClass)webBrowser1.Document;
mshtml.IHTMLWindow2 win = doc.parentWindow;
win.@event.srcElement.style.backgroundColor = "#ff0000";
return false;
}
}
The above solution, has one drawback: the onclick
event does not bubble, even though false
is returned (i.e. clicking at hyperlinks does not navigate to other pages).
精彩评论