0
votes

I am having trouble removing the formatting (bold, font, size etc.) on paste of some formatted text into a RichTextBox.

I have successfully been using the following:

  1. Add a pasting handler to the RichTextBox

DataObject.AddPastingHandler(RichTextBoxControl, TextBoxPasting);

  1. Remove formatting and insert text
private void TextBoxPasting(object sender, DataObjectPastingEventArgs e)
{
   var pastingText = e.DataObject.GetData(DataFormats.Text) as string;
   RichTextBoxControl.Document.ContentEnd.InsertTextInRun(pastingText);
   e.CancelCommand();
}

But unfortunately this always places the inserted text in the end of the RichTextBox. Also the caret is not moving.

Let us say you are at this positing:

Helloꕯ World and you are pasting Beautiful you would get Helloꕯ World Beutiful instead of Hello Beutifulꕯ World.

1

1 Answers

1
votes

Instead of manually inserting the text and cancelling the event you could just alter the text that is to be inserted in the DataObjectPastingEventArgs, and let the chains of the event do all the work for you.

private static void TextBoxPasting(object sender, DataObjectPastingEventArgs e)
{
   e.DataObject = new DataObject(DataFormats.Text, e.DataObject.GetData(DataFormats.Text) as string ?? string.Empty);
}

e.DataObject.GetData(DataFormats.Text) is getting you the plain text without any formatting. The caret will move properly since you are not canceling the events that were supposed to move it.