使用WPF中文本框的KeyDown事件捕获Ctrl-X

dre*_*gan 11 c# wpf

我试图在用户按下时触发事件ctrl- x使用KeyDown事件.这工作正常ctrl- D但是当事件不会触发ctrl- x被按下.我猜这是因为ctrl- x是"剪切"命令.ctrl- X按下后是否有任何方法可以触发事件?

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 16

要在wpf中这样做,我试试这个:

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


H.B*_*.B. 10

您可以覆盖现有的剪切命令:

<TextBox>
    <TextBox.InputBindings>
        <KeyBinding Key="X" Modifiers="Control" Command="{Binding TestCommand}" />
    </TextBox.InputBindings>
</TextBox>
Run Code Online (Sandbox Code Playgroud)

您需要创建一个命令.

  • 谢谢,我无法让它在 xaml 中工作(甚至为命令创建了一个依赖属性),但它在后面的代码中工作得很好。 (2认同)