最近碰到个问题, 需要在服务中检测用户桌面的情况。但是服务程序都是SYSTEM账户下运行, 属于Session0, 不能检测到用户桌面的情况。所以就需要另启一个用户进程来获取这些信息, 然后发送给服务。所以就用到了 CreateProcessAsUser来创建用户进程。
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <Wtsapi32.h>
#include <TlHelp32.h>
#pragma comment(lib, "wtsapi32.lib")
#include <Userenv.h>
#pragma comment(lib,"userenv.lib")
using namespace std;
typedef struct _TOKEN_LINKED_TOKEN {
HANDLE LinkedToken;
} TOKEN_LINKED_TOKEN, *PTOKEN_LINKED_TOKEN;
SERVICE_STATUS_HANDLE hServiceStatus;
SERVICE_STATUS ServiceStatus;
DWORD GetActiveSessionID()
{
DWORD dwSessionId = 0;
PWTS_SESSION_INFO pSessionInfo = NULL;
DWORD dwCount = 0;
WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pSessionInfo, &dwCount);
for(DWORD i = 0; i < dwCount; i++)
{
WTS_SESSION_INFO si = pSessionInfo[i];
if(WTSActive == si.State)
{
dwSessionId = si.SessionId;
break;
}
}
WTSFreeMemory(pSessionInfo);
return dwSessionId;
}
BOOL ServiceExecute(std::wstring wstrCmdLine, INT32& n32ExitResult)
{
ofstream ofile("C:\\logEvent.txt");
ofile<<"start excute"<<std::endl;
DWORD dwProcesses = 0;
BOOL bResult = FALSE;
DWORD dwSid = GetActiveSessionID();
DWORD dwRet = 0;
PROCESS_INFORMATION pi;
STARTUPINFO si;
HANDLE hProcess = NULL, hPToken = NULL, hUserTokenDup = NULL;
if (!WTSQueryUserToken(dwSid, &hPToken))
{
ofile<<"get token error 1"<<std::endl;
PROCESSENTRY32 procEntry;
DWORD dwPid = 0;
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap == INVALID_HANDLE_VALUE)
{