Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

wpf

I'm trying to trigger an event when the user presses ctrl-x using the KeyDown event. This works fine for ctrl-D but the event doesn't trigger when ctrl-x is pressed. I'm guessing this is because ctrl-x is the "cut" command. Is there any way to trigger an event when ctrl-X is pressed?

private void textBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyboardDevice.IsKeyDown(Key.LeftCtrl) || e.KeyboardDevice.IsKeyDown(Key.RightCtrl))
    {
        switch (e.Key)
        {
            case Key.D:
                //handle D key
                break;
            case Key.X:
                //handle X key
                break;
        }
    }
}
like image 537
dregan Avatar asked Nov 09 '11 21:11

dregan


2 Answers

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 :)");
    }
}
like image 198
Rayan Elmakki Avatar answered Sep 19 '22 05:09

Rayan Elmakki


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.

like image 29
H.B. Avatar answered Sep 19 '22 05:09

H.B.