jAdex
jAdex

Reputation: 584

Textbox entry with tab

I want to know if there is any event for entering a TextBox after pressing tab key.

For example: I have a TextBox for Name and LastName, after I fill the TextBox for Name and press the Tab key to go to LastName TextBox I want to change the color or something for TextBox LastName.

Upvotes: 0

Views: 171

Answers (1)

Steve
Steve

Reputation: 216253

This simple class could help a lot for your task

public class ControlColor
{
    private Color _setBColor = Color.FromArgb(255, 255, 0);
    private Color _setFColor = SystemColors.ControlText;

    public ControlColor(params Control[] ctls)
    {
        foreach (Control ctr in ctls)
        {
            ctr.Enter += new EventHandler(onEnter);
            ctr.Leave += new EventHandler(onLeave);
        }
    }
    public ControlColor(Color bkg, Color frg, params Control[] ctls)
    {
        _setFColor = frg;
        _setBColor = bkg;
        foreach (Control ctr in ctls)
        {
            ctr.Enter += new EventHandler(onEnter);
            ctr.Leave += new EventHandler(onLeave);
        }
    }

    private void onEnter(object sender, EventArgs e)
    {
        if (sender is Control)
        {
            Control ctr = (Control)sender;
            ctr.BackColor = _setBColor;
            ctr.ForeColor = _setFColor;
        }

    }
    private void onLeave(object sender, EventArgs e)
    {
        Control ctr = sender as Control;
        ctr.BackColor = SystemColors.Window;
        ctr.ForeColor = SystemColors.ControlText;
    }
}

You could call it with code like this (LinqPAD test, but should be not a problem to adapt to Visual Studio)

void Main()
{
    Form f = new Form();
    TextBox t1 = new TextBox();
    t1.Location = new Point(0, 0);

    TextBox t2 = new TextBox();
    t2.Location = new Point(0, 20);

    ControlColor cl = new ControlColor(t1, t2);
    f.Controls.Add(t1);
    f.Controls.Add(t2);
    f.Show();

}

The class works receiving an array of controls from the caller. For each array the class register an event handler for the Leave and Enter events (these events are triggered when your controls get the focus) The final work is simply to paint the background (and eventually the foreground) with the colors choosen.

Upvotes: 1

Related Questions