Receive Keyboard Events with Window Messages in a WPF-Window (HwndSource.AddHook)

♀尐吖头ヾ 提交于 2020-01-03 06:48:24

问题


I have a Window with a TextBox. The cursor is inside the TextBox. If I press a key, then I receive a message in WndProc (for KeyUp and KeyDown). But if I set e.Handled = true in the KeyUp and KeyDown events, then I don't receive any key messages:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        Loaded += MainWindow_Loaded;
    }

    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        var textBox = new TextBox();
        textBox.KeyDown += TextBox_KeyDown;
        textBox.KeyUp += TextBox_KeyUp;
        Content = textBox;
        (PresentationSource.FromVisual(this) as HwndSource).AddHook(WndProc);
    }

    private void TextBox_KeyDown(object sender, KeyEventArgs e)
    {
        e.Handled = true;
    }

    private void TextBox_KeyUp(object sender, KeyEventArgs e)
    {
        e.Handled = true;
    }

    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        Debug.WriteLine(msg + " " + wParam);
        return IntPtr.Zero;
    }
}

Is it possible to receive a PreviewKeyDown/PreviewKeyUp event in WndProc?


回答1:


There are tons of way to intercept key messages. You don't even need any library for this. Using pure Win32 API is OK but if you want simplicity, try handling the ThreadPreprocessMessage event of ComponentDispatcher:

ComponentDispatcher.ThreadPreprocessMessage += (ref MSG m, ref bool handled) => {
            //check if WM_KEYDOWN, print some message to test it
            if (m.message == 0x100)
            {
                System.Diagnostics.Debug.Print("Key down!");
            }
        };

The event is able to receive any key messages before it is actually sent to your window. So it's what you want in this case if you want to handle raw messages (instead of handling PreviewKeyDown, ...).

The AddHook method allows to add some hook proc for the window but it's really limited in WPF (while the equivalent WndProc protected method of Form in winforms can intercept much more messages).




回答2:


Try using ManagedWinApi. You can install it with NuGet.

PM> Install-Package ManagedWinapi

For extensive examples of keyboard and other msg interception: http://mwinapi.sourceforge.net/

Another alternative is https://easyhook.github.io/

Both libraries are well documented.



来源:https://stackoverflow.com/questions/33101255/receive-keyboard-events-with-window-messages-in-a-wpf-window-hwndsource-addhook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!