The NewWindow2 event
The NewWindow2 event occurs when a new window is to be created for displaying a resource. This event occurs before a new window is created from the WebBrowser control. For example, this event occurs in response to a navigation that is targeted to a new window or to a scripted window.open method.To specify that your browser program is to be used when a new window is opened, set the ppDisp parameter equal to a new WebBrowser object that is contained in a new window that your program creates. In this scenario, if a user chooses to open a Web page in a new window, the new window in your program is used to display the new Web page.
Additionally, set the RegisterAsBrowser property to TRUE. This setting causes the new WebBrowser control to participate in window-name resolution. For example, if the window name is used elsewhere in the script, this control is used instead of a newly created one because the control examines all the existing window names before opening a new window.
Create the project and then add code
The following sample navigates the WebBrowser control to http://www.microsoft.com.- Start Microsoft Visual Studio .NET.
- Create a new Windows Application project in Visual Basic .NET.
- In the toolbox, click General.
- Right-click the open panel, and then click Customize Toolbox.
- Select the Microsoft Web Browser check box, and then click OK.
- In the toolbox, double-click Explorer.
- Add a button and a text box to your form.
- Double-click the button to view the implementation of the
Click event of the Button1 button in the code window. Append the following code to the existing code. This code lets you move to the URL that is specified in the text box.Write the handler function for the AxWebBrowser1.NewWindow2 event as follows.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click AxWebBrowser1.Navigate(TextBox1.Text) End Sub
Private Sub AxWebBrowser1_NewWindow2(ByVal sender As Object, ByVal e As AxSHDocVw.DWebBrowserEvents2_NewWindow2Event) Handles AxWebBrowser1.NewWindow2 Dim frmWB As Form1 frmWB = New Form1() frmWB.AxWebBrowser1.RegisterAsBrowser = True e.ppDisp = frmWB.AxWebBrowser1.Application frmWB.Visible = True End Sub
Verification
- Build the program.
- Start Notepad, and then save the following text as Test.htm
on your Web server.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> <TITLE>Q311282</TITLE> <SCRIPT type = "text/Jscript"> function openWin() { var win; win = window.open("http://www.microsoft.com"); } </SCRIPT> </HEAD> <BODY> <button onClick="openWin()">Open New Window</button> </BODY> </HTML>
- Run the program. The Form1 form appears.
- Type the path of the Test.htm file in the box, and then click Button1. The Open New Window button appears.
- Click Open New Window. Notice that the Microsoft Web page opens in a new instance of the program.