在C#中挂钩IE事件

时间:2017-09-05 19:59:53

标签: c# internet-explorer com

我正在尝试从现有的IE窗口捕获事件。在下面的代码示例中,我试图在用户单击元素时捕获浏览器文档中的mouseClick事件,然后最终撤回有关被单击元素的一些属性。

public partial class frmBrowserElementBuilder : Form
{
    InternetExplorer ie;
    public frmBrowserElementBuilder()
    {
        InitializeComponent();
    }

    private void frmBrowserElementBuilder_Load(object sender, EventArgs e)
    {
        //create IE
        ie = new InternetExplorer();
        ie.Visible = true;

        //handle document completed
        ie.DocumentComplete += new
      DWebBrowserEvents2_DocumentCompleteEventHandler(DocumentComplete);

    }

    public void DocumentComplete(object pDisp, ref object URL)
    {
        //document was loaded
        //MessageBox.Show("DocumentComplete: " + URL);

        //create event handler and hook onclick from IE
        DHTMLEventHandler onClickHandler = new DHTMLEventHandler(ie.Document);
        onClickHandler.assignedEvent += new DHTMLEvent(this.ie_onClick);
        ie.Document.onclick = onClickHandler;
    }

    private void ie_onClick(mshtml.IHTMLEventObj e)
    {
        //something was clicked
        MessageBox.Show(string.Format("Event Hooked {0}, Qualifier {1}", e.type, e.qualifier));
    }

    public delegate void DHTMLEvent(IHTMLEventObj e);

    [ComVisible(true)]
    public class DHTMLEventHandler
    {
        public DHTMLEvent assignedEvent;

        private mshtml.HTMLDocument document;
        public DHTMLEventHandler(mshtml.HTMLDocument doc)
        {
            //assign to instance of IE document
            this.document = doc;
        }

        [DispId(0)]
        public void Call()
        {
            //call the event
            assignedEvent(this.document.parentWindow.@event); //{System.InvalidCastException: "Specified cast is not valid."}
        }

    }

}

代码编译和void Call()按预期触发,但this.document.parentwindow的值为null并抛出System.InvalidCastException: Specified cast is not valid when stepping into the assignedEvent method.

当我检查this.document时,parentWindow的值为

  

功能评估需要运行所有线程。

强迫评估后,

表示:

  

'((mshtml.HTMLDocumentClass)this.document).parentWindow'扔了一个   类型' System.InvalidCastException'。

的例外

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

这是一个threading问题。 Call()调用发生在MTA线程上,您无法从MTA线程访问MSHTML。有很多方法可以改变这种情况,但最简单的方法是:

public void DocumentComplete(object pDisp, ref object URL)
{
    var events = (HTMLDocumentEvents2_Event)ie.Document;
    events.onclick += (evt) =>
    {
        MessageBox.Show(string.Format("Event Hooked {0}, Qualifier {1}", evt.type, evt.qualifier));
        return false;
    };
}