Change background color of TextBox or ComboBox in Windows Forms
After one of the applications is done successfully completed with automatic unit tests and send to users, what else I need to do is that waiting to get feedback from users. You know what the user compliant is user interface (I am wondering how I can test user interface to meet the user requirement beforehand, maybe no way for now). So I add codes to my application but not much is to set background color to be Kaki of TextBox or ComboBox if the cursor is in. Also, if you press enter key the cursor will focus to next control it depends on Tab Order.
Here is the example with User Information form as one of them:
![]()
Implementation
Create one class Utility
using System;
using System.Drawing;
using System.Windows.Forms;
public static class Utility
{
public static void AddEventHandler(Control panel)
{
foreach (Control control in panel.Controls)
{
if (control is TextBox || control is ComboBox)
{
control.KeyDown += control_KeyDown;
control.Enter += control_Enter;
control.Leave += control_Leave;
}
if (control.HasChildren)
{
AddEventHandler(control);
}
}
}
private static void control_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData != Keys.Return) return;
e.Handled = false;
SendKeys.Send("{TAB}");
}
private static void control_Enter(object sender, EventArgs e)
{
((Control) sender).BackColor = Color.Khaki;
}
private static void control_Leave(object sender, EventArgs e)
{
((Control) sender).BackColor = Color.FromKnownColor(KnownColor.Window);
}
}
Call AddEventHandler(this) method in the form load event
private void frmUserInformation_Load(object sender, EventArgs e)
{
Utility.AddEventHandler(this);
}
Loading...
Hi. It’s a good idea but with one flaw.
Since events for Enter and Leave are static, using this class will result in a memory leak, every form ever opened will remain in memory.
You have to unsubscribe from the events before form closes.
Srdjan - May 12, 2009 at 9:42 pm