November 14th, 2003

Preventing edit control text from being autoselected in a dialog box

By default, when the user TABs to an edit control in a dialog box, the entire contents of the edit control are autoselected. This occurs because the edit control responds with the DLGC_HASSETSEL flag in response to the WM_GETDLGCODE message. To prevent it from happening, remove that flag.

LRESULT CALLBACK RemoveHasSetSelSubclassProc
    (HWND hwnd, UINT uiMsg, WPARAM wParam, LPARAM lParam,
     UINT_PTR uIdSubclass, DWORD_PTR dwRefData)
{
    switch (uiMsg) {
    case WM_NCDESTROY:
        RemoveWindowSubclass(hwnd, RemoveHasSetSelSubclassProc,
                             uIdSubclass);
        break;
    case WM_GETDLGCODE:
        return DefSubclassProc(hwnd, uiMsg, wParam, lParam)
                             & ~DLGC_HASSETSEL;
    }
    return DefSubclassProc(hwnd, uiMsg, wParam, lParam);
}

All this subclass procedure does is remove the DLGC_HASSETSEL flag from the return value of the WM_GETDLGCODE message.

INT_PTR CALLBACK DlgProc(HWND hdlg, UINT uiMsg,
                         WPARAM wParam, LPARAM lParam)
{
    switch (uiMsg) {
    case WM_INITDIALOG:
        SetWindowSubclass(GetDlgItem(hdlg, 100),
                          RemoveHasSetSelSubclassProc, 0, 0);
        break;
    case WM_COMMAND:
        switch (GET_WM_COMMAND_ID(wParam, lParam)) {
        case IDCANCEL:
            EndDialog(hdlg, 1);
            break;
        }
    }
    return FALSE;
}

The subclass procedure is installed when the dialog box is initialized.

int WINAPI WinMain(HINSTANCE hinst, HINSTANCE hinstPrev,
                   LPSTR lpCmdLine, int nShowCmd)
{
    DialogBox(hinst, MAKEINTRESOURCE(1), NULL, DlgProc);
    return 0;
}
1 DIALOGEX DISCARDABLE  0, 0, 200,200
STYLE DS_SHELLFONT | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
CAPTION "sample"
FONT 8, "MS Shell Dlg"
BEGIN
  CONTROL         "Blah blah",100,"Edit",WS_TABSTOP,7,4,100,10
    DEFPUSHBUTTON "&Bye", IDCANCEL, 7,24,50,14, WS_TABSTOP
END

And here is the dialog box that we display.

There really isn’t much to it, but I figured a complete sample program might help somebody out. Plus it lets me show off the SetWindowSubclass function.

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

Discussion are closed.