December 1st, 2025
0 reactions

How do I get my edit control text to be autoselected when I choose it to be the default focus in my dialog?

A customer had a Win32 dialog with a bunch of edit controls inside. In their WM_INIT­DIALOG message handler, they filled those edit controls with information and then decided which one should get initial focus when the dialog is shown to the user. To set the focus, they did

SetFocus(GetDlgItem(hDlg, initialControlId));

and then they returned FALSE to indicate that they had already set the focus and the dialog manager should not attempt to set its own focus.

This worked well, with the exception that the edit control they chose did not have its contents autoselected, like the dialog manager would have done if it were given permission to set the focus. How could they get that extra behavior?

This is sort of the reverse of the problem of preventing edit control text from being autoselected in a dialog box. We solved that problem by removing the DLGC_HAS­SET­SEL dialog code from the edit control. In this case, the edit control has the DLGC_HAS­SET­SEL dialog code, but how do we set focus in a way that honors that code?

We saw the answer some time ago: How to set focus in a dialog box. You can have the dialog send itself the WM_NEXT­DLG­CTL message to ask it to set focus to the desired control in the standard dialog manner (which includes autoselecting text in edit controls) and updating the internal dialog box bookkeeping to keep track of things like the dialog default pushbutton, so that you don’t get into weird states like a dialog box with two default buttons.

SendMessage(hDlg, WM_NEXTDLGCTL,
            (WPARAM)GetDlgItem(hDlg, initialControlId), TRUE);
Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments