Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Public Function WaitFor(ByVal seconds As Long)
Sleep(seconds * 1000) '1000 mili seconds per second
End Function I receive an error under the end function: "Function 'Waitfor' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. Thanks in advance Charly
Solution: function problem
For future reference, too, that declaration you had was for VB6 with "Long". For VB.Net you would change the Long to Integer and make your method a sub instead of a function:
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Integer)
If used in a WinForms application you wouldn't want to sleep for long durations though as this would make your app unresponsive.
One solution is to sleep for a small duration, pump the message queue with DoEvents(), and check the time:
Private Sub Delay(ByVal DelayInSeconds As Integer) Dim ts As TimeSpan Dim targetTime As DateTime = DateTime.Now.AddSeconds(DelayInSeconds) Do ts = targetTime.Subtract(DateTime.Now) Application.DoEvents() ' keep app responsive System.Threading.Thread.Sleep(50) ' reduce CPU usage Loop While ts.TotalSeconds > 0 End Sub
Example:
Delay(10) ' hold for ten seconds
You could also use a Timer control instead to eliminate the need for a polling loop.