如何让 Unicode 出现在 C++ RICHEDIT_CLASS 中?

How do I get Unicode to show up in C++ RICHEDIT_CLASS?

我整天都在不停地尝试和研究,尝试了我发现的一切,但似乎没有什么对我有用。

我很确定这是这里某处的问题:

void edit_append (const char *text)
{
    CHARRANGE range = {-1, -1};
    SendMessage(win_log, EM_EXSETSEL, 0, (LPARAM)&range);
    SendMessage(win_log, EM_REPLACESEL, FALSE, (LPARAM)text);
}

如果您需要我的任何其他代码,我很乐意将其粘贴到此处,我已经为此奋斗了一整天。当我 SendMessage() Unicode 时,我只得到奇怪的符号,有一次我什至得到一堆问号。

您正在将 char* 传递给 EM_REPLACESEL。这仅在您的 RichEdit 控件通过 CreateWindow(Ex)A(RICHEDIT_CLASSA) 使用 Ansi HWND 时才有效。如果它通过 CreateWindow(Ex)W(RICHEDIT_CLASSW) 使用 Unicode HWND,则需要传递 wchar_t*

void edit_append (const wchar_t *text)
{
    CHARRANGE range = {-1, -1};
    SendMessage(win_log, EM_EXSETSEL, 0, (LPARAM)&range);
    SendMessage(win_log, EM_REPLACESEL, FALSE, (LPARAM)text);
}

void edit_clear (void)
{
    CHARRANGE range = {0, -1};
    SendMessage(win_log, EM_EXSETSEL, 0, (LPARAM)&range);
    SendMessage(win_log, EM_REPLACESEL, FALSE, (LPARAM)L"");
}

如果您出于某种原因无法更改 text 的数据类型,那么您将不得不使用 MultiByteToWideChar()(或等效的)将数据转换为 UTF-16,然后再将其提供给 SendMessage():

void edit_append (const char *text)
{
    int len = strlen(text);
    int wlen = MultiByteToWideChar(CP_ACP, 0, text, len, NULL, 0);

    wchar_t *wtext = new wchar_t[wlen+1];
    MultiByteToWideChar(CP_ACP, 0, text, len, wtext, wlen);
    wtext[wlen] = 0;

    CHARRANGE range = {-1, -1};
    SendMessage(win_log, EM_EXSETSEL, 0, (LPARAM)&range);
    SendMessage(win_log, EM_REPLACESEL, FALSE, (LPARAM)wtext);

    delete[] wtext;
}