using System; using System.Reflection; using System.Runtime.InteropServices; using System.Windows.Controls; namespace 浏览器测试 { public class WebBrowserHelper { public static void MakeWebBrowserNavigateToSelf(WebBrowser wb) { wb.LoadCompleted += Wb_LoadCompleted; } private static readonly Guid SID_SWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046"); private static void Wb_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e) { if (sender is WebBrowser wb) { IServiceProvider serviceProvider = (IServiceProvider)wb.Document; Guid serviceGuid = SID_SWebBrowserApp; Guid iid = typeof(SHDocVw.IWebBrowser2).GUID; SHDocVw.IWebBrowser2 myWebBrowser2 = (SHDocVw.IWebBrowser2)serviceProvider.QueryService(ref serviceGuid, ref iid); SHDocVw.DWebBrowserEvents_Event wbEvents = (SHDocVw.DWebBrowserEvents_Event)myWebBrowser2; wbEvents.NewWindow += new SHDocVw.DWebBrowserEvents_NewWindowEventHandler(OnWebBrowserNewWindow); void OnWebBrowserNewWindow(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed) { Processed = true; wb.Navigate(URL); } } } [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); } public static void MakeWebBrowserSilent(WebBrowser wb) { if (wb == null) { return; } wb.Navigated += delegate { IOleServiceProvider sp = wb.Document as IOleServiceProvider; if (sp != null) { Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046"); Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11d0-8A3E-00C04FC9E26E"); object webBrowser; sp.QueryService(ref IID_IWebBrowserApp, ref IID_IWebBrowser2, out webBrowser); if (webBrowser != null) { webBrowser.GetType().InvokeMember("Silent", BindingFlags.Instance | BindingFlags.Public | BindingFlags.PutDispProperty, null, webBrowser, new object[] { true }); } } }; } [ComImport, Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IOleServiceProvider { [PreserveSig] int QueryService([In] ref Guid guidService, [In] ref Guid riid, [MarshalAs(UnmanagedType.IDispatch)] out object ppvObject); } } }