1

我正在尝试连接到 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 返回正确的浏览器实例。

4

1 回答 1

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);
        }
于 2012-08-20T14:44:22.213 回答