To be able to catch popup windows and open them in your own window you
have to manage WebBrowser events like NewWindow2.
But how do you do that in WPF?
Well it isn’t really that difficult. These are the steps that you have to follow:
1. Add a COM reference to a reference to %windir%\system32\shdocvw.dll
2. Add a new CodeFile to your project. Lets say CodeFile1.cs And put this code:
using System;
using System.Runtime.InteropServices;
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("6d5140c1-7436-11ce-8034-00aa006009fa")]
internal interface IServiceProvider
{
[return: MarshalAs(UnmanagedType.IUnknown)]
object QueryService(ref Guid guidService, ref Guid riid);
}
3. To make an easy example. Lets assume we have a very simple window like:
And in that form we need some code like this:
private void button1_Click(object sender, RoutedEventArgs e)
{
Guid SID_SWebBrowserApp =
new Guid("0002DF05-0000-0000-C000-000000000046");
IServiceProvider serviceProvider =
(IServiceProvider)myWebBrowser.Document; //<—It seams that you need to
// navigate first to initialize this
Guid serviceGuid = SID_SWebBrowserApp;
Guid iid = typeof(SHDocVw.IWebBrowser2).GUID;
//Here we will get a reference to the IWebBrowser2 interface
SHDocVw.IWebBrowser2 myWebBrowser2 =
(SHDocVw.IWebBrowser2)
serviceProvider.QueryService(ref serviceGuid, ref iid);
//To hook events we just need to do these casts
SHDocVw.DWebBrowserEvents_Event wbEvents =
(SHDocVw.DWebBrowserEvents_Event)myWebBrowser2;
SHDocVw.DWebBrowserEvents2_Event wbEvents2 =
(SHDocVw.DWebBrowserEvents2_Event)myWebBrowser2;
//Adding event handlers is now very simple
wbEvents.NewWindow +=
new SHDocVw.DWebBrowserEvents_NewWindowEventHandler(wbEvents_NewWindow);
wbEvents2.NewWindow2 +=
new SHDocVw.DWebBrowserEvents2_NewWindow2EventHandler(wbEvents2_NewWindow2);
}
void wbEvents2_NewWindow2(ref object ppDisp, ref bool Cancel)
{
//If you want make popup windows to open in your own window
// you need to assign the ppDisp to the .Application of
// the WebBrowser in your window
Window1 wnd = new Window1();
wnd.Show();
//Just navigate to make sure .Document is initilialized
wnd.myWebBrowser.Navigate(new Uri("about:blank"));
Guid SID_SWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
IServiceProvider serviceProvider = (IServiceProvider)wnd.myWebBrowser.Document;
Guid serviceGuid = SID_SWebBrowserApp;
Guid iid = typeof(SHDocVw.IWebBrowser2).GUID;
SHDocVw.IWebBrowser2 myWebBrowser2 = (SHDocVw.IWebBrowser2)serviceProvider.QueryService(ref serviceGuid, ref iid);
ppDisp = myWebBrowser2.Application;
}
void wbEvents_NewWindow(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed)
{
MessageBox.Show(URL);
}
private void button2_Click(object sender, RoutedEventArgs e)
{
myWebBrowser.Navigate(new Uri("file://D:/MyProjects/ExtendedBrowserExample_v2/test0.htm"));
}
Now you can manage your popupwindows:
You can download the test application from HERE