#include <windows.h>
#include <wtsapi32.h>
#include <stdio.h>
#pragma comment(lib, "wtsapi32.lib")
BOOL CreateProcessAsUserInSession(DWORD dwSessionId, LPCTSTR lpApplicationName, LPTSTR lpCommandLine) {
HANDLE hToken = NULL;
HANDLE hNewToken = NULL;
STARTUPINFO si;
PROCESS_INFORMATION pi;
BOOL bResult = FALSE;
// 打开指定会话的用户令牌
if (!WTSQueryUserToken(dwSessionId, &hToken)) {
printf("WTSQueryUserToken failed (%d)\n", GetLastError());
goto Cleanup;
}
// 复制令牌
if (!DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, NULL, SecurityIdentification, TokenPrimary, &hNewToken)) {
printf("DuplicateTokenEx failed (%d)\n", GetLastError());
goto Cleanup;
}
// 初始化 STARTUPINFO 结构
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.lpDesktop = TEXT("winsta0\\default"); // 指定桌面
// 创建进程
if (!CreateProcessAsUser(hNewToken, lpApplicationName, lpCommandLine, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) {
printf("CreateProcessAsUser failed (%d)\n", GetLastError());
goto Cleanup;
}
// 关闭进程和线程句柄
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
bResult = TRUE;
Cleanup:
if (hToken) CloseHandle(hToken);
if (hNewToken) CloseHandle(hNewToken);
return bResult;
}
int main() {
DWORD dwSessionId = WTSGetActiveConsoleSessionId(); // 获取当前活动会话ID
TCHAR szCommandLine[] = TEXT("notepad.exe");
if (CreateProcessAsUserInSession(dwSessionId, NULL, szCommandLine)) {
printf("Process created successfully in session %d\n", dwSessionId);
} else {
printf("Failed to create process in session %d\n", dwSessionId);
}
return 0;
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
所有评论(0)