首页 > 解决方案 > 按下制表键时如何更改文本框的背景颜色

问题描述

我必须在 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();
    }

标签: c#winforms

解决方案


“除非我将其从只读状态中删除并继续在框中输入内容,否则我无法让这些框改变颜色。”

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

private void txtRed_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    if (e.KeyCode == Keys.Tab)
    {         
        txtRed.BackColor = System.Drawing.Color.Red;
        txtYellow.BackColor = System.Drawing.Color.DarkGray;
        txtGreen.BackColor = System.Drawing.Color.DarkGray;
    }
}

推荐阅读