我的应用程序中的控件之一限制了用户只能更改文本的字体样式(B,I,U)和颜色。为此,我创建了一个从RichTextBox继承的自定义控件。我可以拦截CTRL-V,并将粘贴文本的字体设置为SystemFonts.DefaultFont
。我目前面临的问题是,如果粘贴的文本包含例如半大胆的半正规风格 - 大胆丢失。如何在不更改样式的情况下设置RichTextBox.SelectionFont FontFamily?
I.e. “Foo Bar”只会粘贴为“Foo Bar”。
我唯一的想法目前是由字符(非常慢)要经过的文本字符,并且这样做:
public class MyRichTextBox : RichTextBox
{
private RichTextBox hiddenBuffer = new RichTextBox();
/// <summary>
/// This paste will strip the font size, family and alignment from the text being pasted.
/// </summary>
public void PasteUnformatted()
{
this.hiddenBuffer.Clear();
this.hiddenBuffer.Paste();
for (int x = 0; x < this.hiddenBuffer.TextLength; x++)
{
// select the next character
this.hiddenBuffer.Select(x, 1);
// Set the font family and size to default
this.hiddenBuffer.SelectionFont = new Font(SystemFonts.DefaultFont.FontFamily, SystemFonts.DefaultFont.Size, this.hiddenBuffer.SelectionFont.Style);
}
// Reset the alignment
this.hiddenBuffer.SelectionAlignment = HorizontalAlignment.Left;
base.SelectedRtf = this.hiddenBuffer.SelectedRtf;
this.hiddenBuffer.Clear();
}
}
谁能想到一个更清洁的(快)解决方案?