Microsoft Knowledge Base Email Alertz

If you sink the BeforeNavigate2 event of the WebBrowser control in a C# .NET application, the event does not fire.

Search KbAlertz

Advanced Search

Receive Microsoft Knowledge Base articles by E-Mail?

Every night we scan the Microsoft Knowledge Base. If technologies you're interested in are updated, we'll send you an e-mail. You only get one e-mail a day, and only when new articles are added.

Click here to create a
FREE account
Already have an account?
[Click here to Login]











Microsoft Knowledge Base Article

This article contents is Microsoft Copyrighted material.
©2005-©2007 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks

BUG: The BeforeNavigate2 Event of WebBrowser Control Does Not Fire If Hosted in a Visual C# .NET Application

Article ID: 325079 - View products that this article applies to.
This article was previously published under Q325079
For a Microsoft Visual Basic .NET version of this article, see 311298.

On This Page

SYMPTOMS

If you sink the BeforeNavigate2 event of the WebBrowser control in a C# .NET application, the event does not fire.

RESOLUTION

To work around this problem, hook up event handlers to the non-default source interface, in this case, the DWebBrowserEvents interface. This means you have to implement the DWebBrowserEvents and its methods (of which there are 17).
public void BeforeNavigate(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Cancel)
{
MessageBox.Show("C# DWebBrowser::BeforeNavigate event fired!", "DWebBrowser Event");
}
public void PropertyChange(string Property){}
public void NavigateComplete(string URL){}
public void WindowActivate(){}
public void FrameBeforeNavigate(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Cancel){}
public void NewWindow(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed){}
public void FrameNewWindow(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed){}
public void TitleChange(string Text){}
public void DownloadBegin(){}
public void DownloadComplete(){}
public void WindowMove(){}
public void WindowResize(){}
public void Quit(ref bool Cancel){}
public void ProgressChange(int Progress, int ProgressMax){}
public void StatusTextChange(string Text){}
public void CommandStateChange(int Command, bool Enable){}
public void FrameNavigateComplete(string URL){}
				
COM classes advertise that they support events by implementing an interface named IConnectionPointContainer, and by returning connection point objects by means of this interface. Connection point objects, which implement IConnectionPoint, are provided by the connectable objects, representing a collection of events.

The System.Runtime.InteropServices namespace defines common COM interfaces, such as IConnectionPointContainer and IConnectionPoint. These definitions can be confusing because each interface has been renamed with the prefix "UCOM" added. The "U" indicates unmanaged; "COM" indicates that the interface is originally defined in COM.

Under InteropServices, the IConnectionPointContainer and IConnectionPoint interfaces are defined as follows:
  • UCOMIConnectPointContainer
  • UCOMIConnectionPoint
Although the names of the interfaces are different, COM recognizes no difference between a "UCOM" interface and its corresponding unmanaged definition.

When developing code, you must do the following:
  • Obtain the IConnectionPointContainer interface.
    private UCOMIConnectionPoint icp;
    UCOMIConnectionPointContainer icpc = (UCOMIConnectionPointContainer)axWebBrowser1.GetOcx(); 
    					
  • Obtain the IConnectionPoint interface for a specified IID (event interface they want to subscribe to) by using the IConnectionPointContainer::FindConnectinPoint method.
    Guid g = typeof(DWebBrowserEvents).GUID;
    icpc.FindConnectionPoint(ref g, out icp);
    						
    Using the IConnectionPoint interface Advise and Unadvise methods, clients can hook and unhook callback interface pointers. A client calls IConnectionPoint::Advise with the IUnknown pointer to itself, and then Advise passes back an integral cookie that uniquely identifies the connection. On a successful return, Advise contains the connection cookie. The pdwCookie value must be unique for each connection to any particular instance of a connection point.
  • Use the IConnectionPoint::Advise method to establish a connection between the connection point object and the client's sink.
    icp.Advise(this, out cookie);
    					
  • Use the IConnectionPoint::Unadvise method to disconnect a connection between the connection point object and the client's sink.
    icp.Unadvise(cookie);
    					

Visual C# .NET Sample Code:

Paste the following code into a Visual C# .NET Windows form module:
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using SHDocVw;
using System.Runtime.InteropServices;

