本文共 2273 字,大约阅读时间需要 7 分钟。
DWORD dwCount = 0; PWTS_PROCESS_INFOA pi = { 0 }; int i = 0; DWORD dwSize = 0; char username[128] = { 0 }; SID_NAME_USE nameuse = SidTypeUser;char szUName[128];
DWORD dwNameSize;
char curusername[128]={0};
LPSTR pBuffer = NULL; DWORD dwBufferLen;//获得当前程序执行用户名
GetUserNameA(szUName,&dwNameSize);
//获取活动sessionid
DWORD dCurSessionId= WTSGetActiveConsoleSessionId();
//获取活动用户名
WTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE,dCurSessionId,WTSUserName,&pBuffer,&dwBufferLen); lstrcpyA(curusername ,pBuffer);WTSFreeMemory(pBuffer);
//判断是否相等 关闭进程
if (0!=strcmp(curusername,szUName)) { HANDLE hProcessHandle; ULONG nProcessID; ::GetWindowThreadProcessId( GetSafeHwnd(), &nProcessID ); hProcessHandle = ::OpenProcess( PROCESS_TERMINATE, FALSE, nProcessID ); BOOL bRet =::TerminateProcess( hProcessHandle, 0 ); }MessageBoxA(GetSafeHwnd(),szUName,"",0);
//枚举进程
if(WTSEnumerateProcessesA(NULL, 0, 1, &pi, &dwCount) ) { for( i = 0; i < dwCount; i++ ) { memset( username, 0, sizeof(char) * 128 ); dwSize = 128; if( LookupAccountSidA(NULL, pi[i].pUserSid, username, &dwSize, NULL, &dwSize, &nameuse) ) { char* str = new char[MAX_PATH]; sprintf(str,"Process Name: %s Process Id: %d Session Id: %d User Name: %s",pi[i].pProcessName,pi[i].ProcessId,pi[i].SessionId,username); MessageBoxA(GetSafeHwnd(),str,"",0); delete[] str; } }}
// 获取当前活动的会话id
DWORD WINAPI GetActiveSessionId() { PWTS_SESSION_INFO pSessionInfo; DWORD dwCount = 0; DWORD dwSessionId = 0; dwSessionId = ::WTSGetActiveConsoleSessionId(); if (dwSessionId <= 0){ if (!::WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pSessionInfo, &dwCount)){ return -1; } for (DWORD i = 0; i < dwCount; ++i){ WTS_SESSION_INFO si = pSessionInfo[i]; if (si.SessionId == WTSActive){ dwSessionId = si.SessionId; break; } } ::WTSFreeMemory(pSessionInfo); } return dwSessionId; }// 当前用户token
BOOL GetCurrentUserToken( HANDLE& h_primaryToken ) { BOOL bRet = FALSE; HANDLE h_currentToken = NULL; DWORD dwSessionId = 0; dwSessionId = GetActiveSessionId(); //sessionId = 0时错误 if (!::WTSQueryUserToken(dwSessionId, &h_currentToken)){ return bRet; } if (!::DuplicateTokenEx(h_currentToken, MAXIMUM_ALLOWED, NULL, SecurityIdentification, TokenPrimary, &h_primaryToken)){ return bRet; } bRet = TRUE; return bRet; }:CreateProcessAsUser
转载地址:http://reoxb.baihongyu.com/