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
- C#中RTF的SelectionFont属性为null
- hibernate中获取关联属性为null的方式
- C#中打印Rtf文档
- c#中读写rtf文件
- gson中null值替换,gson自动过滤值为null的属性
- 验证对象中属性是否为null
- C#中‘事件’可否赋值为null
- C# Visual Studio 2005中RichTextBox保存文件为rtf格式
- C# Visual Studio 2005中RichTextBox打开文件为rtf格式
- SuperMap属性表操作中遇到的Query结果为null的问题分析及解决
- spring boot 返回的json中去掉值为null的属性
- C#编程:可以为 null 的类型
- C# 可为null的类型
- C#使用可以为null的类型
- C#可以为null的数据类型
- Spring 父类注入的属性 在子类中调用为null
- Spring的JdbcTemplate从数据库中获取对象属性总为null
- Spring MVC 容器中设置Bean属性值 为NULL
- oracle 函数大全 之 coalesce
- 文档规范
- USACO 3.2.4 Feed Ratios
- 高斯消元法(Gauss Elimination) 分析 & 题解 & 模板
- 语言模型训练工具SRILM
- C#中RTF的SelectionFont属性为null
- 经典查询练手第五篇
- 关于流程控制,几个小程序巩固你的流程控制的理解
- 数据库持久化的深入理解
- createrepo:创建本地源
- 透视图开发
- 折半插入排序算法
- HibernateTransactionManager 事务管理实现
- 嵌入学习步骤及方法