c#.net 文本编辑控件——设置RichTextBox的字体和字体大小

      上一篇文章讨论了有关设置字体格式:粗体、斜体和下划线的问题,本文将要继续讨论的是如何设置字体和字体大小。字体和字体大小的设置与字体格式的设置道理是相同的,也要区分被选中文本的SelectionFont是否为空的问题。下面分别是设置字体种类和字体大小的相关代码。

///

/// 设置字体种类,对应于字体下拉框选项 /// /// 被选中的字体名 private void ChangeFont(string fontName) { if (fontName == string.Empty) throw new System.Exception("字体名称参数错误,不能为空"); RichTextBox tempRichTextBox = new RichTextBox(); //用于保存被选中文本的副本 //curRichTextBox是当前文本,即原型 int curRtbStart = curRichTextBox.SelectionStart; int len = curRichTextBox.SelectionLength; int tempRtbStart = 0; Font font = curRichTextBox.SelectionFont; if (len <= 1 && null != font) { curRichTextBox.SelectionFont = new Font(fontName, font.Size, font.Style); return; } tempRichTextBox.Rtf = curRichTextBox.SelectedRtf; for (int i = 0; i < len; i++) //逐个设置字体种类 { tempRichTextBox.Select(tempRtbStart + i, 1); tempRichTextBox.SelectionFont = new Font(fontName, tempRichTextBox.SelectionFont.Size, tempRichTextBox.SelectionFont.Style); } //将副本内容插入到到原型中 tempRichTextBox.Select(tempRtbStart, len); curRichTextBox.SelectedRtf = tempRichTextBox.SelectedRtf; curRichTextBox.Select(curRtbStart, len); curRichTextBox.Focus(); }

 

///

/// 设置字体大小,对应于字号下拉框选项 /// /// 被选中的字号 private void ChangeFontSize(float fontSize) { if (fontSize <= 0.0) throw new InvalidProgramException("字号参数错误,不能小于等于0.0"); RichTextBox tempRichTextBox = new RichTextBox(); int curRtbStart = curRichTextBox.SelectionStart; int len = curRichTextBox.SelectionLength; int tempRtbStart = 0; Font font = curRichTextBox.SelectionFont; if (len <= 1 && null != font) { curRichTextBox.SelectionFont = new Font(font.Name, fontSize, font.Style); return; } tempRichTextBox.Rtf = curRichTextBox.SelectedRtf; for (int i = 0; i < len; i++) { tempRichTextBox.Select(tempRtbStart + i, 1); tempRichTextBox.SelectionFont = new Font(tempRichTextBox.SelectionFont.Name, fontSize, tempRichTextBox.SelectionFont.Style); } tempRichTextBox.Select(tempRtbStart, len); curRichTextBox.SelectedRtf = tempRichTextBox.SelectedRtf; curRichTextBox.Select(curRtbStart, len); curRichTextBox.Focus(); }

你可能感兴趣的:(.net)