C# 编程枚举系统的颜色 - 编程工具 - 原

在系统开发中,经常用到系统颜色,来修饰自己的控件。

在没有美工帮助的时候,靠自己的审美观点以所见即所得的方式选到合适的系统颜色。

下面我们用一段代码来实现。

首先,定义一个窗体,不妨叫做FrmColors,在Text中我们可以输入Enum Colors。然后在FORM中添加一个FlowLayoutPanel控件。

这个控件的作用是自动将生成的控件以列表的方式显示。

我个人比较喜欢在窗体的构造函数中增加InitThisForm方法,来初始化窗体控件。当然,微软官方并不建议这样做的,随个人习惯而已。

枚举系统颜色要用到以下几个方面:

1、使用typeof运算符;

2、使用KnownColor枚举;

3、动态生成控件。

下面贴出该工具的主要代码:

 
  
1 private void InitThisForm()
2 {
3 // Get all the values from the KnownColor enumeration.
4   System.Array colorsArray = Enum.GetValues( typeof (KnownColor));
5 KnownColor[] allColors = new KnownColor[colorsArray.Length];
6
7 for ( int i = 0 ; i < colorsArray.Length; i ++ )
8 {
9 string colorName = colorsArray.GetValue(i).ToString();
10 // KnownColor kc = colorsArray.GetValue(i) as KnownColor;
11   Color color = Color.FromName(colorName);
12
13 string controlName = " lbl_ " + i.ToString();
14 Label lbl = new Label();
15 lbl.Name = controlName;
16
17 lbl.BackColor = color;
18 lbl.Text = colorName;
19
20 lbl.ForeColor = color.R < 128 || color.G < 128 || color.B < 128 ? Color.White : Color.Black;
21 lbl.Click += new EventHandler(lb_Click);
22 lbl.MouseHover += new EventHandler(lb_MouseHover);
23 lbl.MouseLeave += new EventHandler(lb_MouseLeave);
24 lbl.MouseEnter += new EventHandler(lbl_MouseEnter);
25 this .flowLayoutPanel1.Controls.Add(lbl);
26
27 Label lbsplit = new Label();
28 lbsplit.AutoSize = false ;
29 lbsplit.Height = 1 ;
30 this .flowLayoutPanel1.Controls.Add(lbsplit);
31 }

现在,就可以将系统颜色用通过程序创建的Label的BackColor来显示出来了,并且,在TEXT中显示ColorName。

大家注意到我还在Label创建的时候增加了Click事件,这是为了在点击Label时,将Color的名字显示在txtColorName中。

代码如下:

 
  
1 void lb_Click( object sender, EventArgs e)
2 {
3 this .lblSelectColor.BackColor = ((Label)sender).BackColor;
4 this .txtColorName.Text = ((Label)sender).BackColor.Name;
5 this .txtColorName.SelectAll();
6 }

在MouseEnter和MouseLeave事件中,我分别改变了Label的BorderStyle属性,是为了显示丐来更突出。

 
  
1 void lbl_MouseEnter( object sender, EventArgs e)
2 {
3 Label lb = (Label)sender;
4 lb.BorderStyle = BorderStyle.FixedSingle;
5 }
6
7 void lb_MouseLeave( object sender, EventArgs e)
8 {
9 Label lb = (Label)sender;
10 lb.BorderStyle = BorderStyle.None;
11 }

另外,由于在Click事件代码中增加了一句this.txtColorName.SelectAll();则在点击一个理想的颜色时,直接使用Ctrl+C就可以把颜色

名称复制到剪切板了。

效果图如下:

2011031109384970.png


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值