C++: check if computer is locked

后端 未结 4 1234
感动是毒
感动是毒 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条回答
  •  -上瘾入骨i
    2020-12-06 21:22

    Alex Vershynin's version works well, with a few code changes that I had to make.

    I had to: change DW_WTSSessionInfoEx to WTSSessionInfoEx (Answering user586399), define "g_dwSessionID" to WTSGetActiveConsoleSessionId(), include Wtsapi32.h. I think that's it ...

    Since I can't comment, I'll paste the whole code here.

    #include "Wtsapi32.h"
    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 = WTSSessionInfoEx;
        bool bRet = false;
        LPTSTR ppBuffer = NULL;
        DWORD dwBytesReturned = 0;
        LONG dwFlags = 0;
        WTSQuerySessionInformation pWTSQuerySessionInformation = NULL;
        WTSFreeMemory pWTSFreeMemory = NULL;
    
        HMODULE hLib = LoadLibrary( "wtsapi32.dll" );
        if( !hLib )
        {
            return false;
        }
        pWTSQuerySessionInformation = (WTSQuerySessionInformation) GetProcAddress( hLib, "WTSQuerySessionInformationW" );
        if( pWTSQuerySessionInformation )
        {
            pWTSFreeMemory = (WTSFreeMemory) GetProcAddress( hLib, "WTSFreeMemory" );
            if( pWTSFreeMemory != NULL )
            {
                DWORD dwSessionID = WTSGetActiveConsoleSessionId();
                if( pWTSQuerySessionInformation( WTS_CURRENT_SERVER_HANDLE, 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;
                }
            }
        }
        if( hLib != NULL )
        {
            FreeLibrary( hLib );
        }
        return bRet;
    }
    

提交回复
热议问题