目录
????????用switch多路选择语句及窗体的BackColor属性更改窗体的BackColor属性。该属性用于获取或设置控件的背景颜色。
????????可以使用Color结构的静态属性获取Color对象,如Color.Red;也可以使用Color结构的静态方法Color.FromArgb(),并根据RGB3种颜色的组合找到需要的颜色。
????????进一步地,使用Timer组件实现定时更改窗体颜色。使用Timer组件计时,首先向窗体中拖入Timer组件,然后设置其Enable属性为true,设置Interval属性为30000,在Tick事件中写入随机更改窗体颜色的代码,在窗体执行时会自动更换背景颜色。
// 使用switch语句更改窗体颜色
namespace _030
{
public partial class Form1 : Form
{
private Label? label1;
private ComboBox? comboBox1;
public Form1()
{
InitializeComponent();
Load += Form1_Load;
}
private void Form1_Load(object? sender, EventArgs e)
{
//
// label1
//
label1 = new Label
{
AutoSize = true,
Location = new Point(43, 20),
Name = "label1",
Size = new Size(43, 17),
TabIndex = 0,
Text = "选择颜色:"
};
//
// comboBox1
//
comboBox1 = new ComboBox
{
FormattingEnabled = true,
Location = new Point(130, 12),
Name = "comboBox1",
Size = new Size(121, 25),
TabIndex = 1,
DropDownStyle = ComboBoxStyle.DropDownList //设置选项为只读
};
comboBox1.Items.AddRange(["红", "绿", "蓝"]);
comboBox1.SelectedIndexChanged += ComboBox1_SelectedIndexChanged;
//
// Form1
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(284, 61);
Controls.Add(comboBox1);
Controls.Add(label1);
Name = "Form1";
StartPosition = FormStartPosition.CenterScreen;
Text = "switch语句更改颜色";
ResumeLayout(false);
PerformLayout();
}
private void ComboBox1_SelectedIndexChanged(object? sender, EventArgs e)
{
switch (comboBox1!.SelectedIndex) //使用switch判断窗体使用哪种颜色
{
case 0:
BackColor = Color.Red; //窗体设置为红色
break;
case 1:
BackColor = Color.Green; //窗体设置为绿色
break;
case 2:
BackColor = Color.Blue; //窗体设置为蓝色
break;
}
}
}
}
?
?
?