打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C#重写WebBrowser组件,禁止跳转到IE新窗口、脚本错误
  1. <span style="font-family: Arial, Helvetica, sans-serif;"><a href="http://blog.chinaunix.net/uid-16242888-id-146885.html">原创地址</a>  
  2. </span>  
  1. <span style="font-family: Arial, Helvetica, sans-serif;">刚从delphi转到c#,一切重头开始。上来先做个myBrowser,结果发现无法解决跳转到新窗口问题。从网上找到奇客力大侠的《C# webBrowser禁止在新窗口打开,强制在本窗口打开》文章(http://blog.163.com/da7_1@126/blog/static/104072678201031651754880/),结果发现对重写WebBrowser一窍不通,折腾了2天,又找到百度知道里的一篇问答《在C#中如何重写控件》(http://zhidao.baidu.com/question/48991857.html?fr=qrl&cid=869&index=1&fr2=query),再几经周折才搞定。</span>  
  1. <pre class="csharp" name="code">为了纪念第一个C#程序的艰难问世,现将过程详细记录如下:  
  2.     一、在VS2008里用C#新建一个Windows窗体应用程序,起名为MyBrowser。  
  3.     二、在里面添加Label、TextBox、Button,然后整成如下图的样式,同时把各个控件的Anchor和Text归整一下,位置和名称放放好。  
  4.   
  5.     三、重写WebBrowser组件,禁止跳转到IE新窗口。菜单“项目->添加类”,在模板中的“类”图标上确认一下,然后名称改为“ExtendedWebBrowser.cs”。  
  6.     (一)在右边解决方案管理器中右击“查看代码”,然后在ExtendedWebBrowser.cs代码窗口将代码修改成如下:  
  7. using System;  
  8. using System.Collections.Generic;  
  9. using System.Linq;  
  10. using System.Text;  
  11. namespace MyBrowser  
  12. {  
  13.     public class ExtendedWebBrowser : System.Windows.Forms.WebBrowser  
  14.     {  
  15.         System.Windows.Forms.AxHost.ConnectionPointCookie cookie;  
  16.         WebBrowserExtendedEvents events;  
  17.         //This method will be called to give you a chance to create your own event sink  
  18.         protected override void CreateSink()  
  19.         {  
  20.             //MAKE SURE TO CALL THE BASE or the normal events won't fire  
  21.             base.CreateSink();  
  22.             events = new WebBrowserExtendedEvents(this);  
  23.             cookie = new System.Windows.Forms.AxHost.ConnectionPointCookie(this.ActiveXInstance, events, typeof(DWebBrowserEvents2));  
  24.         }  
  25.         protected override void DetachSink()  
  26.         {  
  27.             if (null != cookie)  
  28.             {  
  29.                 cookie.Disconnect();  
  30.                 cookie = null;  
  31.             }  
  32.             base.DetachSink();  
  33.         }  
  34.         //This new event will fire when the page is navigating  
  35.         public event EventHandler<WebBrowserExtendedNavigatingEventArgs> BeforeNavigate;  
  36.         public event EventHandler<WebBrowserExtendedNavigatingEventArgs> BeforeNewWindow;  
  37.         protected void OnBeforeNewWindow(string url, out bool cancel)  
  38.         {  
  39.             EventHandler<WebBrowserExtendedNavigatingEventArgs> h = BeforeNewWindow;  
  40.             WebBrowserExtendedNavigatingEventArgs args = new WebBrowserExtendedNavigatingEventArgs(url, null);  
  41.             if (null != h)  
  42.             {  
  43.                 h(this, args);  
  44.             }  
  45.             cancel = args.Cancel;  
  46.         }  
  47.         protected void OnBeforeNavigate(string url, string frame, out bool cancel)  
  48.         {  
  49.             EventHandler<WebBrowserExtendedNavigatingEventArgs> h = BeforeNavigate;  
  50.             WebBrowserExtendedNavigatingEventArgs args = new WebBrowserExtendedNavigatingEventArgs(url, frame);  
  51.             if (null != h)  
  52.             {  
  53.                 h(this, args);  
  54.             }  
  55.             //Pass the cancellation chosen back out to the events  
  56.             cancel = args.Cancel;  
  57.         }  
  58.         //This class will capture events from the WebBrowser  
  59.         class WebBrowserExtendedEvents : System.Runtime.InteropServices.StandardOleMarshalObject, DWebBrowserEvents2  
  60.         {  
  61.             ExtendedWebBrowser _Browser;  
  62.             public WebBrowserExtendedEvents(ExtendedWebBrowser browser) { _Browser = browser; }  
  63.             //Implement whichever events you wish  
  64.             public void BeforeNavigate2(object pDisp, ref object URL, ref object flags, ref object targetFrameName, ref object postData, ref object headers, ref bool cancel)  
  65.             {  
  66.                 _Browser.OnBeforeNavigate((string)URL, (string)targetFrameName, out cancel);  
  67.             }  
  68.             public void NewWindow3(object pDisp, ref bool cancel, ref object flags, ref object URLContext, ref object URL)  
  69.             {  
  70.                 _Browser.OnBeforeNewWindow((string)URL, out cancel);  
  71.             }  
  72.         }  
  73.         [System.Runtime.InteropServices.ComImport(), System.Runtime.InteropServices.Guid("34A715A0-6587-11D0-924A-0020AFC7AC4D"),  
  74.         System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIDispatch),  
  75.         System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)]  
  76.         public interface DWebBrowserEvents2  
  77.         {  
  78.             [System.Runtime.InteropServices.DispId(250)]  
  79.             void BeforeNavigate2(  
  80.                 [System.Runtime.InteropServices.In,  
  81.                 System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.IDispatch)] object pDisp,  
  82.                 [System.Runtime.InteropServices.In] ref object URL,  
  83.                 [System.Runtime.InteropServices.In] ref object flags,  
  84.                 [System.Runtime.InteropServices.In] ref object targetFrameName, [System.Runtime.InteropServices.In] ref object postData,  
  85.                 [System.Runtime.InteropServices.In] ref object headers,  
  86.                 [System.Runtime.InteropServices.In,  
  87.                 System.Runtime.InteropServices.Out] ref bool cancel);  
  88.             [System.Runtime.InteropServices.DispId(273)]  
  89.             void NewWindow3(  
  90.                 [System.Runtime.InteropServices.In,  
  91.                 System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.IDispatch)] object pDisp,  
  92.                 [System.Runtime.InteropServices.In, System.Runtime.InteropServices.Out] ref bool cancel,  
  93.                 [System.Runtime.InteropServices.In] ref object flags,  
  94.                 [System.Runtime.InteropServices.In] ref object URLContext,  
  95.                 [System.Runtime.InteropServices.In] ref object URL);  
  96.         }  
  97.     }  
  98.     public class WebBrowserExtendedNavigatingEventArgs : System.ComponentModel.CancelEventArgs  
  99.     {  
  100.         private string _Url;   //原文此处多了一个空格,注意修改之...散仙闪电注  
  101.         public string Url  
  102.         {  
  103.             get { return _Url; }  
  104.         }  
  105.         private string _Frame;  //原文此处多了一个空格,注意修改之...散仙闪电注  
  106.         public string Frame  
  107.         {  
  108.             get { return _Frame; }  
  109.         }  
  110.         public WebBrowserExtendedNavigatingEventArgs(string url, string frame)  
  111.             : base()  
  112.         {  
  113.             _Url = url;  
  114.             _Frame = frame;  
  115.         }  
  116.     }  
  117.   }  
  118.     (二)回到Form1.cs[设计]窗口,在菜单“生成”中,点“生成解决方案”。一会之后在工具箱的最上方就会出现一个新的组件“ExtendedWebBrowser”,这正是我们需要的,hehe。  
  119.     三、回到Form1.cs[设计]窗口,把ExtendedWebBrowser拖进来。  
  120.     (一)在属性窗口里调整好Anchor,使之能最大化。  
  121.     (二)双击“ScriptErrorSuppressed”,将之属性改为“True”以禁用所有的对话框,比如提示Activex下载、执行以及安全登录等对话框。当然可以参考MSDN上的代码示例(http://apps.hi.baidu.com/share/detail/379735),有的放矢:  
  122. private void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)  
  123. {  
  124.     ((WebBrowser)sender).Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);  
  125. }  
  126. private void Window_Error(object sender, HtmlElementErrorEventArgs e)  
  127. {  
  128.     // Ignore the error and suppress the error dialog box.   
  129.     e.Handled = true;  
  130. }  
  131.    (三)在ExtendedWebBrowser的事件里双击“BeforeNewWindow”并添加2行代码:  
  132.     private void extendedWebBrowser1_BeforeNewWindow(object sender, MyBrowser.WebBrowserExtendedNavigatingEventArgs e)  
  133.         {  
  134.            e.Cancel=true;  
  135.            ((ExtendedWebBrowser)sender).Navigate(e.Url);  
  136.         }  
  137.    (四)最后一步,回到Form1.cs[设计]窗口,双击Button按钮,添加代码如下:  
  138.       private void button1_Click(object sender, EventArgs e)  
  139.         {  
  140.             extendedWebBrowser1.Navigate(textBox1.Text);  
  141.         }  
  142.       
  143.    F5运行,点几个老跳的链接,oh~yeah,成功了!  
  144.   ,还有些不爽,输完网址后还要点登录,像IE一样敲一下回车就好了。说干就干  
  145.   (五)TextBox事件中,双击KeyPress(不要用Enter事件,试过不行),添加以下代码  
  146.     
  147.      private void textBox1_KeyPress(object sender, KeyPressEventArgs e)  
  148.         {  
  149.             if (e.KeyChar == (char)13)  
  150.             {  
  151.                 button1_Click(null,null);  
  152.             }  
  153.         }</pre><br>  
  154. <pre></pre>  
  155. <pre></pre>  
  156.       
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
增强的WebBrowser浏览器控件,支持NavigateError,支持重写网页的window.alert()方法
ystem.Runtime.InteropServices.COMException (0x800A1066): 命令失败
在WebBroswer里面显示Word
换用代理IP的Webbrowser方法
javascript与Windows Presentation Foundation交互通讯(js与WPF通讯)
Java 8新特性探究(四)类型注解 复杂还是便捷
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服