Search code examples
windowsc++11processforeground

Put application to foreground


I have to put a window to foreground using its name, for example "images". With

findWindowW(NULL, stringName)

I get the handle to the process (HWND). Then with

SetForegroundWindow(windowHandle);

I think that I put it into the foreground automatically, but I have to press 'Enter'. Am I doing something wrong or there's another way to do that? I can use also the PID of the process.
My final purpose is to send shortcuts like CTRL+V to the process after put it into the foreground. Thank you.


Solution

  • From MSDN

    The system restricts which processes can set the foreground window. A process can set the foreground window only if one of the following conditions is true:

    • The process is the foreground process.
    • The process was started by the foreground process.
    • The process received the last input event.
    • There is no foreground process.
    • The process is being debugged.
    • The foreground process is not a Modern Application or the Start Screen.
    • The foreground is not locked (see LockSetForegroundWindow).
    • The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
    • No menus are active.

    So, if your program does not correspond to the above, you can not set foreground automatically.

    I think you can use below code for your case and this link can be help as well.

    void SetForegroundWindowForce(HWND hWnd)
    {
       HWND hWndForeground = ::GetForegroundWindow();
       if(hWndForeground == hWnd) return;
    
       DWORD Strange = ::GetWindowThreadProcessId(hWndForeground, NULL);
       DWORD My = ::GetWindowThreadProcessId(hWnd, NULL);
       if( !::AttachThreadInput(My, Strange, TRUE) )
       {
          ASSERT(0);
       }
       ::SetForegroundWindow(hWnd);
       ::BringWindowToTop(hWnd);
       if( !::AttachThreadInput(My, Strange, FALSE) )
       {
          ASSERT(0);
       }
    }