0

In WPF is it possible to trigger an event if say the keyboard right or left directions are pressed, now matter which control has focus?

No matter where in the form has focus or what they are doing I need something to happen if Right Or Left is hit.

Is it absolutely necessary to track down every keyboard notification (KeyDown and KeyUp events)?

Edit:

For more info, I have a slider that I need to be controlled by left and right buttons at any time. I also have a combobox that I need to open. I tried using this code, but it stops me from using the combobox:

Private Sub sldDays_IsKeyboardFocusedChanged(sender As Object, e As System.Windows.DependencyPropertyChangedEventArgs) Handles sldDays.IsKeyboardFocusedChanged
    Keyboard.Focus(sldDays)
End Sub

Edit 2:

In case anyone stumbles on this in the future I think I solved my issue:

I set this method to the PreviewKeyDown Event (this makes it always go first as the key down)

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    PreviewKeyDown="sliderKey"

Then this is the event:

Private Sub sliderKey(sender As System.Object, e As KeyEventArgs)
    Try
        If e.Key = Key.Right Then
            sldDays.Value += 1
        ElseIf e.Key = Key.Left Then
            sldDays.Value -= 1
        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub
Loogawa
  • 389
  • 6
  • 24
  • 1
    http://stackoverflow.com/questions/1752494/detect-if-any-key-is-pressed-in-c-sharp-not-a-b-but-any Look this answer – d.lavysh Dec 10 '13 at 16:35
  • This doesn't fix my problem because I do have controls on the form that can have key down events and stuff like that. I need regardless of which control has focus the key down to be intercepted. – Loogawa Dec 10 '13 at 16:48

1 Answers1

0

This comes from the way routed events work in WPF. Tunnelling events go from the parent downd to the child while bubbling events come up from the child to the parent. So in your case intercepting the PreviewKeyDown event in the parent Window allows you to catch all keys pressed in any child control. This explanation should clarify any doubts: http://wpf.2000things.com/2012/08/07/619-event-sequence-for-the-key-updown-events/

Super-E-
  • 78
  • 5