WinForms: How to determine if window is no longer active (no child window has focus)?

梦想与她 提交于 2019-12-24 03:32:54

问题


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:


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.




回答2:


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 (Activated versus Deactivate) suggests that the event does indeed come before the actual deactivation.



来源:https://stackoverflow.com/questions/2517295/winforms-how-to-determine-if-window-is-no-longer-active-no-child-window-has-fo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!