本文介绍了如何捕获在WPF形式的网页(WebBrowser控件内打开)的按钮单击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个场景,我在WPF应用程序WebBrowser控件。
一个网页加载WebBrowser控件内。该网页包含一个按钮。
该网页是ASP.NET应用程序的。

Consider a scenario where I have a WebBrowser Control in WPF application.A web page is loaded inside WebBrowser Control. The web page contains a button.The web page is of ASP.NET application.

我要捕捉的网页在WPF表(它承载WebBrowser控件)的按钮点击事件。有什么办法来实现这一功能呢?

I want to capture the button click event of the webpage into WPF Form (which hosts WebBrowser Control). Is there any way to achieve this functionality ?

谢谢,

塔潘

推荐答案

下面为code,它应该做的正是你想要的带有注释,解释正在发生的事情:

Here is code that should do exactly what you want with comments to explain what is going on:

public partial class MainWindow : Window
{

    /// <summary>
    /// This is a helper class.  It appears that we can't mark the Window as ComVisible
    /// so instead, we'll use this seperate class to be the C# code that gets called.
    /// </summary>
    [ComVisible(true)]
    public class ComVisibleObjectForScripting
    {
        public void ButtonClicked()
        {
            //Do whatever you need to do.  For now, we'll just show a message box
            MessageBox.Show("Button was clicked in web page");
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        //Pass an instance of our helper class as the target object for scripting
        webBrowser1.ObjectForScripting = new ComVisibleObjectForScripting();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        //Navigate to your page somehow
        webBrowser1.Navigate("http://www.somewhere.com/");
    }

    private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
    {
        //Once the document is loaded, we need to inject some custom JavaScript.

        //Here is the JavaScript
        var javascript = @"
//This is the JavaScript method that will forward the click to the WPF app
function htmlButtonClicked()
{
    //Do any other procession...here we just always call to the WPF app
    window.external.ButtonClicked();
}

//Find the button that you want to watch for clicks
var searchButton = document.getElementById('theButton');

//Attach an onclick handler that executes our function
searchButton.attachEvent('onclick',htmlButtonClicked);
";

        //Grab the current document and cast it to a type we can use
        //NOTE: This interface is defined in the MSHTML COM Component
        //       You need to add a Reference to it in the Add References window
        var doc = (IHTMLDocument2)webBrowser1.Document;

        //Once we have the document, execute our JavaScript in it
        doc.parentWindow.execScript(javascript);
    }
}

其中的一些是从http://beensoft.blogspot.com/2010/03/two-way-interaction-with-javascript-in.html

这篇关于如何捕获在WPF形式的网页(WebBrowser控件内打开)的按钮单击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 05:37
查看更多