下面來看一個VC++根據explorer.exe進程檢測用戶是否已登錄,希望例子能幫助到各位。
代碼如下void CALLBACK timeCall(UINT timeid, UINT umsg, DWORD_PTR dwUser, DWORD dw1, DWORD_PTR dw2)
{
DWORD dwSessionId = WTSGetActiveConsoleSessionId(); //獲取控制台的session
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); //為創建環境快照
if (hSnap == INVALID_HANDLE_VALUE)
return;
//遍歷快照,通過快照的 procEntry.szExeFile 獲取應用程序名字,從而取得相應的PID
PROCESSENTRY32 procEntry;
procEntry.dwSize = sizeof(PROCESSENTRY32);
Process32First(hSnap, &procEntry);
DWORD dwExplorerPid = -1;
do
{
if (strcmp(procEntry.szExeFile, "explorer.exe") == 0)
{
DWORD dwExplorerSessId = 0;
if (ProcessIdToSessionId(procEntry.th32ProcessID, &dwExplorerSessId) && dwExplorerSessId == dwSessionId)
{
dwExplorerPid = procEntry.th32ProcessID;
break;
}
}
} while (Process32Next(hSnap, &procEntry));
LOG_INFO("檢測用戶是否已經登錄 : %s", (dwExplorerPid == -1) ? "未登錄" : "已經登錄");
if (dwExplorerPid != -1)
{
//已登錄
DoSomething();
}
}