I have a function that calculates by the name of the executable file, the pid of the process.

What WinAPI functions should be used to know the pid of the process, maximize the application window and make it active? Application, for example, Firefox browser.

Windows 10

    2 answers 2

    In order to maximize the main window of the application, the first step is to find this window:

    DWORD dwProcessId, dwPid = 0; HWND hWnd; dwProcessId = ... // ID процесса, окно которого ищем for (hWnd = ::FindWindowEx(NULL, NULL, NULL, NULL); hWnd != NULL; hWnd = ::FindWindowEx(NULL, hWnd , NULL, NULL)) { ::GetWindowThreadProcessId(hWnd, &dwPid); if (dwPid == dwProcessId) break; } _ASSERTE (hWnd != NULL); // Еще лучше вместо ассерта сделать нормальную обработку ошибки 

    After the handle of the window is found, you can work with it in the usual way, for example, call

     ::ShowWindow(hWnd, SW_SHOWMAXIMIZED); 
    • In my opinion, finding a window can be easier ... - Qwertiy
    • 2
      @Qwertiy, so click the "Answer" button and show how to do it. - freim
    • @Qwertiy, share as :), I have almost the same code (key EnumWindows + GetWindowThreadProcessId) has been working for years, tried to simplify, but did not work. - goldstar_labs
    • @goldstar_labs, yes, it seems really necessary. - Qwertiy

    Search window through the function EnumWindows , according to the documentation ( https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-enumwindows ) it lists all the top-lvl windows of the system, which can be faster than pure FindWindowEx

     HWND get_process_wnd(const unsigned long& pid) { std::pair<HWND, DWORD> params = { 0, pid }; BOOL ret = EnumWindows( [](HWND hwnd, LPARAM lParam) -> BOOL { auto pParams = (std::pair<HWND, DWORD>*)(lParam); DWORD processId; if (GetWindowThreadProcessId(hwnd, &processId) && processId == pParams->second) { SetLastError(0); pParams->first = hwnd; return FALSE; // Нашли, заканчиваем перебор } return TRUE; // Не нашли, продолжаем перебор } , (LPARAM)&params); if (ret == FALSE && GetLastError() == 0 && params.first != NULL) return params.first; return NULL; } 

    Using:

     DWORD pid = <my_pid>; HWND hwnd = get_process_wnd(pid); if (hwnd != NULL) ::ShowWindow(hWnd, SW_SHOWMAXIMIZED); 
    • Thank! Compile, run, hwnd gets, but for some reason the window is not displayed and does not unfold :( Maybe because of the fact that Win10? - Kallipso