萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

C++ 檢測 explorer.exe 進程判斷使用者是否已登入 Windows

在 Windows 服務或無 UI 應用程式中,需判斷目前是否有使用者互動登入 (非服務帳號、非遠端桌面離線)。常見做法是檢查 **目前作用中 Session (WTSGetActiveConsoleSessionId) 下是否存在 `explorer.exe` 進程**。本文提供完整 C++ 代碼、錯誤處理、權限說明與替代方案。

核心邏輯

  1. 取得 **主控台 Session ID** (`WTSGetActiveConsoleSessionId`),通常為 1 (本機登入)。
  2. 建立進程快照 (`CreateToolhelp32Snapshot`)。
  3. 遍歷進程 (`Process32First/Next`),比對 `szExeFile == "explorer.exe"`。
  4. 對候選進程呼叫 `ProcessIdToSessionId` 取得其 Session ID,若等於主控台 Session ID → **使用者已登入**。

完整代碼 (可編譯為 DLL/EXE)

#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 說明

API用途需連結庫
WTSGetActiveConsoleSessionId取得實體主控台 Session ID (通常 1)Wtsapi32.lib
CreateToolhelp32Snapshot建立系統進程快照Kernel32.lib
Process32FirstW / Process32NextW遍歷進程 (Unicode 版)Kernel32.lib
ProcessIdToSessionId取得進程所屬 Session IDKernel32.lib
timeSetEvent / timeKillEvent多媒體定時器 (高精度週期性)Winmm.lib

權限與部署注意

  • **服務執行身分**:若作為 Windows Service 執行,需以 **LocalSystem** 或具備 `SeTcbPrivilege` 的帳號運行,才能枚舉所有 Session 進程。
  • **位元數一致**:64-bit 進程才能正確枚舉 64-bit `explorer.exe`;建議編譯為 x64。
  • **Session 0 隔離**:Vista+ 服務運行於 Session 0,無法直接啟動 UI 進程;若需啟動使用者桌面程序,需用 `WTSQueryUserToken` + `CreateProcessAsUser`。
  • **多使用者/遠端桌面**:`WTSGetActiveConsoleSessionId` 僅回傳主控台 Session;RDP 連線屬於不同 Session,若需偵測所有互動 Session,改用 `WTSEnumerateSessions` 篩選 `WTSActive` 狀態。

替代方案 (C# / .NET)

// 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();

適用場景

  • 自動化測試代理:等待使用者登入後再啟動 UI 自動化腳本。
  • 數位看板/自助機:偵測使用者在場,喚醒畫面或重置閒置計時。
  • 安全稽核:記錄互動登入/登出時間軸。

透過 `explorer.exe` 存在性判斷互動登入,是 Windows 平台經典且可靠的做法;結合 Session ID 過濾可精準排除系統服務進程與遠端桌面殘留進程。

copyright © 萬盛學電腦網 all rights reserved