Changing font for richtextbox without losing formatting

后端 未结 4 2032
滥情空心
滥情空心 2020-11-27 22:11

How to change the font of all the contents of a richtextbox without losing formatting?

I am trying to use

rtb.SelectAll();
rtb.SelectionFont = new F         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 22:36

    You can pass the new font name while keeping other values intact by using the existing richtextbox font properties. For changing only font name of a selected text, you need to do:

    if (rtb.SelectionFont !=null)
        rtb.SelectionFont = new Font(fontName, rtb.SelectionFont.Size, rtb.SelectionFont.Style);
    

    Note that above code will only work, if all the selected text has same formatting (font size, style etc). This is detected by checking the SelectionFont property first, it will be null if the selection contains a mix of styles.

    Now to change the font name of all the contents of richtextbox while keeping other formatting intact, you need to loop through all the characters of the richtextbox and apply font name one by one.

    for (int i = 0; i < rtb.TextLength; i++)
    {
        rtb.Select(i, 1);
        rtb.SelectionFont = new Font(fontName, rtb.SelectionFont.Size, rtb.SelectionFont.Style);
    }
    

提交回复
热议问题