I have a countdown timer – a user enters values and then it start a new form – A min size one or a max size one based on a radio button selected from first form. There is buttons on the user control form to pause/stop the timer, etc. However I want to also add if a keyboard button is pressed do the same.
Here is the code for click the pause button…
private void btnPause_Click (object sender, EventArgs e)
{
_CountdownTimer.Pause ();
}
This works fine and if the pause button is clicked it pauses the Timer. I then tried to add the following code for KeyDown – does anyone know why this would not be working? When I press p it just keeps counting down…..
Thanks.
private void btnPause_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode.ToString() == "p")
{
_CountdownTimer.Pause();
}
}
The KeyDown event delivers virtual keys. Like Keys.P. If you want to detect typing keys, like “p” then you should use the KeyPressed event instead.
But that’s not the proper way. The Button control already knows you to display and handle shortcut keys. Set its Text property to &Pause. The & character indicates the mnemonic, the P gets underlined as soon as the user holds down the Alt key. And pressing Alt+P automatically invokes the Click event. A Windows user interface standard, no need to educate the user. Another significant advantage of doing it this way is that the button doesn’t have to be focused. And you don’t have to write any code. Recommended.