我的程序有很多RadioButtons
。我想在鼠标悬停时更改每个鼠标的背景颜色,并在鼠标离开时将背景颜色重置为透明。
我知道我可以使用每个MouseHover
的{{1}}和MouseLeave
事件,但如果我这样做,代码会很长,因为RadioButtons太多了。
答案 0 :(得分:1)
这应该适合你,它可以用不同的方式完成,但我修改了一些我必须满足你需要的东西......顺便说一句,这是递归,如果它包含一个我们可以改变的单选按钮,则挖掘一个控件它等等......
经过试用和测试
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim rButton As New List(Of Control)
For Each rd As System.Windows.Forms.RadioButton In LoopControls(rButton, Me, GetType(System.Windows.Forms.RadioButton))
AddHandler rd.MouseHover, AddressOf Me.ChangeColor
AddHandler rd.MouseLeave, AddressOf Me.Transparent
Next
End Sub
Public Shared Function LoopControls(ByVal list As List(Of Control), ByVal parent As Control, ByVal ctrlType As System.Type) As List(Of Control)
If parent Is Nothing Then Return list
If parent.GetType Is ctrlType Then
list.Add(parent)
End If
For Each child As Control In parent.Controls
LoopControls(list, child, ctrlType)
Next
Return list
End Function
Private Sub Transparent()
Dim rButton As New List(Of Control)
For Each rd As System.Windows.Forms.RadioButton In LoopControls(rButton, Me, GetType(System.Windows.Forms.RadioButton))
rd.BackColor = Color.Transparent
Next
End Sub
Private Sub ChangeColor()
Dim rButton As New List(Of Control)
For Each rd As System.Windows.Forms.RadioButton In LoopControls(rButton, Me, GetType(System.Windows.Forms.RadioButton))
rd.BackColor = Color.Red
Next
End Sub
End Class
答案 1 :(得分:1)
另一种方法是使用 MouseEnter 事件而不是MouseHover:
Public Class Form
Private radioButtonsList As List(Of RadioButton)
Private Sub Form_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
For Each rb As RadioButton In Me.radioButtonsList
RemoveHandler rb.MouseEnter, AddressOf Me.RadioButtons_MouseEnter
RemoveHandler rb.MouseLeave, AddressOf Me.RadioButtons_MouseLeave
Next
Me.radioButtonsList = Nothing
End Sub
Private Sub Form_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Me.radioButtonsList = New List(Of RadioButton)
Me.GetAllRadioButtonsFromMe()
For Each rb As RadioButton In Me.radioButtonsList
AddHandler rb.MouseEnter, AddressOf Me.RadioButtons_MouseEnter
AddHandler rb.MouseLeave, AddressOf Me.RadioButtons_MouseLeave
Next
End Sub
Private Sub GetAllRadioButtonsFromMe()
Dim ctl As Control = Me.GetNextControl(Me, True)
While ctl IsNot Nothing
If TypeOf ctl Is RadioButton Then
Me.radioButtonsList.Add(ctl)
End If
ctl = Me.GetNextControl(ctl, True)
End While
End Sub
Private Sub RadioButtons_MouseEnter(sender As Object, e As System.EventArgs)
Dim rb As RadioButton = DirectCast(sender, RadioButton)
rb.BackColor = Color.DodgerBlue
End Sub
Private Sub RadioButtons_MouseLeave(sender As Object, e As System.EventArgs)
Dim rb As RadioButton = DirectCast(sender, RadioButton)
rb.BackColor = Color.Transparent
End Sub
End Class