【发布时间】:2014-05-01 02:03:47
【问题描述】:
我试图让一个线程同时移动两个图片框,但这不会发生,第一个开始移动,然后当第二个开始移动。我不知道如何让它们同时移动。
代码如下:
Imports System.Threading
Public Class Form1
Private picuser As New PictureBox()
Private y As Integer
Private thread1 As Thread
Private thread2 As Thread
Private thread3 As Thread
Private thread4 As Thread
Public Sub enemy1()
picUser = New System.Windows.Forms.PictureBox()
picUser.Visible = True
picUser.Size = New System.Drawing.Size(32, 32)
picuser.Location = New System.Drawing.Point(100, 100)
picuser.BackColor = Color.Purple
Dim e As New AddControlEventArgs(picuser)
' Create EventHandler
Dim ehnd As New EventHandler(AddressOf AddControl)
' Invoke EventHandler with EventArgs (don't need sender as of now)
thread1 = New Thread(Sub() Me.Invoke(ehnd, Nothing, e))
thread1.Start()
End Sub
Public Sub enemy2()
picuser = New System.Windows.Forms.PictureBox()
picuser.Visible = True
picuser.Size = New System.Drawing.Size(32, 32)
picuser.Location = New System.Drawing.Point(150, 100)
picuser.BackColor = Color.Red
Dim e As New AddControlEventArgs(picuser)
' Create EventHandler
Dim ehnd As New EventHandler(AddressOf AddControl)
' Invoke EventHandler with EventArgs (don't need sender as of now)
thread2 = New Thread(Sub() Me.Invoke(ehnd, Nothing, e))
thread2.Start()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
thread3 = New Thread(AddressOf enemy1)
thread4 = New Thread(AddressOf enemy2)
thread3.Start()
thread4.Start()
End Sub
Private Sub mover(ByVal x As PictureBox)
For z = 0 To 10
x.Location = New Point(x.Location.X, x.Location.Y + 10)
Threading.Thread.Sleep(100)
Me.Refresh()
Next
End Sub
Public Class AddControlEventArgs : Inherits EventArgs
Public Sub New(p_control As Control)
m_control = p_control
End Sub
Private m_control As Control
Public ReadOnly Property Control As Control
Get
Return m_control
End Get
End Property
End Class
Private Sub AddControl(sender As Object, e As EventArgs)
' Cast EventArgs to your custom EventArgs
Dim ec As AddControlEventArgs = DirectCast(e, AddControlEventArgs)
Me.Controls.Add(ec.Control)
Call mover(ec.Control)
End Sub
End Class
【问题讨论】:
-
你认为
Invoke()是做什么的?你实际上并没有在你的线程上做任何事情。相反,请使用 WinForms 计时器或Await。 -
我编辑了代码以使用
Await,它仍然和我描述的@SLaks完全一样 -
否;完全摆脱线程并使用
Await Task.Delay()
标签: vb.net multithreading object picturebox