I'm using the following code to try to get the PID of notepad.exe
, but it doesn't find the process.
I'm currently running on Windows 10 and compiling using VS Studio 19 as Release x64.
Also tried to find other processes, like chrome.exe
, calculator.exe
, etc, but couldn't find anything.
DWORD GetProcessId(LPCTSTR ProcessName)
{
PROCESSENTRY32 pt;
HANDLE hsnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
std::wcout << "Error: " << GetLastError() << std::endl; // Error: 0
pt.dwSize = sizeof(PROCESSENTRY32);
std::wcout << "Error: " << GetLastError() << std::endl; // Error: 0
if (Process32First(hsnap, &pt)) { // must call this first
do {
if (!lstrcmpi(pt.szExeFile, ProcessName)) {
CloseHandle(hsnap);
return pt.th32ProcessID;
}
} while (Process32Next(hsnap, &pt));
}
std::wcout << "Error: " << GetLastError() << std::endl; // Error: 24
CloseHandle(hsnap); // close handle on failure
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
DWORD processId;
processId = GetProcessId(TEXT("notepad.exe"));
std::wcout << "processId: " << processId << std::endl;
return 0;
}
While debugging, I see the code is skipping the do while
and jumping directly to CloseHandle(hsnap)
GetLastError()
returns 24 at this line.
CodePudding user response:
The image you posted of your debug output window shows pt.dwSize
is set to 2168
. This looks wrong. pt.dwSize
is important, it used by Windows for version control.
On my computer sizeof(PROCESSENTRY32)
is 556
(it depends on Windows version, I am using Windows 10). If project is not Unicode, the size should about half that. In VS, you can right click on PROCESSENTRY32
and it takes you to this definition:
typedef struct tagPROCESSENTRY32W
{
DWORD dwSize;
DWORD cntUsage;
DWORD th32ProcessID; // this process
ULONG_PTR th32DefaultHeapID;
DWORD th32ModuleID; // associated exe
DWORD cntThreads;
DWORD th32ParentProcessID; // this process's parent process
LONG pcPriClassBase; // Base priority of process's threads
DWORD dwFlags;
WCHAR szExeFile[MAX_PATH]; // Path
} PROCESSENTRY32W;
MAX_PATH
should be 260
. My guess is that you have redefined MAX_PATH
or you have put the wrong #pragma
statement somewhere. Or there is something weird happening. Try restarting Windows (use Restart instead of shutdown/start)
Also, zero the memory with PROCESSENTRY32 pt = {0}
PROCESSENTRY32 pt = { 0 };
pt.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(hsnap, &pt))
{
DWORD err = GetLastError();
std::cout << "Process32First failed\n";
std::cout << pt.dwSize << " GetLastError : " << err << "\n";
CloseHandle(hsnap);
return DWORD(-1);
}
The only expected GetLastError
is ERROR_NO_MORE_FILES
as shown in Windows documentation. If the error is something else, it means the function has totally failed.
If your project is Unicode, as it should be, consider avoiding those T
macros. Just use GetProcessId(L"notepad.exe");
and LPCWSTR
etc.
Ps, I ran your code and it was fine in my computer. The only difference was sizeof(PROCESSENTRY32)