C# 通过扩展WebBrowser捕获网络连接错误信息


想捕获WebBrowser连接指定网站过程中发生的错误信息,包括网络无法连接、404找不到网页等等错误!经过网上的搜集,找到了以下解决方案,该解决方案不会在网站连接前发出多余的测试请求。

向Webbrowser中注册NavigateError事件,以扩展webbrowser:

[ComImport, Guid("34A715A0-6587-11D0-924A-0020AFC7AC4D"),
InterfaceType(ComInterfaceType.InterfaceIsIDispatch),
TypeLibType(TypeLibTypeFlags.FHidden)]
public interface DWebBrowserEvents2
{
    [DispId(271)]
    void NavigateError(
        [In, MarshalAs(UnmanagedType.IDispatch)] object pDisp,
        [In] ref object URL, [In] ref object frame,
        [In] ref object statusCode, [In, Out] ref bool cancel);
}

自定义NavigateError事件的参数:

using System;
using System.Runtime.InteropServices;
public class WebBrowserNavigateErrorEventArgs : EventArgs
{
    private String urlValue;
    private String frameValue;
    private Int32 statusCodeValue;
    private Boolean cancelValue;
    public WebBrowserNavigateErrorEventArgs(
        String url, String frame, Int32 statusCode, Boolean cancel)
    {
        urlValue = url;
        frameValue = frame;
        statusCodeValue = statusCode;
        cancelValue = cancel;
    }
    public String Url
    {
        get { return urlValue; }
        set { urlValue = value; }
    }
    public String Frame
    {
        get { return frameValue; }
        set { frameValue = value; }
    }
    public Int32 StatusCode
    {
        get { return statusCodeValue; }
        set { statusCodeValue = value; }
    }
    public Boolean Cancel
    {
        get { return cancelValue; }
        set { cancelValue = value; }
    }
}

扩展webbrowser为MyWebBrowser,在程序中将webbrowser改成Mywebbrowser即可:

using System.Windows.Forms;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System;
public class MyWebBrowser : WebBrowser
{
    AxHost.ConnectionPointCookie cookie;
    MyWebBrowserEventHelper helper;
    public delegate void WebBrowserNavigateErrorEventHandler(object sender,
        WebBrowserNavigateErrorEventArgs e);

    [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
    protected override void CreateSink()
    {
        base.CreateSink();
        // Create an instance of the client that will handle the event
        // and associate it with the underlying ActiveX control.
        helper = new MyWebBrowserEventHelper(this);
        cookie = new AxHost.ConnectionPointCookie(
            this.ActiveXInstance, helper, typeof(DWebBrowserEvents2));
    }
    [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
    protected override void DetachSink()
    {
        // Disconnect the client that handles the event
        // from the underlying ActiveX control.
        if (cookie != null)
        {
            cookie.Disconnect();
            cookie = null;
        }
        base.DetachSink();
    }
    public event WebBrowserNavigateErrorEventHandler NavigateError;
    // Raises the NavigateError event.
    protected virtual void OnNavigateError(
        WebBrowserNavigateErrorEventArgs e)
    {
        if (this.NavigateError != null)
        {
            this.NavigateError(this, e);
        }
    }
    // Handles the NavigateError event from the underlying ActiveX 
    // control by raising the NavigateError event defined in this class.
    private class MyWebBrowserEventHelper :
        StandardOleMarshalObject, DWebBrowserEvents2
    {
        private MyWebBrowser parent;
        public MyWebBrowserEventHelper(MyWebBrowser parent)
        {
            this.parent = parent;
        }
        public void NavigateError(object pDisp, ref object url,
            ref object frame, ref object statusCode, ref bool cancel)
        {
            // Raise the NavigateError event.
            this.parent.OnNavigateError(
                new WebBrowserNavigateErrorEventArgs(
                (String)url, (String)frame, (Int32)statusCode, cancel));
        }
    }
}

将以上代码完全复制粘贴到您的程序当中,然后将您原本程序中使用webbrowser的地方修改成MyWebBrowser就行了。这个时候你的mywebbrowser控件就有了onnavigateerror事件,在这个事件里编写您的错误处理方法。您或许需要用到错误消息中的错误代码,具体错误代码请参照里的每个错误代码代表的意义。

本人项目中所使用的错误处理代码如下:

 private void WebBrowserIE_NavigateError(object sender, WebBrowserNavigateErrorEventArgs e)
        {
            log.Debug("ERROR:----------" + e.Url);
            int code = e.StatusCode;
            // 发生错误时,转向本地页面
            if (code == -2146697211)
            {                WebBrowserIE.Navigate("本地页面");
            }
        }

这个扩展方法完全不会影响webbrowser原有的任何功能,当然,您还可以按照这种思路继续进行扩展,比如扩展使其用有mousemove事件,也是可以的!


优质内容筛选与推荐>>
1、基于deepin搭建家庭教育服务器
2、Tomcat内存溢出的解决方法
3、ubuntu中mysql安装失败
4、些许的文字
5、JavaScript 闭包


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn