C++: check if computer is locked

后端 未结 4 1253
感动是毒
感动是毒 2020-12-06 20:36

I\'m trying to figure out whether the computer is locked.

I\'ve looked at LockWorkStation function, but the function that I\'m hoping to find is IsWorkStation

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-06 21:18

    For windows 7 and abowe WTS API can be used:

    bool IsSessionLocked() {
        typedef BOOL (PASCAL * WTSQuerySessionInformation)(HANDLE hServer, DWORD SessionId, WTS_INFO_CLASS WTSInfoClass, LPTSTR* ppBuffer, DWORD* pBytesReturned);
        typedef void (PASCAL * WTSFreeMemory)( PVOID pMemory);
    
        WTSINFOEXW * pInfo = NULL;
        WTS_INFO_CLASS wtsic = DW_WTSSessionInfoEx;
        bool bRet = false;
        LPTSTR ppBuffer = NULL;
        DWORD dwBytesReturned = 0;
        LONG dwFlags = 0;
        WTSQuerySessionInformation pWTSQuerySessionInformation = NULL;
        WTSFreeMemory pWTSFreeMemory = NULL;
    
        HMODULE hLib = LoadLibrary( _T("wtsapi32.dll") );
        if (!hLib) {
            return false;
        }
        pWTSQuerySessionInformation = (WTSQuerySessionInformation)GetProcAddress(hLib, "WTSQuerySessionInformationW" );
        if (!pWTSQuerySessionInformation) {
            goto EXIT;
        }
    
        pWTSFreeMemory = (WTSFreeMemory)GetProcAddress(hLib, "WTSFreeMemory" );
        if (pWTSFreeMemory == NULL) {
            goto EXIT;
        }
    
        if(pWTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, g_dwSessionID, wtsic, &ppBuffer, &dwBytesReturned)) {
            if(dwBytesReturned > 0) {
                pInfo =  (WTSINFOEXW*)ppBuffer; 
                if (pInfo->Level == 1) {
                    dwFlags = pInfo->Data.WTSInfoExLevel1.SessionFlags;
                }
                if (dwFlags == WTS_SESSIONSTATE_LOCK) {
                    bRet = true;
                }
            }
            pWTSFreeMemory(ppBuffer);
            ppBuffer = NULL;
        }
    EXIT:
        if (hLib != NULL) {
            FreeLibrary(hLib);
        }
        return bRet;
    }
    

    Please check following article for supported platforms for WTSINFOEX structure: https://technet.microsoft.com/ru-ru/sysinternals/ee621017

提交回复
热议问题