如何确定我的应用程序是否处于活动状态(拥有焦点)我的、应用程序、状态、焦点

2023-09-03 12:59:15 作者:荼糜未谢

有没有办法告诉我的应用程序是否处于活动状态,即任何一件事的窗户已经.IsActive =真的吗?

Is there a way to tell whether my application is active i.e. any of it's windows has .IsActive=true?

我写的信使应用程序,并希望它在任务栏闪烁当它不活跃,新邮件到达。

I'm writing messenger app and want it to flash in taskbar when it is inactive and new message arrives.

推荐答案

用于P /调用和循环

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

private static bool IsActive(Window wnd)
{
    // workaround for minimization bug
    // Managed .IsActive may return wrong value
    if (wnd == null) return false;
    return GetForegroundWindow() == new WindowInteropHelper(wnd).Handle;
}

public static bool IsApplicationActive()
{
    foreach (var wnd in Application.Current.Windows.OfType<Window>())
        if (IsActive(wnd)) return true;
    return false;
}