views:

157

answers:

2

My application uses multiple windows

I want to hide one specific window in case the application loses focus (when the Active Window is not the application window) source

I am handling the Deactivate event of my main form.

    private void MainForm_Deactivate(object sender, EventArgs e) 
    {
      Console.WriteLine("deactivate");
      if (GetActiveWindow() == this.Handle) 
      {
        Console.WriteLine("isactive=true");
      }
      else
      {
        Console.WriteLine("isactive=false");
      }
    }

[DllImport("user32.dll")]
static extern IntPtr GetActiveWindow();

The output is always

deactivate
isactive=true

I have observed the same behavior if a new window within my application receives focus and also if I click into a different application.

I would expect GetActiveWindow to return the handle of the new active window when called from the Deactivate handler. Instead it always returns the handle of my application window.

How is this possible? Is the Deactivate event handled "too soon"? (while the main form is still active?).

How can I detect that my application has lost focus (my application window is not the active window) and another application gained it without running GetActiveWindow on a timer?

+1  A: 

From what I can see GetActiveWindow get's the active window for the calling thread, i.e. your app so it's always going to return the current window of your app. I think perhaps you are looking for GetForegroundWindow which will return the handle to the window the user currently has active.

Lazarus
yes, GetForegroundWindow does it. Thanks!
Marek
Good point. Be aware, by the way, that `GetForegroundWindow` may return NULL in some situations (e.g. switching focus by clicking a taskbar button).
Thomas
@Thomas, good programming practice to check for NULL even if you don't expect it but good to highlight it (+1)
Lazarus
A: 

I'm observing the same behaviour (.NET 3.5, Visual Studio 2008). The documentation is hazy:

Occurs when the form loses focus and is no longer the active form.

However, the contrast between the event names (Activate*d* versus Deactivate) suggests that the event does indeed come before the actual deactivation.

Thomas