Applies to: desktop apps only
Sets the keyboard focus to the specified window. The window must be attached to the calling thread's message queue.
Syntax
HWND WINAPI SetFocus( __in_opt HWND hWnd );
Parameters
- hWnd [in, optional]
-
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.
Remarks
The SetFocus 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 will produce the WM_SYSCHAR, WM_SYSKEYDOWN, or WM_SYSKEYUP message. If the VK_MENU key is also pressed, the lParam parameter of the message will have bit 30 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
|
Minimum supported client | Windows 2000 Professional |
|---|---|
|
Minimum supported server | Windows 2000 Server |
|
Header |
|
|
Library |
|
|
DLL |
|
See also
- Reference
- GetFocus
- WM_KILLFOCUS
- WM_SETFOCUS
- WM_SYSCHAR
- WM_SYSKEYDOWN
- WM_SYSKEYUP
- Conceptual
- Keyboard Input
- Other Resources
- AttachThreadInput
Send comments about this topic to Microsoft
Build date: 3/6/2012
To explicitly set the focus to a dialog's control call SendMessage(hDialog, WM_NEXTDLGCTL, (WPARAM)hwndCtrl, TRUE). The WM_NEXTDLGCTL message notifies the dialog manager that the focus has changed.
The exception is the initial WM_INITDIALOG message. When you receive WM_INITIDIALOG call SetFocus on the desired control's hWnd. You must return FALSE to notify the dialog manager that you set the initial focus.
When handling other dialog messages if you use SetFocus (and not WM_NEXTDLGCTL) it prevents the dialog manager from updating its internal bookkeeping. For example, it might cause the dialog manager to display the wrong default pushbutton or fail to select the text of an edit control. For details see Raymond Chen's book The Old New Thing, page 227, "How to set focus in a dialog box." (Or see his blog.)
[DllImport("user32", CharSet=CharSet.Ansi, SetLastError=true, ExactSpelling=true)]
internal static extern IntPtr SetFocus(IntPtr hwnd);