I try to detect the process name of a currently active window. I have the following code.
#include <iostream>
#include <functional>
#include <thread>
#include <windows.h>
#include <Psapi.h>
using namespace std;
int main()
{
while (true) {
wchar_t buffer[512];
HWND hwnd = GetForegroundWindow(); // get handle of currently active window
DWORD processId;
GetWindowThreadProcessId(hwnd, &processId);
auto processHandle = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, false, processId);
DWORD length = sizeof(buffer) / sizeof(buffer[0]);
auto success = QueryFullProcessImageNameW(processHandle, 0, buffer, &length);
if (success) {
wcout << endl << buffer << endl;
}
else {
wcout << endl << L"An error has occurred. Code: " << GetLastError() << endl;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
It works well, but currently the path to the executable is printed into the console, e.g.
C:\Program Files (x86)\Opera\68.0.3618.63\opera.exe
But I would like to get a human readable name of the process, as in the Windows Task Manager, that is:
Opera Internet Browser
Also, when I select the Task Manager's window, the current code just prints an error code:
An error has occurred. Code: 6
Thus, how to get a process name like in the Task Manager via WinAPI?