When I move to a CEdit control on my dialog using the tab key or the arrow keys all the text in the control is selected. This behaviour is causing me problems and I would prefer it if the control just put the cursor at the start (or end) of the text and didn't select anything. Is there a simple way to do this (e.g. a property of the control that I can set)?
3 Answers
Another way of achieving your goal is to prevent the contents from being selected. When navigating over controls in a dialog the dialog manager queries the respective controls about certain properties pertaining to their behavior. By default an edit control responds with a DLGC_HASSETSEL
flag (among others) to indicate to the dialog manager that its contents should be auto-selected.
To work around this you would have to subclass the edit control and handle the WM_GETDLGCODE message to alter the flags appropriately. First, derive a class from CEdit
:
class CPersistentSelectionEdit : public CEdit {
public:
DECLARE_MESSAGE_MAP()
afx_msg UINT OnGetDlgCode() {
// Return default value, removing the DLGC_HASSETSEL flag
return ( CEdit::OnGetDlgCode() & ~DLGC_HASSETSEL );
}
};
BEGIN_MESSAGE_MAP( CPersistentSelectionEdit, CEdit )
ON_WM_GETDLGCODE()
END_MESSAGE_MAP()
Next subclass the actual control. There are a number of ways to do this. To keep things simple just declare a class member m_Edit1
of type CPersistentSelectionEdit
in your dialog class and add an appropriate entry in DoDataExchange
:
// Subclass the edit control
DDX_Control( pDX, IDC_EDIT1, m_Edit1 );
At this point you have an edit control that doesn't have its contents auto-selected when navigated to. You can control the selection whichever way you want.

- 46,945
- 8
- 85
- 181
-
2If you use this method you don't lose the caret position every time you set focus to the text box, so I would prefer it. – DanDan Aug 14 '14 at 23:22
I don't think that such a style exists.
But you can add OnSetfocus handler with the wizard:
void CMyDlg::OnSetfocusEdit1()
{
CEdit* e = (CEdit*)GetDlgItem(IDC_EDIT1);
e->SetSel(0); // <-- hide selection
}

- 42,588
- 16
- 104
- 136
-
This did not quite work for me. My edit control is multi-line and whose contents can be taller than the control (I have a vertical scroll bar). The bNoScroll needs to be TRUE, and the selection for "no select" is -1, 0, so my code called it like `e->SetSel(-1, 0, TRUE);`. This maintains any current scroll position as I tab through the controls of my dialog, but also ensures nothing is selected once focus returns back to my edit control. – franji1 Jul 05 '17 at 16:25
Please note that there must be a code in your program to highlight the selection. Please find something like this:
CEdit* pEdit = ((CEdit*)GetDlgItem(IDC_EDIT1));
pEdit->SetFocus();
pEdit->SetSel(0, -1); // select everything
Simply comment the last two lines, instead of >SetSel(0). Your code is enabling and disabling which is meaningless to me.

- 81
- 6