Reputation: 1149
I have the code below but when I click on the web page it fires 2 - 6 times. How can I make it just fire once?
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser1.Document != null)
{
htmlDoc = webBrowser1.Document;
htmlDoc.Click += htmlDoc_Click;
//htmlDoc.MouseDown += htmlDoc_MouseDown;
//htmlDoc.MouseMove += htmlDoc_MouseMove;
htmlDoc.ContextMenuShowing += htmlDoc_ContextMenuShowing;
}
}
void htmlDoc_Click(object sender, HtmlElementEventArgs e)
{
Console.WriteLine("Mouse Click");
if (e.CtrlKeyPressed)
{
if (webBrowser1.Document.GetElementFromPoint(e.ClientMousePosition).InnerHtml != null)
{
//MessageBox.Show(webBrowser1.Document.GetElementFromPoint(webBrowser1.PointToClient(MousePosition)).InnerText.ToString());
Debug.WriteLine(webBrowser1.Document.GetElementFromPoint(e.ClientMousePosition).InnerHtml);
}
e.ReturnValue = false;
return;
}
// stop mouse events moving on to the HTML doc return false
e.ReturnValue = true;
}
Upvotes: 1
Views: 1820
Reputation: 942000
If the web page you visit contains frames then the DocumentCompleted event will fire multiple times, once for each frame. And thus you'll subscribe the event multiple times. Filter this by checking e.Url.Equals(webBrowser1.Url), it is only true for the last one.
Another problem you'll have to solve is unsubscribing the event, right now you'll leak the HtmlDocument. Be sure to unsubscribe before calling Navigate().
Upvotes: 3
Reputation: 7213
You need to implement your own Dispose method and unsubscribe there from all the events:
htmlDoc.Click -= htmlDoc_Click;
htmlDoc.ContextMenuShowing -= htmlDoc_ContextMenuShowing;
Loos like your variables are global so should not be an issue.
Upvotes: 0