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.

Comments (2)
  1. Joe says:

    (I hope people understand that this is really only acceptable for multi-line edit controls, ala Notepad or this blog, or possibly read-only controls (there may be other, special case exceptions). Having the text of an edit control become selected is a consistent user-experience across Windows — when I tab to a single-line edit control I expect the text to be highlighted so that if I start typing a new value, the old value disappears. To change this behavior, even if you don’t agree with it, just confuses users.

    In my opinion, of course.

Comments are closed.

Skip to main content