Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bring to front window using its process name in C++

Tags:

c++

windows

I am a beginner in C++ (always been a C#) and I was put in to troublshooting/update on of our legacy program written in C++.

I have a process name "setup.exe" that runs on window and I knew how to find its HANDLE and DWORD process id. I know it has a window for sure but I can't seem to find out how to bring this window to a foreground and that is what I am trying to do: To bring a window to a foreground using its process name.

Upon reading on the internet I came to the following algorithm which i'm also not sure is the proper way to do it:

  1. Find the process ID from the process name.
  2. Enumerate all the windows which belong to this process ID using EnumWindows
  3. the above step will give me the window handle(s) variable of type - HWND
  4. I can set focus or set the foreground by passing in this HWND variable.

My problem here is syntax wise, I don't really know how to begin to write up enumwindows, can anybody point me toward a set of sample code or if you have any pointer to how I should approach this issue?

Thank you.

like image 953
Fylix Avatar asked Dec 27 '22 03:12

Fylix


2 Answers

SetWindowPos(windowHandle, HWND_TOPMOST, 0, 0, 0, 0, SWP_SHOWWINDOW|SWP_NOSIZE|SWP_NOMOVE);  // it will bring window at the most front but makes it Always On Top.

SetWindowPos(windowHandle, HWND_NOTOPMOST, 0, 0, 0,    0, SWP_SHOWWINDOW|SWP_NOSIZE|SWP_NOMOVE); // just after above call, disable Always on Top.
like image 41
maxpayne Avatar answered Jan 06 '23 04:01

maxpayne


The EnumWindows procedure evaluates all top level windows. If you are sure the window you are looking for is top level, you can use this code:

#include <windows.h>

// This gets called by winapi for every window on the desktop
BOOL CALLBACK EnumWindowsProc(HWND windowHandle, LPARAM lParam)  {
    DWORD searchedProcessId = (DWORD)lParam;  // This is the process ID we search for (passed from BringToForeground as lParam)
    DWORD windowProcessId = 0;
    GetWindowThreadProcessId(windowHandle, &windowProcessId); // Get process ID of the window we just found
    if (searchedProcessId == windowProcessId)  {  // Is it the process we care about?
      SetForegroundWindow(windowHandle);  // Set the found window to foreground
      return FALSE;  // Stop enumerating windows
    }
    return TRUE;  // Continue enumerating
}

void BringToForeground(DWORD processId)  {
   EnumWindows(&EnumWindowsProc, (LPARAM)processId);
}

Then just call BringToForeground with the process ID you want.

DISCLAIMER: not tested but should work :)

like image 77
Karel Petranek Avatar answered Jan 06 '23 02:01

Karel Petranek