使用 WPF 浏览器控件时如何覆盖 ie 的 BeforeNavigate2?

发布于 2024-10-17 11:36:03 字数 132 浏览 2 评论 0原文

据我了解,WPF的Brwoser控件是ie Active-X控件的包装。后者有一个 BeforeNavigate2 方法,而我在 WPF WebBrowser 控件中没有找到这个方法。有什么办法可以解决这个问题吗?

谢谢! 马克

As far as I understand, WPF's Brwoser control is a wrapper of the ie Active-X control. The later has a BeforeNavigate2 Method, while I don't find this in the WPF WebBrowser control. Is there a way I can work around this?

Thx!
Marc

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自在安然 2024-10-24 11:36:03

是的。 WPF的WebBrowser控件真是脑残。最重要的是它甚至是密封的。

您必须使用 Windows.Forms 的 WebBrowser 控件并将其嵌入到 WindowsFormsHost 中。

此外,您还必须从 WebBrowser 派生一个类并在其中执行一些 COM 魔法。

像这样创建一个用户控件:

<UserControl x:Class="MP.Assistant.WpfClient.DialogContentControls.WebBrowserHost"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:DialogContentControls="clr-namespace:MP.Assistant.WpfClient.DialogContentControls"
         mc:Ignorable="d"
         d:DesignHeight="300"
         d:DesignWidth="300">
<Grid Name="BrowserHost">
    <WindowsFormsHost>
        <DialogContentControls:ExtendedWinFormsWebBrowser x:Name="WebBrowser" />
    </WindowsFormsHost>
</Grid>

然后像这样修改 Windows.Forms WebBrowser:

using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Windows.Forms;

namespace MP.Assistant.WpfClient.DialogContentControls
{
    /// Imports the BeforeNavigate2 method from the OLE DWebBrowserEvents2 
    /// interface. 
    [ComImport]
    [Guid("34A715A0-6587-11D0-924A-0020AFC7AC4D")]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    [TypeLibType(TypeLibTypeFlags.FHidden)]
    public interface DWebBrowserEvents2
    {
        [PreserveSig]
        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType =    MethodCodeType.Runtime)]
    [DispId(250)] 

    void BeforeNavigate2([In] [MarshalAs(UnmanagedType.IDispatch)] object pDisp,
                         [In] [MarshalAs(UnmanagedType.Struct)] ref object URL,
                         [In] [MarshalAs(UnmanagedType.Struct)] ref object Flags,
                         [In] [MarshalAs(UnmanagedType.Struct)] ref object TargetFrameName,
                         [In] [MarshalAs(UnmanagedType.Struct)] ref object PostData,
                         [In] [MarshalAs(UnmanagedType.Struct)] ref object Headers,
                         [In] [Out] ref bool Cancel);
}

public class ExtendedWinFormsWebBrowser : WebBrowser
{
    // Handles the NavigateError event from the underlying ActiveX 
    // control by raising the NavigateError event defined in this class.
    AxHost.ConnectionPointCookie cookie;
    ExtendedWinFormsWebBrowserEventHelper helper;
    bool renavigating;

    public ExtendedWinFormsWebBrowser()
    {
        AdditionalHeaders = new string[] {};
    }

    public string[] AdditionalHeaders { get; set; }

