Skip to content

Instantly share code, notes, and snippets.

@tbhaxor
Created Feb 24, 2020
Embed
What would you like to do?
Process listing api
#include <stdio.h>
#include <Windows.h>
#include <WtsApi32.h> // for process enumerations
#include <tchar.h>
#include <sddl.h>
#include "Source.h"
#define MAX_ACC_NAME 1000
#define MAX_DOM_NAME 1000
#pragma comment(lib, "wtsapi32")
#pragma comment(lib, "Advapi32")
int main()
{
DWORD pLevel = 0; // using this because we only want: WTS_PROCESS_INFO_EX
PWTS_PROCESS_INFO procInfo = NULL; // using this to hold all the processes
DWORD pCount; // this will hold all the process count
// finding process of WTS_CURRENT_SERVER_HANDLE and of WTS_ANY_SESSION
if (!WTSEnumerateProcessesEx(WTS_CURRENT_SERVER_HANDLE, &pLevel, WTS_ANY_SESSION, (LPWSTR*)&procInfo, &pCount))
{
_tprintf(_T("Can't enumerate process"));
}
else
{
// print total processes
_tprintf(_T("Total processes: %d\n"), pCount);
for (DWORD _ = 0; _ < pCount; _++)
{
_tprintf(_T("PID: %d\n"), procInfo->ProcessId);
_tprintf(_T("Process Name: %s\n"), procInfo->pProcessName);
TCHAR accountName[MAX_ACC_NAME];
DWORD bufferLen = MAX_ACC_NAME;
TCHAR domainName[MAX_DOM_NAME];
DWORD domainNameBufferLen = MAX_DOM_NAME;
SID_NAME_USE peUse;
LPWSTR SID = NULL;
if (ConvertSidToStringSid(procInfo->pUserSid, &SID))
{
_tprintf(_T("SID: %s\n"), SID);
}
else
{
_tprintf(_T("SID: -\n"));
}
LocalFree((HLOCAL)SID); // freeing the SID
if (LookupAccountSid(NULL, procInfo->pUserSid, (LPWSTR)accountName, &bufferLen, (LPWSTR)domainName, &domainNameBufferLen, &peUse))
{
_tprintf(_T("User Account: %s\\%s\n"), domainName, accountName);
}
else
{
_tprintf(_T("User Account: -\\-\n"));
}
_tprintf(_T("---------------------------------------\n"));
procInfo++;
}
// freeing the memory
WTSFreeMemoryEx(WTSTypeProcessInfoLevel1, procInfo, pCount);
procInfo = NULL; // this won't work, debugger triggering a breakpoint
return 0;
}
}
@eetoa
Copy link

eetoa commented Apr 3, 2021

pLevel = 0 is means we want to use WTS_PROCESS_INFOA but not WTS_PROCESS_INFO_EX.
btw, thnx for sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment