C#中RTF的SelectionFont属性为null

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

代码:

    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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值