namespace wbcs
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form, DWebBrowserEvents
	{
		private UCOMIConnectionPoint icp; 
		private int cookie = -1; 
		
		private AxSHDocVw.AxWebBrowser axWebBrowser1;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public Form1()
		{
			// 
			// Required for Windows Form Designer support
			// 
			InitializeComponent();
			UCOMIConnectionPointContainer icpc = (UCOMIConnectionPointContainer)axWebBrowser1.GetOcx(); // ADDed
 
			Guid g = typeof(DWebBrowserEvents).GUID;
			icpc.FindConnectionPoint(ref g, out icp);
			icp.Advise(this, out cookie);
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				// Release event sink
				if (-1 != cookie) icp.Unadvise(cookie);
				        cookie = -1;
                                if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support; do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
			this.axWebBrowser1 = new AxSHDocVw.AxWebBrowser();
			((System.ComponentModel.ISupportInitialize)(this.axWebBrowser1)).BeginInit();
			this.SuspendLayout();
			// 
			// axWebBrowser1
			// 
			this.axWebBrowser1.Enabled = true;
			this.axWebBrowser1.Location = new System.Drawing.Point(8, 16);
			this.axWebBrowser1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axWebBrowser1.OcxState")));
			this.axWebBrowser1.Size = new System.Drawing.Size(448, 240);
			this.axWebBrowser1.TabIndex = 0;
			// 
			// Form1
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(472, 273);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.axWebBrowser1});
			this.Name = "Form1";
			this.Text = "Form1";

			this.Load += new System.EventHandler(this.Form1_Load); 
			((System.ComponentModel.ISupportInitialize)(this.axWebBrowser1)).EndInit();
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}

		private void Form1_Load(object sender, System.EventArgs e)
		{
			object obj = null;
			axWebBrowser1.Navigate ("http://www.microsoft.com", ref obj, ref obj, ref obj, ref obj);
		}

		public void BeforeNavigate(string URL, int Flags, string TargetFrameName, 
			ref object PostData, string Headers, ref bool Cancel)
		{
			MessageBox.Show("C# DWebBrowser::BeforeNavigate event fired!", "DWebBrowser Event");
		}

		public void PropertyChange(string Property){}

		public void NavigateComplete(string URL){}

		public void WindowActivate(){}

		public void FrameBeforeNavigate(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Cancel){}

		public void NewWindow(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed){}

		public void FrameNewWindow(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed){}

		public void TitleChange(string Text){}

		public void DownloadBegin(){}

		public void DownloadComplete(){}

		public void WindowMove(){}

		public void WindowResize(){}

		public void Quit(ref bool Cancel){}

		public void ProgressChange(int Progress, int ProgressMax){}

		public void StatusTextChange(string Text){}

		public void CommandStateChange(int Command, bool Enable){}

		public void FrameNavigateComplete(string URL){}
	}



}
				

STATUS

Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article.

MORE INFORMATION

A supported fix is now available from Microsoft. For additional information about this fix, click the article number below to view the article in the Microsoft Knowledge Base:
327135 BeforeNavigate2 Event of WebBrowser Control Does Not Fire

Steps to Reproduce the Behavior

  1. Start Visual Studio .NET.
  2. Create a new Visual C# .NET Windows Application project.
  3. Right-click in the Toolbox window, and then click Customize Toolbox.
  4. On the COM Components tab, select the Microsoft Web Browser check box.

    Notice that the WebBrowser control is added to the Controls tab in the toolbox that you chose to customize from.
  5. Drag the WebBrowser control from the toolbox to the Visual C# .NET form. AxWebBrowser1 is the default name.
  6. Double-click the form to open the code window for the Form1_Load method. Add the following code for the Form1_Load method:
    private void Form1_Load(object sender, System.EventArgs e)
    		{
    			object oURL = "http://www.microsoft.com";
    			object oEmpty = "";
    			axWebBrowser1.Navigate2(ref oURL, ref oEmpty, ref oEmpty, ref oEmpty, ref oEmpty);
    
    		}
    					
  7. To display the events for the object, in the AxWebBrowser1 Properties window, click Events, and then follow these steps:
    1. In the list of available events, click the BeforeNavigate2 event to create an event handler.
    2. In the box to the right of the event name, type the name of the handler TestBeforeNavigate2, and then press ENTER. The Code Editor appears; the code for the form is displayed, and an event handler method is generated in the code.

      NOTE: the Events Properties Window toolbar is available only when a form or control designer is active in the context of a Visual C# .NET project.
  8. Add the following code to the AxWebBrowser1 BeforeNavigate2 event handler method event:
    private void TestBeforeNavigate2(object sender, AxSHDocVw.DWebBrowserEvents2_BeforeNavigate2Event e)
    		{
    		 MessageBox.Show ("BeforeNavigate event fired!");
    		}
    					
  9. On the Debug menu, click Start to run the code. Alternatively, you can press F5 to run the code.

    Notice that the WebBrowser control opens the Microsoft Web site. However, notice that the BeforeNavigate2 event does not fire before it browses to the Microsoft Web site.

REFERENCES

311298 BUG: The BeforeNavigate2 Event of WebBrowser Control Does Not Fire If Hosted in Visual Basic .NET Application
IConnectionPointContainer Interface
http://msdn.microsoft.com/en-us/library/cc218729.aspx
IConnectionPoint Interface
tp://msdn.microsoft.com/en-us/library/cc218728.aspx
UCOMIConnectionPointContainer Interface
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.ucomiconnectionpointcontainer(VS.71).aspx
UCOMIConnectionPoint Interface
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.ucomiconnectionpoint(VS.71).aspx

Properties

Article ID: 325079 - Last Review: June 25, 2004 - Revision: 2.1
APPLIES TO
  • Microsoft Visual C# .NET 2002 Standard Edition
Keywords: 
kbcominterop kbwebbrowser kbctrlcreate kbctrl kbevent kbbug kbnofix KB325079
       

Community Feedback System

Very often, it takes hours to solve a problem. Very often, you've looked high and low, and have tried a lot of solutions. When you finally found it, chances are, it was because someone else helped you. Here's your chance to give back. Use our community feedback tool to let others know what worked for you and what didn't.

Please also understand that the community feedback system is not warranted to be correct, it's simply a system that we've built to let people try and help each other. If something in a feedback response doesn't make sense to you, or you're not comfortable making changes that the feedback talks about (like registry edits), please consult a professional.

Thank you for using kbAlertz.com Feedback System.

-- Scott Cate