是否可以将文本粘贴到富文本框中,同时保留粘贴内容在富文本框中使用的字体?
换句话说,我想从 Word 中复制一些已格式化的内容(即:使用字体 X 并带有下划线和蓝色的文本),然后将其粘贴到我的 RichTextBox 中。
我希望粘贴的内容具有与 RichTextBox 相同的字体,但保留其原始颜色和下划线。
这样的事可能吗?
我用的是winform。
Thanks
这是不可能开箱即用的。但你可以这样做:
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 的字体更改为粘贴时插入符号位置之前的字符的字体。
我认为如果您粘贴的文本很大(呃),那么很快就会出现问题。此外,这可以通过某种方式进行优化,即按照汉斯的建议,为具有相同基本字体的行中的所有字符仅设置一次字体。
Update:
这是优化版本,它为具有相同原始字体的连接字符集设置字体:
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;
}
这是相当丑陋的代码,我相信它可以被改进和清理。但它做了它应该做的事。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)