cover re
cover re

Reputation: 1

How to detect if the screen is unlocked when the system starts up?

My program needs to show a popup after user startup. Currently, I'm using SwitchDesktop's success/failure to determine the state, but when testing on Windows 10, I found that SwitchDesktop still succeeds if the password input screen hasn't appeared yet. How should I improve this?

    typedef HDESK(WINAPI *PFNOPENDESKTOP)(LPSTR, DWORD, BOOL, ACCESS_MASK);
    typedef BOOL(WINAPI *PFNCLOSEDESKTOP)(HDESK);
    typedef BOOL(WINAPI *PFNSWITCHDESKTOP)(HDESK); 
    bool IsScreenLocked()
    {
        BOOL bLocked = FALSE;
        static HMODULE hUser32 = LoadLibrary(_T("user32.dll"));

        if (hUser32) 
        { 
            static PFNOPENDESKTOP fnOpenDesktop = (PFNOPENDESKTOP)GetProcAddress(hUser32, "OpenDesktopA"); 
            static PFNCLOSEDESKTOP fnCloseDesktop = (PFNCLOSEDESKTOP)GetProcAddress(hUser32, "CloseDesktop"); 
            static PFNSWITCHDESKTOP fnSwitchDesktop = (PFNSWITCHDESKTOP)GetProcAddress(hUser32, "SwitchDesktop"); 

            if (fnOpenDesktop && fnCloseDesktop && fnSwitchDesktop) 
            { 
                HDESK hDesk = fnOpenDesktop("Default", 0, FALSE, DESKTOP_SWITCHDESKTOP); 

                if (hDesk) 
                {  
                    bLocked = !fnSwitchDesktop(hDesk); 
                    fnCloseDesktop(hDesk); 
                }  
            } 
        }
        return bLocked;
    }

Upvotes: 0

Views: 33

Answers (1)

patthoyts
patthoyts

Reputation: 33223

You can monitor the screen lock/unlock status using WTSRegisterSessionNotification. This will send your application a WM_WTSSESSION_CHANGE window message when the screen gets locked or unlocked so if you have a long running application you can keep track of this state.

Though it might be more appropriate to start your application using a scheduled task bound to the user login event depending upon the purpose of the application.

Upvotes: 0

Related Questions