Enumerating Modules with CreateToolhelp32Snapshot

Here is a quick and dirty example in C++ showing how to use CreateToolhelp32Snapshot to enumerate modules loaded by processes running on a Windows machine.

CreateToolhelp32Snapshot is part of the Tool Helper Library.

#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
#include <iostream>

DWORD EnumModules(DWORD pid) {
	HANDLE modulesnap = INVALID_HANDLE_VALUE;
	MODULEENTRY32 mod;

	modulesnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid);
	if (modulesnap == INVALID_HANDLE_VALUE) {
		return GetLastError();
	}

	mod.dwSize = sizeof(MODULEENTRY32);

	if (!Module32First(modulesnap, &mod)) {
		CloseHandle(modulesnap);
		return GetLastError();
	}

	do {
		std::wcout << "\t" << mod.szExePath << std::endl;
	} while (Module32Next(modulesnap, &mod));

	CloseHandle(modulesnap);
	return NO_ERROR;
}

DWORD EnumProcs() {
	HANDLE snap;
	PROCESSENTRY32 pe;
	DWORD pid = 0;

	snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (snap == INVALID_HANDLE_VALUE) {
		return GetLastError();
	}

	pe.dwSize = sizeof(PROCESSENTRY32);

	if (!Process32First(snap, &pe)) {
		CloseHandle(snap);
		return GetLastError();
	}

	do {
		std::wcout << pe.th32ProcessID << " " << pe.szExeFile << " " << pe.cntThreads << " " << pe.th32ParentProcessID << std::endl;
		EnumModules(pe.th32ProcessID);

	} while (Process32Next(snap, &pe));

	CloseHandle(snap);

	return NO_ERROR;
}

int main() {
	EnumProcs();
	return NO_ERROR;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s