参数
family
新 Font 的 FontFamily。
emSize
新字体的全身大小(以磅值为单位)。
style
新字体的 FontStyle。
第三个参数就是用来设置字体样式的,FontStyle是个枚举类型,可以从MSDN里查到它的说明如下:
FontStyle 枚举
指定应用到文本的字形信息。
此枚举有一个 FlagsAttribute 属性,允许其成员值按位组合。
而它的成员如下:
成员名称 说明
Bold 加粗文本。
Italic 倾斜文本。
Regular 普通文本。
Strikeout 中间有直线通过的文本。
Underline 带下划线的文本。
补充:如果想要FontStyle可以拥有多个属性,如同时拥有加粗和倾斜效果,则可以通过位运算符 | ,快速得到,其它的操作类似。
2.讲一个具体调控选中文本的加粗效果的事例(其它效果可照搬)
//设置粗体
private void toolStripButton3_Click(object sender, EventArgs e)
{
if (this.fileContent.SelectionFont != null) //当前选定文本只具有一种字体,字体Font只要其中的三个属性中的一个不同,就不属于统一字体
{//获取或设置当前选定文本或插入点的字体。
Font oldFont, newFont;
oldFont = this.fileContent.SelectionFont;
if (oldFont.Bold)
{
newFont = new Font(oldFont, oldFont.Style ^ FontStyle.Bold); //通过异或操作,去掉粗体属性
}
else
{
newFont = new Font(oldFont, oldFont.Style | FontStyle.Bold);
}
this.fileContent.SelectionFont = newFont;
this.fileContent.Focus();
}
else //选定的文本具有多种字体
{
RichTextBox tempRichTextBox = new RichTextBox(); //将要存放被选中文本的副本
//得到实际富文本框中所选取的文本信息
int curRtbStart = this.fileContent.SelectionStart;
int len = this.fileContent.SelectionLength;
//设置副本信息
int tempRtbStart = 0;
tempRichTextBox.Rtf = this.fileContent.SelectedRtf;
//设置个计数器
int amount = 0;
for (int i = 0; i < len; i++)
{
tempRichTextBox.Select(tempRtbStart + i, 1); //一个一个选中每一个字
if(tempRichTextBox.SelectionFont.Bold == true)
{
amount++;
}
}
//如果其中至少有一个而不是全部是粗体,那么全部设置成粗体
if(amount>0&&amount<len)
{
for (int i = 0; i < len; i++)
{
tempRichTextBox.Select(tempRtbStart + i, 1); //一个一个选中每一个字
if (tempRichTextBox.SelectionFont.Bold != true)
{
Font oldFont, newFont;
oldFont = tempRichTextBox.SelectionFont;
newFont = new Font(oldFont, oldFont.Style | FontStyle.Bold);
tempRichTextBox.SelectionFont = newFont;
}
}
}
//如果其中全部为粗体,那么全部去掉它的粗体属性
if(amount == len)
{
for (int i = 0; i < len; i++)
{
tempRichTextBox.Select(tempRtbStart + i, 1); //一个一个选中每一个字
if (tempRichTextBox.SelectionFont.Bold == true)
{
Font oldFont, newFont;
oldFont = tempRichTextBox.SelectionFont;
newFont = new Font(oldFont, oldFont.Style ^ FontStyle.Bold);
tempRichTextBox.SelectionFont = newFont;
}
}
}
//如果其中全部不为粗体,那么全部设置为粗体
if(amount == 0)
{
for (int i = 0; i < len; i++)
{
tempRichTextBox.Select(tempRtbStart + i, 1); //一个一个选中每一个字
if (tempRichTextBox.SelectionFont.Bold != true)
{
Font oldFont, newFont;
oldFont = tempRichTextBox.SelectionFont;
newFont = new Font(oldFont, oldFont.Style | FontStyle.Bold);
tempRichTextBox.SelectionFont = newFont;
}
}
}
tempRichTextBox.Select(tempRtbStart, len);
this.fileContent.SelectedRtf = tempRichTextBox.SelectedRtf; //将设置格式后的副本拷贝给原型
this.fileContent.Select(curRtbStart, len);
}
}