You created the event-handler for the KeyDown event, but we cannot see if you set this handler in the event's delegate list.
Moreover, as you want to use a shortcut with ALT key, there may be a simpler way to accomplish what you want to do.
Using your event handler:
Just insert this statement in your form's constructor:
this.KeyDown += Form1_KeyDown;
You may also create a specialized method
ConfirmExit
, which you would call from both your event-handlers (in general, I really don't like direct implementations in event handlers).
private void ConfirmExit()
{
DialogResult result = MessageBox.Show("Are you sure you want to exit?", "Exiting", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
this.Close();
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt && e.KeyCode == Keys.X)
{
ConfirmExit();
}
}
private void btnExit_Click(object sender, EventArgs e)
{
ConfirmExit();
}
One implementation, used in two different places. Clean and easy to read/follow.
Using a much simpler solution:
As you want to use the ALT key, you may use an in-built functionnality: in your button's Text property, prefix the letter you want to use as shortcut (the X key) with the ampersand sign (
&
).
Example:
btnExit.Text = "E&xit";
You can do that in design mode from the property grid.
The letter X will be underlined, meaning that you can activate the button from keyboard by pressing ALT + X.
Of course, this is not a solution if:
- you want another combination key than ALT;
- or the letter you want as shortcut does not appear in the button's Text property.
Hope this helps.
Edited: simplified alt test in KeyDown handler.