Search code examples
c#.netshortcutcontextmenustrip

How to show underscore (shortcut) without holding Alt?


I've created a form with ContextMenuStrip. I set its shortcut using Text field in following way: "&File". However, when I open this context menu by right mouse button click, underscore is shown only when I simultaneously hold Alt button. Is there a way to show underscore on a mouse click without holding Alt button?


Solution

  • You can modify the text rendering behaviour (HidePrefix) via a custom ToolStripSystemRenderer:

    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                contextMenuStrip1.Renderer = new AccessKeyMenuStripRenderer();
            }
    
            private void Form1_Click(object sender, EventArgs e)
            {
                contextMenuStrip1.Show(Cursor.Position);
            }
        }
    
        class AccessKeyMenuStripRenderer : ToolStripSystemRenderer 
        {
            protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
            {
                e.TextFormat &= ~TextFormatFlags.HidePrefix;
                base.OnRenderItemText(e);
            }
        }
    }