Search code examples
c#.netwinformscontrolsbackcolor

How to change back color on focus tools by dynamically in c#.net desktop application


In my desktop form there are many control. I want to change back color of that active control on Focus & back to its Original color once it lost focus.

Here is my code,

public BillingMetal(Billing _frm)
{
    this.frm = _frm;
    InitializeComponent();

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

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

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

Actually this code is working but for the button only not for textbox, combobox or any other tools.


Solution

  • Your code seems basically ok but you would want to make sure that you iterated all the children (of all the children...) of your Control tree as well.

    combo, textbox etc in panel

    public partial class BillingMetal : Form
    {
        public BillingMetal()
        {
            InitializeComponent();
            foreach (var ctrl in IterateControls(Controls))
            {
                ctrl.GotFocus += (sender, e) =>
                { 
                    if(sender is Control ctrl)
                    {
                        ctrl.Tag = ctrl.BackColor;
                        ctrl.BackColor = Color.Red;
                    }
                };
                ctrl.LostFocus += (sender, e) =>
                {
                    if(sender is Control ctrl && ctrl.Tag is Color color)
                    {
                        ctrl.BackColor = color;
                    }
                };
            }
        }
    

    Iterator

        IEnumerable<Control> IterateControls(Control.ControlCollection controls)
        {
            foreach (Control control in controls)
            {
                yield return control;
                foreach (Control child in IterateControls(control.Controls))
                {
                    yield return child;
                }
            }
        }
    }