共用方式為


列舉進程的所有模組

若要判斷哪些進程已載入特定 DLL,您必須列舉每個進程的模組。 下列範例程式代碼會使用 EnumProcessModules 函式來列舉系統中目前進程的模組。

#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <psapi.h>

// To ensure correct resolution of symbols, add Psapi.lib to TARGETLIBS
// and compile with -DPSAPI_VERSION=1

int PrintModules( DWORD processID )
{
    HMODULE hMods[1024];
    HANDLE hProcess;
    DWORD cbNeeded;
    unsigned int i;

    // Print the process identifier.

    printf( "\nProcess ID: %u\n", processID );

    // Get a handle to the process.

    hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
                            PROCESS_VM_READ,
                            FALSE, processID );
    if (NULL == hProcess)
        return 1;

   // Get a list of all the modules in this process.

    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.

                _tprintf( TEXT("\t%s (0x%08X)\n"), szModName, hMods[i] );
            }
        }
    }
    
    // Release the handle to the process.

    CloseHandle( hProcess );

    return 0;
}

int main( void )
{

    DWORD aProcesses[1024]; 
    DWORD cbNeeded; 
    DWORD cProcesses;
    unsigned int i;

    // Get the list of process identifiers.

    if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
        return 1;

    // Calculate how many process identifiers were returned.

    cProcesses = cbNeeded / sizeof(DWORD);

    // Print the names of the modules for each process.

    for ( i = 0; i < cProcesses; i++ )
    {
        PrintModules( aProcesses[i] );
    }

    return 0;
}

main 函式會使用 EnumProcesses 函式來取得進程清單。 針對每個進程,main 函式會呼叫 PrintModules 函式,並傳遞進程標識碼。 PrintModules 接著會呼叫 OpenProcess 函式,以取得進程句柄。 如果 OpenProcess 失敗,則輸出只會顯示進程識別碼。 例如,嘗試使用 OpenProcess 開啟空閒和 CSRSS 處理程序會失敗,因為其存取限制會阻止使用者層級程式碼開啟它們。 接下來,PrintModules 會呼叫 EnumProcessModules 函式,以取得模組句柄函式。 最後,PrintModules 會呼叫 GetModuleFileNameEx 函式,每個模組一次,以取得模組名稱。