Irsu85
Irsu85

Reputation: 123

How do you keyboard focus on a specific item?

I am making a game where I need a constant keyboard listener (to navigate through the game). I tried getting the keyboard focus to one place and let it stay there using a seperate thread in a while true loop. This seems to crash my program.

Question: Is there a method to get my keyboard focused on one element so I can grab my key input from there?

What can I use?:

What have I tried?

public MainWindow()
{
    InitializeComponent();
    Thread keyboardfocus = new Thread(GetFocus);
    keyboardfocus.Start();
}
private void GetFocus()
{
    while (true)
    {
        Keyboard.Focus(KeyboardButton);
    }
}

private void KeyboardButton_OnKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Z)
    {
        map.PosUp -= 1;
        MainCanvas.Background = Brushes.Aqua;
    }
    else if (e.Key == Key.S)
    {
        map.PosUp += 1;
        MainCanvas.Background = Brushes.Black;
    }
}

Thanks

Upvotes: 1

Views: 240

Answers (1)

Rekshino
Rekshino

Reputation: 7325

Add event handler for Window.Loaded and set there a focus to the desired control:

private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    Keyboard.Focus(KeyboardButton);
}

Add event handler for the UIElement.LostKeyboardFocus in your case KeyboardButton and just set the keybord focus again to the KeyboardButton:

private void KeyboardButton_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    Keyboard.Focus(KeyboardButton);
}

Upvotes: 1

Related Questions