4

我有一个 RichTextBox。我想更改所选文本的字体样式而不更改 FontFamily。

我使用此代码

 RTBMain.SelectionFont = new Font(RTBMain.SelectionFont, FontStyle.Bold);

这是更改字体样式,但我的问题是:

当我选择更改 fontfamily 的文本时,出现错误

你调用的对象是空的。

因为

RTBMain.SelectionFont=null

例如 :

我的文字是“我有一个学生”

“a”的 FontFamily 是“Tahoma”

“学生”的字体家族是“探戈”

然后我选择“a student”:FontFamily 为空。

但是当我选择“a”或“student”时:字体系列不是空的。

4

2 回答 2

3
if(RTBMain.SelectionFont != null)
{
 RTBMain.SelectionFont = new Font(RTBMain.SelectionFont, FontStyle.Bold);
}

或者

if (RTBMain.SelectionLength > 0)
{
 RTBMain.SelectionFont = new Font(RTBMain.SelectionFont, FontStyle.Bold);
}

参考

private void ToggleBold()
{
 if (richTextBox1.SelectionFont != null)
 {
  System.Drawing.Font currentFont = richTextBox1.SelectionFont;
  System.Drawing.FontStyle newFontStyle;

  if (richTextBox1.SelectionFont.Bold == true)
  {
     newFontStyle = FontStyle.Regular;
  }
  else
  {
     newFontStyle = FontStyle.Bold;
  }

  richTextBox1.SelectionFont = new Font(
     currentFont.FontFamily, 
     currentFont.Size, 
     newFontStyle
  );
 }

}

于 2013-01-30T10:10:09.863 回答
1

例如:

richTextBox1.Find("Text", RichTextBoxFinds.MatchCase);

richTextBox1.SelectionFont = new Font("Verdana", 12, FontStyle.Bold);
richTextBox1.SelectionColor = Color.Red;

首先,您需要选择要更改格式的文本。

并且SelectionFont不能同时是两种字体。

于 2013-01-30T10:01:23.860 回答