Categories > Coding > C++ >
Why does this return process id 0
Posted
#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>
#include <tchar.h>
DWORD GetProcId(const wchar_t* ProcName) {
DWORD procId = 0;
HANDLE wandle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (wandle == INVALID_HANDLE_VALUE) {
printf("asdw");
}
PROCESSENTRY32 proc;
proc.dwSize = sizeof(proc);
if (Process32First(wandle, &proc)) {
do {
if ((const wchar_t*)proc.szExeFile == ProcName) {
procId = proc.th32ProcessID;
break;
}
} while (Process32Next(wandle, &proc));
}
CloseHandle(wandle);
return procId;
}
int main()
{
DWORD procId = GetProcId(L"mpv.exe");
std::cout << procId << std::endl;
std::cin.get();
}
Well why does procId equal
Don't buy exploits its not worth it your gonna quit anyway
Taking accountability will help you excel in life
Replied
the first issue you made was trying to make an ANSI string wide, you can't just cast it. There's a struct specifically for the wide version of PROCESSENTRY32 (PROCESSENTRY32W), and second when you're doing "==" you have to understand that you're comparing the pointers, the only time that would work is if the compiler optimized 2 constant strings to point to the same thing, in a dynamic scenario that wouldn't work.
Here's some improved code
#include <iostream>
#include <Windows.h>
#include <tlhelp32.h>
#include <tchar.h>
std::uint32_t get_proc_id(const std::wstring& name)
{
auto result = 0ul;
auto snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE)
return result;
auto pe32w = PROCESSENTRY32W{}; // use the wide version of the struct
pe32w.dwSize = sizeof(PROCESSENTRY32W);
if (!Process32FirstW(snapshot, &pe32w))
return CloseHandle(snapshot), result;
while (Process32NextW(snapshot, &pe32w))
{
if (name == pe32w.szExeFile) // use std::wstring's operator, not comparing pointers here
{
result = pe32w.th32ProcessID;
break;
}
}
CloseHandle(snapshot);
return result;
}
int main()
{
const auto pid = get_proc_id(L"explorer.exe");
std::cout << pid;
std::cin.get();
}
Cancel
Post
when the function got hennessey
Don't buy exploits its not worth it your gonna quit anyway
Taking accountability will help you excel in life
Replied
@0x90 your code is trash, do you even know C++ or are you just pretending to be something bigger than you actually are?
auto is bad practice in C++, and stop using snake_case
Cancel
Post
Replied
@dynamic_cast you're funny lol.
You should've done some research before you made yourself look stupid.
Even basic C++ programmers know AAA practice in C++, and why don't you take a look at the STL, it's snake_case for a reason, of course you think you're better than the libstdc++ devs, the people who literally define modern.
Cancel
Post
Users viewing this thread:
( Members: 0, Guests: 1, Total: 1 )
Cancel
Post