0

我正在为一个课程作业创建一个棋盘游戏。对于电路板,我使用一些嵌套的 For 循环通过 2D 数组运行,以在每个方格生成一个“空间”对象。

Space 对象包含一个图片框和一些关于该空间的数据。

如何处理由单击生成的图片框引起的事件,而不必为每个空间进行硬编码?

我注意到这个问题似乎解决了这个问题,但它在 C# 中,我无法将它翻译成 VB.Net。

编辑:这就是板的生成方式

 Dim board(23, 24) As Space

 Private Sub GenerateBoard()

    Dim spaceSize As New Size(30, 30)
    Dim spaceLocation As New Point
    Dim validity As Boolean

    For Y = 0 To 24
        For X = 0 To 23
            spaceLocation.X = 6 + (31 * X)
            spaceLocation.Y = 6 + (31 * Y)

            If validSpaces(Y).Contains(X + 1) Then
                validity = True
            Else
                validity = False
            End If

            board(X, Y) = New Space(validity, spaceSize, spaceLocation)
            Me.Controls.Add(board(X, Y).imageBox)
            board(X, Y).imageBox.BackColor = Color.Transparent
            board(X, Y).imageBox.BringToFront()
        Next
    Next
End Sub

空间类:

Public Class Space

Dim _active As Boolean
Dim _imageBox As PictureBox

Public Sub New(ByVal activeInput As Boolean, ByVal size As Size, ByVal location As Point)
    _active = activeInput
    _imageBox = New PictureBox
    With _imageBox
        .Size = size
        .Location = location
        .Visible = False
    End With
End Sub

Property active As Boolean
    Get
        Return _active
    End Get
    Set(value As Boolean)
        _active = value
    End Set
End Property

Property imageBox As PictureBox
    Get
        Return _imageBox
    End Get
    Set(value As PictureBox)
        _imageBox = value
    End Set
End Property

Public Sub highlight()
    With _imageBox
        .Image = My.Resources.Highlighted_slab
        .Visible = True
    End With
End Sub
End Class
4

1 回答 1

0

首先由设计器(文本框、标签...)创建的所有控件也是由代码生成的,但 VisualStudio 会为您编写。如果您打开 Designer 文件(yourForm.Designer.vb),那么您可以看到如何生成控件的所有代码。

如果你想为你的创建事件处理程序pictureBox,那么:

//Initialize control
Private WithEvents _imageBox as PictureBox

然后创建一个事件处理方法:

Private Sub imageBox_Click(sender as Object, e as EventArgs)
    //Your code
End Sub

然后在 VB.NET 中,您可以通过两种方式将事件处理程序分配给事件

首先:在你创建了一个pictureBox( New PictureBox())之后的类构造函数中添加

AddHandler Me._imageBox, AddressOf Me.imageBox_Click

第二:在线我们您创建了一个事件处理程序添加下一个:

Private Sub imageBox_Click(sender as Object, e as EventArgs) Handles _imageBox.Click
    //Your code
End Sub

并记住将您的图片框添加到表单控件YourForm.Controls.Add(spaceInstance.ImageBox)

于 2013-04-07T07:00:42.867 回答