简体   繁体   English

如何使用winapi在Windows中获取当前活动窗口的进程名称?

[英]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. 我试图在Windows中使用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. 所以,我能够使用GetForegroundWindow()获取活动窗口,并且我正在使用OpenProcess()来获取进程,问题是OpenProcess需要进程ID,所以我虽然可以使用GetProcessId()但是这个接收处于HANDLE类型的窗口,我有HWND类型的当前窗口。

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 ?? 所以任何人都可以告诉我如何在HWND中获取窗口的进程ID? 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++ 我正在使用Qt和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);
}

You can use GetWindowThreadProcessId() , which takes in an HWND and outputs the ID of the window's owning process. 您可以使用GetWindowThreadProcessId() ,它接收HWND并输出窗口拥有进程的ID。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM