自动更改活动控件的属性 [英] Changing the properties of the active control automatically
问题描述
请认为我是 C# 的新手.扫描了大约 700 个帖子后,我决定再发一个问题:
Please consider that im a newcomer to c#. After scanning about 700 posts i decided to post one more question:
在我的 windows 窗体 (c#) 上,我有一些控件,包括文本框、复选框等.每当控件变为活动状态时,我都想更改背景色.我知道我可以为每个控件引发 'enter' 和 'leave' 事件以更改相应的属性,但应该有另一种方式.
On my windows form (c#) I have some controls including textboxes, checkboxes and so on. I want to change the backcolor whenever the controls become active. I know i could raise 'enter' and 'leave' events for each control to change the corresponding properties but there should be another way.
推荐答案
只需挂钩 Enter 和 Leave 事件 - 在每个事件中切换颜色.保存在 OnEnter
中保存的最后一个颜色以在 OnLeave
Simply hook Enter and Leave events - toggling the color in each. Save the last color saved in OnEnter
to use in 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;
};
}
}
这篇关于自动更改活动控件的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!