在VB.net中生成的Picturebox上的Mousedown

时间:2015-03-12 23:10:00

标签: vb.net visual-studio-2013

所以,我有一些像这样的代码:

Dim box As PictureBox = New PictureBox
Dim Y As Integer
Dim X As Integer
Dim RandomClass As New Random()


Private Sub enspawn_Tick(sender As Object, e As EventArgs) Handles enspawn.Tick
    For pos = 30 To 100
        Y = RandomClass.Next(530)
        X = RandomClass.Next(980)
        box.Location = New Point(X, Y)
    Next pos
    box.Size = New Size(60, 60)
    box.Image = VB.NET_Game___1st.My.Resources.Resources.bittenfleax
    Controls.Add(box)
End Sub

所以基本上这会在屏幕周围生成随机图片框。但是,如果点击它(Mouse_Down)它会做什么,我将如何做到这一点。

我真的不知道如何处理这个问题。会不会像以下那样:

If box_MouseDown Then
    MsgBox("Mouse has been pressed on the image box") 
End If 

我真的不确定。提前致谢。

修改

如果这是我认为的那样,我会创建一个新的私人潜水艇吗?或者它会在Form_Load中吗?

1 个答案:

答案 0 :(得分:1)

对于需要动态控件的AddHandler语句,将其事件指向Sub。这些变量都不需要是类级别的。在您不需要时,可以避免持有内存。

Private Sub enspawn_Tick(sender As Object, e As EventArgs) Handles enspawn.Tick
  Static RandomClass As New Random
  Dim box As New PictureBox
  box.Location = New Point(RandomClass.Next(980),RandomClass.Next(530))
  box.Size = New Size(60, 60)
  box.Image = VB.NET_Game___1st.My.Resources.Resources.bittenfleax
  AddHandler box.MouseDown, AddressOf box_MouseDown
  Controls.Add(box)
End Sub

Private Sub box_MouseDown(sender As Object, e As MouseEventArgs)
   ' sender is the PictureBox object
   Dim pb As PictureBox = DirectCast(sender, PictureBox)
End Sub