Reputation: 13
I want to display an image for 1 second and then disappear it. The code i'm trying to use is:
PictureBox4.Visible = True
System.Threading.Thread.Sleep(1000) ' 1 second delay
PictureBox4.Visible = False
But so far it's not working, is there a way to make this code works or any other methods to implement a delay in vb.net?
Upvotes: 0
Views: 1505
Reputation: 26
Try this
PictureBox4.Visible = True
Application.DoEvents()
System.Threading.Thread.Sleep(1000)
PictureBox4.Visible = False
Upvotes: 0
Reputation: 6131
The reason why your code isn't working is because Sleep
is tying up the UI thread and the control is never redrawn. So technically the Visible
property is being changed, it is just that the user never sees the change.
You have a couple of options. One is to use a System.Timers.Timer (documentation) and set the AutoReset
to false and the Interval
to 1,000. Before you start the timer you would show the control and then in the Timer's Elapsed
event you would hide the control. Here is a quick example:
Private ReadOnly _timer As Timers.Timer
Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
_timer = New Timers.Timer() With {
.AutoReset = False,
.Interval = 1000,
.SynchronizingObject = Me
}
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' create an event handler for the Elapsed event
AddHandler _timer.Elapsed, Sub() PictureBox4.Hide()
' show the control then start the timer
PictureBox4.Show()
_timer.Start()
End Sub
Update
Per JMcIlhinney's suggestion, I'm setting the SynchronizingObject
property so that you don't have to call the Invoke
method when hiding the control.
Upvotes: 1