private string ReadRTF(IntPtr handle)
{
string result = String.Empty;
using (MemoryStream stream = new MemoryStream())
{
EDITSTREAM editStream = new EDITSTREAM();
editStream.pfnCallback = new EditStreamCallback(EditStreamProc);
editStream.dwCookie = stream;
SendMessage(handle, EM_STREAMOUT, SF_RTF, editStream);
stream.Seek(0, SeekOrigin.Begin);
using (StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
}
}
return result;
}
private int EditStreamProc(MemoryStream dwCookie, IntPtr pbBuff, int cb, out int pcb)
{
pcb = cb;
byte[] buffer = new byte[cb];
Marshal.Copy(pbBuff, buffer, 0, cb);
dwCookie.Write(buffer, 0, cb);
return 0;
}
private delegate int EditStreamCallback(MemoryStream dwCookie, IntPtr pbBuff, int cb, out int pcb);
[StructLayout(LayoutKind.Sequential)]
private class EDITSTREAM
{
public MemoryStream dwCookie;
public int dwError;
public EditStreamCallback pfnCallback;
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(HandleRef hwnd, uint msg, uint wParam, ref EDITSTREAM lParam);
public const int WM_USER = 0x0400;
public const int EM_STREAMOUT = WM_USER + 74;
public const int SF_RTF = 2;
//apply the above
here's how you can call this:
string temp = ReadRTF(richTextBox1.Handle);
Console.WriteLine(temp);
on my test richedit this returns following string:
{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}} \viewkind4\uc1\pard\qc\f0\fs17 test paragraph\par \pard test paragraph\par }
static DWORD CALLBACK
MyStreamOutCallback(DWORD dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb)
{
HANDLE pFile = (HANDLE) dwCookie;
DWORD dwW;
WriteFile(pFile,pbBuff,cb,&dwW,NULL);
*pcb = cb;
return 0;
}
void SaveTest(HWND hWnd, int nIDDlgItem)
{
HANDLE hFile = CreateFile("c:\\myfile.rtf",GENERIC_WRITE,0,NULL,
CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
EDITSTREAM es;
es.dwCookie = (DWORD) &hFile;
es.pfnCallback = MyStreamOutCallback;
SendDlgItemMessage(hWnd,nIDDlgItem,EM_STREAMOUT,(WPARAM)SF_RTF,(LPARAM)&es);
CloseHandle(hFile);
}
The above line might be wrong:
es.dwCookie = (DWORD) &hFile;
You're passing the address of the file's handle, not the handle itself, which is what your MyStreamOutCallback() function is expecting. Just try
es.dwCookie = (DWORD) hFile;
-Mike
By the way, EM_STREAMIN/EM_STREAMOUT can load or save unicode content to/from a file if the flag SF_UNICODE is set:
SendMessageW(richeditWindow, EM_STREAMOUT, (WPARAM) SF_TEXTIZED | SF_UNICODE, (LPARAM) &eds);