Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Form - MouseClick will click the actual control after losing form focus

If you ever remove focus from any professional application like Chrome/FireFox/Visual Studio, and then reclick a button/menu item, it will actually click it as if you never lost focus.

How can I apply the same concept in C# WinForm? I tried many things like

private void form1_MouseClick(object sender, MouseEventArgs e)
    {
        BringToFront();
        Activate();
    }

Activate/focus/select/etc... nothing worked to react the same way, it always takes 3-4 clicks to actually click on a menu!

I thought about making a click event for every single control, but that seemed rather redundant.

Check this for example (Yellow Clicks)

like image 452
Khalil Ghanem Avatar asked Sep 14 '25 14:09

Khalil Ghanem


1 Answers

You are right about Menues taking an extra click to get focus.

Which is extra annoying since the menue get highlighted anyway but doesn't react to the 1st click..

You can avoid that by coding the MouseEnter event:

private void menuStrip1_MouseEnter(object sender, EventArgs e)
{
    // either 
    menuStrip1.Focus();
    // or
    this.Focus();
}

The downside of this is, that it is stealing focus from other applications, which is not something a well-behaved application should do..

So I think it is better to wait for a definitive user action; code the MouseDown event in a similar way..:

private void menuStrip1_MouseDown(object sender, MouseEventArgs e)
{
    menuStrip1.Focus();
}

Or use the event that was made for the occasion:

private void menuStrip1_MenuActivate(object sender, EventArgs e)
{
    menuStrip1.Focus();
}

I can't confirm a similar problem with Buttons or any other controls, though.

like image 153
TaW Avatar answered Sep 17 '25 03:09

TaW