如果浏览器从网站关闭,请避免关闭 WebBrowser 控件 javascript C#

Avoid closing WebBrowser control if browser is closed from website javascript C#

我正在尝试在我的 C# winforms 应用程序中托管 WebBrowser 控件,以便打开客户的网站。客户的网站经常尝试通过 Javascript 代码关闭 WebBrowser。我怎样才能阻止我的 WebBrowser 关闭?

我正在实施 ExtendedWebBrowser class 如下:

// A delegate type for hooking up close notifications.
public delegate void ClosingEventHandler(object sender, EventArgs e);

// We need to extend the basic Web Browser because when a web page calls
// "window.close()" the containing window isn't closed.
public class ExtendedWebBrowser : WebBrowser
{
    // Define constants from winuser.h
    private const int WM_PARENTNOTIFY = 0x210;
    private const int WM_DESTROY = 2;

    public event ClosingEventHandler Closing;

    protected override void WndProc(ref Message m)
    {
        switch (m.Msg)
        {
            case WM_PARENTNOTIFY:
                if (!DesignMode)
                {
                    if (m.WParam.ToInt32() == WM_DESTROY)
                    {
                        Closing(this, EventArgs.Empty);
                    }
                }
                DefWndProc(ref m);
                break;
            default:
                base.WndProc(ref m);
                break;
        }
    }
}

如 Microsoft 文档 here 所述,当您处理 WM_PARENTNOTIFY 消息时,您只需使用 wParam 的 LOWORD 值来检查 WM_DESTROY 消息。您应该像这样过滤值:

if ((wParam.ToInt32() & 0x0000FFFF) == WM_DESTROY)

历史上 "word" 是 16 位,所以 wParam 是一个 "double-word"(双字),它包含两个 16 位值。第一个值存储在两个低位字节中,第二个值存储在两个高位字节中。