[英]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.