首页 > 解决方案 > Get path of a known HWND

问题描述

I'm trying to make an app that will run something only if in the moment that the dll is called, the window that is focused in that moment has the same path as a values that is given. That being said, the following code will be added in a dll which will have a function with the path value as it parameter that returns true if the condition is met, or false otherwise. The problem I have is that I can't seem to find a way to get the path of the focused window, the following code always returns an empty string. And I can't simply use the title of the windows because there are apps that yes, the title is static like Task Manager, but there are others that the title is changed, like Windows Explorer changes it's title depending where the user is in. What do I have to change?

The following code is used only as a test, because later on that is the base for what I need, and I will only have to add a comparison on path variable, and based on that to return true or false:

#include "Windows.h";
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;

int main() {
    // 2 seconds delay to have time to switch windows
    std::this_thread::sleep_for(std::chrono::milliseconds(2000));

    HWND hWnd = GetForegroundWindow(); 
    int length = GetWindowTextLength(hWnd);
    wchar_t* title = new wchar_t[length];
    GetWindowTextW(hWnd, title, length);

    DWORD id;
    GetWindowThreadProcessId(hWnd, &id); 

    wchar_t* path = new wchar_t[MAX_PATH];
    HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);
    GetModuleFileNameW((HMODULE)hProc, path, MAX_PATH);
    CloseHandle(hProc);

    wcout << "ID: " << id << " | Title: " << title << " | Path: " << path << endl << endl;
    return 1;
} 

Output example: ID: 2536 | Title: Task Manage | Path:

标签: c++winapi

解决方案


为了得到我想要的结果,我切换到了QueryFullProcessImageName(就像 CherryDT 建议看一下),但是你必须小心,你需要以Admin权限运行它才能获得我遇到的某些应用程序的路径Task Manager,也许是因为它是一个 Windows 应用程序,不确定,如果您需要更多详细信息,则必须对此进行一些研究。这是一个小例子:

#include "Windows.h";
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;

int main() {
    // 2 seconds delay to have time to switch windows
    std::this_thread::sleep_for(std::chrono::milliseconds(2000));

    HWND hWnd = GetForegroundWindow(); 
    int lgth = GetWindowTextLength(hWnd) + 1;
    wchar_t* title = new wchar_t[lgth];
    GetWindowTextW(hWnd, title, lgth);

    DWORD id;
    GetWindowThreadProcessId(hWnd, &id); 

    wchar_t* path = new wchar_t[MAX_PATH];
    DWORD size = MAX_PATH;
    HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, id);
    QueryFullProcessImageNameW(hProc, 0, path, &size);
    CloseHandle(hProc);

    wcout << "ID: " << id << " | Title: " << title << " | Path: " << path << endl << endl;
    return 1;
} 

输出示例:ID: 12580 | Title: Task Manage | Path: C:\Windows\System32\Taskmgr.exe


推荐阅读