Skip to content

Instantly share code, notes, and snippets.

@FrendaWinter
Created December 17, 2024 07:57
Show Gist options
  • Save FrendaWinter/6b5c0e58ac5fce9e8f669f7fe7478bba to your computer and use it in GitHub Desktop.
Save FrendaWinter/6b5c0e58ac5fce9e8f669f7fe7478bba to your computer and use it in GitHub Desktop.
Check user login using Windows API
// 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