【问题标题】:How can I get the process name of the current active window in windows with winapi?如何使用winapi在windows中获取当前活动窗口的进程名称?
【发布时间】:2015-12-11 23:13:11
【问题描述】:

我正在尝试使用 winapi 在 Windows 中获取当前窗口或活动窗口以及该窗口的进程名称。

所以,我能够使用GetForegroundWindow() 获取活动窗口,并且我正在使用OpenProcess() 来获取进程,问题是OpenProcess 需要进程ID,所以我虽然可以使用GetProcessId() 但是这个接收 HANDLE 类型的窗口,我有 HWND 类型的当前窗口。

我尝试了几件事,但无法成功。那么任何人都可以告诉我如何在 HWND 中获取带有窗口的进程 ID 吗?或者获取当前窗口的句柄??

我把我的代码留在这里,以防有人看到对我有帮助的解决方案。我正在使用 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);
}

【问题讨论】:

  • GetProcessId() 不接受窗口句柄作为输入,而是接受进程句柄。它检索指定进程的 ID。

标签: c++ windows qt winapi pid


【解决方案1】:

您可以使用GetWindowThreadProcessId(),它接受HWND,并输出窗口所属进程的ID。

例如:

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

【讨论】:

  • 感谢您的回答,但此解决方案不适用于所有进程,它适用于 Skype、Qt Creator、firefox、chrome,但在桌面、Windows 提示符下不显示任何内容,单词,我的文件等...
  • 哦,不,问题不是在获取 id 时,那部分工作正常,我之前提到的所有这些进程的问题是当我尝试获取进程名称时,GetModuleFileNameEx 它不是为所有进程工作。
  • 我解决了将进程名称更改为 GetModuleFileNameExGetProcessImageFileName 的问题,感谢 Remy Lebeau。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-16
  • 1970-01-01
相关资源
最近更新 更多