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:

User Information

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

1 person has left a comment

Srdjan - Gravatar

Srdjan said:

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.

Posted on: May 12, 2009 at 9:42 pmQuote this Comment

Commentors on this Post-

Leave a Comment-

Comment Guidelines: Basic XHTML is allowed (a href, strong, em, code). All line breaks and paragraphs are automatically generated. Off-topic or inappropriate comments will be edited or deleted. Email addresses will never be published. Keep it PG-13 people!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

All fields marked with "*" are required.