Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the process name of the current active window in windows with winapi?

I'm trying to get the current window or the active window and the process name of that window, in Windows with winapi.

So, I was able to get the active window with GetForegroundWindow() and I'm using OpenProcess() to get the process, the problem it's that OpenProcess needs the process id, so I though I could use GetProcessId() but this one receives the window in a HANDLE type and I have the current window in HWND type.

I've try a couple of things but couldn't made it work. So can anyone tell how can I get the process id with the window in HWND ?? or get the HANDLE of current window ??

I leave my code in here in case some sees a solution that could be helpful for me. I'm working with Qt and C++

char wnd_title[256];
HWND hwnd=GetForegroundWindow(); // get handle of currently active window
GetWindowText(hwnd,wnd_title,sizeof(wnd_title));
HANDLE Handle = OpenProcess(
                  PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
                  FALSE,
                  GetProcessId(hwnd) // GetProcessId is returning 0
                );
if (Handle)
{
  TCHAR Buffer[MAX_PATH];
  if (GetModuleFileNameEx(Handle, 0, Buffer, MAX_PATH))
  {
    printf("Paht: %s", Buffer);
    // At this point, buffer contains the full path to the executable
  }
  CloseHandle(Handle);
}
like image 842
SujaM Avatar asked Sep 15 '15 15:09

SujaM


1 Answers

You can use GetWindowThreadProcessId(), which takes in an HWND and outputs the ID of the window's owning process.

For example:

#include <tchar.h>

TCHAR wnd_title[256];
HWND hwnd = GetForegroundWindow(); // get handle of currently active window
GetWindowTextA(hwnd, wnd_title, 256);

DWORD dwPID;
GetWindowThreadProcessId(hwnd, &dwPID);

HANDLE Handle = OpenProcess(
                  PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
                  FALSE,
                  dwPID
                );
if (Handle)
{
    TCHAR Buffer[MAX_PATH];
    if (GetModuleFileNameEx(Handle, 0, Buffer, MAX_PATH))
    {
        _tprintf(_T("Path: %s"), Buffer);
        // At this point, buffer contains the full path to the executable
    }
    CloseHandle(Handle);
}
like image 56
zaw Avatar answered Nov 13 '22 04:11

zaw