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

I am a beginner in C ++ (there has always been C #), and I was put in troublooting / update from our inherited program written in C ++.

I have a process name "setup.exe" that works in a window, and I knew how to find its process identifier HANDLE and DWORD. I know that it has a window for sure, but I can’t understand how to bring this window to the foreground, and this is what I am trying to do: Bring the window to the foreground using its process name.

After reading on the Internet, I came up with the following algorithm, which is also not sure if this is the correct way:

  • Find the process ID from the process name.
  • List all windows belonging to this process ID using EnumWindows
  • the above step will give me a window type variable - HWND
  • I can set focus or set foreground by passing this HWND variable.

My problem here is the syntax, I really don’t know how to start writing enumwindows, can someone point me to a set of sample code, or if you have a pointer to how I should approach this problem?

Thanks.

+4
source share
2 answers

The EnumWindows procedure evaluates all top-level windows. If you are sure that the window you are looking for is the 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 required process id.

DISCLAIMER: not verified, but should work :)

+5
source
 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. 
+3
source

Source: https://habr.com/ru/post/1403163/


All Articles