获取当前进程所加载的模块列表

    HMODULE hMods[1024];
    HANDLE hProcess;
    DWORD cbNeeded;
    unsigned int i;

    CFile file;
    file.Open(L"d:\\mods.txt", CFile::modeCreate | CFile::modeReadWrite);

    // Get a list of all the modules in this process.
    // 关键在于获取当前进程的句柄
    // 直接使用 theApp.m_hInstance 或者 
    // AfxGetInstanceHandle() 获取的句柄
    // 在运行 EnumProcessModules() 函数时
    // 会到的“句柄无效”的错误
    // GetLastError() 返回 6
    // 因此,此处首先使用 GetCurrentProcessId() 
    // 获取进程 Id,再利用 OpenProcess()
    // 获取句柄即可

    hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
        PROCESS_VM_READ,
        FALSE, GetCurrentProcessId());

    if (NULL == hProcess)
        return;

    if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
    {
        for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
        {
            TCHAR szModName[MAX_PATH];

            // Get the full path to the module's file.

            if (GetModuleFileNameEx(hProcess, hMods[i], szModName,
                sizeof(szModName) / sizeof(TCHAR)))
            {
                // Print the module name and handle value.
                CStringA modName(szModName);
                file.Write(modName, modName.GetLength());
                file.Write("\r\n", 2);
                //_tprintf(TEXT("\t%s (0x%08X)\n"), szModName, hMods[i]);
            }
        }
    }
    DWORD lastError = GetLastError();
    file.Close();

你可能感兴趣的:(获取当前进程所加载的模块列表)