Get handle to desktop / shell window

前端 未结 2 587
灰色年华
灰色年华 2020-12-18 01:03

In one of my programs I need to test if the user is currently focusing the desktop/shell window. Currently I\'m using GetShellWindow() from user32.dll and compare the result

2条回答
  •  情深已故
    2020-12-18 02:02

    Here is a workaround that uses GetClassName() to detect if the desktop is active:

    • When Windows first starts, the desktop's Class is "Progman"
    • After changing the wallpaper, the desktop's Class will be "WorkerW"

    You can test against these to see if the desktop is focused.

    [DllImport("user32.dll")]
    static extern int GetForegroundWindow();
    
    [DllImport("user32.dll")]
    static extern int GetClassName(int hWnd, StringBuilder lpClassName, int nMaxCount);
    
    public void GetActiveWindow() {
        const int maxChars = 256;
        int handle = 0;
        StringBuilder className = new StringBuilder(maxChars);
    
        handle = GetForegroundWindow();
    
        if (GetClassName(handle, className, maxChars) > 0) {
            string cName = className.ToString();
            if (cName == "Progman" || cName == "WorkerW") {
                // desktop is active
            } else {
                // desktop is not active
            }
        }
    }
    

提交回复
热议问题