I don't know what something wrong with my code. i already put condition when the handle is invalid. it will CloseHandle. but it seems not work. this code trying to get processName. when i input exist PID. it return the processName. opposite when i input doesn't exist PID like 10000. it return handle is invalid. and Error Exception throw. but in my code i already put condition when invalid. it will Close Handle.
std::wstring GetProcessNameById(DWORD i_processId)
{
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, i_processId);
if (hProcess != NULL)
{
wchar_t processFilePath[MAX_PATH];
if (GetModuleFileNameExW(hProcess, NULL, processFilePath, MAX_PATH))
{
CloseHandle(hProcess);
wchar_t *processFileName = PathFindFileNameW(processFilePath);
return processFileName;
}
else
{
CloseHandle(hProcess);
SystemErrorMessage();
}
}
else
{
CloseHandle(hProcess);
SystemErrorMessage();
}
}
int main()
{
std::wcout << GetProcessNameById(10000);
return 0;
}