Skip to main content
 首页 » 编程设计

c#之自动更改事件控件的属性

2024年02月23日26duanxz

请考虑我是 C# 的新手。在扫描了大约 700 个帖子后,我决定再发布一个问题:

在我的 Windows 窗体 (c#) 上,我有一些控件,包括文本框、复选框等。 我想在控件激活时更改背景颜色。 我知道我可以为每个控件引发“进入”和“离开”事件以更改相应的属性,但应该有另一种方法。

请您参考如下方法:

只需 Hook Enter 和 Leave 事件 - 在每个事件中切换颜色。保存在 OnEnter 中保存的最后一个颜色以在 OnLeave

中使用
public Form1() 
{ 
    InitializeComponent(); 
 
    var lastColorSaved = Color.Empty; 
 
    foreach(Control child in this.Controls) 
    { 
        child.Enter += (s, e) => 
                            { 
                                var control = (Control)s; 
                                lastColorSaved = control.BackColor; 
                                control.BackColor = Color.Red; 
                            }; 
        child.Leave += (s, e) => 
                            { 
                                ((Control)s).BackColor = lastColorSaved; 
                            }; 
    } 
}