locked
How to know if the "Active" application changes? RRS feed

  • Question

  • Hi All.

    Is there any way to be notified when the "Active" application
    changes? By active I mean which application currently has
    mouse and keyboard focus.

    I need to be able to know when my application becomes active
    and when it becomes non-active. (i.e.: via minimization, or
    alt-tab, etc)

    I tried handling the LostFocus, Activate and Deactivate events
    on my main form, but this didn't solve my problem because
    I have a number of top level windows, and when anyone
    of those gets focus, the event handlers fire on the main form.

    What I really need to determine is if the application is in focus
    or not - regardless of what form of the application looses/gains
    focus.
    Tuesday, November 21, 2006 7:25 PM

Answers

  • Windows sends the WM_ACTIVATEAPP message to a window when a window in another application becomes active.  Trap it like this:

        protected override void WndProc(ref Message m) {
          if (m.Msg == 0x1c) { // WM_ACTIVATEAPP
            if (m.WParam == IntPtr.Zero) label1.Text = "Not active";
            else label1.Text = "Active";
          }
          base.WndProc(ref m);
        }

    Wednesday, November 22, 2006 12:45 PM

All replies

  • Windows sends the WM_ACTIVATEAPP message to a window when a window in another application becomes active.  Trap it like this:

        protected override void WndProc(ref Message m) {
          if (m.Msg == 0x1c) { // WM_ACTIVATEAPP
            if (m.WParam == IntPtr.Zero) label1.Text = "Not active";
            else label1.Text = "Active";
          }
          base.WndProc(ref m);
        }

    Wednesday, November 22, 2006 12:45 PM
  • Excellent and elegant solution - thanks very much.
    Wednesday, November 22, 2006 3:51 PM