4

(对不起我的疯狂英语)我想以 RTF 格式获取 Rich Edit 中的所有文本,而不是纯文本到变量。我尝试使用带有 EM_STREAMOUT 的 SendMessage() 直接将 Rich Edit 写入文件,但我无法将内容保存到特定变量,例如 LPWSTR。请记住,只有 Win API,而不是 MFC。谢谢你的帮助!

4

2 回答 2

6

您可以将变量传递给EM_STREAMOUT回调,以便可以根据需要对其进行更新,例如:

DWORD CALLBACK EditStreamOutCallback(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb)
{
    std::stringstream *rtf = (std::stringstream*) dwCookie;
    rtf->write((char*)pbBuff, cb);
    *pcb = cb;
    return 0;
}

.

std::stringstream rtf;

EDITSTREAM es = {0};
es.dwCookie = (DWORD_PTR) &rtf;
es.pfnCallback = &EditStreamOutCallback; 
SendMessage(hRichEditWnd, EM_STREAMOUT, SF_RTF, (LPARAM)&es);

// use rtf.str() as needed...

更新:要将 RTF 数据加载到 RichEdit 控件中,请使用EM_STREAMIN,例如:

DWORD CALLBACK EditStreamInCallback(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb)
{
    std::stringstream *rtf = (std::stringstream*) dwCookie;
    *pcb = rtf->readsome((char*)pbBuff, cb);
    return 0;
}

.

std::stringstream rtf("...");

EDITSTREAM es = {0};
es.dwCookie = (DWORD_PTR) &rtf;
es.pfnCallback = &EditStreamInCallback; 
SendMessage(hRichEditWnd, EM_STREAMIN, SF_RTF, (LPARAM)&es);
于 2013-03-27T19:13:19.397 回答
3

使用EM_STREAMOUT消息就是答案。

这是我可以构建来演示的最简单的示例。这会将富编辑控件的内容保存到文件中。

DWORD CALLBACK EditStreamOutCallback(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb)
{
    HANDLE hFile = (HANDLE)dwCookie;
    DWORD NumberOfBytesWritten;
    if (!WriteFile(hFile, pbBuff, cb, &NumberOfBytesWritten, NULL))
    {
        //handle errors
        return 1;
        // or perhaps return GetLastError();
    }
    *pcb = NumberOfBytesWritten;
    return 0;
}

void SaveRichTextToFile(HWND hWnd, LPCWSTR filename)
{
    HANDLE hFile = CreateFile(filename, GENERIC_WRITE, 0, NULL,
        CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile == INVALID_HANDLE_VALUE)
    {
        //handle errors
    }
    EDITSTREAM es = { 0 };
    es.dwCookie = (DWORD_PTR) hFile;
    es.pfnCallback = EditStreamOutCallback; 
    SendMessage(hWnd, EM_STREAMOUT, SF_RTF, (LPARAM)&es);
    CloseHandle(hFile);
    if (es.dwError != 0)
    {
        //handle errors
    }
}
于 2013-03-27T11:17:17.423 回答