Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding the webBrowser click event

Tags:

c#

winforms

I need some information about what happens when a user clicks a hyperlink in a webBrowser control. My thinking is that it calls the .Navigate() method, but I am not sure.

I have created a wrapper method that wraps around the navigate method. What I want to do is that when a user clicks a link, or a button or watever, my method is called instead of the .Navigate() method.

What do I need to ovverride to achieve this?

Thanks

Edit: It seems there is some trouble understanding my question, let me try to refrase:

I have created my own webBrowser control that inherits from WebBrowser. In my control, there is a method I use to navigate which does some steps before actually calling the navigate() method.

Now calling this method from my code is easy, just call my method instead of .Navigate. But what I want is that when a user clicks a link on a page my method runs instead of .Navigate.

like image 259
TheGateKeeper Avatar asked Sep 19 '25 09:09

TheGateKeeper


2 Answers

No need to override, just attach an event handler to every link on the page on the WebBrowser.DocumentCompleted event.

private bool bCancel = false;

private void webBrowser_DocumentCompleted(object sender,
                                 WebBrowserDocumentCompletedEventArgs e)
{
  int i;
  for (i = 0; i < webBrowser.Document.Links.Count; i++)
  {
     webBrowser.Document.Links[i].Click += new    
                            HtmlElementEventHandler(this.LinkClick);
  }
}
private void LinkClick(object sender, System.EventArgs e)
{
  bCancel = true;
  MessageBox.Show("Link Was Clicked Navigation was Cancelled");
}
private void webBrowser_Navingating(object sender, 
                                WebBrowserNavigatingEventArgs e )
{
  if (bCancel == true)
  {
     e.Cancel=true;
     bCancel = false;
  }
}

Hope it helps!

EDIT:

If you would like to find more info about the link that was clicked simply modify the LinkClick event handler with something like this:

private void LinkClick(object sender, System.EventArgs e)
{
    HtmlElement element = ((HtmlElement)sender);
    string id = element.Id;
    string href = element.GetAttribute("href");

    bCancel = true;
    MessageBox.Show("Link Was Clicked Navigation was Cancelled");        
}
like image 126
Reinaldo Avatar answered Sep 20 '25 22:09

Reinaldo


The Navigating event is raised. You can implement an event handler for it to reject and redirect the navigation request:

    private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) {
        // Redirect expertsexchange to stackoverflow
        if (e.Url.ToString().Contains("experts-exchange")) {
           e.Cancel = true;
           webBrowser1.Navigate("http://stackoverflow.com");
        }
    }
like image 39
Hans Passant Avatar answered Sep 20 '25 23:09

Hans Passant