How do I see if my form is currently on top of the other ones?

前端 未结 4 1064
别那么骄傲
别那么骄傲 2021-01-13 02:40

Basically, how do I tell if my program is layered above all the other ones?

4条回答
  •  情歌与酒
    2021-01-13 03:25

    A good solution is given by this answer to an identical question: https://stackoverflow.com/a/7162873/386091

    /// 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);
    

    The currently accepted solution by Euric doesn't work if your program shows a dialog box or has detachable windows (like if you use a windows docking framework).

提交回复
热议问题