The problem is that you are using the TCHAR
versions of Process32First()
/Process32Next()
, and your debugger screnshot clearly shows that you are compiling your project for Unicode, so TCHAR
maps to WCHAR
and thus process.szExeFile
is a WCHAR[]
array. You are incorrectly type-casting that array to a char*
pointer. You cannot directly compare a Unicode string to an Ansi string. You need to convert one string to the encoding of the other string before then comparing them.
You are also leaking the HANDLE
returned by CreateToolhelp32Snapshot()
.
Since you are passing an Ansi std::string
as input to your GetProcessValues()
function, the easiest solution would be to use the Ansi versions of Process32First()
/Process32Next()
instead, so process.szExeFile
is now a CHAR[]
array, and thus no conversion is needed:
HANDLE GetProcessValues(std::string ProcName)
{
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE)
return NULL;
PROCESSENTRY32A process;
ZeroMemory(&process, sizeof(process));
process.dwSize = sizeof(process);
const char* ProcNameChar = ProcName.c_str();
HANDLE hProc = NULL;
if (Process32FirstA(snapshot, &process))
{
do
{
if (_stricmp(process.szExeFile, ProcNameChar) == 0)
{
hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process.th32ProcessID);
break;
}
}
while (Process32NextA(snapshot, &process));
}
CloseHandle(snapshot);
return hProc;
}
However, you really should stay away from using Ansi APIs. Windows is a Unicode-based OS, and has been for a long time. Use Unicode APIs instead:
HANDLE GetProcessValues(std::wstring ProcName)
{
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE)
return NULL;
PROCESSENTRY32W process;
ZeroMemory(&process, sizeof(process));
process.dwSize = sizeof(process);
const wchar_t* ProcNameChar = ProcName.c_str();
HANDLE hProc = NULL;
if (Process32FirstW(snapshot, &process))
{
do
{
if (_wcsicmp(process.szExeFile, ProcNameChar) == 0)
{
hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process.th32ProcessID);
break;
}
}
while (Process32NextW(snapshot, &process));
}
CloseHandle(snapshot);
return hProc;
}
If your ProcName
parameter absolutely must be a std::string
, then you can either:
convert ProcName
to Unicode using MultiByteToWideChar()
, std::wstring_convert
, etc, and then compare that result to the strings returned by the Unicode API.
convert strings from the Unicode API to Ansi using WideCharToMultiByte()
, std::wstring_convert
, etc, and then compare those results to ProcName
.