我正在尝试制作Connect 4游戏,只是为了练习一些Windows初次接触的窗体。我的代码要做的是创建一个7 x 6的网格,规则地间隔空白PictureBox。但是,因为我是在脚本中创建它们而不使用form1设计窗口,所以我不知道如何向它们添加Handles,尤其是因为PictureBox位于数组中。有什么想法吗?
Public Class Form1
Dim Grid(6, 5) As PictureBox
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Visible = False
Me.FormBorderStyle = FormBorderStyle.FixedSingle
For i As Integer = 0 To 6
For j As Integer = 0 To 5
Grid(i, j) = New PictureBox
Grid(i, j).BackColor = Color.LightGray
Grid(i, j).Size = New Size(90, 90)
Grid(i, j).Location = New Point((i * 100) + 10, (j * 100) + 10)
Grid(i, j).Visible = True
Controls.Add(Grid(i, j))
Next
Next
End Sub
Private Sub Grid_MouseHover(sender As Object, e As EventArgs) Handles Grid(x, y).MouseHover 'Doesnt work
'Run depending on which picturebox in array
End Sub
End Class
我会收到一个错误消息,即“ Handles子句需要在包含类型或其基本类型之一中定义一个WithEvents变量。”
答案 0 :(得分:0)
一种可能的方法是使用坐标设置.Tag
属性-
在您的For..Next
循环中添加类似内容
Grid(i, j).Tag = i.ToString & j.ToString
并使用
AddHandler Grid(i, j).MouseHover, AddressOf Grid_MouseHover
并将其添加到上面的一个之后。
然后,将MouseHover
Sub的第一行更改为
Private Sub Grid_MouseHover(sender As Object, e As EventArgs)
最后没有处理程序。
最后,将发送者的类型更改为PictureBox
Private Sub Grid_MouseHover(sender As Object, e As EventArgs)
Dim Pbox As PictureBox = CType(sender, PictureBox)
Dim i As Integer = Integer.Parse(Pbox.Tag.ToString(0))
Dim j As Integer = Integer.Parse(Pbox.Tag.ToString(1))
End Sub
要访问Picturebox
及其属性,只需使用PBox
,如果需要坐标,则使用i
和j