gpt4 book ai didi

C#:在 RichTextBox 中粘贴 RTF,但保留颜色和格式(即:粗体、下划线等)

转载 作者:行者123 更新时间:2023-12-03 22:20:23 24 4
gpt4 key购买 nike

是否可以将文本粘贴到富文本框中,同时保留富文本框中用于粘贴内容的字体?

换句话说,我想从格式化的 Word 中复制一些内容(即:使用字体 X 并带有下划线和蓝色的文本),然后将其粘贴到我的 RichTextBox 中。

我希望粘贴的内容具有与我的 RichTextBox 相同的字体,但保留其原始颜色和下划线。

这样的事情可能吗?

我用的是winforms。

谢谢

最佳答案

开箱即用是不可能的。但是你可以这样做:

public void SpecialPaste()
{
var helperRichTextBox = new RichTextBox();
helperRichTextBox.Paste();
for(int i=0;i<helperRichTextBox.TextLength;++i)
{
helperRichTextBox.SelectionStart = i;
helperRichTextBox.SelectionLength = 1;
helperRichTextBox.SelectionFont = new Font(richTextBox1.SelectionFont.FontFamily, richTextBox1.SelectionFont.Size,helperRichTextBox.SelectionFont.Style);
}

richTextBox1.SelectedRtf = helperRichTextBox.Rtf;
}

这会将粘贴的 RTF 的字体更改为粘贴时插入符号位置之前的字符的字体。
如果您粘贴的文本很大(呃),我认为这会很快出现问题。此外,这可以在某种程度上进行优化,它只为一行中的所有字符设置一次字体,使用与 Hans 建议的相同的基本字体。

更新:
这是优化版本,它为一组连接的字符设置相同原始字体的字体:

public void SpecialPaste()
{
var helperRichTextBox = new RichTextBox();
helperRichTextBox.Paste();
helperRichTextBox.SelectionStart = 0;
helperRichTextBox.SelectionLength = 1;

Font lastFont = helperRichTextBox.SelectionFont;
int lastFontChange = 0;
for (int i = 0; i < helperRichTextBox.TextLength; ++i)
{
helperRichTextBox.SelectionStart = i;
helperRichTextBox.SelectionLength = 1;
if (!helperRichTextBox.SelectionFont.Equals(lastFont))
{
lastFont = helperRichTextBox.SelectionFont;
helperRichTextBox.SelectionStart = lastFontChange;
helperRichTextBox.SelectionLength = i - lastFontChange;
helperRichTextBox.SelectionFont = new Font(richTextBox1.SelectionFont.FontFamily, richTextBox1.SelectionFont.Size, helperRichTextBox.SelectionFont.Style);
lastFontChange = i;
}
}
helperRichTextBox.SelectionStart = helperRichTextBox.TextLength-1;
helperRichTextBox.SelectionLength = 1;
helperRichTextBox.SelectionFont = new Font(richTextBox1.Font.FontFamily, richTextBox1.Font.Size, helperRichTextBox.SelectionFont.Style);

richTextBox1.SelectedRtf = helperRichTextBox.Rtf;
}

这是非常难看的代码,我相信它可以改进和清理。但它做了它应该做的。

关于C#:在 RichTextBox 中粘贴 RTF,但保留颜色和格式(即:粗体、下划线等),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5477676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com