The user input system delivers keyboard messages containing scan code, virtual key code, and character information to the appropriate window. To understand how this system works, you need to understand the relationship between the active window, the focus window, and the foreground window.
Each thread maintains its own active window and focus window. The active window is a top-level window. The focus window is either the active window or one of its descendents. At any one time, there is one thread in the system that is considered the foreground thread. The active window of this thread is the foreground window. The user-input system places keyboard messages in the message queue of the foreground thread. The thread's message loop pulls the message from the queue and sends it to the thread's focus window. If the focus window is NULL, the active window receives the message.
To summarize the relationship between these window types:
There are a number of ways that 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. For more information on Z order, see Windows.
In most cases, if the user taps on a window, the system will bring that window to 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's thread becomes the foreground thread. You can use 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 as the user selects and closes windows with the stylus. Use the SetActiveWindow function to activate a window. If the calling thread is the foreground thread, then the new active window automatically becomes the foreground window. When the activation changes, the system sends a WM_ACTIVATE message to the window that is being deactivated and to the window that is being activated. A thread can use the GetActiveWindow function to access its active window.
An application thread uses the SetFocus function to move the focus between its windows. When the focus changes, the system sends a WM_KILLFOCUS message to the window that is losing the focus. It sends a WM_SETFOCUS message to the window that is gaining the focus.
The system ensures that the focus window is always the active window or a descendent of the active window. If the focus is changed to a window with a different top-level ancestor, the system first changes the activation, and then it changes the focus.