Reputation: 1852
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:
DataObject.AddPastingHandler(RichTextBoxControl, TextBoxPasting);
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
.
Upvotes: 0
Views: 778
Reputation: 1852
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.
Upvotes: 2