Как зафиксировать событие нажатия кнопки веб-страницы (открытой внутри элемента управления WebBrowser) в форме WPF? - PullRequest
5 голосов
/ 26 июля 2011

Рассмотрим сценарий, в котором у меня есть элемент управления WebBrowser в приложении WPF.Веб-страница загружается внутри элемента управления WebBrowser.Веб-страница содержит кнопку.Веб-страница имеет приложение ASP.NET.

Я хочу записать событие нажатия кнопки на веб-странице в форму WPF (в которой находится элемент управления WebBrowser).Есть ли способ достичь этой функциональности?

Спасибо,

Tapan

1 Ответ

6 голосов
/ 20 августа 2011

Вот код, который должен делать именно то, что вы хотите с комментариями, чтобы объяснить, что происходит:

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...