[英]Capturing Ctrl-X with the KeyDown event of a textbox in WPF
I'm trying to trigger an event when the user presses ctrl - x using the KeyDown
event.我试图在用户使用
KeyDown
事件按下ctrl - x时触发一个事件。 This works fine for ctrl - D but the event doesn't trigger when ctrl - x is pressed.这适用于ctrl - D但当按下ctrl - x时不会触发事件。 I'm guessing this is because ctrl - x is the "cut" command.
我猜这是因为ctrl - x是“剪切”命令。 Is there any way to trigger an event when ctrl - X is pressed?
当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;
}
}
}
To do that in wpf I try this:要在 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 :)");
}
}
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
}
}
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
.由于 CTRL 首先被按下,所以它应该被分开,这样它就可以被跳过并且只被一个
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;
}
}
}
try following in keydown event尝试在 keydown 事件中关注
if (e.Control == true && e.KeyCode==keys.x)
{
e.Handled = true;
textBox1.SelectionLength = 0;
//Call your method
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.