14

I want to create a text editor where I can make text bold, change its color, etc.

I found this code to approximately work:

public static void BoldSelectedText(RichTextBox control)
{
     control.SelectionFont = new Font(control.Font.FontFamily, control.Font.Size,         FontStyle.Bold);
}

But when I type in more letters in the RichTextBox the text is still bold.

How can I make it so that only the selected text is bold and the next characters aren't unless I select the text and hit the "Make Bold" button?

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
chrs
  • 5,906
  • 10
  • 43
  • 74

1 Answers1

24

You should set the font after the selection to the original font.

If you want you can save the SelectionStart and SelectionLength and call the Select method to select the text again.

// Remember selection
int selstart = control.SelectionStart;
int sellength = control.SelectionLength;

// Set font of selected text
// You can use FontStyle.Bold | FontStyle.Italic to apply more than one style
control.SelectionFont = new Font(control.Font, FontStyle.Bold);

// Set cursor after selected text
control.SelectionStart = control.SelectionStart + control.SelectionLength;
control.SelectionLength = 0;
// Set font immediately after selection
control.SelectionFont = control.Font;

// Reselect previous text
control.Select(selstart, sellength);

this way the text stays selected, and the font afterwards is still correct.

Patrick
  • 17,669
  • 6
  • 70
  • 85
  • Do you know how i can bold and italic text? – chrs Oct 28 '11 at 01:05
  • 1
    http://stackoverflow.com/questions/4198429/substract-flag-from-fontstyle-toggling-fontstyles-c that helped – chrs Oct 28 '11 at 01:35
  • 1
    I know this is an old thread, but for the benefit of others, FontStyle has the Flags attribute, so you can do things like FontStyle.Bold | FontStyle.Italic, etc. – j2associates Sep 04 '15 at 08:58
  • I think this is a tad outdated.. It only keeps the text BEFORE the bold text's font, but the text thereafter is also bold, which I assume is not how this is supposed to go.. – Momoro Mar 21 '20 at 22:02