![](/img/trans.png)
[英]Simulate Ctrl key at keyDown event of textBox in Silverlight
[英]Capturing Ctrl-X with the KeyDown event of a textbox in WPF
我試圖在用戶使用KeyDown
事件按下ctrl - x時觸發一個事件。 這適用於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;
}
}
}
要在 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 :)");
}
}
您可以覆蓋現有的剪切命令:
<TextBox>
<TextBox.InputBindings>
<KeyBinding Key="X" Modifiers="Control" Command="{Binding TestCommand}" />
</TextBox.InputBindings>
</TextBox>
不過,您需要創建一個命令。
我正在使用這種方法:
private void SomeWindow_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.X && (e.KeyboardDevice.Modifiers & ModifierKeys.Control) != 0)
{
//Ctrl + X is pressed
}
}
大多數答案都能完成工作,但讓調試變得痛苦。 由於 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;
}
}
}
嘗試在 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.