Determine if current application is activated (has focus)

前端 未结 7 775
情歌与酒
情歌与酒 2020-11-27 15:26

Note: There\'s a very similar question, but it\'s WPF-specific; this one is not.

How can I determine if the current application is activ

7条回答
  •  温柔的废话
    2020-11-27 15:43

    This works:

    /// Returns true if the current application has focus, false otherwise
    public static bool ApplicationIsActivated()
    {
        var activatedHandle = GetForegroundWindow();
        if (activatedHandle == IntPtr.Zero) {
            return false;       // No window is currently activated
        }
    
        var procId = Process.GetCurrentProcess().Id;
        int activeProcId;
        GetWindowThreadProcessId(activatedHandle, out activeProcId);
    
        return activeProcId == procId;
    }
    
    
    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    private static extern IntPtr GetForegroundWindow();
    
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);
    

    It has the advantage of being thread-safe, not requiring the main form (or its handle) and is not WPF or WinForms specific. It will work with child windows (even independent ones created on a separate thread). Also, there's zero setup required.

    The disadvantage is that it uses a little P/Invoke, but I can live with that :-)

提交回复
热议问题