You need to override the ProcessCmdKey
method for your form. That's the only way you're going to be notified of key events that occur when child controls have the keyboard focus.
Sample code:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// look for the expected key
if (keyData == Keys.A)
{
// take some action
MessageBox.Show("The A key was pressed");
// eat the message to prevent it from being passed on
return true;
// (alternatively, return FALSE to allow the key event to be passed on)
}
// call the base class to handle other key events
return base.ProcessCmdKey(ref msg, keyData);
}
As for why this.Focus()
doesn't work, it's because a form can't have the focus by itself. A particular control has to have the focus, so when you set focus to the form, it actually sets the focus to the first control that can accept the focus that has the lowest TabIndex
value. In this case, that's your button.