上一篇文章讨论了有关设置字体格式:粗体、斜体和下划线的问题,本文将要继续讨论的是如何设置字体和字体大小。字体和字体大小的设置与字体格式的设置道理是相同的,也要区分被选中文本的SelectionFont是否为空的问题。下面分别是设置字体种类和字体大小的相关代码。 -
-
-
-
- private void ChangeFont(string fontName)
- {
- if (fontName == string.Empty)
- throw new System.Exception("字体名称参数错误,不能为空");
-
- 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(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();
- }
|