Archive for the Annoying Windows beep on Alt key. Category

How to get rid of that annoying beep with Alt keys in Windows programs (C#)

Posted in Annoying Windows beep on Alt key., C#, Trapping Key Events, VB with tags , on July 6, 2010 by christophermelvin

If you’ve ever programmed Windows programs you have probably noticed that the menus are activated and handled by Windows itself, not by your program. This has been the case with all versions of Windows that I’ve ever programmed going back to 3.1.

Because the menus are handled by Windows and the Alt key is used to activate menus, attempting to use the Alt key to cause the displaying of your own popup menu causes Windows sound that annoying nasty beep indicating that the key sequence is invalid. It doesn’t matter that you handle the Alt key in an event. The beep still occurs.

Handling:

You can get rid of the annoying beep by adding a undocked Windows menu and setting the menu visibility to false.

You trap the Alt key using KeyDown event on form.

Here’s the event code for KeyDown event:

private void frmYourFormName_KeyDown(object sender, KeyEventArgs e)
{

// We are only interested in certain keys here.

if (e.Alt == true)

{

if (e.KeyValue == 70)   // Alt F (Can use any character)
{

// CODE YOU WANT TO EXECUTE WHEN USER PRESSES ALT-F

}

}

}

Clean-up

With this method there is one clean up that is needed. Pressing Alt-F activates the Windows menu even though it’s invisible. The Windows menu does not deactivate until an item in the Windows menu is selected, or the user presses Alt or Escape, or the user clicks somewhere else in the window.

There is no menu.Deactivate function. :(

The answer to this  is to send an Escape key to the program. If you do not do this the invisible Windows menu will retain focus regardless of anything else you do. Setting focus to a control will not deactivate the menu. This is done in C# with the following code:

System.Windows.Forms.SendKeys.Send(“{ESC}”);

This handling also should work for VB.NET, C and C++.

Follow

Get every new post delivered to your Inbox.