Skip to main content
A newer version of this page is available. .

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 document = server.Document;
document.BeginUpdate();
document.AppendText("Normal\nFormatted\nNormal");
document.EndUpdate();
DocumentRange range = document.Paragraphs[1].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;
document.EndUpdateCharacters(cp);