All pastes #962507 Raw Edit

Something

public text v1 · immutable
#962507 ·published 2008-03-29 20:19 UTC
rendered paste body
unsigned long FindProcessId(std::wstring ProcessName)
{
    unsigned long ProcessIds[256];
    unsigned long _bytesReturned;
    unsigned long _totalProcesses;
    wchar_t fileName[256];
    std::wstring executableName;
    HANDLE hProcess;

    std::wstring upperOne, upperTwo;

    if (EnumProcesses(ProcessIds, sizeof(ProcessIds), &_bytesReturned) == 0)
    {
        sConsole.OutError(L"FindProcessId: EnumProcesses has returned 0!");
        ErrorExit(L"EnumProcesses");
    }

    _totalProcesses = (_bytesReturned / 4);

    for (unsigned int i = 0; i < _totalProcesses; i++)
    {
        hProcess = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessIds[i]);
        if (!hProcess)
        {
            sConsole.OutDebug(L"Cannot ::OpenProcess, continue");
            continue;
        }

        GetModuleFileNameEx(hProcess, NULL, fileName, 128);
        executableName = fileName;

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

        upperOne = ProcessName;
        std::transform(upperOne.begin(), upperOne.end(), upperOne.begin(), ::toupper);
        upperTwo = executableName;
        std::transform(upperTwo.begin(), upperTwo.end(), upperTwo.begin(), ::toupper);

        if (upperOne == upperTwo)
        {
            CloseHandle(hProcess);
            sConsole.OutNormal(L"FindProcessId: Found %s process id: %i", ProcessName.c_str(), ProcessIds[i]);
            return ProcessIds[i];
        }
        else
            CloseHandle(hProcess);
    }

    sConsole.OutNormal(L"FindProcessId: Cannot find %s process id.", ProcessName.c_str());
    return 0;
}