C# Pass Click Event to MenuStrip or ToolStrip Control Without Form Focus

More often than not, I want the click event for menus (MenuStrip) and toolbars (ToolStrip) to trigger on the first click, even when the firm does not have focus. I figure if Windows is going to show the hover effects, the user expects the click to trigger without having to first focus focus on the form.

A work around is to use your own ToolStrip and let the mouse activation give the control the focus, which in turn will then let the button fire it’s click event:

LarsTechStackOverflow Answer

If you incorporate these two WndProc overrides in your code, you’ll see 2 new controls in your Visual Studio toolbox. To avoid clicking twice (once to activate form, again to actually click MenuStrip or ToolStrip item) use the overridden controls.

public class ToolStripIgnoreFocus : ToolStrip
    {
        private const int WM_MOUSEACTIVATE = 0x21;

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_MOUSEACTIVATE && this.CanFocus && !this.Focused)
            {
                this.Focus();
            }

            base.WndProc(ref m);
        }
    }
    public class MenuStripIgnoreFocus : MenuStrip
    {
        private const int WM_MOUSEACTIVATE = 0x21;

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_MOUSEACTIVATE && this.CanFocus && !this.Focused)
            {
                this.Focus();
            }

            base.WndProc(ref m);
        }
    }

I’d like to combine these overrides for less code duplication, but didn’t spend the time to see if there was a way to make that happen, so I’m open to suggestions.

Leave a Reply

Your email address will not be published. Required fields are marked *