Process snapshot can't be compared against wide strings

442 views Asked by At

I have the following problem:

I want to keep track of the running processes by using CreateToolhelp32Snapshot and Process32First/Next. However I want to use the Unicode charset by default.

bool active( const std::wstring& process_name )
{
    HANDLE snapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );

    if ( snapshot == INVALID_HANDLE_VALUE )
        return false;

    PROCESSENTRY32 entry;

    if ( Process32First( snapshot, &entry ) )
    {
        if ( process_name.compare( entry.szExeFile ) == 0 )
        {
            CloseHandle( snapshot );
            return true;
        }
    }

    while ( Process32Next( snapshot, &entry ) )
    {
        if ( process_name.compare( entry.szExeFile ) == 0 )
        {
            CloseHandle( snapshot );
            return true;
        }
    }

    CloseHandle( snapshot );

    return false;
}

int main( )
{
    SetConsoleTitle( L"Lel" );

    if ( active( L"notepad++.exe" ) )
        std::cout << "Hello" << std::endl;
    else
        std::cout << ":(" << std::endl;
}

However, if I use multibyte-charset everything's working fine.

1

There are 1 answers

2
Barmak Shemirani On

You must initialize entry and set dwSize value. dwSize value is Windows's idea of version control and is required:

PROCESSENTRY32 entry = { 0 };
entry.dwSize = sizeof(PROCESSENTRY32);

Comparison should not be case sensitive:

while (Process32Next(snapshot, &entry))
{
    if (_wcsicmp(process_name.c_str(), entry.szExeFile) == 0)
    {
        CloseHandle(snapshot);
        return true;
    }
}