下面的这个函数可以获取Windows是否处于锁屏状态:
代码来自stackoverflow,C++: check if computer is locked。
#include <Windows.h>
#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(L"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;
}
我们可以简单地写一个测试程序,然后在锁屏和不锁屏之间切换,看看输出是否符合期望。
int main()
{
while (true)
{
std::cout << std::boolalpha << IsSessionLocked() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
}
return 0;
}