-1

Is it possible to get the HWND from a window by a process name? The name of the window changes on every restart (random windowname), like this:

image

I just found something to get it by window name.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
rck
  • 33
  • 6

2 Answers2

1

The connection between processes and windows is not obvious. First of all, a process can have several windows. Second, it looks like Windows APIs do not provide a method to look up windows based on a process (which I find weird, given your screenshot shows just that).

However, you can go through all open windows and filter based on a process. See this question with an elaborate answer on how to do it: Find Window and change it's name

ypnos
  • 50,202
  • 14
  • 95
  • 141
-3

I have found this solution, but I get multiple HWNDs for the one process ID

#include <Windows.h>

void GetAllWindowsFromProcessID(DWORD searchPID, std::vector <HWND> &wnds)
{
    HWND hCurWnd = NULL;
    do
    {
        hCurWnd = FindWindowEx(NULL, hCurWnd, NULL, NULL);
        DWORD processID = 0;
        GetWindowThreadProcessId(hCurWnd, &processID);
        if (searchPID == processID)
        {
            wnds.push_back(hCurWnd);
        }
    } while (hCurWnd != NULL);
}

int main()
{
    DWORD PID = 0x00001D7C;
    std::vector<HWND> HWND_List;
    GetAllWindowsFromProcessID(PID, HWND_List);

    return 0;
}
Zebrafish
  • 11,682
  • 3
  • 43
  • 119
  • yeap, trough code, i just find out, to get it by the window name but its random -.- – rck Mar 18 '18 at 12:30
  • You want to use [EnumWindows](https://msdn.microsoft.com/en-us/library/windows/desktop/ms633497.aspx) instead. Besides, posting code which you do not understand hardly ever produces a quality answer. This one certainly isn't. – IInspectable Mar 18 '18 at 13:37
  • this was helpful, got the same result, multiple HWND´s, i find out that the second index contains the right HWND to the window. – rck Mar 18 '18 at 17:17
  • @rck: You are looking to enumerate top-level windows. `EnumWindows` does. This solution does not. And it suffers from a race condition, that'll hit you at some point. As always, if someone doesn't know, why their (is it, really?) code works, it doesn't. Please don't accept this answer, if only for lacking any explanation. – IInspectable Mar 18 '18 at 18:30