Web browser control: How to capture document events?

后端 未结 2 1051
忘了有多久
忘了有多久 2020-11-29 12:34

I am using WPF\'s WebBrowser control to load a simple web page. On this page I have an anchor or a button. I want to capture the click event of that button in my application

相关标签:
2条回答
  • 2020-11-29 12:53

    Here is another example.

    I was trying to inject a remote javascript file and execute some code when ready by adding a DOM element <script src="{path to remote file}" /> to the header, essentially the same idea as jQuery.getScript(url, callback)..

    The code below works fine.

    HtmlElementCollection head = browser.Document.GetElementsByTagName("head");
    if (head != null)
    {
        HtmlElement scriptEl = browser.Document.CreateElement("script");
        IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
        element.src = url;
        element.type = "text/javascript";
        head[0].AppendChild(scriptEl);
        // Listen for readyState changes
        ((mshtml.HTMLScriptEvents2_Event)element).onreadystatechange += delegate
        {
            if (element.readyState == "complete" || element.readyState == "loaded")
            {
                Callback.execute(callbackId);
            }
        };
    }
    
    0 讨论(0)
  • 2020-11-29 13:02

    Ok Answer found - tested and it works:

    • Add a reference from the COM tab called: Microsoft HTML Object Library

    The following is an example code:

    You will need two components: WebBrowser (webBrowser1) and a TextBox (textBox1)

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
    
            webBrowser1.LoadCompleted += new LoadCompletedEventHandler(webBrowser1_LoadCompleted);
        }
    
        private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
        {
            mshtml.HTMLDocument doc;
            doc = (mshtml.HTMLDocument)webBrowser1.Document;
            mshtml.HTMLDocumentEvents2_Event iEvent;
            iEvent = (mshtml.HTMLDocumentEvents2_Event)doc;
            iEvent.onclick += new mshtml.HTMLDocumentEvents2_onclickEventHandler(ClickEventHandler);
        }
    
        private bool ClickEventHandler(mshtml.IHTMLEventObj e)
        {
            textBox1.Text = "Item Clicked";
            return true;
        }
    }
    
    0 讨论(0)
提交回复
热议问题