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 au开发者_如何转开发tomatically, 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 ;)
精彩评论