c# - RichTextBox 选择突出显示

标签 c# .net winforms selection richtextbox

是否有可能在用户选择后,每个选择的字母都显示其原始颜色?并不总是默认的白色?

我想实现这样的目标 enter image description here你可以在写字板中看到。

而不是 enter image description here您在 RichTextBox 中看到的。

最佳答案

您可以使用最新版本的RichTextBoxRICHEDIT50W,为此您应该继承标准 RichTextBox 并覆盖 CreateParams 并将 ClassName 设置为 RICHEDIT50W:

代码

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class ExRichText : RichTextBox
{
    [DllImport("kernel32.dll", EntryPoint = "LoadLibraryW", 
        CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern IntPtr LoadLibraryW(string s_File);
    public static IntPtr LoadLibrary(string s_File)
    {
        var module = LoadLibraryW(s_File);
        if (module != IntPtr.Zero)
            return module;
        var error = Marshal.GetLastWin32Error();
        throw new Win32Exception(error);
    }
    protected override CreateParams CreateParams
    {
        get
        {
            var cp = base.CreateParams;
            try
            {
                LoadLibrary("MsftEdit.dll"); // Available since XP SP1
                cp.ClassName = "RichEdit50W";
            }
            catch { /* Windows XP without any Service Pack.*/ }
            return cp;
        }
    }
}

截图

enter image description here

注意:

  • 多亏了这个古老而有用的 visual studio 工具,我可以使用 Spy++ 看到写字板的 RichTextBox 类。

  • 如果您在操作系统中使用 RICHEDIT50W 有任何问题,您可以打开 Spy++WordPad 然后选择 RichTextBox 并查看类名是什么。

enter image description here

  • 当我搜索有关将 RICHEDIT50W 类应用到我的控件时,我找到了 this @Elmue 的精彩帖子,感谢他。

关于c# - RichTextBox 选择突出显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32591157/

相关文章:

c# - Fluent NHibernate 自动映射基类覆盖

c# - 派生类型的 FluentValidation SetCollectionValidator

c# - 按字母顺序显示 ListBox 中显示的内容

c# - 一个解决方案中最多的项目

c# - 基于列内容和标题的 ListView AutoResizeColumns

c# - 更改特定类型(不是我的)的 JSON.NET 序列化

c# - 如何使用字符串格式修剪绑定(bind)数据

c# - ASP.NET无法使用itext7下载PDF(但可以保存到磁盘)

c# - 使用 C# 代码删除文件夹?

c# - 从用户控件/类/页面访问母版页公共(public)方法