获取一个指定的windows程序的模块句柄 c++代码
以下是获取一个指定的windows程序的模块句柄的C++代码示例:
#include <windows.h>
// Function to get module handle of a specified process
HMODULE GetModuleHandleOfProcess(DWORD pid, const char* moduleName)
{
// Get handle to the specified process
HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
if (processHandle == NULL)
return NULL;
// Enumerate the modules of the specified process
HMODULE moduleHandles[1024];
DWORD cbNeeded;
if (EnumProcessModules(processHandle, moduleHandles, sizeof(moduleHandles), &cbNeeded))
{
// Get the number of modules
int numModules = cbNeeded / sizeof(HMODULE);
// Iterate through the modules and find the one with the specified name
for (int i = 0; i < numModules; ++i)
{
char moduleNameBuffer[MAX_PATH];
if (GetModuleBaseName(processHandle, moduleHandles[i], moduleNameBuffer, sizeof(moduleNameBuffer)) > 0)
{
if (_stricmp(moduleNameBuffer, moduleName) == 0)
{
// Return the module handle
CloseHandle(processHandle);
return moduleHandles[i];
}
}
}
}
CloseHandle(processHandle);
return NULL;
}
int main()
{
// Get the module handle of Notepad.exe
HMODULE moduleHandle = GetModuleHandleOfProcess(1234, "notepad.exe");
if (moduleHandle == NULL)
{
printf("Could not find module handle.\n");
return 1;
}
printf("Module handle: 0x%X\n", moduleHandle);
return 0;
}
在上述代码中,GetModuleHandleOfProcess函数接受两个参数:进程ID和模块名称。它首先使用OpenProcess函数打开指定的进程句柄,然后使用EnumProcessModules函数枚举该进程的所有模块,并使用GetModuleBaseName函数获取每个模块的名称。最后,该函数将模块名称与指定的名称进行比较,如果匹配,则返回该模块的句柄。如果没有找到匹配的模块,则返回NULL。在上面的示例中,我们在主函数中调用GetModuleHandleOfProcess函数以获取Notepad.exe的模块句柄。如果找到了模块句柄,则将其打印到控制台上。
原文地址: https://www.cveoy.top/t/topic/bGVE 著作权归作者所有。请勿转载和采集!