Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture Ctrl + Tab and Ctrl + Shift + Tab in WPF?

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.

like image 444
FarrEver Avatar asked May 01 '09 21:05

FarrEver


3 Answers

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");
   }
}
like image 147
Szymon Rozga Avatar answered Oct 15 '22 19:10

Szymon Rozga


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;
}
like image 31
mikeB Avatar answered Oct 15 '22 21:10

mikeB


You have to use KeyUp event, not KeyDown...

like image 8
Gus Cavalcanti Avatar answered Oct 15 '22 19:10

Gus Cavalcanti