XBAP中的键盘快捷键

时间:2020-03-06 14:39:36  来源:igfitidea点击:

我想在WPF XBAP应用程序中支持键盘快捷键,例如" Open"等的Ctrl + O。如何禁用浏览器内置的键盘快捷键,并用自己的快捷键替换?

解决方案

我们不能禁用浏览器的内置键处理功能。这不是我们浏览器内容的地方,不能覆盖浏览器自己的快捷键。

不是答案,而是评论。最好在XBAP中禁用Backspace键的行为,无非就是在没有元素的情况下按下Backspace键,并且浏览器会将我们导航到上一个网页。

如果我们不愿意这样做,则可以尝试添加Windows钩子并拦截我们感兴趣的击键。

我们必须这样做以防止IE帮助打开(愿上帝怜悯我的灵魂)。

看:
http://msdn.microsoft.com/zh-cn/library/system.windows.interop.hwndsource.addhook(VS.85).aspx

这是一些代码(从我们的app.xaml.vb中摘录)可能会有所帮助(对不起,VB):

Private Shared m_handle As IntPtr
Private Shared m_hook As Interop.HwndSourceHook
Private Shared m_hookCreated As Boolean = False

'Call on application start
Public Shared Sub SetWindowHook(ByVal visualSource As Visual)
    'Add in a Win32 hook to stop the browser app from loading
    If Not m_hookCreated Then
        m_handle = DirectCast(PresentationSource.FromVisual(visualSource), Interop.HwndSource).Handle
        m_hook = New Interop.HwndSourceHook(AddressOf WindowProc)
        Interop.HwndSource.FromHwnd(m_handle).AddHook(m_hook)
        m_hookCreated = True
    End If
End Sub

'Call on application exit
Public Shared Sub RemoveWindowHook()
   'Remove the win32 hook
    If m_hookCreated AndAlso Not m_hook Is Nothing Then
        If Not Interop.HwndSource.FromHwnd(m_handle) Is Nothing Then
            Interop.HwndSource.FromHwnd(m_handle).RemoveHook(m_hook)
        End If
        m_hook = Nothing
        m_handle = IntPtr.Zero
    End If
End Sub

'Intercept key presses
Private Shared Function WindowProc(ByVal hwnd As System.IntPtr, ByVal msg As Integer, ByVal wParam As System.IntPtr, ByVal lParam As System.IntPtr, ByRef handled As Boolean) As System.IntPtr
    'Stop the OS from handling help
    If msg = WM_HELP Then
        handled = True
    End If
    Return IntPtr.Zero
End Function