我想点击一个按钮,创建一个新的图片框控件。因此,每次我点击它,它都会添加另一个新的图片框控件。这些图片框都具有相同的功能,如能够移动它们并在它们上绘制。但是按钮只会生成一个,之后不再使用以下代码。我错过了什么?
Public Class Form1
Dim xpos As New Integer
Dim ypos As New Integer
Dim pos As New Point
Dim x As Integer
Dim y As Integer
Dim canvas As New PictureBox
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer = 0
i = i + 1
canvas.Name = "canvas" & i
canvas.BackColor = Color.White
canvas.BorderStyle = BorderStyle.FixedSingle
canvas.Image = Nothing
canvas.Height = TextBox1.Text
canvas.Width = TextBox2.Text
AddHandler canvas.MouseDown, AddressOf PictureBox1_MouseDown
AddHandler canvas.MouseMove, AddressOf PictureBox1_MouseMove
Controls.Add(canvas)
End Sub
Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
xpos = Cursor.Position.X - canvas.Location.X
ypos = Cursor.Position.Y - canvas.Location.Y
End Sub
Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
If e.Button = Windows.Forms.MouseButtons.Left Then
pos = MousePosition
pos.X = pos.X - xpos
pos.Y = pos.Y - ypos
canvas.Location = pos
End If
End Sub
Private Sub PictureBox1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
End Class
答案 0 :(得分:1)
Dim canvas As New PictureBox
您的代码中存在多个错误,但这是最严重的错误。 As New
语法确保您始终创建PictureBox对象,但它只会是一个对象。当然,一个变量无法跟踪多个图片框。
您需要做的是在点击按钮时创建一个新的。跟踪您创建的图片框通常是个好主意。所以正确的代码如下:
Dim canvases As New List(Of PictureBox)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim canvas = New PictureBox
canvases.Add(canvas)
canvas.Name = "canvas" & canvases.Count.ToString()
'' etc...
End Sub
Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
Dim canvas = DirectCast(sender, PictureBox)
xpos = Cursor.Position.X - canvas.Location.X
ypos = Cursor.Position.Y - canvas.Location.Y
End Sub
请注意 sender 参数如何为您提供一个返回正在被鼠标的图片框对象的引用。在任何其他事件处理程序中执行相同的操作。
答案 1 :(得分:0)
每当创建新画布时增加计数器:
Public Class Form1
Dim counter As New Integer
...
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
counter += 1
canvas.Name = "canvas" & counter.ToString()
...
访问鼠标当前正在移动的画布:
Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
If e.Button = Windows.Forms.MouseButtons.Left Then
pos = MousePosition
pos.X = pos.X - xpos
pos.Y = pos.Y - ypos
DirectCast(sender, PictureBox).Location = pos
End If
End Sub