问题
What would be some sample code that will trap the Ctrl+Tab and Ctrl+Shift+Tab for a WPF application?
We have created KeyDown
events and also tried adding command bindings with input gestures, but we were never able to trap these two shortcuts.
回答1:
What KeyDown handler did you have? The code below works for me. The one that gives me trouble is: Alt + Tab, but you didn't ask for that :D
public Window1()
{
InitializeComponent();
AddHandler(Keyboard.KeyDownEvent, (KeyEventHandler)HandleKeyDownEvent);
}
private void HandleKeyDownEvent(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab && (Keyboard.Modifiers & (ModifierKeys.Control | ModifierKeys.Shift)) == (ModifierKeys.Control | ModifierKeys.Shift))
{
MessageBox.Show("CTRL + SHIFT + TAB trapped");
}
if (e.Key == Key.Tab && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
MessageBox.Show("CTRL + TAB trapped");
}
}
回答2:
Gustavo's answer was exactly what I was looking for. We want to validate input keys, but still allow pasting:
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
if ((e.Key == Key.V || e.Key == Key.X || e.Key == Key.C) && Keyboard.IsKeyDown(Key.LeftCtrl))
return;
}
回答3:
You have to use KeyUp
event, not KeyDown
...
回答4:
Working version of Szymon Rozga answer (sorry, I can't comment). We don't look on Alt, but it's accounting can be simply added at first if
public View()
{
InitializeComponent();
AddHandler(Keyboard.PreviewKeyDownEvent, (KeyEventHandler)controlKeyDownEvent);
}
private void controlKeyDownEvent(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab && Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
{
if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
MessageBox.Show("CTRL + SHIFT + TAB trapped");
else
MessageBox.Show("CTRL + TAB trapped");
}
}
回答5:
Hi you can use this on keydown event
private void OnButtonKeyDown(object sender, KeyEventArgs e)
{
if(Keyboard.IsKeyDown(Key.LeftCtrl) && Keyboard.IsKeyDown(Key.Tab) && Keyboard.IsKeyDown(Key.LeftShift))
{
//
// TODO: somthing here
//
}
}
来源:https://stackoverflow.com/questions/813389/how-to-capture-ctrl-tab-and-ctrl-shift-tab-in-wpf