如何在WPF WebBrowser中使用"后退"和"前进"导航按钮事件?

Jin*_*ung 8 c# wpf webbrowser-control

WebBrowserWPF中的控件继承自UIElement,但我们无法在UIElement事件中注册事件处理程序.为什么?在WPF WebBrowser鼠标事件没有按预期工作,它得到了回答,但我仍然无法理解.

无论如何,将处理程序连接到WebBrowser可以捕获大多数鼠标事件的文档提供的事件但不能使用"后退"和"前进"导航按钮事件.由于互联网浏览器可以做到这一点,我认为这是可能的.有什么方法可以解决这个问题吗?

更新: 在这个问题中,'Back' & 'Forward' navigation buttons5键鼠标系统中的XButton1和XButton2.

更新2:我用Navid Rahmani的答案解决了这个问题.我认为有人会需要这个答案,所以我附上了主要部分.如果发现任何问题或更合理的解决方案,请告诉我.

    //This code assumes the `WebBrowser` field named _webBrowser is already initiated.
    //For the detail out of this code, please refer to the Navid Rahmani's answer.

    private bool _isMouseOver;
    private HTMLDocumentEvents2_Event _docEvent;    

    public ctor()
    {
        _webBrowser.LoadCompleted += _webBrowser_LoadCompleted;
    }

    private void _webBrowser_LoadCompleted(object sender, NavigationEventArgs e)
    {
        if (_docEvent != null)
        {
            _docEvent.onmouseover -= _docEvent_onmouseover;
            _docEvent.onmouseout -= _docEvent_onmouseout;
        }
        if (_webBrowser.Document != null)
        {
            _docEvent = (HTMLDocumentEvents2_Event)_webBrowser.Document;
            _docEvent.onmouseover += _docEvent_onmouseover;
            _docEvent.onmouseout += _docEvent_onmouseout;
        }
    }

    void _docEvent_onmouseout(IHTMLEventObj pEvtObj)
    {
        _isMouseOver = false;
    }

    void _docEvent_onmouseover(IHTMLEventObj pEvtObj)
    {
        _isMouseOver = true;
    }


    private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (_isMouseOver)
        {
            if (nCode >= 0 && (MouseMessages)wParam == MouseMessages.XBUTTON)
            {
                var hookStruct = (Msllhookstruct)Marshal.PtrToStructure(lParam, typeof(Msllhookstruct));
                if (hookStruct.mouseData == 0x10000)
                {
                    //do something when XButto1 clicked
                }
                else if (hookStruct.mouseData == 0x20000)
                {
                    //do something when XButto2 clicked
                }
            }
        }
        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }


    private enum MouseMessages
    {
        //WM_LBUTTONDOWN = 0x00A1,
        //WM_LBUTTONUP = 0x0202,
        //WM_MOUSEMOVE = 0x0200,
        //WM_MOUSEWHEEL = 0x020A,
        //WM_RBUTTONDOWN = 0x0204,
        //WM_RBUTTONUP = 0x0205,
        XBUTTON = 0x020B,
    }
Run Code Online (Sandbox Code Playgroud)

Nav*_*ani 2

您可以使用鼠标的低级钩子并检查是否单击了 xbutton1 或 xbutton2
这里

WM_XBUTTONDOWN查看http://msdn.microsoft.com/en-us/library/ms646245(VS.85).aspx的值