    [PermissionSet(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 ExtendedWinFormsWebBrowserEventHelper(this);
        cookie = new AxHost.ConnectionPointCookie(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();
    }

    void OnBeforeNavigate2(object pDisp,
                           ref object url,
                           ref object flags,
                           ref object targetFrameName,
                           ref object postData,
                           ref object headers,
                           ref bool cancel)
    {
        if (!renavigating)
        {
            if (AdditionalHeaders.Length > 0)
            {
                headers += string.Join("\r\n", AdditionalHeaders) + "\r\n";
                renavigating = true;
                cancel = true;
                Navigate((string)url, (string)targetFrameName, (byte[])postData, (string)headers);
            }
        }
        else
        {
            renavigating = false;
        }
    }

    #region Nested type: ExtendedWinFormsWebBrowserEventHelper

    class ExtendedWinFormsWebBrowserEventHelper : StandardOleMarshalObject, DWebBrowserEvents2
    {
        readonly ExtendedWinFormsWebBrowser parent;

        public ExtendedWinFormsWebBrowserEventHelper(ExtendedWinFormsWebBrowser parent)
        {
            this.parent = parent;
        }

        #region DWebBrowserEvents2 Members

        public void BeforeNavigate2(object pDisp,
                                    ref object URL,
                                    ref object Flags,
                                    ref object TargetFrameName,
                                    ref object PostData,
                                    ref object Headers,
                                    ref bool Cancel)
        {
            parent.OnBeforeNavigate2(pDisp,
                ref URL,
                ref Flags,
                ref TargetFrameName,
                ref PostData,
                ref Headers,
                ref Cancel);
        }

        #endregion
    }

    #endregion
}
}

然后从代码隐藏中使用 WebBrowser(其名称与 XAML 中的名称类似),并为 AnotherHeaders 提供所需的值。

Yes. The WebBrowser control of WPF is really braindead. On top of that it is even sealed.

You have to use the WebBrowser control of Windows.Forms and embed it in a WindowsFormsHost.

Additionally you have to derive a class from WebBrowser and do some COM magic in it.

Make a UserControl like this:

<UserControl x:Class="MP.Assistant.WpfClient.DialogContentControls.WebBrowserHost"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:DialogContentControls="clr-namespace:MP.Assistant.WpfClient.DialogContentControls"
         mc:Ignorable="d"
         d:DesignHeight="300"
         d:DesignWidth="300">
<Grid Name="BrowserHost">
    <WindowsFormsHost>
        <DialogContentControls:ExtendedWinFormsWebBrowser x:Name="WebBrowser" />
    </WindowsFormsHost>
</Grid>

Then modify Windows.Forms WebBrowser like this:

using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Windows.Forms;

namespace MP.Assistant.WpfClient.DialogContentControls
{
    /// Imports the BeforeNavigate2 method from the OLE DWebBrowserEvents2 
    /// interface. 
    [ComImport]
    [Guid("34A715A0-6587-11D0-924A-0020AFC7AC4D")]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    [TypeLibType(TypeLibTypeFlags.FHidden)]
    public interface DWebBrowserEvents2
    {
        [PreserveSig]
        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType =    MethodCodeType.Runtime)]
    [DispId(250)] 

    void BeforeNavigate2([In] [MarshalAs(UnmanagedType.IDispatch)] object pDisp,
                         [In] [MarshalAs(UnmanagedType.Struct)] ref object URL,
                         [In] [MarshalAs(UnmanagedType.Struct)] ref object Flags,
                         [In] [MarshalAs(UnmanagedType.Struct)] ref object TargetFrameName,
                         [In] [MarshalAs(UnmanagedType.Struct)] ref object PostData,
                         [In] [MarshalAs(UnmanagedType.Struct)] ref object Headers,
                         [In] [Out] ref bool Cancel);
}

public class ExtendedWinFormsWebBrowser : WebBrowser
{
    // Handles the NavigateError event from the underlying ActiveX 
    // control by raising the NavigateError event defined in this class.
    AxHost.ConnectionPointCookie cookie;
    ExtendedWinFormsWebBrowserEventHelper helper;
    bool renavigating;

    public ExtendedWinFormsWebBrowser()
    {
        AdditionalHeaders = new string[] {};
    }

    public string[] AdditionalHeaders { get; set; }

    [PermissionSet(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 ExtendedWinFormsWebBrowserEventHelper(this);
        cookie = new AxHost.ConnectionPointCookie(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();
    }

    void OnBeforeNavigate2(object pDisp,
                           ref object url,
                           ref object flags,
                           ref object targetFrameName,
                           ref object postData,
                           ref object headers,
                           ref bool cancel)
    {
        if (!renavigating)
        {
            if (AdditionalHeaders.Length > 0)
            {
                headers += string.Join("\r\n", AdditionalHeaders) + "\r\n";
                renavigating = true;
                cancel = true;
                Navigate((string)url, (string)targetFrameName, (byte[])postData, (string)headers);
            }
        }
        else
        {
            renavigating = false;
        }
    }

    #region Nested type: ExtendedWinFormsWebBrowserEventHelper

    class ExtendedWinFormsWebBrowserEventHelper : StandardOleMarshalObject, DWebBrowserEvents2
    {
        readonly ExtendedWinFormsWebBrowser parent;

        public ExtendedWinFormsWebBrowserEventHelper(ExtendedWinFormsWebBrowser parent)
        {
            this.parent = parent;
        }

        #region DWebBrowserEvents2 Members

        public void BeforeNavigate2(object pDisp,
                                    ref object URL,
                                    ref object Flags,
                                    ref object TargetFrameName,
                                    ref object PostData,
                                    ref object Headers,
                                    ref bool Cancel)
        {
            parent.OnBeforeNavigate2(pDisp,
                ref URL,
                ref Flags,
                ref TargetFrameName,
                ref PostData,
                ref Headers,
                ref Cancel);
        }

        #endregion
    }

    #endregion
}
}

Then use WebBrowser (its named like that in XAML) from your code-behind and provide AdditionalHeaders with the required value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文