简体   繁体   English

将鼠标放在VB.net中生成的Picturebox上

[英]Mousedown on generated Picturebox in VB.net

So, I have some code like this: 所以,我有一些这样的代码:

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

So basically this will generate random picture boxes around the screen. 因此,基本上,这将在屏幕周围生成随机图片框。 However, how would I go about making it so when it is clicked (Mouse_Down) it does something. 但是,我将如何制作它,以便在单击(Mouse_Down)时会执行某些操作。

I do not really have a clue how to approach this. 我真的不知道如何解决这个问题。 Would it be something along the lines of: 可能是这样的:

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

I am really unsure. 我真的不确定。 Thanks in advance. 提前致谢。

Edit 编辑

If it was what I thought it was, would I create a new Private Sub to put it in? 如果这是我的想法,我是否会创建一个新的“私人小组”来放置它? Or would it be in Form_Load? 还是会在Form_Load中?

For dynamic controls for need an AddHandler statement to point it's events to a Sub. 对于需要AddHandler语句将其事件指向Sub的动态控件。 None of those variables need to be class level. 这些变量都不需要是类级别的。 Saves you from holding memory when you don't need to. 不需要时可以节省存储空间。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM