Ian H.
Ian H.

Reputation: 3919

Prevent button from being focused by arrow key click

How can I prevent that if the user presses one of the arrow keys, a button on the form is focused?
I am programming a small game, so this would prevent the user from being able to move. Sorry for the vague explanation.

EDIT:

The player is a PictureBox with a graphic in it that is moved by:

private async void Form1_KeyDown(object sender, KeyEventArgs e)

Upvotes: 0

Views: 1987

Answers (3)

CaptainSkyWalker
CaptainSkyWalker

Reputation: 11

What works for me is to set the button property "TabStop" to false and you can also play with the TabIndex property of the controls on the form to technically set what will be focused when the form loads.

TabStop - sets if pressing TAB can set/give focus to the control and when pressing the TAB key it will increment through the controls on the form according to the - TabIndex - which dictates which control will get focus next.

So if Button A has tabIndex 1 and Button B has tabIndex 2 and button C has tabIndex 3, but Button B has tabStop = false, then pressing TAB will go from button A to Button C, it will skip Button B.

-Keep in mind that not all controls seem to have a "TabStop" property, I have noticed that textbox, button and datagridview does have the property, but stuff like labels and groupbox and picturebox does not have TabStop, only TabIndex.

Upvotes: 0

Gian Paolo
Gian Paolo

Reputation: 4249

A way to handle this scenario is to set form.KeyPreview = true (see MSDN) and then handle the keys in KeyPress / KeyDown event handlers:

Quoting MSDN for KeyPress Event:

To handle keyboard events only at the form level and not enable other controls to receive keyboard events, set the KeyPressEventArgs.Handled property in your form's KeyPress event-handling method to true.

Test for arrow in your keysEvent, manage them the way you need and set Handled=true to avoid default behavior (move focus to next control)

Upvotes: 2

Salah Akbari
Salah Akbari

Reputation: 39946

In your Form.cs override the ProcessCmdKey like this:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
     if (!msg.HWnd.Equals(Handle) &&
         (keyData == Keys.Left || keyData == Keys.Right ||
          keyData == Keys.Up || keyData == Keys.Down))
          return true;
     return base.ProcessCmdKey(ref msg, keyData);
}

Upvotes: 2

Related Questions