我正在尝试在用户使用KeyDown
事件按 ctrl - x 时触发事件。这适用于 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;
}
}
}
答案 0 :(得分:15)
要在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 :)");
}
}
答案 1 :(得分:8)
您可以覆盖现有剪切命令:
<TextBox>
<TextBox.InputBindings>
<KeyBinding Key="X" Modifiers="Control" Command="{Binding TestCommand}" />
</TextBox.InputBindings>
</TextBox>
您需要创建command。
答案 2 :(得分:0)
我正在使用这种方法:
private void SomeWindow_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.X && (e.KeyboardDevice.Modifiers & ModifierKeys.Control) != 0)
{
//Ctrl + X is pressed
}
}
答案 3 :(得分:0)
大多数答案都可以完成工作,但是调试却很麻烦。由于先按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;
}
}
}
答案 4 :(得分:-1)
在keydown事件中尝试以下
if (e.Control == true && e.KeyCode==keys.x)
{
e.Handled = true;
textBox1.SelectionLength = 0;
//Call your method
}