Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a ToolStrip button immediately clickable without clicking on the form first? [duplicate]

I have a windows forms app with a toolstrip that contains buttons. Frustratingly, I have to click twice on any button to get it to fire when the form isn't focused. The first click seems to activate the form, and then second click clicks the button (alternatively, I can click anywhere on the form and then click the button once). How can I fix this so that, even when the form is not activated, I can click directly on a button?

EDIT: I feel like this should be feasible, since it works in programs like SQL Server Profiler and Visual Studio (not that these use WinForms, but it would suggest that it's not an OS issue).

like image 868
ChaseMedallion Avatar asked Feb 28 '14 19:02

ChaseMedallion


1 Answers

Try something like this:

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);

private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
private const int MOUSEEVENTF_RIGHTUP = 0x10;

private const int WM_PARENTNOTIFY = 0x210;
private const int WM_LBUTTONDOWN = 0x201;

protected override void WndProc(ref Message m)
{
    if (m.Msg == WM_PARENTNOTIFY)
    {
        if (m.WParam.ToInt32() == WM_LBUTTONDOWN && ActiveForm != this)
        {
            Point p = PointToClient(Cursor.Position);
            if (GetChildAtPoint(p) is ToolStrip)
                mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, (uint)p.X, (uint)p.Y, 0, 0);
        }
    }
    base.WndProc(ref m);
}

EDIT: Works for ToolStrip now.

like image 103
Dmitry Avatar answered Sep 28 '22 21:09

Dmitry