我试图在Windows和winapi中获取当前窗口或活动窗口以及该窗口的进程名。
所以,我能够用GetForegroundWindow()
获得活动窗口,我使用OpenProcess()
来获取进程,问题是OpenProcess需要进程id,所以我想我可以使用GetProcessId()
,但是这个窗口以句柄类型接收,并且我有当前窗口为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);
}
发布于 2015-09-15 16:14:45
您可以使用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);
}
https://stackoverflow.com/questions/32590428
复制相似问题