简体   繁体   中英

C# - Change font of text in RichTextBox dynamically?

I am having some text in a "richTextBox" and a "comboBox" having names of some fonts. I want to change the font of text in "richTextBox" if a new font is selected from the "comboBox". I am using following code.

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (comboBox1.SelectedIndex == 1)
        richTextBox1.Font = new Font("Comic Sans MS", 14);
}

The problem is that if I select the font, the text does not change its font automatically, it only changes if I type some new text. I also tried richTextBox1.SelectionFont instead of richTextBox1.Font . I also added InputTextBox.Refresh(); after the above code to refresh the text box but in vein.

How I can change font of the text by just selecting from comboBox?

Update: I just figured out that above code is fine, the problem is that I was using wrong event call, used comboBox1_SelectedValueChanged() in place of comboBox1_SelectedIndexChanged() and it works fine now.

Tip: If you want to change font of entire TextBox use richTextBox1.Font , if you want to change font of selected text only use richTextBox1.SelectionFont .

You could select all the text before changing SelectedFont option:

this.richTextBox1.SelectAll();
this.richTextBox1.SelectionFont = newFont;

You have to iterate throughout your text for that. This is a method it might help you:

private void ChangeFontStyleForSelectedText(string familyName, float? emSize, FontStyle? fontStyle, bool? enableFontStyle)
    {
        _maskChanges = true;
        try
        {
            int txtStartPosition = txtFunctionality.SelectionStart;
            int selectionLength = txtFunctionality.SelectionLength;
            if (selectionLength > 0)
                using (RichTextBox txtTemp = new RichTextBox())
                {
                    txtTemp.Rtf = txtFunctionality.SelectedRtf;
                    for (int i = 0; i < selectionLength; ++i)
                    {
                        txtTemp.Select(i, 1);
                        txtTemp.SelectionFont = RenderFont(txtTemp.SelectionFont, familyName, emSize, fontStyle, enableFontStyle);
                    }

                    txtTemp.Select(0, selectionLength);
                    txtFunctionality.SelectedRtf = txtTemp.SelectedRtf;
                    txtFunctionality.Select(txtStartPosition, selectionLength);
                }
        }
        finally
        {
            _maskChanges = false;
        }
    }

If you want to see how I did this you can read this article: http://how-to-code-net.blogspot.ro/2014/01/how-to-make-custom-richtextbox-control.html Good luck ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM