3

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?

2
  • 1
    When I do this the button event fires.
    – Kyeotic
    Commented Jul 4, 2012 at 0:50
  • 5
    A lot of people seem to think this is normal Windows behavior. It's worth noting, it is not. Try opening two Explorer windows, giving focus to one, then clicking a file in the other. The click in the out of focus window still registers as a click.
    – ahouse101
    Commented Mar 21, 2013 at 23:24

4 Answers 4

12

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.

2
  • 2
    It is WM_MOUSEACTIVATE, not active. Nice fix. Commented Jul 4, 2012 at 1:27
  • Added that override to my ToolStrip and MenuStrip controls. Brilliant, clean and spot-on solution. TYVM!
    – Mavelo
    Commented Aug 7, 2023 at 18:00
0

This is how most Windows apps work - the app needs to have focus before it can receive click events.

0

As far as I know, you've described an inherent Windows behaviour and as such it could be impossible to do.

An alternative is to harness 'Always on top' style of windows app which is explained here:

How to make a window always stay on top in .Net?

0

This is normal windows behavior. Something that I don't think you can override (so that the click event fires, but doesn't bring your app to the foreground, and active state).

If you don't want to bring focus to the window, but still want to provide some 'interaction' with the window itself, try keyboard hooks or hotkey events. Examples:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.