0

我只想在 vb2008 中问一个非常重要的问题:我正在研究 2D 关卡设计师,我只是将所有图像和碰撞矩形放在他的位置,然后程序生成正确的代码。问题是:我制作了一个按钮并在他的点击事件中添加了一个新的图片框,当它添加时我必须用鼠标移动它,我有“移动”代码但就像你知道它是一个新的图片框所以我在图片框添加之前不能写代码。(如果你不明白我可以再解释一下我的情况)

为了更清楚,这是代码:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

    Dim i As Integer

    newPictureBox.Image = Image.FromFile("C:\Users\hp\Desktop\ground.bmp")
    newPictureBox.Name = "image" & (i)
    newPictureBox.Visible = True
    newPictureBox.Top = 200
    newPictureBox.Width = 100
    newPictureBox.Height = 50
    newPictureBox.Left = 100 + goToRight
    newPictureBox.SizeMode = PictureBoxSizeMode.AutoSize
    'add control to form
    Controls.Add(newPictureBox)
    goToRight = goToRight + newPictureBox.Width
    i += 1
End Sub

这是“移动图片框”代码(用于现有的图片框):

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Dim endPoint As Integer = Val(TextBox1.Text)
    Label1.Text = "X: " & MousePosition.X - (Location.X + 8)
    Label2.Text = "Y: " & MousePosition.Y - (Location.Y + 29)
    RadioButton1.Left = endPoint + RadioButton2.Left
    Panel1.Left = 0

    'Move picture code :
    If IcanMove = True Then

        PictureBox1.Left = MousePosition.X - (Location.X + 8) - differenceX
        PictureBox1.Top = MousePosition.Y - (Location.Y + 29) - differenceY
    End If


End Sub

Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
    IcanMove = True
    differenceX = (MousePosition.X - (Location.X + 8)) - PictureBox1.Left
    differenceY = (MousePosition.Y - (Location.Y + 29)) - PictureBox1.Top
End Sub
Private Sub PictureBox1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseUp
    IcanMove = False
End Sub

谢谢你的阅读:)

4

1 回答 1

0

您需要为新添加的事件处理程序PictureBox,这里是如何做到这一点。

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim NewPictureBox As PictureBox = New PictureBox
    NewPictureBox.Parent = Me
    NewPictureBox.Location = New Point(100, 100)
    Me.Controls.Add(NewPictureBox)
    'you can use existing event handlers like your PictureBox1_MouseDown
    AddHandler NewPictureBox.MouseUp, AddressOf PictureBox_MouseUp
    AddHandler NewPictureBox.MouseDown, AddressOf PictureBox_MouseDown
End Sub

Private Sub PictureBox_MouseDown(sender As Object, e As MouseEventArgs)
    MessageBox.Show("Triggered MouseDown Event")
End Sub

Private Sub PictureBox_MouseUp(sender As Object, e As MouseEventArgs)
    MessageBox.Show("Triggered MouseUp Event")
End Sub

(如果您PictureBox在关闭表单之前还删除了 's,请务必删除它们的处理程序)
有关更多信息,请检查AddHandlerRemoveHandler

于 2013-08-15T19:54:01.867 回答