.netmnemonics

How can I prevent Alt codes in a .NET app?


I have a .NET app with buttons which use numbers for mnemonics. (e.g. "&1 - Check" and "&2 - Cash") When I hit Alt+1, I expect the Check button to be clicked. This works when I use the standard number keys on a keyboard. However, when I hit Alt+1 using the number pad, Windows takes over and inserts the symbol that matches the "alt code" of 1. See http://alt-codes.org/list/. How can I prevent this from happening in my application?

Thanks!


Solution

  • This can be done by enabling KeyPreview on the form and handling the KeyUp event. The following code bypasses the Windows alt codes functionality and causes the button to click when I hit Alt+NumPad1:

    if (e.Alt && e.KeyCode == Keys.NumPad1)
    {
         e.Handled = true;
         button1.PerformClick();
    }