c# - 按下制表键时如何更改文本框的背景颜色
问题描述
我必须在 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();
}
解决方案
“除非我将其从只读状态中删除并继续在框中输入内容,否则我无法让这些框改变颜色。”
这是因为您正在使用 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;
}
}
推荐阅读
- javascript - 使用单击的数据 ID 更新隐藏输入的值
- dialogflow-es - 如何使用 python 从 webhook 修改参数的值 - Dialogflow 聊天机器人
- php - $_SESSION 标记内的索引未定义,即使我在登录后立即定义了它
- c# - 404错误但文件/目录在那里
- c# - MVC DropDownList 模型绑定
- ios - Swift 中的 UIView 扩展
- php - 用表格理解方法帖子
- java - 如何在android studio java中检查函数的生命状态
- excel - Excel VBA For then 循环
- excel - 当使用条件格式突出显示单元格时,如何识别/解决 Excel 单元格颜色?