All pastes #962550 Raw Edit

Something

public text v1 · immutable
#962550 ·published 2008-03-29 20:56 UTC
rendered paste body
HMODULE FindModuleHandle(unsigned long ProcessId, const std::wstring ModuleName)
{
    HMODULE hModules[256];
    HANDLE hProcess;
    unsigned long _bytesReturned;
    unsigned char cTotalModules;
    wchar_t fileName[256];
    std::wstring ModName;

    std::wstring upperOne, upperTwo;

    hProcess = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessId);
    if (!hProcess)
    {
        sConsole.OutError(L"FindModuleHandle: Cannot open process!");
        ErrorExit(L"OpenProcess");
    }

    if (EnumProcessModules(hProcess, &hModules[0], sizeof(hModules), &_bytesReturned) == 0)
    {
        sConsole.OutError(L"FindModuleHandle: EnumProcessModules has returned 0!");
        ErrorExit(L"EnumProcessModules");
    }

    cTotalModules = static_cast<unsigned char>((_bytesReturned / 4));

    for (unsigned char i = 0; i < cTotalModules; i++)
    {
        GetModuleFileNameEx(hProcess, hModules[i], fileName, 128);
        ModName = fileName;

        if (ModName.length() > 3 && ModName.find(L"\\"))
        {
            ModName = ModName.substr(ModName.find_last_of(L"\\")+1, ModName.length()-1);
        }

        upperOne = ModuleName;
        std::transform(upperOne.begin(), upperOne.end(), upperOne.begin(), ::toupper);
        upperTwo = ModName;
        std::transform(upperTwo.begin(), upperTwo.end(), upperTwo.begin(), ::toupper);

        if (upperOne == upperTwo)
        {
            CloseHandle(hProcess);
            sConsole.OutNormal(L"FindModuleHandle: Found module handle: %s", ModName.c_str());
            return hModules[i];
        }
    }

    sConsole.OutNormal(L"FindModuleHandle: Cannot find module handle.");
    return NULL;
}