Reputation: 181
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.
Upvotes: 1
Views: 3933
Reputation: 5733
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;
}
}
Upvotes: 0
Reputation: 26846
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;
}
Upvotes: 4