添加命名空间
using System.Drawing.Text;
添加两个类型分别为Color和int的私有变量:
private Color textColor;
private int textSize;
双击窗体,插入load事件,从而将NumericUpDown控件的Value属性设置为10,并在组合框控件中添加所有已安装的字体。
private void Form1_Load(object sender,
System.EventArgs e)
{
numericUpDown1.Value = 10;
// Create InstalledFontCollection object
InstalledFontCollection
sysFontCollection =
new InstalledFontCollection();
// Get the array of FontFamily objects.
FontFamily[] fontFamilies =
sysFontCollection.Families;
// Read all font familes and
// add to the combo box
foreach (FontFamily ff in fontFamilies)
{
comboBox1.Items.Add(ff.Name);
}
comboBox1.Text = fontFamilies[0].Name;
}
“Color”按钮的click事件将调用ColorDialog,以便用户可以选择文本的颜色。
private void button1_Click(object sender,
System.EventArgs e)
{
// Create a Color dialog and let
// the user select a color
// Save the selected color
ColorDialog colorDlg = new ColorDialog();
if(colorDlg.ShowDialog() == DialogResult.OK)
{
textColor = colorDlg.Color;
}
}
“Apply”按钮将从组合框中读取选中的字体名称,并从NumericUpDown控件中读取字体的大小。然后它将使用字体家族的名称和大小创建一个Font对象。最后,我们设置RichTextBox控件的ForeColor和Fort属性。
private void button2_Click(object sender,
System.EventArgs e)
{
// Get the size of text from
// numeric up down control
textSize = (int)numericUpDown1.Value;
// Get current font name from the list
string selFont = comboBox1.Text;
// Create a new font from the current selection
Font textFont = new Font(selFont, textSize);
// Set color and font of richtext box
richTextBox1.ForeColor = textColor;
richTextBox1.Font = textFont;
}