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?

Stuart Helwig
  • 9,318
  • 8
  • 51
  • 67
karan
  • 69
  • 3
  • 1
    When I do this the button event fires. – Kyeotic Jul 04 '12 at 00: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 Mar 21 '13 at 23:24

4 Answers4

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.

LarsTech
  • 80,625
  • 14
  • 153
  • 225
0

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

saille
  • 9,014
  • 5
  • 45
  • 57
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?

Community
  • 1
  • 1
Fellmeister
  • 591
  • 3
  • 24
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:

Community
  • 1
  • 1
justderb
  • 2,835
  • 1
  • 25
  • 38