我为RichTextBox创建了一个ToolStrigMenuItem.在它的Click事件中,我将剪贴板中的一些文本粘贴到RichTextBox中.

The problem is that in the Form Designer the ForeColor of the RichTextBox is set to Color.Yellow, but if the text in the Clipboard contains different colors, some sections of the text won't be visible all, because the BackColor of the RichTextBox is black.
I want to select the pasted text and color it in yellow.

这是我粘贴文本的事件:

private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
    // Handle the Paste event
    richTextBox1.Paste();

    // Set the desired formatting (e.g., yellow color) for the pasted text
    richTextBox1.SelectionColor = Color.Yellow;
}

我试着添加了这句话:

richTextBox1.SelectionColor = Color.Yellow;

但这并没有解决任何问题.

Here is a screenshot example of text I paste in the RichTextBox. The text in the Clipboard is partially colored in blue and brown.
The brown color is swallowed in the black background and the blue is hard to see. I want it all to be in yellow.

colors

如何更改代码,以便无论粘贴到RichTextBox中的文本是什么,都将使用RichTextBox ForeColor进行着色?

推荐答案

When you paste text into a RichTextBox, the caret is moved to the end of the new text.
Setting the SelectionColor does nothing, since nothing is selected.
If any formatting - that the Control understands - is applied to the pasted text, that format is preserved (e.g., if you paste text copied from the Visual Studio editor, MS Word, etc.)

可以在粘贴新文本之前存储插入符号位置,然后从指向粘贴文本末尾的当前位置减go 该位置,以确定粘贴文本的长度.

然后仅 Select 该块,以更改其 colored颜色 .例如:

var previousStartPosition = richTextBox1.SelectionStart;

richTextBox1.Paste();

var newTextLength = richTextBox1.SelectionStart - previousStartPosition;
richTextBox1.Select(previousStartPosition, newTextLength);
richTextBox1.SelectionColor = Color.Yellow; // Or richTextBox1.ForeColor 

Csharp相关问答推荐

无法解析数据库上下文的服务

如何使用XmlSerializer反序列化字符串数组?

方法从数据表中只 Select 一个条件?

如何将MongoDB序列化程序设置为内部对象属性

如何注册类使用多级继承与接口

集合表达式没有目标类型

有空容错运算符的对立面吗?

.NET 8在appsettings.json中核心使用词典URI、URI&>

未在Windows上运行的Maui项目

在同一个捕获中可以有多种类型的异常吗?

FakeItEasy自动嘲弄内容

Visual Studio如何使用当前的框架?

具有嵌套属性的IGGroup

如何从SignalR获取连接客户端的域

Linq SELECT的多条指令

如何消除Visual Studio错误,因为它不识别集合表达式的新C#12语法?

在ObservableCollection上使用[NotifyPropertyChangedFor()]源代码生成器不会更新UI

无法将.Net Framework 4.8.1升级到.Net 7

阻止CLR释放已封送的双字符指针的内存?

C#AWS S3上载损坏的文件