Capturing Ctrl-X with the KeyDown event of a textbox in WPF

You can override the existing cut command:

<TextBox>
    <TextBox.InputBindings>
        <KeyBinding Key="X" Modifiers="Control" Command="{Binding TestCommand}" />
    </TextBox.InputBindings>
</TextBox>

You need to create a command though.


To do that in wpf I try this:

private void HandleKeyDownEvent(object sender, KeyEventArgs e)
{
    if (e.Key == Key.X && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
    {
        MessageBox.Show("You press Ctrl+X :)");
    }
}

Most of the answers get the job done, but make debugging a pain. Since CTRL is pressed first, it should be separated so it can be skipped and only checked by a single if. The following should be efficient and easier to debug.

public MyApp() {
    // other constructor code
    KeyDown += MyApp_KeyDown;    
}

private void MyApp_KeyDown(object sender, KeyEventArgs e) {
    // hold that CTRL key down all day... you'll never get in unless there's another key too. 
    if (Keyboard.Modifiers == ModifierKeys.Control && e.Key!=Key.LeftCtrl && e.Key != Key.RightCtrl) 
    {
        switch (e.Key) // <--- Put the BREAK here.  Stops iff there's another key too.
        {
            case Key.C: UndoRedoStack.InsertInUnDoRedoForCopy(CopyArgs); break;
            case Key.X: UndoRedoStack.InsertInUnDoRedoForCut(CutArgs); break;
            case Key.V: UndoRedoStack.InsertInUnDoRedoForPaste(PasteArgs); break;
            case Key.Y: UndoRedoStack.Redo(1); break;
            case Key.Z: UndoRedoStack.Undo(1); break;
            default: break;
        }
    }
}

I am using this method:

private void SomeWindow_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.X && (e.KeyboardDevice.Modifiers & ModifierKeys.Control) != 0)
    {
        //Ctrl + X is pressed
    }
}

Tags:

C#

Wpf