when the selection area is combined with 2 areas that has different fonts, it returns null.代码如下:
private Font myGetSelectionFont()
{
Font t = this.workspace.SelectionFont;
if (t == null)
return defaultFont;
else return t;
}
private void toolStripComboBox_size_SelectedIndexChanged(object sender, EventArgs e)
{
string sizeString = ((ToolStripComboBox)sender).SelectedItem.ToString();
float curSize = float.Parse(sizeString);
Font oldFont = myGetSelectionFont();
Font newFont = this.getFont(oldFont.FontFamily.Name, curSize, oldFont.Style);
this.setFontIcons(newFont);
this.workspace.SelectionFont = newFont;
this.workspace.Focus();
}
为所选区域设置不同的字体没有问题,但我不知道所选区域的字体大小和其他属性。我该怎么办?
我想我可以选择将字体设置为选中区域之前的字体,或者选中区域之后的字体,但我不知道该怎么做。
最佳答案
一个可能的解决方案是循环
private void toolStripComboBox_size_SelectedIndexChanged(object sender, EventArgs e)
{
float size = float.Parse(((ToolStripComboBox)sender).SelectedItem.ToString());
SetFontSize(richTextBox1, size);
}
private void SetFontSize(RichTextBox rtb, float size)
{
int selectionStart = rtb.SelectionStart;
int selectionLength = rtb.SelectionLength;
int selectionEnd = selectionStart + selectionLength;
for (int x = selectionStart; x < selectionEnd; ++x)
{
// Set temporary selection
rtb.Select(x, 1);
// Toggle font style of the selection
rtb.SelectionFont = new Font(rtb.SelectionFont.FontFamily, size, rtb.SelectionFont.Style);
}
// Restore the original selection
rtb.Select(selectionStart, selectionLength);
}
关于c# - 使用 RichTextBox.SelectionFont 时出现 nullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21089167/