Skip to content
Search

WindowsApi:BringWindowToTop

lastmod 2018-08-17created 2016-04-134 edits

The BringWindowToTop function brings the specified window to the top of the Z order. If the window is a top-level window, it is activated. If the window is a child window, the top-level parent window associated with the child window is activated.

Warning

Use the BringWindowToTop function to uncover a window that is partially or completely obscured by other windows. Calling this function is similar to calling the SetWindowPos function to change a window's position in the Z order. BringWindowToTop does not make a window a top-level window. If an application is not in the foreground and wants to be in the foreground, it should call the SetForegroundWindow function.

Window TopMost

When writing code that brings a window to the top, it is better to use the BringWindowToTop function than the SetWindowPos() function. However, simply calling BringWindowToTop does not bring the window to the front. To use BringWindowToTop, you must first attach the current thread to the thread of the currently active window. So to call BringWindowToTop properly, structure the code as follows.

if(::GetForegroundWindow() != this->m_hWnd){ 
    HWND h_active_wnd = ::GetForegroundWindow(); 
    if(h_active_wnd != NULL){ 
        DWORD thread_id = GetWindowThreadProcessId(h_active_wnd, NULL); 
        DWORD current_thread_id = GetCurrentThreadId(); 
        if(current_thread_id != thread_id){ 
            if(AttachThreadInput(current_thread_id, thread_id, TRUE)){ 
                BringWindowToTop(); 
                AttachThreadInput(current_thread_id, thread_id, FALSE); 
            } 
        } 
    } 
} 

For how to use SetWindowPos(), see here.

With the SetWindowPos() method, the window comes to the front but remains inactive. In short, use BringWindowToTop when you want to bring a window to the front and activate it, and use the SetWindowPos() method when you want to bring a window to the front without activating it.

How to force window focus

void SetForegroundWindowForce(HWND hWnd)
{
   HWND hWndForeground = ::GetForegroundWindow();
   if(hWndForeground == hWnd) return;

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

See also

Favorite site