Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable focus changes by arrow keys

I have a WPF window with a few controls (buttons, groupboxes, etc) and one big Viewport3D within a Border.

The viewport shows a 3D scene and I want the arrow keys to move its camera around. The problem: the arrow keys always change the focus to another UIElement.

How can I disable focus changes by the arrow keys and have them change the camera position instead?

like image 969
xelor Avatar asked Jun 27 '14 08:06

xelor


3 Answers

It always difficult to answer without having some code to actually test, because without it, we are just guessing really. Either way, I can't comment on your particular situation, but in general, if we want to stop some pre-defined action from happening in an event, then we typically handle that event and set the e.Handled property to true.

Seeing as you already want to handle the KeyDown event to detect the use of the arrow keys, then you could set the e.Handled property to true at the same time. However, you should handle the PreviewKeyDown event instead, because it occurs before the KeyDown event and so is more likely to have the effect that you want. Try something like this:

private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Left || e.Key == Key.Right)
    {
        // Move your camera here
        e.Handled = true;
    }
}
like image 168
Sheridan Avatar answered Sep 23 '22 13:09

Sheridan


If we want to be able to tab between controls but not arrow key through the same set of controls once they are in keyboard navigation mode it should be that we can set KeyboardNavigation.DirectionalNavigation="None" for the container (in this case the window).

However it seems there is some bug stopping that solution from working.

The workaround of setting KeyboardNavigation.DirectionalNavigation="Once" works though.

  • The only caveat I've noticed so far is that upon pressing an arrow key the FocusVisualStyle is reloaded for the currently selected element.
like image 42
Jonathan Allan Avatar answered Sep 20 '22 13:09

Jonathan Allan


You can try

KeyboardNavigation.TabNavigation = "Local"

for not shifting your focus outside the Viewport3D.

like image 24
Ashok Rathod Avatar answered Sep 21 '22 13:09

Ashok Rathod