在 Windows 服務或無 UI 應用程式中,需判斷目前是否有使用者互動登入 (非服務帳號、非遠端桌面離線)。常見做法是檢查 **目前作用中 Session (WTSGetActiveConsoleSessionId) 下是否存在 `explorer.exe` 進程**。本文提供完整 C++ 代碼、錯誤處理、權限說明與替代方案。
#include
#include
#include
#include
#pragma comment(lib, "Wtsapi32.lib")
// 回呼函數:定時器觸發
void CALLBACK TimerCallback(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD dw1, DWORD dw2) {
DWORD consoleSessionId = WTSGetActiveConsoleSessionId();
if (consoleSessionId == 0xFFFFFFFF) { // 無主控台 Session
OutputDebugString(L"[Detector] No active console session.\n");
return;
}
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap == INVALID_HANDLE_VALUE) {
OutputDebugString(L"[Detector] CreateToolhelp32Snapshot failed.\n");
return;
}
PROCESSENTRY32W pe = { sizeof(PROCESSENTRY32W) };
BOOL found = FALSE;
DWORD explorerPid = 0;
if (Process32FirstW(hSnap, &pe)) {
do {
if (_wcsicmp(pe.szExeFile, L"explorer.exe") == 0) {
DWORD pidSessionId = 0;
if (ProcessIdToSessionId(pe.th32ProcessID, &pidSessionId) && pidSessionId == consoleSessionId) {
explorerPid = pe.th32ProcessID;
found = TRUE;
break;
}
}
} while (Process32NextW(hSnap, &pe));
}
CloseHandle(hSnap);
wchar_t msg[256];
swprintf_s(msg, L"[Detector] User logged %s (Session=%lu, ExplorerPID=%lu)\n",
found ? L"ON" : L"OFF", consoleSessionId, explorerPid);
OutputDebugString(msg);
if (found) {
// 使用者已登入,執行業務邏輯
DoUserLoggedInWork();
}
}
void DoUserLoggedInWork() {
// TODO: 實際業務,如啟動 UI 進程、發送通知、同步資料等
OutputDebugString(L"[Detector] Executing user-logged-in work...\n");
}
int main() {
// 建立週期性定時器 (每 10 秒檢查一次)
TIMECAPS tc; timeGetDevCaps(&tc, sizeof(tc));
timeBeginPeriod(tc.wPeriodMin);
MMRESULT timerId = timeSetEvent(10000, tc.wPeriodMin, TimerCallback, 0, TIME_PERIODIC);
if (timerId == 0) {
fprintf(stderr, "timeSetEvent failed\n");
return 1;
}
printf("Detector running. Press Enter to exit...\n");
getchar();
timeKillEvent(timerId);
timeEndPeriod(tc.wPeriodMin);
return 0;
}
| API | 用途 | 需連結庫 |
|---|---|---|
| WTSGetActiveConsoleSessionId | 取得實體主控台 Session ID (通常 1) | Wtsapi32.lib |
| CreateToolhelp32Snapshot | 建立系統進程快照 | Kernel32.lib |
| Process32FirstW / Process32NextW | 遍歷進程 (Unicode 版) | Kernel32.lib |
| ProcessIdToSessionId | 取得進程所屬 Session ID | Kernel32.lib |
| timeSetEvent / timeKillEvent | 多媒體定時器 (高精度週期性) | Winmm.lib |
// C# 版本 (需引用 System.Diagnostics, System.Management)
public static bool IsUserLoggedOnInteractively() {
int sessionId = WTSGetActiveConsoleSessionId();
if (sessionId == 0xFFFFFFFF) return false;
var query = new ObjectQuery($"SELECT SessionId FROM Win32_Process WHERE Name = 'explorer.exe'");
using (var searcher = new ManagementObjectSearcher(query)) {
foreach (var obj in searcher.Get()) {
uint pidSessionId = (uint)obj["SessionId"];
if (pidSessionId == sessionId) return true;
}
}
return false;
}
[DllImport("wtsapi32.dll")] static extern int WTSGetActiveConsoleSessionId();
透過 `explorer.exe` 存在性判斷互動登入,是 Windows 平台經典且可靠的做法;結合 Session ID 過濾可精準排除系統服務進程與遠端桌面殘留進程。