Visual Basic如何修改满足条件的数组元素颜色,仅更新已着色方格
实现步骤
- 新增二维布尔数组记录每个方格的着色状态,避免用颜色判断出现的随机误判问题
- 为每个Label控件存储对应的行列索引,方便鼠标悬停时快速更新状态标记
- 优化冗余的循环逻辑,调整计时器触发时的着色范围
完整修改后代码
Public Class Form1 Dim r, g, b As Integer Dim grid(0 To 9, 0 To 9) As Label ' 新增标记数组:True代表对应方格已被鼠标着色过 Dim colored(0 To 9, 0 To 9) As Boolean = False Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Timer1.Enabled = False Randomize() For row = 0 To 9 For col = 0 To 9 grid(row, col) = New Label grid(row, col).Width = 50 grid(row, col).Height = 50 grid(row, col).Left = 55 * col + 55 grid(row, col).Top = 55 * row + 55 grid(row, col).BackColor = Color.White ' 存储当前方格的行列坐标,方便后续快速查找 grid(row, col).Tag = New Point(row, col) Me.Controls.Add(grid(row, col)) AddHandler grid(row, col).MouseEnter, AddressOf mouse_enter Next Next End Sub Private Sub mouse_enter(sender As Label, e As EventArgs) ' 获取当前触发事件的方格坐标 Dim pos As Point = CType(sender.Tag, Point) Dim row = pos.X Dim col = pos.Y ' 生成随机颜色并着色 r = Int(Rnd() * 256) g = Int(Rnd() * 256) b = Int(Rnd() * 256) sender.BackColor = Color.FromArgb(r, g, b) ' 标记当前方格为已着色 colored(row, col) = True End Sub Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick Dim row As Integer Dim col As Integer For row = 0 To 9 For col = 0 To 9 ' 仅对已经被鼠标着色过的方格更新颜色 If colored(row, col) = True Then r = Int(Rnd() * 256) g = Int(Rnd() * 256) b = Int(Rnd() * 256) grid(row, col).BackColor = Color.FromArgb(r, g, b) End If Next Next End Sub Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click Timer1.Enabled = True Timer1.Interval = 800 End Sub End Class
关键修改说明
- 新增的
colored数组初始值全为False,代表所有方格初始都是未着色状态 - 移除了
mouse_enter里冗余的100次循环逻辑,原逻辑无实际作用仅重复赋值100次 - 计时器触发时仅判断
colored标记为True的方格才更新随机颜色,未被鼠标悬停过的白色方格不会被修改
内容的提问来源于stack exchange,提问作者No Thanks
相关产品推荐
相关产品推荐

