简体   繁体   中英

How to change the backcolor of control on focus

i am developing windows form which contain so many control.i want to change back color of that active control on Focus & back to its Original color once it lost focus. i see This Link which give solution to write code for each control on the form. is any solution to write common function which find Current Active control in Form & change back color of it.

In form constructor you can assign GotFocus and LostFocus events handlers to each control of your form like this:

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

And then in handlers method do some logic around focused control's BackColor (for example, on GotFocus save current BackColor to control's tag and then set BackColor to red, on LostFocus restore original BackColor from control'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;
}

I will write an extension method and use like this:

this.textBox1.HookFocusChangeBackColor(Color.Blue);

Extension method:

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; 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM