DWORD Snapshots::getWindow(const char* windowName)
{
initVariables::hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pEntry; /// new variable named pEntry, that works around tagPROCESSENTRY32
pEntry.dwSize = sizeof(PROCESSENTRY32); /// compiler will deny any other value that doesn't fit in tagPROCESSEENTRY32 /// also using tagPROCESENTRY32
do
{
if (!strcmp(pEntry.szExeFile, windowName)) /// we compare the found exe to the exe's name we need.
{
}
return 0;
} while(Process32Next(initVariables::hSnapshot, &pEntry)); /// 1. arg = our handle 2. arg = us referencing pEntry as our lpme
return 0;
}
我正在使用多字节字符集,此错误仅在调试模式下发生,而在发布时则不然。
最佳答案
当项目字符集设置为Unicode(显然是这种情况)时,此代码将不会编译,因为strcmp()
接受char*
输入,而不是wchar_t*
输入。
由于代码使用的是Win32 API的TCHAR
版本,因此应使用_tcscmp()
进行匹配:
#include <tchar.h>
DWORD Snapshots::getWindow(const char* windowName)
{
initVariables::hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (initVariables::hSnapshot == INVALID_HANDLE_VALUE)
return 0;
PROCESSENTRY32 pEntry; /// new variable named pEntry, that works around tagPROCESSENTRY32
pEntry.dwSize = sizeof(PROCESSENTRY32); /// compiler will deny any other value that doesn't fit in tagPROCESSEENTRY32 /// also using tagPROCESENTRY32
if (Process32First(initVariables::hSnapshot, &pEntry))
{
do
{
if (!_tcscmp(pEntry.szExeFile, windowName)) /// we compare the found exe to the exe's name we need.
{
}
}
while (Process32Next(initVariables::hSnapshot, &pEntry)); /// 1. arg = our handle 2. arg = us referencing pEntry as our lpme
}
CloseHandle(initVariables::hSnapshot);
return 0;
}
但是,由于
windowName
是char*
而不是TCHAR*
,因此不受项目字符集的影响,请直接使用基于ANSI的API:#include <tchar.h>
DWORD Snapshots::getWindow(const char* windowName)
{
initVariables::hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (initVariables::hSnapshot == INVALID_HANDLE_VALUE)
return 0;
PROCESSENTRY32 pEntry; /// new variable named pEntry, that works around tagPROCESSENTRY32
pEntry.dwSize = sizeof(PROCESSENTRY32); /// compiler will deny any other value that doesn't fit in tagPROCESSEENTRY32 /// also using tagPROCESENTRY32
if (Process32FirstA(initVariables::hSnapshot, &pEntry))
{
do
{
if (!strcmp(pEntry.szExeFile, windowName)) /// we compare the found exe to the exe's name we need.
{
}
}
while (Process32NextA(initVariables::hSnapshot, &pEntry)); /// 1. arg = our handle 2. arg = us referencing pEntry as our lpme
}
CloseHandle(initVariables::hSnapshot);
return 0;
}
关于c++ - WCHAR类型的参数与const char *类型的参数不兼容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59002920/