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.

NOTE

Make sure that the SubDocument.BeginUpdateCharacters method always has its corresponding SubDocument.EndUpdateCharacters method to ensure proper operation of the control.

The following code snippet changes the font and the color of the specified paragraph.

The result is shown below:

FontFormattingExample

document.BeginUpdate();
document.AppendText("Normal\nFormatted\nNormal");
document.EndUpdate();
// The target range is the second paragraph 
DocumentRange range = document.Paragraphs[1].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);