带选项卡的文本框条目

时间:2015-07-18 13:09:45

标签: c# windows forms

我想知道按Tab键后是否有任何事件进入TextBox。

例如:在我填充Name的TextBox并按Tab键转到{后,我有LastNameName的TextBox {1}} TextBox我想更改TextBox LastName的颜色或其他内容。

1 个答案:

答案 0 :(得分:1)

这个简单的课程可以为你的任务提供很多帮助

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

你可以用这样的代码调用它(LinqPAD测试,但是应该不是适应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();

}

该类可以从调用者接收一组控件。对于每个数组,类为Leave和Enter事件注册事件处理程序(当控件获得焦点时会触发这些事件)最后的工作只是用选择的颜色绘制背景(最终是前景)。