问题
I want to add click event of webBrowser control. This is my code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
HtmlDocument htmlDoc;
public Form1()
{
InitializeComponent();
OpenFileDialog open = new OpenFileDialog();
open.ShowDialog();
this.webBrowser1.Navigate(open.FileName);
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser1.Document != null)
{
htmlDoc = webBrowser1.Document;
htmlDoc.Click += new HtmlElementEventHandler(htmlDoc_Click);
}
}
private void htmlDoc_Click(object sender, HtmlElementEventArgs e)
{
MessageBox.Show("Click");
}
}
}
I want it to diplay a .ppt file. It is ok to display but when I click the webBrowser there is no messagebox show up. Is there any other solution? thanks
回答1:
I'm using ObjectForScripting
to do these kind of things. It allows JavaScript to call a C#-Method. Let JavaScript react on events, thats much easier and you don't need MSHTML. It's nicely explained here. Youl'll need using System.Runtime.InteropServices;
for it to work, so that the app knows the ComVisible-Annotation.
You don't have to be a JavaScript-pro to use this. For example: Just add a button like this:
<button onclick="javascript:window.external.showPpt('test.ppt');">Click me</button>
which will call a method named showPpt
in the ObjectForScripting
. Remember: You may create the HTML using C# too. This way you can store information in the document. Here is a full example:
public partial class frmBrowser : Form
{
HtmlDocument doc;
[ComVisible(true)]
public class ScriptManager
{
private frmBrowser mForm;
public ScriptManager(frmBrowser form)
{
mForm = form;
}
public void recall(string statusID)
{
mForm.RestoreStatus(statusID);
}
}
public frmBrowser()
{
InitializeComponent();
this.webBrowser.ObjectForScripting = new ScriptManager(this);
string url = "file:///" + Application.StartupPath + "\\start\\start.html";
this.webBrowser.Navigate(url);
}
private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
doc = webBrowser.Document;
showRecent();
}
private void showRecent()
{
HtmlElement divRecent = doc.GetElementById("recent_cont");
List<DaoStatus> status = Center.DB.GetUIStatus();
string html = "";
foreach (DaoStatus st in status)
{
html += "<button onclick=\"javascript:window.external.recall('" + st.ID + "');\">" + st.Name + "</button>";
}
divRecent.InnerHtml = html;
}
}
The webBrowser
control navigates to a local file. If fully loaded showRecent()
is called, which gets information from a database and creates buttons accordingly using a div-Element with the id "recent_cont".
来源:https://stackoverflow.com/questions/17540644/handling-click-event-of-web-browser-control