Created
December 17, 2024 07:57
-
-
Save FrendaWinter/6b5c0e58ac5fce9e8f669f7fe7478bba to your computer and use it in GitHub Desktop.
Check user login using Windows API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Complie with w64devkit: | |
// g++ main.cpp -o b -lWtsapi32 | |
#define SECURITY_WIN32 | |
#include <windows.h> | |
#include <Wtsapi32.h> | |
#include <iostream> | |
bool IsUserLoggedIn() | |
{ | |
WTS_SESSION_INFO *pSessionInfo = nullptr; | |
DWORD sessionCount = 0; | |
// Enumerate all sessions | |
if (!WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pSessionInfo, &sessionCount)) | |
{ | |
std::cerr << "Failed to enumerate sessions." << std::endl; | |
return false; | |
} | |
bool userLoggedIn = false; | |
// Iterate through all sessions to check if any are active | |
for (DWORD i = 0; i < sessionCount; ++i) | |
{ | |
if (pSessionInfo[i].State == WTSActive) | |
{ | |
userLoggedIn = true; | |
break; // Found an active user | |
} | |
} | |
// Clean up | |
if (pSessionInfo) | |
{ | |
WTSFreeMemory(pSessionInfo); | |
} | |
return userLoggedIn; | |
} | |
int main() | |
{ | |
if (IsUserLoggedIn()) | |
{ | |
std::cout << "A user is logged in." << std::endl; | |
} | |
else | |
{ | |
std::cout << "No user is logged in." << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment