How do I maintain RichText formatting (bold/italic/etc) when changing any one element?

后端 未结 5 781
醉酒成梦
醉酒成梦 2020-12-05 15:52

I have a rich text box that may contain a string that has elements of bold, italics, or even different fonts and sizes. If I select the entire string, including all of the d

5条回答
  •  离开以前
    2020-12-05 16:31

    To make a text selection bold while keeping its formatting intact, use this:

    if (rtb.SelectionFont !=null)
        rtb.SelectionFont = new Font(rtb.SelectionFont, rtb.SelectionFont.Style | FontStyle.Bold);
    

    To unBold text selection while keeping its formatting intact, use this:

    if (rtb.SelectionFont !=null)
        rtb.SelectionFont = new Font(rtb.SelectionFont, rtb.SelectionFont.Style & ~FontStyle.Bold);
    

    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 do this with all text in richtextbox,

    Now to Bold/unBold the entire text of richtextbox while keeping other formatting intact, you need to loop through all the characters of the richtextbox and apply Bold/unBold one by one. Here is the complete code:

    private void tsBold_Click(object sender, EventArgs e)
    {
        //Loop through all the characters of richtextbox
        for (int i = 0; i < rtb.TextLength; i++)
        {
            //Select current character
            rtb.Select(i, 1);
    
            if (tsBold.Checked)
                //Make the selected character Bold
                rtb.SelectionFont = new Font(rtb.SelectionFont, rtb.SelectionFont.Style | FontStyle.Bold);
            else
                //Make the selected character unBold
                rtb.SelectionFont = new Font(rtb.SelectionFont, rtb.SelectionFont.Style & ~FontStyle.Bold);
        }
    }
    

    If you need to toggle the existing state of Bold (i.e. make non-bold text Bold and make bold text unBold), use this instead:

            if (rtb.SelectionFont.Style.ToString().Contains("Bold")) //If the selected character is Bold
                //Make the selected character unBold
                rtb.SelectionFont = new Font(rtb.SelectionFont, rtb.SelectionFont.Style & ~FontStyle.Bold);
            else //If the selected character is unBold
                //Make the selected character Bold
                rtb.SelectionFont = new Font(rtb.SelectionFont, rtb.SelectionFont.Style | FontStyle.Bold);
    

提交回复
热议问题