添加命名空間
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;
}