Search code examples
c#winformsfontsrichtextboxselectionchanged

how to get the fontsize of a certain line in a richtextbox in c# using winforms


I have 2 comboboxes for the font and the fontsize. When I click them it changes the font size or the font in my richtextbox. Now I want it to work like in word. If the line you just moved to is in a different font or size. It should detect that and change the comboxes to match the font and size of the current line. Somoeone else asked this same question and got a result which didn't work for me. It was as follows

    private void richTextBox1_SelectionChanged(object sender, EventArgs e)
    {
        MessageBox.Show("we got here"); // this is my added part to let me know if the code is even getting executed. It is not.
        richTextBox1.SelectionStart = 1;
        richTextBox1.SelectionLength = 1;
        comboBox1.Text = richTextBox1.SelectionFont.ToString();
        comboBox2.Text = null;
        comboBox2.Text = richTextBox1.SelectionFont.Size.ToString();

    }

I held out hope that it was my answer but I could not see how SelectionFont would make any difference when nothing was selected. Also the richTextBox1_SelectionChanged event seems to not be being called when I move through the document with the up/down arrows. The problem is not with the comboboxes, the problem is that as I arrow through my document I need to be able to know what font and size it is at the caret position so it can fire an event to change the combo boxes to match.


Solution

  • You should save the values for the new comboBox position temporarily in variables, otherwise if you do it directly

    comboBox1.SelectedIndex = comboBox1.FindStringExact(richTextBox1.SelectionFont.Name);
    

    the comboBox1_SelectedIndexChanged event will be immediately called and could affect the results.

    So just try:

    private void richTextBox1_SelectionChanged(object sender, EventArgs e)
    {
        int comboBox1Index = comboBox1.FindStringExact(richTextBox1.SelectionFont.Name);
        int comboBox2Index = comboBox2.FindStringExact(richTextBox1.SelectionFont.Size.ToString());
    
        comboBox1.SelectedIndex = comboBox1Index;
        comboBox2.SelectedIndex = comboBox2Index;
    }