【问题标题】:How to Set BackColor of Inactive Control如何设置非活动控件的背景颜色
【发布时间】:2015-01-06 08:42:12
【问题描述】:

我有一个包含多个文本框和组合框的表单。我已将活动控件的背景颜色属性设置为天蓝色。我想在所有文本框和组合框不活动时将它们的背景颜色设置为白色。

【问题讨论】:

  • 您的意思是不活动为不专注或启用=false?

标签: vb.net winforms backcolor


【解决方案1】:

有正确的方法和错误的方法。你在问错误的方法。正确的方法是从 TextBox 派生您自己的类并覆盖 OnEnter 和 OnLeave 方法。对 ComboBox 重复此操作。

但是您要求的方式错误,并且您可能尝试添加此功能为时已晚,因此我们必须通过在运行时找到控件来解决它。将构造函数添加到您的表单类并使其看起来像:

Public Sub New()
    InitializeComponent()
    FindControls(Me.Controls)
End Sub

Private Sub FindControls(ctls As Control.ControlCollection)
    For Each ctl As Control In ctls
        Dim match As Boolean
        If TypeOf ctl Is TextBoxBase Then match = True
        If TypeOf ctl Is ComboBox Then
            Dim combo = DirectCast(ctl, ComboBox)
            If combo.DropDownStyle <> ComboBoxStyle.DropDownList Then match = True
        End If
        If match Then
            AddHandler ctl.Enter, AddressOf ControlEnter
            AddHandler ctl.Leave, AddressOf ControlLeave
        End If
        FindControls(ctl.Controls)
    Next
End Sub

Private controlColor As Color

Private Sub ControlEnter(sender As Object, e As EventArgs)
    Dim ctl = DirectCast(sender, Control)
    controlColor = ctl.BackColor
    ctl.BackColor = Color.AliceBlue
End Sub

Private Sub ControlLeave(sender As Object, e As EventArgs)
    Dim ctl = DirectCast(sender, Control)
    ctl.BackColor = controlColor
End Sub

【讨论】:

  • 为我们想要的控件添加EnterLeave 事件的事件处理程序还不够,而无需派生控件且没有FindControl?例如在构造函数中
  • 对不起,为什么它容易出错。这种方式有什么缺点?(除了一个:如果您希望所有表单都具有相同的行为,则需要为项目中的每个表单添加事件处理程序)。
  • 您只会忽略一个控件,尤其是嵌套在容器中的控件。请注意 FindControls 如何使用递归。从现在起一两年后,您将永远忘记。这是《日内瓦程序员权利公约》禁止的奴隶劳动。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-23
  • 2018-09-14
  • 1970-01-01
  • 2010-12-11
  • 1970-01-01
相关资源
最近更新 更多