There is a known bug:
BUG: The BeforeNavigate2 Event of the WebBrowser Control Does Not Fire If Hosted in a Visual Basic .NET Application (Article ID: 311298)
BUG: The BeforeNavigate2 Event of WebBrowser Control Does Not Fire If Hosted in a Visual C# .NET Application (Article ID: 325079)
If you are using the second solution from our FAQ "How can I host a WebBrowser control in a Windows Form" you will not have this problem but if you use the automatically generated wrapper classes see the following solution:
The problem of the BeforeNavigate2 event not firing in C# applications has been floating around various groups for several months. Microsoft has not yet fixed the problem, although it is documented in the knowledge base. Until they do provide a fix, I suggest the following workaround to the problem which uses the fact the the old Webbrowser_V1 BeforeNavigate event can be caught. Note, use of this interface is deprecated, however since there doesn't appear to be any chance of a fix any time soon.
// define the webbrowser object
private AxSHDocVw.AxWebBrowser axDocument;
// define an IE3 compatible webbrowser object.
private SHDocVw.WebBrowser_V1 axDocumentV1;
public Form1()
{
//...
object o = null;
axDocument.Navigate("about:blank", ref o, ref o, ref o, ref o);
object oOcx = axDocument.GetOcx();
try
{
axDocumentV1 = oOcx as WebBrowser_V1;
axDocumentV1.BeforeNavigate +=
new SHDocVw.DWebBrowserEvents_BeforeNavigateEventHandler(
axDocumentV1_BeforeNavigate );
}
catch ( Exception ex )
{
// ignore errors. If it doesn't work, there's not a lot to do!
Console.WriteLine( "Add BeforeNavigate event handler failed with{0}.",
ex.Message);
}
//...
}
private void axDocumentV1_BeforeNavigate( string URL, int Flags,
string TargetFrameName, ref object PostData, string Headers, ref bool Processed )
{
Console.WriteLine( "BeforeNavigateURL= {0}", URL );
//false= allow navigate to continue.
//true= cancel navigation.
Processed = false;
}
George Shepherd, Syncfusion, and John Cullen