1 void ImpersonateConsoleSession(DWORD dwSessionId)
2 {
3 PROCESSENTRY32 procEntry;
4 HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5 procEntry.dwSize = sizeof(PROCESSENTRY32);
6 Process32First(hSnap, &procEntry);
7 DWORD winlogonPid = 0;
8 do {
9 if (!wcscmp(procEntry.szExeFile, L"winlogon.exe"))
10 {
11 DWORD winlogonSessId = 0;
12 if (ProcessIdToSessionId(procEntry.th32ProcessID, &winlogonSessId) && winlogonSessId == dwSessionId)
13 {
14 winlogonPid = procEntry.th32ProcessID;
15 break;
16 }
17 }
18 } while (Process32Next(hSnap, &procEntry) != 0);
19 CloseHandle(hSnap);
20 if (winlogonPid)
21 {
22 HANDLE hProcess = OpenProcess(MAXIMUM_ALLOWED, 0, winlogonPid);
23 HANDLE hPToken;
24 OpenProcessToken(hProcess, TOKEN_QUERY | TOKEN_DUPLICATE, &hPToken);
25 CloseHandle(hProcess);
26 HANDLE hUserTokenDup;
27 DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, 0, SecurityIdentification, TokenPrimary, &hUserTokenDup);
28 CloseHandle(hPToken);
29 ImpersonateLoggedOnUser(hUserTokenDup);
30 CloseHandle(hUserTokenDup);
31 }
32 }
ImpersonateConsoleSession(WTSGetActiveConsoleSessionId());
HANDLE hdevice = CreateFile(..., SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, 0);
RevertToSelf();
转自:https://oomake.com/question/1063645