I'm able to display a few characters inside a CEdit
control by using the code shown below in the OnInitDialog()
function, but I'm not able to highlight the same text within the body of the OnInitDialog()
function. I just don't know how to do it. In my CReplaceCharacterDlg
class I added using the wizard a CEdit ReplaceCharsCtrl
variable and created the CEdit
control using the resource editor. I tried the following line in my OnInitDialog()
function as seen below but get a Debug Assertion Failed error. Can someone give me a hint on this can be done please ?
// CReplaceCharacter dialog
class CReplaceCharacterDlg : public CDialogEx
{
DECLARE_DYNAMIC(CReplaceCharacterDlg)
public:
CReplaceCharacterDlg(CWnd* pParent = nullptr); // standard constructor
CReplaceCharacterDlg(CWnd* pPar, CStringW replaceStrW);
virtual ~CReplaceCharacterDlg();
// Dialog Data
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_REPLACE_CHAR };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual BOOL OnInitDialog();
DECLARE_MESSAGE_MAP()
public:
CEdit ReplaceCharsCtrl;
CStringW ReplacementCharacterStr;
afx_msg void OnBnClickedOk();
};
// Implementation
BOOL CReplaceCharacterDlg::OnInitDialog()
{
GetDlgItem(IDC_EDIT1)->SetWindowTextW(ReplacementCharacterStr);
ReplaceCharsCtrl.SetHighlight(0, 2); <---- GIVES ASSERT ERROR ReplaceCharsCtrl hWnd = NULL
return TRUE;
}
See the body of the post.
Change your code as shown below (partially based on @Mark Ransom comments):
BOOL CReplaceCharacterDlg::OnInitDialog()
{
CDialogEx::OnInitDialog(); // Do not delete this, among others binds control variables to controls
ReplaceCharsCtrl.SetWindowTextW(ReplacementCharacterStr); // Control is already bound to IDC_EDIT1, no need do create a temporary CWnd object
ReplaceCharsCtrl.SetSel(0, -1); // Select the entire text
ReplaceCharsCtrl.SetFocus();
return FALSE; // We explicitly set the focus to a non-default control
}
EDIT:
Finally made some test and found that the SetHighlight()
function (EM_SETHILITE
message) has no effect, it is a relic of some very old versions of Windows. It does nothing and the Win32 documentation says it is "not implemented". Also found this post. You can use SetSel()
instead, as you have already found.