Overriding webBrowser click event
I need information on what happens when a user clicks a hyperlink in a webBrowser control. I think it is calling a method .Navigate()
, but I'm not sure.
I created a wrapper method that wraps around the navigation method. What I want to do is that when the user clicks on a link or button or whatever, my method is called instead of the method .Navigate()
.
What do I need to achieve this?
thank
Edit: There seems to be some trouble understanding my question, let me try to rephrase:
I have created my own webBrowser control that inherits from WebBrowser. There is a method in my control that I use to navigate that goes through some steps before actually calling the navigate () method.
Now it's easy to call this method from my code, just call my method instead of .Navigate. But I want so that when the user clicks on a link on the page, my method gets triggered instead of .Navigate.
source to share
No need to override, just attach an event handler to every link on the page in 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 information about the link that was clicked, simply change the LinkClick event handler to 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");
}
source to share
Navigation event added. You can implement an event handler so that it rejects and redirects 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");
}
}
source to share