0

我在一个数组中制作了一组图块(图片框),并且需要它们在单击时都执行某些操作,但不知道如何操作。具体来说,我希望能够通过单击一个图块并使该对象转到该图块的位置来在其上放置一些其他对象。我知道您可能会建议查看 mouseposition 变量并在所有图块上设置一些不可见的框来注册点击,但我想知道如何为数组中的对象注册任何事件以用于将来出现的任何事件。顺便说一下,我确实知道如何为不在数组中的对象注册事件。我想在图片框顶部移动的对象也将来自对象数组,但是是不同的。

这是我的代码:

Public Class Form1
    Dim tiles(50) As PictureBox 'This is the object array of tiles
    Dim plants() As String 'I haven't set this up yet, but this will be for the objects to be 'placed' on the pictureboxes.

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim tileWidth As Integer = 50
        Dim tileHeight As Integer = 50
        Dim xindent As Integer = 10
        Dim yindent As Integer = 10
        For x = 0 To 9
            For y = 0 To 4
                ReDim Preserve tiles(x * y)
                tiles(x * y) = New PictureBox With {.Visible = True, .Size = New System.Drawing.Size(50, 50), .Parent = Me, .BackColor = Color.GreenYellow, .Image = Nothing}
                tiles(x * y).Location = New System.Drawing.Point(x * tileWidth + xindent, y * tileHeight + yindent)
                If (x Mod 2 = 0 And y Mod 2 = 0) Or (x Mod 2 <> 0 And y Mod 2 <> 0) Then
                    tiles(x * y).BackColor = Color.Green
                End If
            Next
        Next
    End Sub
End Class

我根本不知道如何为图块数组设置点击事件处理程序,所以这就是为什么它不在上面的代码中。

在此先感谢您的帮助。

4

2 回答 2

0

the_lotus 已经给你很好的答案了。

只是想分享一个我在使用AddHandler.

WithEvents在你的类中使用声明一个临时变量:

Public Class Form1

    Private WithEvents Tile As PictureBox

    ...

现在,在代码编辑器顶部的两个下拉菜单中,更改Form1Tile和(或任何您想要的事件)(Declarations)Click这将为您输入一个具有正确方法签名的方法:

Private Sub Tile_Click(sender As Object, e As EventArgs) Handles Tile.Click

End Sub

删除Handles Tile.Click出现在第一行末尾的部分:

Private Sub Tile_Click(sender As Object, e As EventArgs) 

End Sub

最后,删除您使用的临时声明WithEvents

现在您已经有了一个具有正确签名的方法,您可以使用AddHandler. 这对于没有标准签名的事件非常方便。

于 2014-12-11T16:12:06.143 回答
0

AddHandler就是为此而存在的。在 New 之后,您只需要将函数附加到事件

AddHandler tiles(x * y).Click, AddressOf Tile_Click

并有一个处理事件的函数

Private Sub Tile_Click(sender As Object, e As System.EventArgs)

    ' sender represent the reference to the picture box that was clicked

End Sub

如果您已经知道数组的大小,则应该只重新调整一次数组,而不是每次循环(将 ReDim 移出循环)。此外,由于 y 在第一个循环中为 0,因此您基本上是在执行 0 个元素的 ReDim(当 y = 0 时 x*y = 0)

于 2014-12-11T15:27:24.853 回答