SetFocus function (winuser.h)
Sets the keyboard focus to the specified window. The window must be attached to the calling thread's message queue.
Syntax
HWND SetFocus(
[in, optional] HWND hWnd
);
Parameters
[in, optional] hWnd
Type: HWND
A handle to the window that will receive the keyboard input. If this parameter is NULL, keystrokes are ignored.
Return value
Type: HWND
If the function succeeds, the return value is the handle to the window that previously had the keyboard focus. If the hWnd parameter is invalid or the window is not attached to the calling thread's message queue, the return value is NULL. To get extended error information, call GetLastError function.
Extended error ERROR_INVALID_PARAMETER (0x57) means that window is in disabled state.
Remarks
This function sends a WM_KILLFOCUS message to the window that loses the keyboard focus and a WM_SETFOCUS message to the window that receives the keyboard focus. It also activates either the window that receives the focus or the parent of the window that receives the focus.
If a window is active but does not have the focus, any key pressed produces the WM_SYSCHAR, WM_SYSKEYDOWN, or WM_SYSKEYUP message. If the VK_MENU key is also pressed, bit 30 of the lParam parameter of the message is set. Otherwise, the messages produced do not have this bit set.
By using the AttachThreadInput function, a thread can attach its input processing to another thread. This allows a thread to call SetFocus to set the keyboard focus to a window attached to another thread's message queue.
Examples
For an example, see Initializing a Dialog Box.
Requirements
Requirement | Value |
---|---|
Minimum supported client | Windows 2000 Professional [desktop apps only] |
Minimum supported server | Windows 2000 Server [desktop apps only] |
Target Platform | Windows |
Header | winuser.h (include Windows.h) |
Library | User32.lib |
DLL | User32.dll |
API set | ext-ms-win-ntuser-window-l1-1-4 (introduced in Windows 10, version 10.0.14393) |
See also
AttachThreadInput function, GetFocus function, WM_KILLFOCUS, WM_SETFOCUS, WM_SYSCHAR, WM_SYSKEYDOWN, WM_SYSKEYUP, Keyboard Input