How to determine whether my application is active (has focus)

前端 未结 5 1271
天命终不由人
天命终不由人 2021-02-05 18:53

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

I\'m writing messenger app and want it to flash in taskbar when it is

5条回答
  •  说谎
    说谎 (楼主)
    2021-02-05 19:26

    Used P/Invoke and loop

    [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())
            if (IsActive(wnd)) return true;
        return false;
    }
    

提交回复
热议问题