当选择区域与两个具有不同字体的区域组合时,它将返回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/