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

(Sorry for my crazy English) I want to get all the text in Rich Edit with RTF format, not plain text into a variable. I tried SendMessage () with EM_STREAMOUT to directly write Rich Edit to a file, but I cannot save the content for certain variables like LPWSTR. Remember that only Win API, not MFC. Thanks for the help!

+4
source share
2 answers

You can pass your variable to the EM_STREAMOUT so that it can be updated as needed, for example:

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

Update: To load RTF data into a RichEdit control, use EM_STREAMIN , for example:

 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); 
+6
source

Using the EM_STREAMOUT message is the answer.

Here is the simplest example that I can build for a demonstration. This will save the contents of the 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 } } 
+3
source

All Articles