How to make some text bold in a rich text box in C#

前端 未结 1 944
悲哀的现实
悲哀的现实 2020-12-16 00:19

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 BoldSel         


        
相关标签:
1条回答
  • 2020-12-16 00:54

    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.

    0 讨论(0)
提交回复
热议问题