Retrieves a list of all the modules that have been loaded into a specified process.
BOOL EnumProcessModules(
<a href="/docs/windows/api/psapi/nf-psapi-openprocess">HANDLE</a> hProcess,
<a href="/docs/windows/api/psapi/ns-psapi-lpmoduleinfo">LPMODULEINFO</a> lpBaseArr,
DWORD cb,
LPDWORD lpcbNeeded
);
PROCESS_QUERY_INFORMATION or PROCESS_QUERY_LIMITED_INFORMATION access right.
MODULEINFO structures that receives the module information.
lpBaseArr parameter, in bytes.
lpBaseArr is not large enough, this variable will contain the number of bytes required.
GetLastError.The EnumProcessModules function retrieves information about all the modules that have been loaded into a specified process. The information is returned as an array of MODULEINFO structures.
To get the handle to the process, you can use the OpenProcess function.
The maximum number of modules that can be enumerated for a process is limited by the available memory.
EnumProcessModules twice. The first call retrieves the required buffer size in lpcbNeeded. Then, allocate a buffer of that size and call the function again to fill the buffer with module information.
The following C++ code snippet demonstrates how to use EnumProcessModules to list the modules loaded by a process:
#include <windows.h>
#include <psapi.h>
#include <iostream>
#include <vector>
// Function to get the module name from a module handle
std::wstring GetModuleName(HANDLE hProcess, HMODULE hModule) {
WCHAR szBuffer[MAX_PATH];
if (GetModuleFileNameExW(hProcess, hModule, szBuffer, MAX_PATH)) {
return szBuffer;
}
return L"Unknown Module";
}
int main() {
// Get the handle to the current process
HANDLE hProcess = GetCurrentProcess();
if (hProcess == NULL) {
std::cerr << "Failed to get current process handle. Error: " << GetLastError() << std::endl;
return 1;
}
// Get the number of modules and the required buffer size
DWORD cbNeeded;
if (!EnumProcessModules(hProcess, NULL, 0, &cbNeeded)) {
std::cerr << "Failed to get module count. Error: " << GetLastError() << std::endl;
CloseHandle(hProcess);
return 1;
}
// Allocate buffer to store module handles
DWORD cch = cbNeeded / sizeof(HMODULE);
std::vector<HMODULE> hMods(cch);
// Enumerate the modules
if (!EnumProcessModules(hProcess, hMods.data(), cbNeeded, &cbNeeded)) {
std::cerr << "Failed to enumerate modules. Error: " << GetLastError() << std::endl;
CloseHandle(hProcess);
return 1;
}
// Print the module names
std::wcout << L"Modules loaded in current process:" << std::endl;
for (unsigned int i = 0; i < cch; i++) {
std::wcout << L" - " << GetModuleName(hProcess, hMods[i]) << std::endl;
}
CloseHandle(hProcess);
return 0;
}