In MFC/C++, I have a rich edit 2.0 control, class CRichEditCtrl, which is RichEdit20W. Rich edit 2.0 controls are supposed to support Unicode. I am using it to display Unicode characters. But the ReplaceSel function doesn't accept Unicode strings. For example
CRichEditCtrl re;
wstring line;
auto x = line.c_str(); // array of const wchar_t
re.ReplaceSel(x); // ERROR
gets a compiler error because CRichEditCtrl::ReplaceSel is prototyped as
void ReplaceSel(LPCTSTR lpszNewText, BOOL bCanUndo = FALSE);
and LPCTSTR is a const char *.
How can I replace using a Unicode string?
Windows 11 Pro Visual Studio 2022
If
LPCTSTRisconst char *then your project settings are multibyte characters and not unicode. The answer is simple, you have to convert the unicode string to ansi, using your preferred conversion function, egWidecharToMultibyte(),wcstombs()orstd::codecvt. Please note that you are converting the string to a type capable of representing fewer character values, ie these functions may fail.EDIT:
You can call the
IsWindowUnicode()function to check if the control is indeed unicode. And you can experiment further with theWM_SETTEXTmessage for example (not theSetWindowText()function) to find out with more certainty (ie if it works with ansi or wide strings). If your project setting is multibyte chars (ie theUNICODEidentifier is not defined), thenCEdit::ReplaceSel()takes an ansi string (as the function uses the dual/conditionalTnotation, which translates to eitherWorA, depending onUNICODEbeing defined/undefined), even if the underlying control is actually Unicode. This is a discrepancy of course, arising from the fact that MFC assumes that all its controls are ansi or unicode, consistent with the project setting. In this case I would try sending theEM_REPLACESELmessage directly, (of whichCEdit::ReplaceSel()is a wrapper), (iere.SendMessage(EM_REPLACESEL, bCanUndo, (LPARAM)x)), or even callingReplaceSel()with the string type cast (iere.ReplaceSel((LPCTSTR)x)); although this may seem wrong it's actually not, as the cast won't perform any conversion, it will just keep the compiler from complaining and will pass the wide string address to the function (and finally the message), which is correct, assuming a Unicode underlying control.