开发者

How to detect if the current WPF Window is in the user session foreground?

开发者 https://www.devze.com 2023-02-14 17:14 出处:网络
I used System.Windows.Window.IsActive to detect whether the window is in the foreground and it worked in some cases. But I have found cases where it doesn\'t and I wonder if there is any way to detect

I used System.Windows.Window.IsActive to detect whether the window is in the foreground and it worked in some cases. But I have found cases where it doesn't and I wonder if there is any way to detect it开发者_C百科.


The method below works except when a background-only process gets the focus. This is the case with the Windows Desktop. It steals the status of foreground window but it isn't 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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号