我正在尝试连接到Internet Explorer并将侦听器添加到任何DOM事件,包括自定义事件。如何才能做到这一点? 我正在尝试这种变体,但没有任何结果:
//...
using mshtml;
using SHDocVw;
using System.Windows.Browser;
class Test {
public Test(){
IWebBrowser2 browser = BrowserHelper.GetBrowserInstance();
var a = browser.Document as HTMLDocument;
mydelegate obj = this.somefunction;
a.attachEvent("onclick", obj);
}
public delegate void mydelegate(object sender, HtmlEventArgs args);
public void somefunction(object sender, HtmlEventArgs args)
{
MessageBox.Show("Clicked!");
}
}
BrowserHelper返回正确的浏览器实例。
答案 0 :(得分:4)
这对我有用,不直接使用SHDOCVW。我不知道从DOM获取自定义事件的解决方案。如果您知道要监听的自定义事件列表,则可以轻松完成。
private void webBrowser1_DocumentCompleted(
object sender,
WebBrowserDocumentCompletedEventArgs e)
{
// obtain HtmlDocument
HtmlDocument htmlDoc = webBrowser1.Document;
// loop over ALL elements in HtmlDoc
foreach(HtmlElement element in htmlDoc.All)
{
// for the HtmlElements type fetch its suported Events
// from the typeinfo
// we use a LinqQuery to filter in the future
var listOfEvents = from domInt in element.GetType().GetEvents()
// where domInt.Name.Contains("click")
select domInt;
// iterated over the EventMembers
foreach (var htmlevent in listOfEvents)
{
// invoke .Net managed AddEventHandler
htmlevent.AddEventHandler(
element,
new HtmlElementEventHandler(GenericDomEvent));
}
}
}
// do usefull stuff with the even raised
private void GenericDomEvent(object sender, HtmlElementEventArgs e)
{
Debug.WriteLine(e.EventType);
}