C# 不同元件使用同方法 文字修改範例
一、使用同一方法 改變TextBox的文字、顏色
private void FontSizeChange(object sender, EventArgs e)
{
RadioButton rb = sender as RadioButton;
//將互斥的RadioButton使用同一個方法FontSizeChange
if (rb.Checked)
{
Font ff = new Font("標楷體", int.Parse(rb.Text), FontStyle.Regular);
textBox1.Font = ff;
}
}
private void FontColorChange(object sender, EventArgs e)
{
RadioButton rb = sender as RadioButton;
//將互斥的RadioButton使用同一個方法FontColorChange
if (rb.Checked)
{
switch (rb.Text)
{
case "黑色": textBox1.ForeColor = Color.Black; break;
case "紅色": textBox1.ForeColor = Color.Red; break;
case "綠色": textBox1.ForeColor = Color.Green; break;
case "藍色": textBox1.ForeColor = Color.Blue; break;
}
}
}
說明:以上2個方法,可修改textBox1的文字大小及顏色
一、在設計界面上拉出數個RadioButton,並將互斥的放入同一groupBox中
二、設定互斥的RadioButton的CheckedChange使用同一方法
二、數個checkBox 改變文字型態(複寫)
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
Font oldFont=textBox1.Font;
//抓出textBox1.Font的樣式
Font newFont;
if (checkBox1.Checked)
newFont = new Font(oldFont.FontFamily, oldFont.Size, oldFont.Style | FontStyle.Bold);
//若被選取,new出Font並加上粗體
else
newFont = new Font(oldFont.FontFamily, oldFont.Size, oldFont.Style ^ FontStyle.Bold);
//若取消選取,new出Font並斥掉粗體
textBox1.Font = newFont;
//寫回textbox1
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
//同checkBox1,不同是加上或斥掉斜體
Font oldFont = textBox1.Font;
Font newFont;
if (checkBox2.Checked)
newFont = new Font(oldFont.FontFamily, oldFont.Size, oldFont.Style | FontStyle.Italic);
else
newFont = new Font(oldFont.FontFamily, oldFont.Size, oldFont.Style ^ FontStyle.Italic);
textBox1.Font = newFont;
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
//同checkBox1,不同是加上或斥掉刪除線
Font oldFont = textBox1.Font;
Font newFont;
if (checkBox3.Checked)
newFont = new Font(oldFont.FontFamily, oldFont.Size, oldFont.Style | FontStyle.Strikeout);
else
newFont = new Font(oldFont.FontFamily, oldFont.Size, oldFont.Style ^ FontStyle.Strikeout);
textBox1.Font = newFont;
}
說明:以上3個方法,可修改textBox1的文字型態
一、在設計界面上拉出數個CheckButton,並放入同一groupBox中
二、由於文字是可以多種型態(可同時斜體、粗體等等)所以要各寫出對應的方法

留言
張貼留言