【发布时间】:2011-09-16 07:42:21
【问题描述】:
WPF 中的WebBrowser 控件继承自UIElement,但我们无法在UIElement 事件中注册事件处理程序。为什么? WPF WebBrowser Mouse Events not working as expected有回答,但还是看不懂。
无论如何,将处理程序连接到WebBrowser 的文档提供的事件可以捕获大多数鼠标事件,但不能使用“后退”和“前进”导航按钮事件。由于Internet Explorer可以做到这一点,我认为这是可能的。有没有办法解决这个问题?
更新:
在这个问题中,'Back' & 'Forward' navigation buttonsmean XButton1 和 XButton2 在 5 键鼠标系统中。
UPDATE2:我用 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,
}
【问题讨论】:
-
没问题。这是通过您的努力解决的。
标签: c# wpf webbrowser-control