Find Window's Handle through PID

```cpp
typedef _ProcessHwnd

{

  DWORD ProcessID;
  HWND hwndProcess;

} PROCESSHWND, * PPROCESSHWND;


DWORD GetHWNDForProcess(DWORD ProcessID, PHWND ProcessHWND);
BOOL CALLBACK FindProcessHWNDThruEnum(HWND hwnd, LPARAM lParam);

// example function
// returns 0 if success, results of GetLast Error if not
// ProcessID is the process you are interested in
// ProcessHWND will have the process' associated window handle.
// Or NULL, if the process doesn't have a window
//
// Usage: GetHWNDForProcess(ProcId, &ProcHWND);
//

DWORD GetHWNDForProcess(DWORD ProcessID, PHWND ProcessHWND)
{
  DWORD ErrValue = 0;
  BOOL fEnumWindows = FALSE;
  PROCESSHWND prochwndFind;

// Initialize the structure
  memset(&prochwndFind, 0, sizeof(prochwndFind));
  prochwndFind.ProcessID = ProcessID;
  fEnumWindows = EnumWindows(FindProcessHWNDThruEnum, (LPARAM) &prochwndFind);

// Make sure EnumWindows succeeded
  if(fEnumWindows){
    *ProcessHWND = prochwndFind.hwndProcess;
  }else{
   ErrValue = GetLastError();
  }
  return ErrValue;
}

// The EnumWindowsProc callback
BOOL CALLBACK FindProcessHWNDThruEnum(HWND hwnd, LPARAM lParam)
{
  PPROCESSHWND prochwndFind;
  DWORD ThisProcessID = 0;
  DWORD ThisThreadID = 0; // For completeness, not needed

  prochwndFind = (PPROCESSHWND) lParam;
  ThisThreadID = GetWindowThreadProcessId(hwnd, &ThisProcessID);

  if(ThisProcessID == prochwndFind.ProcessID)
  {
    prochwndFind.hwndProcess = hwnd);
    return FALSE;
  }else{
    return TRUE;
  }
}
```

No comments:

Post a Comment

Build docker image from multiple build contexts

Build docker image from multiple build contexts ...