如何改变焦点控制的背景颜色

时间:2015-03-04 07:31:38

标签: c# .net winforms

我正在开发包含如此多控件的窗体。我希望改变焦点和放大器上该活动控件的颜色。一旦失去焦点,就恢复原来的颜色。 我看到This链接为表单上的每个控件编写代码提供了解决方案。 是编写常用函数的任何解决方案,它在Form& amp;中找到Current Active控件。改变它的颜色。

2 个答案:

答案 0 :(得分:2)

在表单构造函数中,您可以将GotFocusLostFocus事件处理程序分配给表单的每个控件,如下所示:

foreach (Control ctrl in this.Controls)
{
    ctrl.GotFocus += ctrl_GotFocus;
    ctrl.LostFocus += ctrl_LostFocus;
}

然后在处理程序方法中围绕聚焦控件的BackColor执行一些逻辑(例如,在GotFocus上保存当前BackColor以控制标签,然后将BackColor设置为红色,在LostFocus上从控件中恢复原始BackColor&# 39; s tag):

void ctrl_LostFocus(object sender, EventArgs e)
{
    var ctrl = sender as Control;
    if (ctrl.Tag is Color)
        ctrl.BackColor = (Color)ctrl.Tag;
}

void ctrl_GotFocus(object sender, EventArgs e)
{
    var ctrl = sender as Control;
    ctrl.Tag = ctrl.BackColor;
    ctrl.BackColor = Color.Red;
}

答案 1 :(得分:0)

我将编写一个扩展方法并使用如下:

this.textBox1.HookFocusChangeBackColor(Color.Blue);

扩展方法:

public static class ControlExtension
{
    public static void HookFocusChangeBackColor(this Control ctrl, Color focusBackColor)
    {
        var originalColor = ctrl.BackColor;
        var gotFocusHandler = new EventHandler((sender, e) => 
        { 
            (ctrl as Control).BackColor = focusBackColor; 
        });
        var lostFocusHandler = new EventHandler((sender, e) => 
        { 
            (ctrl as Control).BackColor = originalColor; 
        });

        ctrl.GotFocus -= gotFocusHandler;
        ctrl.GotFocus += gotFocusHandler;

        ctrl.LostFocus -= lostFocusHandler;
        ctrl.LostFocus += lostFocusHandler; 
    }
}