c# - 输入时更改文本框的背景颜色

标签 c# visual-studio

我的表单有以下代码:

    private void txt1_Enter(object sender, EventArgs e)
    {
        txt1.SelectAll();
        txt1.BackColor = Color.LightBlue;
    }

    private void txt2_Enter(object sender, EventArgs e)
    {
        txt2.SelectAll();
        txt2.BackColor = Color.LightBlue;            
    }

    private void txt1_Leave(object sender, EventArgs e)
    {
        txtThermalConductivity.BackColor = Color.White;
    }

    private void txt2_Leave(object sender, EventArgs e)
    {
        txtThermalConductivity.BackColor = Color.White;
    }

我的表单上还有另外 20 个文本框,我想对其执行相同的操作。是否可以将所有进入事件和所有离开事件合并起来,这样我总共有两个事件而不是 44 个单独的事件?

最佳答案

在设计器 View 中,选择每个文本框并设置 EnterLeave 事件以指向每个文本框的单个实现。

然后你可以这样做:

private void txt_enter(object sender, EventArgs e) {
    ((TextBox)sender).BackColor = Color.LightBlue;
}

private void txt_leave(object sender, EventArgs e) {
    ((TextBox)sender).BackColor = Color.White;
}

此外,SelectAll 不是必需的,因为您要设置整个文本框的背景颜色。而不是 RichTextBoxSelectionColor

关于c# - 输入时更改文本框的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15868881/

相关文章:

javascript - 是否有可能在客户端有一个进度条链接到 saveAs() 的进度?

c# - FtpWebRequest 下载文件大小不正确

c# - 如果 linq 查询计数返回零,则返回值 1

c# - 如何绘制颜色范围较柔和的图像?

c# - 使用 EnvDTE 以编程方式更改 Visual Studio 项目的调试属性

c# - NEST无法找到elasticsearch可以找到的文档

c++ - 可以将预编译 header 与 MIDL 生成的文件一起使用吗?

c# - 更新 Visual Studio 2019 错误

c# - C#-如何停止使用其他格式的音频文件(不是正在播放的格式)

windows - 安装 Windows 8 SDK 时出错