Example of using EM_STREAMOUT with c# and RichEditBox

情到浓时终转凉″ 提交于 2019-12-11 04:22:59

问题


i trying to get a text from a RichEdit field with WM_GETTEXT, but i run into some problems, so I found EM_STREAMOUT, this is especially for RichEdit. I found this code and played a little bit with it, but i can't get them to work:

delegate uint EditStreamCallback(IntPtr dwCookie, IntPtr pbBuff, int cb, out int pcb);

struct EDITSTREAM
{
public IntPtr dwCookie;
public uint dwError;
public EditStreamCallback pfnCallback;
}

[DllImport("user32.dll", CharSet=CharSet.Auto)]
static extern IntPtr SendMessage(HandleRef hwnd, uint msg, uint wParam, ref EDITSTREAM lParam);

maybe someone have a working example of using this in c#?

thx david


回答1:


Pls, check if an example below would work for you:

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;

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 }

hope this helps, regards



来源:https://stackoverflow.com/questions/3236086/example-of-using-em-streamout-with-c-sharp-and-richeditbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!