c# - 使用 Windows API 从富文本控件检索文本的正确方法是什么?

标签 c# .net winapi pinvoke sendmessage

下面的 GetRTF() 方法可以工作,但它仅检索元数据:

    public string GetRTF(IntPtr handle)
    {
        string result = String.Empty;
        using (System.IO.MemoryStream stream = new MemoryStream())
        {
            EDITSTREAM editStream = new EDITSTREAM();
            editStream.pfnCallback = new EditStreamCallback(EditStreamProc);
            editStream.dwCookie = stream;

            SendMessage(handle, EM_STREAMOUT, SF_RTF, ref 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 struct EDITSTREAM
    {
        public MemoryStream dwCookie;
        public int dwError;
        public EditStreamCallback pfnCallback;
    }

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

    private const int WM_USER = 0x0400;
    private const int SF_RTF = 2;
    private const int EM_STREAMOUT = WM_USER + 74;

所以当我用富文本控件的句柄调用 GetRTF() 时,返回值是:

     {\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fprq2\fcharset0 Tahoma;}}{\colortbl ;\red59\green59\blue59;}{\*\generator Riched20 14.0.6015.1000;}{\*\mmathPr\mwrapIndent1440}\viewkind4\uc1\pard\cf1\f0\fs17{\pict\wmetafile0}}

但这不是富文本控件显示的文本(它只是一个电子邮件地址)。

检索我要查找的数据的正确方法是什么?

最佳答案

您的代码已经检索了所有数据。这是控件内容的 RTF 表示形式。没有文本,因为您的控件中没有任何文本。它似乎只包含一个图元文件矢量图像。

如果您向该控件发送 WM_GETTEXT 消息以获取纯文本,那么您将一无所获。因为该控件不包含文本,仅包含图像。

关于c# - 使用 Windows API 从富文本控件检索文本的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13530637/

相关文章:

c# - 如何禁用窗体上除按钮以外的所有控件?

c# - 如何使用.NET 创建选项卡式窗口?

.net - 带有 .Net 的 Active Directory 服务器

c++ - 符号 (&) 在 .rc 文件中的含义

c# - 尝试从 Windows 服务读取 IIS 站点的 web.config 文件

c# - 选择对象并添加到列表 linq c#

c# - 在 ASP.Net Core MVC 中读取 JSON post 数据

.net - 使用 System.AddIn 和进程隔离实现应用程序可靠性

c++ - 从 C 中的函数返回 char 数组的首选方法

c# - 如何访问隐藏的分区/卷