C# shortcut key underscore not displayed in built application

Nidrax picture Nidrax · Jan 3, 2014 · Viewed 8.8k times · Source

I have a small problem with .Net 4.0 ToolStripMenuItem caption.
I want it to underscore the Shortcut (access) key letter in the item text.
I used the ampersand sign in the item text field: '&New map', and it looks fine in the editor:
enter image description here

But, when I build the application, the underscores disappear:
enter image description here

Does anyone know why does it happen and how to make the underscored display in the built form?

Answer

BartoszKP picture BartoszKP · Jan 3, 2014

As mentioned in other answers, this the default behaviour. Accelerators are being shown only after the ALT key is pressed.

However it seems possible to force Windows to display accelerator keys constantly:

[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern int SystemParametersInfo(int uAction, int uParam, int lpvParam, int fuWinIni);

private const int SPI_SETKEYBOARDCUES = 4107; //100B
private const int SPIF_SENDWININICHANGE = 2;

[STAThread]
static void Main()
{
    // always show accelerator underlines
    SystemParametersInfo(SPI_SETKEYBOARDCUES, 0, 1, 0);

    Application.Run(new MainForm());
}

Found here.

As I've just verified (after ken2k's suggestion in the comments), this unfortunately affects the whole system. So it needs some tweaking: 1) remember current value of SPI_SETKEYBOARDCUES on startup 2) reset the setting to this value on exit, 3) create a domain exception handler, to be sure that the setting always gets reset back.

Unfortunately this behaves this way even if the last parameter is zero, even though documentation says:

This parameter can be zero if you do not want to update the user profile or broadcast the WM_SETTINGCHANGE message

Simple version is of course just:

[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern int SystemParametersInfo(int uAction, int uParam, int lpvParam, int fuWinIni);

private const int SPI_SETKEYBOARDCUES = 4107; //100B
private const int SPIF_SENDWININICHANGE = 2;

[STAThread]
static void Main()
{
    // always show accelerator underlines
    SystemParametersInfo(SPI_SETKEYBOARDCUES, 0, 1, 0);

    Application.Run(new MainForm());

    SystemParametersInfo(SPI_SETKEYBOARDCUES, 0, 0, 0);
}

In this answer you can find a code example on how to achieve this locally only for your application.