There are a number of ways a thread can become the foreground thread. If an application calls the SetForegroundWindow function and specifies a top-level window, the thread that owns the window becomes the foreground thread and the window becomes its active window. This function also moves the window to the top of the z-order. You can use SetForegroundWindow on any top-level window.
In most cases, if the user chooses a window, the system will place that window in the foreground. The thread that created the window becomes the foreground thread. If the foreground window is hidden or destroyed, the system designates another window as the foreground window. In that case, the new foreground window thread becomes the foreground thread. Call the GetForegroundWindow function to get the current foreground window.
In general, an application thread does not need to set the foreground window explicitly. This is usually done by the system when the user selects and closes windows. Call the SetActiveWindow function to activate a window. If the calling thread is the foreground thread, the new active window automatically becomes the foreground window. When the activation changes, the system sends a WM_ACTIVATE message to both the deactivated and activated windows. A thread can call the GetActiveWindow function to access its active window.
An application thread calls the SetFocus function to move the focus between its windows. When the focus changes, the system sends a WM_KILLFOCUS message to the window losing the focus. It sends a WM_SETFOCUS message to the window gaining the focus.
The system ensures that the focus window is always the active window or a descendant of the active window. If the focus changes to a window with a different top-level ancestor, the system first changes the activation, and then it changes the focus.