One of the controls in my application limits a user to be able to change only the font style (B, I, U) and colour of the text. I have created a custom control which inherits from the RichTextBox for this purpose. I am able to intercept CTRL-V, and set the font of the pasted text to SystemFonts.DefaultFont. The problem I am currently facing is if the pasted text contains, for example, half bold half regular style - the bold is lost.
i.e. 'Foo**Bar**' will just paste as 'FooBar'.
My only idea currently is to go through the text character by character (VERY slow), and do something like:
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();
}
}
Can anyone think of a cleaner (and faster) solution?