Peguei o seguinte método, de dentro do código do RichBoxExtended
, não fui eu quem fez, mas pode te ajudar:
public void ChangeFontStyle(FontStyle style, bool add)
{
//This method should handle cases that occur when multiple fonts/styles are selected
// Parameters:-
// style - eg FontStyle.Bold
// add - IF true then add else remove
// throw error if style isn't: bold, italic, strikeout or underline
if ( style != FontStyle.Bold
&& style != FontStyle.Italic
&& style != FontStyle.Strikeout
&& style != FontStyle.Underline)
throw new System.InvalidProgramException("Invalid style parameter to ChangeFontStyle");
int rtb1start = rtb1.SelectionStart;
int len = rtb1.SelectionLength;
int rtbTempStart = 0;
//if len <= 1 and there is a selection font then just handle and return
if(len <= 1 && rtb1.SelectionFont != null)
{
//add or remove style
if (add)
rtb1.SelectionFont = new Font(rtb1.SelectionFont, rtb1.SelectionFont.Style | style);
else
rtb1.SelectionFont = new Font(rtb1.SelectionFont, rtb1.SelectionFont.Style & ~style);
return;
}
// Step through the selected text one char at a time
rtbTemp.Rtf = rtb1.SelectedRtf;
for(int i = 0; i < len; ++i)
{
rtbTemp.Select(rtbTempStart + i, 1);
//add or remove style
if (add)
rtbTemp.SelectionFont = new Font(rtbTemp.SelectionFont, rtbTemp.SelectionFont.Style | style);
else
rtbTemp.SelectionFont = new Font(rtbTemp.SelectionFont, rtbTemp.SelectionFont.Style & ~style);
}
// Replace & reselect
rtbTemp.Select(rtbTempStart,len);
rtb1.SelectedRtf = rtbTemp.SelectedRtf;
rtb1.Select(rtb1start,len);
return;
}
rtbTemp
é um RichTextBox
auxiliar, e rtb1
é o RichTextBox
principal.