Share via


列舉進程的所有模組

若要判斷哪些進程已載入特定 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 失敗,輸出只會顯示進程識別碼。 例如,Idle 和 CSRSS 進程的 OpenProcess 失敗,因為其存取限制會防止使用者層級的程式碼開啟它們。 接下來,PrintModules 會呼叫 EnumProcessModules 函式,以取得模組控制碼函式。 最後,PrintModules 會針對每個模組呼叫 GetModuleFileNameEx 函式一次,以取得模組名稱。