How to: Change Formatting of Selected Text
- 2 minutes to read
This code sample demonstrates how you can get the selected text in code, and modify its attributes.
To apply direct formatting to characters in a range, call the SubDocument.BeginUpdateCharacters method for the specified range, modify the properties of the returned CharacterProperties object, and subsequently call the SubDocument.EndUpdateCharacters method to finalize the modification.
The Document.Selection property is used to obtain the DocumentRange object, representing the user selection. To change default character formatting for the current document, use the Document.DefaultCharacterProperties property.
The following code snippet changes the font and the color of the specified paragraph.
The result is shown below:
A complete sample project is available at https://github.com/DevExpress-Examples/winforms-richedit-document-api-e5219
document.BeginUpdate(); document.AppendText("Normal\nFormatted\nNormal"); document.EndUpdate(); // The target range is the second paragraph DocumentRange range = document.Paragraphs.Range; // Create and customize an object // that sets character formatting for the selected range CharacterProperties cp = document.BeginUpdateCharacters(range); cp.FontName = "Comic Sans MS"; cp.FontSize = 18; cp.ForeColor = Color.Blue; cp.BackColor = Color.Snow; cp.Underline = UnderlineType.DoubleWave; cp.UnderlineColor = Color.Red; // Finalize modifications // with this method call document.EndUpdateCharacters(cp);