0

我有以下问题:

我想通过使用 CreateToolhelp32Snapshot 和 Process32First/Next 来跟踪正在运行的进程。但是我想默认使用 Unicode 字符集。

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;
}

但是,如果我使用多字节字符集,一切正常。

4

1 回答 1

0

您必须初始化entry并设置dwSize值。dwSizevalue 是 Windows 的版本控制思想,是必需的:

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

比较不应该区分大小写:

while (Process32Next(snapshot, &entry))
{
    if (_wcsicmp(process_name.c_str(), entry.szExeFile) == 0)
    {
        CloseHandle(snapshot);
        return true;
    }
}
于 2016-11-05T18:48:33.253 回答