WPF中的WebBrowser
控件繼承自UIElement
,但我們無法在UIElement
事件中註冊事件處理程序。爲什麼?在WPF WebBrowser Mouse Events not working as expected,這是回答,但我仍然不明白。如何使用WPF WebBrowser中的'Back'和'Forward'導航按鈕事件?
無論如何,將處理程序連接到由WebBrowser
文檔提供的事件可以捕獲大多數鼠標事件,但不能使用「後退」&「前進」導航按鈕事件。由於Internet Explorer可以做到這一點,我認爲這是可能的。有什麼辦法可以解決這個問題嗎?
UPDATE: 在這個問題中,'Back' & 'Forward' navigation buttons
意味着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,
}
感謝您的更新 – 2011-06-20 09:27:40
沒問題。這是通過你的努力來解決的。 – 2011-06-21 06:57:59