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

前端 未结 4 1208
温柔的废话
温柔的废话 2020-12-17 03:52

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

4条回答
  •  甜味超标
    2020-12-17 04:49

    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.

提交回复
热议问题