【问题标题】:Example of using EM_STREAMOUT with c# and RichEditBox将 EM_STREAMOUT 与 c# 和 RichEditBox 一起使用的示例
【发布时间】:2010-07-13 10:08:18
【问题描述】:

我尝试使用 WM_GETTEXT 从 RichEdit 字段中获取文本,但遇到了一些问题,因此我找到了 EM_STREAMOUT,这尤其适用于 RichEdit。我找到了这段代码并玩了 有点用,但我无法让它们工作:

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);

也许有人有一个在 c# 中使用它的工作示例?

谢谢大卫

【问题讨论】:

    标签: c# winapi richtextbox hook subclass


    【解决方案1】:

    请检查以下示例是否适合您:

    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;
    

    你可以这样称呼它:

    string temp = ReadRTF(richTextBox1.Handle);
    Console.WriteLine(temp);
    

    在我的测试 Richedit 中,这将返回以下字符串:

    {\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 微软无衬线;}} \viewkind4\uc1\pard\qc\f0\fs17 测试 段落\par \pard 测试段落\par }

    希望这会有所帮助,问候

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2011-05-29
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      • 2016-02-09
      • 2011-12-01
      相关资源
      最近更新 更多