Reputation: 3911
I want to make a program that gets the name of the program that created an open window:
#include <iostream>
using namespace std;
#include <windows.h>
#include <Psapi.h>
#pragma comment(lib, "Psapi.lib")
int main()
{
system("color 1f");
DWORD dwProcessId;
DWORD dwThreadId ;
while(1)
{
Sleep(2000);
HWND hForg = GetForegroundWindow();
dwThreadId = GetWindowThreadProcessId(hForg, &dwProcessId);
//cout << "Thread Id: " << dwThreadId << endl;
//cout << "Process Id: " << dwProcessId << endl;
DWORD dwDesiredAccess = PROCESS_QUERY_INFORMATION | PROCESS_VM_READ;
bool bInheritHandle = false;
HANDLE hProcess = OpenProcess(dwDesiredAccess,
bInheritHandle, dwProcessId);
if(INVALID_HANDLE_VALUE == hProcess)
cout << "Failed to open process!" << endl;
HMODULE hMod = (HMODULE)GetWindowLongPtr(hForg, GWLP_HINSTANCE);
if(!hMod)
cout << "Null Module!" << endl;
char szModFileName[MAX_PATH];
GetModuleFileNameEx(hProcess, (HMODULE)hMod, szModFileName, MAX_PATH);
char szWindowName[MAX_PATH];
GetWindowText(hForg, szWindowName, MAX_PATH);
cout << "Window Name: " << szWindowName << endl;
cout << "Created by: " << szModFileName << endl << endl;
}
cout << endl << endl << endl;
return 0;
}
when I run the program it works but it never retrieves the name of the program but instead it retrieves the name of the visual c++ program???!!! can anyone edit or help about my code. thnx in advance
Upvotes: 0
Views: 1625
Reputation: 32732
INVALID_HANDLE_VALUE
is defined as -1
, while OpenProcess returns NULL if the function fails. I don't know what GetModuleFileNameEx
will do if given a NULL process handle, but if HMODULE is NULL the name of the current executable is returned so it might do that for other invalid input.
According to the MSDN documentation for GetModuleFileNameEx
, the recommended way to get the name of the executable for a process is by calling GetProcessImageFileName
and not GetModuleFileNameEx
. You'll have to resolve your issue with OpenProcess
first.
Upvotes: 1