WinForms: How to determine if window is no longer active (no child window has focus)?
- by Marek
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?