my issue is i need to wait 3-4 seconds after a button has been pressed before i can check for it, here is my code under button1_click:
While Not File.Exists(LastCap)
Application.DoEvents()
MsgBox("testtestetstets")
End While
PictureBox1.Load(LastCap)
I think i'm doing something really simple wrong, i'm not the best at VB as i'm just learning so any explaining would be great!
~Thanks
If the reason you are needing to wait is for the file to be created try using a FileSystemWatcher and respond to the Created and Changed Events that way you are responding to an event rather than arbitrarily waiting a select period of time.
Something like:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
FileSystemWatcher1.Path = 'Your Path Here
FileSystemWatcher1.EnableRaisingEvents = True
'Do what you need to todo to initiate the file creation
End Sub
Private Sub FileSystemWatcher1_Created(sender As Object, e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Created, FileSystemWatcher1.Changed
If e.Name = LastCap Then
If (System.IO.File.Exists(e.FullPath)) Then
FileSystemWatcher1.EnableRaisingEvents = False
PictureBox1.Load(e.FullPath)
End If
End If
End Sub
You can use, although not recommended:
Threading.Thread.Sleep(3000) 'ms
This will wait 3 seconds, but also block everything else on the same thread. If you run this in the form your user-interface will not response until the wait is over.
just as a side note: use MessageBox.Show("My message") instead of MsgBox (latter is from old VB).
If you want your form to continue to function while the 3 seconds pass, you can add a Timer control instead, with some code like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' set the timer
Timer1.Interval = 3000 'ms
Timer1.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Timer1.Stop()
'add delayed code here
'...
'...
MessageBox.Show("Delayed message...")
End Sub
Drag and drop a Timer control from your toolbox to your form. It's not visible at runtime
or better yet making a wait function using stop watch, this wont halt the process in the same thread like thread sleep
' Loops for a specificied period of time (milliseconds)
Private Sub wait(ByVal interval As Integer)
Dim sw As New Stopwatch
sw.Start()
Do While sw.ElapsedMilliseconds < interval
' Allows UI to remain responsive
Application.DoEvents()
Loop
sw.Stop()
End Sub
usage
wait(3000)
for 3 sec delay
You could use this
Public Sub BeLazy()
For i = 1 To 30
Threading.Thread.Sleep(100)
Application.DoEvents()
Next
End Sub
It will delay for 3 seconds.
Related
I want the vb.net app to close after 1 minute of inactive time.
this code will close the app after 1 min for active user as well.
Dim app As Application
Private Sub MainWindow_Loaded(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim aTimer As System.Timers.Timer
aTimer = New System.Timers.Timer()
aTimer.Interval = 60000
AddHandler aTimer.Elapsed, AddressOf OnTimedEvent
aTimer.Enabled = True
End Sub
Private Sub OnTimedEvent(ByVal source As Object, ByVal e As System.Timers.ElapsedEventArgs)
app.Exit()
End Sub
You can try as follow.
Create a System.Timers.Timerin your window.xaml.vb file:
Private WithEvents CloseTimer As New Timers.Timer
In the constructor, add the following lines:
CloseTimer.Interval = 1000 * 5 ' Remember that interval is set in milliseconds
CloseTimer.Start()
Every time the mouse is moved on the window, the timer has to be reset, so use the MouseMove event like this:
Private Sub Window_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
ResetTimer()
End Sub
And define the ResetTimer() subroutine as follow:
Private Sub ResetTimer()
CloseTimer.Stop()
CloseTimer.Start()
End Sub
Obviously you can change / improve that condition: for example, if the user doesn't move the mouse because he's typing in a Textbox, you should manage this condition, too:
Private Sub Window_PreviewKeyDown() Handles Me.PreviewKeyDown
ResetTimer()
End Sub
This will catch all KeyDown event from the window and all its children controls.
Finally add the Timer_Elapsed event, which will be fired when the timer interval elapsed:
Private Shared Sub Timer_Elapsed() Handles CloseTimer.Elapsed
Environment.Exit(0)
End Sub
If you notice there are more conditions to keep the application running, just find the appropriate event and in its subscription call ResetTimer().
Note that this method is quite simple but, depending on the architecture of the application, there may be better methods.
I have messed with this long enough and had to come for help. I am reading in some text file values on form_load. I want to refresh/reload the form every 5 minutes (Disregard my test time). The form loads and runs ok, but after a couple of minutes it seems to crash and I get an error at timer.start. The time until it crashes is very random. I don't understand enough yet about timers, so hopefully someone can tell me where I am going wrong here.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim timer = New Timer
timer.Interval = 30 * 1000
NewMethod(timer)
timer.Start()
'''Run other code
End Sub
Private Sub NewMethod(timer As Timer)
AddHandler timer.Tick, AddressOf Timer1_Tick
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Form1_Load(Me, e:=Nothing)
End Sub
I'm making a simple progress bar to be used as a splash screen within my application but when the code is executed, the loading bar does not reach the end of the progress bar.
I've used the code:
splashprogressbar.Increment(1)
If splashprogressbar.Value = 100 Then
Main_Menu.Show()
Me.Hide()
End If
to open a form when the progress bar reaches 100, which has been set as the maximum value.
The issue is more so related to appearance rather than functionality but i would still like to understand why this occurs and hopefully get a fix.
To clarify, the form Main_Menu, opens when the bar is about 3/4 of the way completed and i can't get my head around why this occurs. Any ideas?
I couldn't imagine that VB has such a bug. Probably you are running an old or incompatible ".Net Framework" that causes that.
You can try to set your Progressbars maximum programatically while running the program.
Use this code in the Form1_Load event:
ProgressBar1.Maximum = 100
It should work. But if it doesn't, maybe it's just code related. Try to fill your progressbar this way (It must be in a timer):
If splashprogressbar.Value = splashprogressbar.Maximum Then
Main_Menu.Show()
Me.Hide()
Else
splashprogressbar.Value += 100
End If
Just a friendly advice: It seems you're simulating a fake loading bar which fills and then, only then, open the app (Potentially wasting the users time). Don't do that.
You could also try taking a look at the following link. This may help with your approach;
Trigger Background Worker
The below was copied from the link above...
Dim WithEvents bgWorker As New BackgroundWorker With { _
.WorkerReportsProgress = True, _
.WorkerSupportsCancellation = True}
Private Sub bgWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgWorker.DoWork
For i As Integer = 0 To 100
'Threw in the thread.sleep to illustrate what's going on. Otherwise, it happens too fast.
Threading.Thread.Sleep(250)
bgWorker.ReportProgress(i)
Next
End Sub
Private Sub bgWorker_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgWorker.ProgressChanged
If e.ProgressPercentage Mod 10 = 0 Then
MsgBox(e.ProgressPercentage.ToString)
End If
End Sub
Private Sub bgWorker_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgWorker.RunWorkerCompleted
MsgBox("Done")
End Sub
you could try something like this;
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Me.Show()
Dim i As Integer
splashprogressbar.Minimum = 0
splashprogressbar.Maximum = 100
If splashprogressbar.Value < splashprogressbar.Maximum Then
For i = 0 To 100
splashprogressbar.Value = i
Application.DoEvents()
System.Threading.Thread.Sleep(100)
Next
End If
Me.Hide()
MsgBox("Here I am") 'Use your "Main_Menu.Show" here
End Sub
I have a loop that increases a a progress bar value every second. It works fine, but if you click anywhere in the form, the window turns white and it says "YOURTITLEHERE (No response)".
Here is the loop code:
Private Sub incprogress()
While ProgressBar1.Value < 1000
ProgressBar1.Value += 1
System.Threading.Thread.Sleep(1000)
End While
End Sub
Better yet, use a timer that ticks once per second. It's best not to play with Threads if you don't know what you are doing.
If you look in your toolbox, you'll find a Timer control that you can drag onto your form.
Set its interval to 1000, Enable it, and handle its Tick event to have something happen once per second.
If you want to do something more complicated than sleep between progress bar updates (like process lines in a file or wait for network traffic) you might use the BackgroundWorker instead of Timer. It is a little more complex to set up, but it will let you do all the heavy lifting off of your GUI thread so the GUI remains responsive.
Public Class Form1
Dim bgw As System.ComponentModel.BackgroundWorker
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
bgw = New System.ComponentModel.BackgroundWorker
bgw.WorkerReportsProgress = True
AddHandler bgw.DoWork, AddressOf bgw_DoWork
AddHandler bgw.ProgressChanged, AddressOf bgw_ProgressChanged
bgw.RunWorkerAsync()
End Sub
Private Sub bgw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
While ProgressBar1.Value < 1000
System.Threading.Thread.Sleep(1000) 'Optionally do some useful work here off the UI thread
bgw.ReportProgress(0) 'optionally report a real percentage done
End While
End Sub
Private Sub bgw_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs)
If ProgressBar1.Value < 1000 Then
ProgressBar1.Value += 1 'optionally set progress bar to real percentage done
End If
End Sub
End Class
I am trying to play and stop the timer at a certain time that i typed in a textbox because i want to play an audio after the time is done.
Can you guys help me out?
Here is my code:
Private Sub Simulate_Click(sender As Object, e As EventArgs) Handles Simulate.Click
AxWindowsMediaPlayer1.Show()
AxWindowsMediaPlayer1.Ctlcontrols.play()
AxWindowsMediaPlayer1.Ctlcontrols.fastForward()
Simulate.Enabled = False
If TextBox1.Text = 1 Then
My.Computer.Audio.Play(My.Resources._1, AudioPlayMode.Background)
ElseIf TextBox1.Text = 2 Then
My.Computer.Audio.Play(My.Resources._2, AudioPlayMode.Background)
If i type say for example 2 seconds, it would take two seconds before the audio file plays.
Drop a timer control on the form and set it to the time interval where you would like it to stop at. In the timer's tick event disable the timer so that it doesn't fire again, and play your sound.
The timer will fire off X milliseconds after you set it's Enabled property to true.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
tmrAlarm.Interval = TimeSpan.FromSeconds(2).TotalMilliseconds
tmrAlarm.Enabled = True
End Sub
Private Sub tmrAlarm_Tick(sender As Object, e As EventArgs) Handles tmrAlarm.Tick
tmrAlarm.Enabled = False
MsgBox("Beep!")
End Sub
In this example a message box will pop up 2 seconds after pressing the button.
It requires a Timer control to be placed on the form named tmrAlarm.
This method will keep your application responsive without having to worry about complex multi-threading issues.
If you're not concerned about application responsiveness a simple System.Threading.Thread.Sleep(timeInSeconds * 1000) will do the trick. This will lock up the application for the sleep time.
If responsiveness is an issue you will need to have the playing of audio occur as a response to a new event you will create. Then you would need to start a new thread that sleeps and after sleep raises your new event.
You have to add a timer called "Timer1" for this to work. If textbox contains number "1" then time is set to 1000 milliseconds and timer is started, when 1000ms is up, then it will start playing the sound and then stop the timer.
Public Class Form1
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If TextBox1.Text.Contains("1") Then
Timer1.Interval = ("1000")
Timer1.Start()
ElseIf TextBox1.Text.Contains("2") Then
Timer1.Interval = ("2000")
Timer1.Start()
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Timer1.Stop()
My.Computer.Audio.Play(My.Resources._1, AudioPlayMode.Background)
End Sub
End Class