Tuesday, December 30, 2008

Unicode and RichEditCtrl

[source]

Unicode and RichEditCtrl
Unicode Strings in MFC
The easiest way to deal with Unicode strings is to use CStringW class. As it is, CStringW can edit Unicode strings. Another option is to use char* equivalent wide-byte type in MFC called LPWSTR.

Writing and reading Unicode strings to and from controls in MFC is not exactly as straight forward. GetDlgItemText and SetDlgItemText only take single byte character strings. This page explains how to send messages to set and retrieve Unicode strings to the controls without the use of those functions.

Take a look at the following functions. Those functions read and write Unicode strings from and to MFC controls (RichEditCtrl). Sending messages requires several steps. First is to specify the type of the message. The type of the message, the codepage, and other optional settings are set to a structure called GETTEXTEX and SETTEXTEX. Then calculate and prepare space to store the results.

LPWSTR GetUnicodeString(UINT id)
{
CRichEditCtrl* edit=(CRichEditCtrl*)GetDlgItem(id);
int nLength = edit->GetTextLengthEx(GTL_DEFAULT,1200);
LPWSTR lpszWChar = new WCHAR[nLength+1];

GETTEXTEX getTextEx;
getTextEx.cb=(nLength+1)*sizeof(WCHAR);
getTextEx.codepage=1200;
getTextEx.flags=GT_DEFAULT;
getTextEx.lpDefaultChar=NULL;
getTextEx.lpUsedDefChar=NULL;

edit->SendMessage(EM_GETTEXTEX, (WPARAM)&getTextEx, (LPARAM)lpszWChar);

return lpszWChar;
}

void SetUnicodeString(UINT id, LPWSTR str)
{
SETTEXTEX setTextEx;
setTextEx.codepage=1200;
setTextEx.flags=ST_DEFAULT;

CRichEditCtrl *caption=(CRichEditCtrl*)GetDlgItem(id);
if(caption!=NULL)
caption->SendMessage(EM_SETTEXTEX, (WPARAM)&setTextEx, (LPARAM)str);
}




The usage of GetUnicodeString above is shown below. Specify the ID of the RichEditCtrl control.

CStringW str=GetUnicodeString(IDC_RICHEDITCTRL);


Likewise, the usage of SetUnicodeString above is shown below. Specify the ID of the RichEditCtrl control, and the Unicode string to be set to the control.

SetUnicodeString(IDC_RICHEDITCTRL,str);

No comments: