當你點擊一個控制和你按住鼠標按鈕,在移動鼠標時,這種控制捕獲以下鼠標事件,這樣你就不會從其他標貼獲取事件他們。
訣竅是設置label.Capture = False
。
允許定義顏色:
Private ReadOnly selectedColor As Color = Color.Blue
Private ReadOnly unselectedColor As Color = Color.White
和布爾值存儲我們的操作的當前狀態
Private isSelecting As Boolean = False
Private isUnselecting As Boolean = False
(全4的窗體類的字段)
現在讓我們寫這三事件處理程序:
Private Sub Label_MouseDown(sender As Object, e As EventArgs)
'This event starts selecting/unselecting
Dim label = DirectCast(sender, Label)
label.Capture = False '<=== THIS IS IMPORTANT!
If label.BackColor = selectedColor Then
isUnselecting = True
Else
isSelecting = True
End If
SelectLabel(label)
End Sub
Private Sub Label_MouseUp(sender As Object, e As EventArgs)
'This event stops selecting/unselecting
isSelecting = False
isUnselecting = False
End Sub
Private Sub Label_MouseEnter(sender As Object, e As EventArgs)
SelectLabel(DirectCast(sender, Label))
End Sub
我們需要這個過程,選擇或取消選擇標籤:
Private Sub SelectLabel(label As Label)
If isSelecting Then
label.BackColor = selectedColor
ElseIf isUnselecting Then
label.BackColor = unselectedColor
End If
End Sub
這就是它!
腳註:我創建了標貼這樣的:
Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Const w As Integer = 50, h As Integer = 50
For x = 1 To 10
For y = 1 To 10
Dim lbl As New Label() With {
.Location = New Point(x * w, y * h),
.Size = New Size(w, h),
.BorderStyle = BorderStyle.FixedSingle,
.BackColor = unselectedColor
}
AddHandler lbl.MouseDown, AddressOf Label_MouseDown
AddHandler lbl.MouseUp, AddressOf Label_MouseUp
AddHandler lbl.MouseEnter, AddressOf Label_MouseEnter
Controls.Add(lbl)
Next
Next
End Sub
未綁定的datagridview控件可能會訣竅。這些單元都是可尋址的。您可以在加載時對單元格進行尋址以更改顏色,也可以使用cellformat事件。您可以將網格綁定到您自己的類或數據表。點擊事件可用。 – rheitzman
@rheitzman你會有這樣的解決方案的例子嗎? – jplanglais