How to immediately click the ToolStrip button without clicking on the form?

I have a Windows Forms application with a toolbar that contains buttons. Disappointingly, I have to double-click on any button so that it lights up when the shape is not focused. The first click seems to activate the form, and then the second click presses the button (alternatively, I can click anywhere on the form and then click the button once). How can I fix this, so that even if the form is not activated, I can click directly on the button?

EDIT: I feel this should be feasible as it works in programs such as SQL Server Profiler and Visual Studio (not to use WinForms, but this suggests that this is not an OS problem).

+7
c # winforms focus toolstrip
source share
2 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)pX, (uint)pY, 0, 0); } } base.WndProc(ref m); } 

EDIT: Now works for ToolStrip .

+1
source share

Here is an alternative way to do this. You can use the β€œForm Activation” event, and then check if the mouse is above the toolbar button, and if so, call PerformClick() .

 private void Form1_Activated(object sender, EventArgs e) { for (int i = 0; i < toolStrip1.Items.Count; i++) { ToolStripItem c = toolStrip1.Items[i]; if (new RectangleF(new Point(i * (c.Size.Width - 1) + this.Location.X + 18, this.Location.Y + 32), c.Size).Contains(MousePosition)) c.PerformClick(); } } 

(18 and 32 are toolstripcontainer offsets from the form location). Maybe there is a way to actually hide what should be the offset of X and Y, but that worked for me. NTN

0
source share

All Articles