How to determine if the current WPF window is in the foreground of a user session?

I used System.Windows.Window.IsActiveto determine if a window is in the foreground and in some cases it works. But I have discovered cases where this is not the case, and I am wondering if there is a way to detect this.

+3
source share
1 answer

The method below works, except when the focus-only process is focused. This applies to Windows Desktop. He steals the status of the foreground window, but he is not in the foreground.

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

public bool IsForeground()
{
     Window window = Application.Current.MainWindow;
     IntPtr windowHandle = new WindowInteropHelper(window).Handle;
     IntPtr foregroundWindow = GetForegroundWindow();
     return windowHandle == foregroundWindow;
}
+2
source

Source: https://habr.com/ru/post/1795569/


All Articles