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

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

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

更新:在这个问题中, 'Back' & 'Forward' navigation buttons意味着5键鼠标系统中的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, } 

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

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

更简单的方式….

这适用于WPF和.net 4.5

 private void Window_MouseDown(object sender, MouseButtonEventArgs e) { if (e.ChangedButton.Equals(MouseButton.XButton1)) MessageBox.Show(@"back"); if (e.ChangedButton.Equals(MouseButton.XButton2)) MessageBox.Show(@"forward"); } 

WebBrowser控件实际上只是Trident COM对象的瘦包装器。 与其他内置控件一样,它不是“纯WPF”……所以很多普通的东西都无法使用它。 要回答您的问题,您可以获得的最接近的是进入导航事件。 这不会告诉您用户是在尝试前进还是后退或其他地方,但它会为您提供URL并有机会设置e.Cancel = true以停止导航(通常后面会调用Navigate(url)用户在其他地方)。