Search code examples
c#wpfwndprockeyboard-hookwindow-messages

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


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?


Solution

  • 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).