提问人:Jack 提问时间:11/16/2023 最后编辑:JimiJack 更新时间:11/16/2023 访问量:74
将剪贴板中的文本粘贴到 RichTextBox 中时,新文本不会在 RichTextBox ForeColor 中着色
When pasting text from the Clipboard into a RichTextBox, the new text is not colored in the RichTextBox ForeColor
问:
我为 RichTextBox 创建了一个 ToolStripMenuItem。在其 Click 事件中,我将剪贴板中的一些文本粘贴到 RichTextBox 中。
问题在于,在窗体设计器中,RichTextBox 的 设置为 ,但如果剪贴板中的文本包含不同的颜色,则文本的某些部分将不可见,因为 RichTextBox 的 BackColor 是黑色的。
我想选择粘贴的文本并将其涂成黄色。ForeColor
Color.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;
但它没有解决任何问题。
下面是我粘贴到 RichTextBox 中的文本的屏幕截图示例。剪贴板中的文本部分为蓝色和棕色。
棕色被吞没在黑色背景中,蓝色很难看到。我希望它都是黄色的。
如何更改我的代码,以便无论我粘贴到RichTextBox中的什么文本,它都将使用RichTextBox着色?ForeColor
答:
2赞
Jimi
11/16/2023
#1
将文本粘贴到 RichTextBox 中时,插入符号将移动到新文本的末尾。
设置 不执行任何操作,因为未选择任何内容。
如果将控件理解的任何格式应用于粘贴的文本,则将保留该格式(例如,如果粘贴从 Visual Studio 编辑器、MS Word 等复制的文本)SelectionColor
您可以在粘贴新文本之前存储插入符号位置,然后从指向粘贴文本末尾的当前位置中减去该位置,以确定粘贴文本的长度。
然后仅选择该块以更改其颜色。例如:
var previousStartPosition = richTextBox1.SelectionStart;
richTextBox1.Paste();
var newTextLength = richTextBox1.SelectionStart - previousStartPosition;
richTextBox1.Select(previousStartPosition, newTextLength);
richTextBox1.SelectionColor = Color.Yellow; // Or richTextBox1.ForeColor
评论
0赞
Jack
11/16/2023
例如,当我从 visua lstudio 复制并粘贴这一行时,它是黄色的:private void toolStripMenuItem1_Click(object sender, EventArgs e),但如果我复制并粘贴例如此链接:stackoverflow.com/questions/77489637/... 那么它是白色的,而不是黄色的。我试过你的解决方案。
0赞
Jimi
11/16/2023
如果 RichTextBox 具有 ,则计算出的对比色将应用于链接。将其设置为应用您的颜色DetectUrls = true
false
评论