我为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相关问答推荐

Microsoft.AspNetCore.Mvc. Controller Base.用户:属性或索引器Controller Base.用户无法分配给--它是只读的

如何在NServicebus中配置学习传输的文件夹(NService bus 8)

在FilePath中搜索一个词,并根据First Match从左到右提取文件路径

C#.NET依赖项注入顺序澄清

不带身份的Blazor服务器.Net 8 Cookie身份验证

在EF Core中,有没有什么方法可以防止在查询中写入相同的条件,而代之以表达式?

NET8 Maui&;iOS:AppCenter崩溃错误

什么时候接受(等待)信号灯?尽可能的本地化?

对于PowerShell中的ConvertTo-SecureString方法,Microsoft如何将初始化向量添加到AES加密中的安全字符串?

为什么Docker中没有转发该端口?

用C#从XML内部元素中获取特定值

如何将%{v_扩展}转换为%{v_扩展}>>

如何在特定环境中运行dotnet测试?

在.NET8中如何反序列化为私有字段?

如何使用IHostedService添加数据种子方法

如何在单击按钮后多次异步更新标签

如何在C#控制台应用程序中获取用户输入并将其作为订单项目进行处理?

C#中使用ReadOnlySpan的泛型类型推理

如何在特定时间间隔运行多个后台任务?

使用';UnityEngineering.Random.Range()';的IF语句仅适用于极高的最大值