Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I ensure my control catches the first event regardless of whether my form has focus?

Tags:

c#

winforms

I am relatively new to C#. I have a window with buttons. If the window is out of focus and I click on a button the first time, the first click grabs focus for the window and all subsequent clicks will perform their respective actions.

Is there a way to execute the event associated with the button instead of grabbing focus?

like image 777
karan Avatar asked Dec 20 '22 19:12

karan


1 Answers

It sounds like you are describing how ToolStrips operate, which does not fire a click event unless the application has the focus.

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:

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);
  }
}

Rebuild your solution and you should see a ToolStripIgnoreFocus control available in your tool box. Try adding that to your form and then add your tool buttons accordingly.

like image 81
LarsTech Avatar answered May 10 '23 16:05

LarsTech