views:

4242

answers:

4

Does anyone have 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 are never able to trap these 2 shortcuts.

+8  A: 

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");
        }
    }
siz
Siz, thanks...that does work for our WPF. We also have an XBAP that we need to trap this for and it doesn't appear to work on the XBAP. Any ideas on how to do this with an XBAP as well?
FarrEver
A: 

You have to use Key**Up** event, not KeyDown...

Gustavo Cavalcanti
Interesting. Haven't tried this, but can you please explain why?
siz
Sure Siz. When you are trying to capture 2 or more key strokes at the same time you cannot use KeyDown checking for e.Key because it captures one key at a time. If KeyDown is necessary, like doing something when the user is holding down a key combination for example, you should use KeyDown and the Keyboard class, specifically IsKeyDown(), testing for specific keys.
Gustavo Cavalcanti
Sorry, I don't understand what you're trying to say here. The KeyUp event also only passes a single Key value in e.Key. Can you give a specific example where handling KeyUp instead of KeyDown would be better for "capturing 2 or more keystrokes at the same time"? Thanks.
Ray Burns
A: 

Gustavo gave me 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;

Thanks!

mikeB
+1  A: 

@siz

You can clean up your If statements by using the following syntax: Keyboard.Modifiers.HasFlag(ModifierKeys.Control)

Pakman