I have a form which I’m trying to catch keyboard events from, but the form has buttons and so whenever I press the Space key one of the buttons thinks I’m pressing it down.
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (btnclock.Text == "Start")
e.Handled = false;
else
{
i = Convert.ToInt16(rtb1.Text.IndexOf(e.KeyChar));
if (i == 0)
{
rtb1.Text = rtb1.Text.Remove(0, 1);
}
else
j++;
textBox1.Text = Convert.ToString((j));
}
}
How can I avoid this and keep capturing keystrokes on the form?
Pressing the
spacekey causes the button with focus to act as if it was clicked. Try explicitly setting the focus on the form upon displaying the form and also after a button click, so as to move focus away from the button after it carries out its action:form1.Focus().However as mentioned by Shani, it may be easier to have the user type inside a textbox. When a textbox has focus, most keystrokes (including
space, but thetabkey will shift focus to another control) can be caught with a handler to the textbox’sKeyPressevent, in a way very similar to the way you’re capturing the form’sKeyPressevent.