问题
I'm using .NET visual C# 2008 and in my webbrowser, I added click event handler to capture what html tag name I've clicked.
But then I lost control to the webbrowser.
When I start the application, in the webbrowser, I cannot enter texts into text field in the browser. It still accepts mouse clicks to the links though.
I've found few people having this issue in forums but no solution is found. What am I doing wrong?
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace IERecorder
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private mshtml.HTMLDocument doc = null;
private void Form1_Load_1(object sender, EventArgs e)
{
txtRecord.Items.Add("start...");
txtRecord.Items.Add("start2...");
webBrowser1.Navigate("http://www.google.com");
}
private void webBrowser1_DocumentComplete(object sender, WebBrowserDocumentCompletedEventArgs e)
{
txtRecord.Items.Add(e.Url.ToString() + " loaded...");
if (doc == null)
{
doc = (mshtml.HTMLDocument)webBrowser1.Document.DomDocument;
mshtml.HTMLDocumentEvents2_Event iEvent;
iEvent = (mshtml.HTMLDocumentEvents2_Event)doc;
iEvent.onclick += new mshtml.HTMLDocumentEvents2_onclickEventHandler(ClickEventHandler);
}
}
private bool ClickEventHandler(mshtml.IHTMLEventObj e)
{
txtRecord.Items.Add("clicked ==>" + e.srcElement.tagName);
txtRecord.Items.Add("clicked2 ==>" + e.srcElement.getAttribute("name", 0));
txtRecord.Items.Add("clicked3 ==>" + e.srcElement.innerHTML);
return true;
}
}
}
回答1:
Its a framework related issue, It will not work on framework 3.5. Change the project framework to 4.5.2, It will work.
回答2:
I don't see a text field in your code? Did you mean the google search box?
This is a screenshot of what I was able to reproduce with the code that you supplied. I was able to search for stackoverflow and browse to it. I would doublecheck that your event handlers are still wired up correctly.

来源:https://stackoverflow.com/questions/6039903/why-lose-webbrowser-control-when-adding-click-event-handler