使用WPF中文本框的KeyDown事件捕获Ctrl-X
本文关键字:事件 Ctrl-X KeyDown WPF 中文 文本 使用 | 更新日期: 2023-09-27 18:13:54
我试图触发一个事件,当用户按下ctrl-x使用KeyDown
事件。这在ctrl-D时工作得很好,但是当ctrl-x被按下时事件不会触发。我猜这是因为ctrl-x是"cut"命令。当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;
}
}
}
要在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 :)");
}
}
您可以覆盖现有的cut命令:
<TextBox>
<TextBox.InputBindings>
<KeyBinding Key="X" Modifiers="Control" Command="{Binding TestCommand}" />
</TextBox.InputBindings>
</TextBox>
您需要创建一个命令
大多数答案都可以完成工作,但是使调试变得很痛苦。因为CTRL是先按下的,所以它应该被分开,这样可以跳过它,只由单个if
检查。下面的代码应该是高效且易于调试的。
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;
}
}
}
我使用这个方法:
private void SomeWindow_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.X && (e.KeyboardDevice.Modifiers & ModifierKeys.Control) != 0)
{
//Ctrl + X is pressed
}
}
try following in keydown event
if (e.Control == true && e.KeyCode==keys.x)
{
e.Handled = true;
textBox1.SelectionLength = 0;
//Call your method
}