How to get text with RTF format from Rich Edit Win API?

前端 未结 2 591
无人共我
无人共我 2021-01-03 08:12

(Sorry for my crazy English) I want to get all the text in Rich Edit with RTF format, not plain text to a variable. I tried SendMessage() with EM_STREAMOUT to write directly

2条回答
  •  太阳男子
    2021-01-03 08:24

    Using the EM_STREAMOUT message is the answer.

    Here is the simplest example that I can construct to demonstrate. This will save the contents of a rich edit control to a file.

    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
        }
    }
    

提交回复
热议问题