C#中RTF的SelectionFont属性为null

来源:互联网 发布:final cut pro mac 编辑:程序博客网 时间:2024/05/19 18:48

目的:黑体改为非黑体,非黑体改为黑体。

代码:

    private void buttonBold_Click(object sender, EventArgs e)    {      Font oldFont;      Font newFont;      // Get the font that is being used in the selected text      oldFont = this.richTextBoxText.SelectionFont;      // If the font is using bold style now, we should remove the      // Formatting      if (oldFont.Bold)        newFont = new Font(oldFont, oldFont.Style & ~FontStyle.Bold);      else        newFont = new Font(oldFont, oldFont.Style | FontStyle.Bold);      // Insert the new font and return focus to the RichTextBox      this.richTextBoxText.SelectionFont = newFont;      this.richTextBoxText.Focus();    }

问题:当字体不一样时SelectionFont属性为null,会报错。

原因:SelectionFont仅能给出一种字体,当被选择的字有多种字体时返回null。

解决方法:逐字处理。

另外考虑到正常情况下bold起的作用为:被选择的字存在非黑体时把所有字转为黑体,被选择的字全部为黑体时则转为非黑体。但每个字的其他属性(如斜体,下划线,字号)应该保持不变。修改后的代码:

        private void btnBold_Click(object sender, EventArgs e)        {            Font oldFont;            Font newFont;                 int len = this.rtfText.SelectionLength;                int st = this.rtfText.SelectionStart;                bool flag = true;                //寻找非黑体                for (int i = 0; i < len; i++)                {                    this.rtfText.Select(st+i,1);                    flag = this.rtfText.SelectionFont.Bold;                    if (flag == false)//存在非黑体,提前结束                    {                        break;                    }                                      }                if (flag)//全部为黑体,全部转为非黑体                {                    for (int i = 0; i < len; i++)                    {                        this.rtfText.Select(st + i, 1);                        oldFont = this.rtfText.SelectionFont;                        newFont = new Font(oldFont, oldFont.Style & ~FontStyle.Bold);                        this.rtfText.SelectionFont = newFont;                    }                }                else//存在非黑体,全部转为黑体                {                    for (int i = 0; i < len; i++)                    {                        this.rtfText.Select(st + i, 1);                        oldFont = this.rtfText.SelectionFont;                        newFont = new Font(oldFont, oldFont.Style | FontStyle.Bold);                        this.rtfText.SelectionFont = newFont;                    }                }                this.rtfText.Select(st, len);                this.rtfText.Focus();                  }

参考文章:

http://topic.csdn.net/u/20100504/10/cbb60952-0c4b-473f-9a1d-b78c7fea039e.html