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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With