按Tab键时如何更改文本框的BackColor

时间:2018-06-05 21:10:16

标签: c# winforms

我必须在visual studio 2015中创建一个C#程序,首先显示三个只读文本框,底部是绿色,中间和顶部框是灰色的。按下Tab键时,中间框应变为黄色,另外两个框应为灰色。然后再次按下Tab键,顶部框变为红色,底部两个变为灰色,然后用Tab键重复。我不能让盒子改变颜色,除非我把它从只读取出并继续输入框。如何使用tab键修改代码以更改颜色?

    //when the txtRed box is active, it turns red and the others go gray
    private void txtRed_TextChanged(object sender, EventArgs e)
    {
        txtRed.BackColor = System.Drawing.Color.Red;
        txtYellow.BackColor = System.Drawing.Color.DarkGray;
        txtGreen.BackColor = System.Drawing.Color.DarkGray;
    }

    //when the txtYellow box is active, it turns yellow and the others go gray
    private void txtYellow_TextChanged(object sender, EventArgs e)
    {
        txtRed.BackColor = System.Drawing.Color.DarkGray;
        txtYellow.BackColor = System.Drawing.Color.Yellow;
        txtGreen.BackColor = System.Drawing.Color.DarkGray;
    }

    //when the txtGreen box is active, it turns green and the others go gray
    private void txtGreen_TextChanged(object sender, EventArgs e)
    {
        txtRed.BackColor = System.Drawing.Color.DarkGray;
        txtYellow.BackColor = System.Drawing.Color.DarkGray;
        txtGreen.BackColor = System.Drawing.Color.Green;
    }

    //allows btnExit to terminate the program
    private void btnExit_Click(object sender, EventArgs e)
    {
        this.Close();
    }

2 个答案:

答案 0 :(得分:1)

要达到预期效果,您需要回复 Enter 事件,而不是 TextChange 事件。

您的代码应如下所示,文本框之间的标签将背景设置为黄色如果文本框具有焦点或灰色,如果不是:

void txtRed_Enter(object sender, EventArgs e)
{
    txtRed.BackColor = Color.Yellow;
    txtYellow.BackColor = Color.Gray;
    txtGreen.BackColor = Color.Gray;
}
void txtYellow_Enter(object sender, EventArgs e)
{
    txtRed.BackColor = Color.Gray;
    txtYellow.BackColor = Color.Yellow;
    txtGreen.BackColor = Color.Gray;
}
void txtGreen_Enter(object sender, EventArgs e)
{
    txtRed.BackColor = Color.Gray;
    txtYellow.BackColor = Color.Gray;
    txtGreen.BackColor = Color.Yellow;
}

您可以在此处查看相关文档:Control.Enter Event

答案 1 :(得分:0)

"我不能让盒子改变颜色,除非我把它从只读中取出并继续输入方框。"

这是因为您正在使用TextChanged事件处理程序。如果您在按Tab键后想要执行操作,则需要使用 PreviewKeyDown 事件处理程序:

Offset start;

void verticalDragStart(DragStartDetails details) {
  // process the start by working with the details
  start = details.globalPosition;
  // ...
}

void verticalDragUpdate(DragUpdateDetails details) {
  // apply your logic
  Offset delta = details.delta;
  // ...
}

// use DragEnd, also for horizontal, pan etc.

@override
Widget build(BuildContext context) => GestureDectector(
  onVerticalDragStart: verticalDragStart,
  // ...
);