![](/img/trans.png)
[英]How can I get the name of any process having a visible window - WinAPI?
[英]How can I get the process name of the current active window in windows with winapi?
我试图在Windows中使用winapi获取当前窗口或活动窗口以及该窗口的进程名称。
所以,我能够使用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);
}
您可以使用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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.