I'm trying to redirect new Window event to a new tab:
myWebBrowser.NewWindow += add_NewTab;
//...
private void add_NewTab(object sender, CancelEventArgs e)
{
WebBrowser thisWebBrowser = (WebBrowser)sender;
e.Cancel = true; //should block the default browser to open a new window
TabPage addedTabPage = new TabPage("redirected tab"); //create a new tab
tabControl_webBrowsers.TabPages.Add(addedTabPage); //add the new tab to the TabControl
WebBrowser addedWebBrowser = new WebBrowser() //create the new web browser inside the new tab
{
Parent = addedTabPage,
Dock = DockStyle.Fill
};
addedWebBrowser.Navigate(thisWebBrowser.StatusText.ToString()); //set the new browser destination url
}
I'm not sure that using WebBrowser.StatusText
is the best way to obtain the new window url (this doesn't work for every site I've tested).
Is there a better class/method to call to get new window destination instead?
UPDATE:
I've tried the solution suggested by Charlie
used the code:
System.Windows.Forms.WebBrowser myWebBrowser = new System.Windows.Forms.WebBrowser();
SHDocVw.WebBrowser axBrowser = (SHDocVw.WebBrowser)myWebBrowser.ActiveXInstance;
axBrowser.NewWindow3 += new DWebBrowserEvents2_NewWindow3EventHandler(Browser_NewWindow3);
Unfortunately I've received a NullReference Exception
on third line that I wasn't able to correct.
SOLUTION:
I don't think the solution is in the related answer (or I wasn't able to find it) because it explains how to implement the NewWindow2 event (instead of NewWindow3 which handles the original destination url) and the implementation is the same suggested here which leads to the NullReference Exception error.
Anyway I've discovered this two posts:
The suggest is to modify the previous three lines into this one:
(myWebBrowser.ActiveXInstance as SHDocVw.WebBrowser).NewWindow3 += new SHDocVw.DWebBrowserEvents2_NewWindow3EventHandler(Browser_NewWindow3);
Everything is working now and I was able to keep using the original System.Windows.Forms.WebBrowser
in all the rest of the code.
It looks like the WebBrowser
control is a really lame wrapper around SHDocVw
. Fortunately Microsoft exposes the underlying implementation through WebBrowser.ActiveXInstance
.
This code from http://www.codeproject.com/Articles/71592/How-to-easily-capture-the-NewWindow3-event-and-det will do the trick:
First, add a reference to Microsoft Internet Controls
. Then implement a NewWindow3 handler:
SHDocVw.WebBrowser axBrowser = (SHDocVw.WebBrowser)webBrowser.ActiveXInstance;
axBrowser.NewWindow3 += new DWebBrowserEvents2_NewWindow3EventHandler(Browser_NewWindow3);