C# Express and the WebBrowser control
I love the WebBrowser control - it makes it easy to create customized Web browsers in my C# applications (for example, adding tabs as in this article). Recently I was trying to find a way to block the custom browser from opening up new pages in a separate window - not least because the separate window wasn't my WebBrowser control anymore, it was Internet Explorer.
In other words, if the user clicked on a link that opened a page in a new browser, my application was just left hanging there like a nerd at a dance competition.
So I tried playing with some of the event messages that the WebBrowser fires off. Firstly, I tried the Navigation event - if that was fired when the user clicked on a link, surely I could trap it, and redirect it back to the original WebBrowser.
Sadly, the Navigation event doesn't seem to fire when clicking on a target="_blank" link. But... the NewWindow event does. This means I've been able to write code that traps a new window (the new Internet Explorer) from opening, which is a good start. However, after that I can only manage to force my WebBrowser control to open a specific page - I can't make it open the page that the new window was going to display. Here's the code that stops the window from opening.
private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
{
// Stop the new browser from opening.
e.Cancel = true;
// Go to a new webpage.
webBrowser1.Navigate(https://www.msn.com);
}
So if anyone has any suggestions, please let me know, thanks!
Comments
- Anonymous
April 26, 2005
Hmmm... well it's nice and easy in COM/C++...
For starters you don't want to cancel the navigation, you simply want to redirect the navigation to your own window. With COM you just set the first parameter to your own browser interface and you're set.
http://msdn.microsoft.com/workshop/browser/webbrowser/reference/ifaces/dwebbrowserevents2/newwindow2.asp
However it doesn't look like it's that simple in your case :( - Anonymous
April 26, 2005
Thanks, PatriotB.
That's sort of like Irish directions.. "You want to get there? Oh, well I wouldn't start from here if I was you..." ;-) - Anonymous
May 03, 2005
private void browser_NewWindow(object sender, CancelEventArgs e)
{
browser.Navigate(browser.StatusText);
e.Cancel = true;
}
Works for me :) - Anonymous
May 03, 2005
XIU - Worked like a charm. Thank you! I have been trying to get that working for a long time.
John - Thanks for all your help with this too!