Stop timer at a certain time in Visual Studio 2013 - vb.net

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

Related

Refresh/Reload Form using timer in VB.NET

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

How to constantly check for changes in system time?

I'm trying to make a program that makes a sound every hour, how would I do this?
I thought maybe constantly checking the system time and if it's equal to either "1:00 2:00 3:00 etc..." then play a sound, but I don't know how to do this, some help would be appreciated :)
Add a Timer, set Interval for 1000 (1 second) and in Tick event check current time
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'check time here and put it in Label1
Label1.Text = TimeOfDay.ToString("hh:mm:ss")
'if currenttime = alarmtime then do something
If TimeOfDay.ToString("hh:mm:ss") = "10:01:00" Then Beep()
End Sub
For more info how to read current time:
https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.dateandtime(v=vs.110).aspx
Create a timer, set the interval for 500 milliseconds (.5s), setting to 1 second could cause the tick to be missed. This will fire the tick event, check if the current time minutes and seconds are equal to zero, then fires. The timer is disabled between the sound firing in case the timer checks again within the second (because the timer is called ever half a second).
ReadOnly _tmr As New Timer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
_tmr.Interval = 500
AddHandler _tmr.Tick, AddressOf tmr_Tick
_tmr.Enabled = True
End Sub
Private Sub tmr_Tick(sender As Object, e As EventArgs)
Dim curDateTime As DateTime = Now
If curDateTime.Minute = 0 And curDateTime.Second = 0 Then
_tmr.Enabled = False
PlaySound()
_tmr.Enabled = True
End If
End Sub
Private Sub PlaySound()
'// Play Sound
End Sub

Application.DoEvents() CheckBox Bug (VB)

I was having problems running my application when (God Mode) was running... I found online, that it seems to be a common bug. The fix is to put Application.DoEvents() Within the loop, which I did... But now everytime I turn God Mode on, The CheckBoxes bug out, when they're clicked they activate... The program doesn't stop responding but there needs to be two clicks for the program to visually show that it's active:
Full Code:
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked = True Then
Do
Application.DoEvents()
WriteDMAInteger("Dishonored", GetModuleHandle("Dishonored", "Dishonored.exe") + &H100C810, {&H344}, 70, 1, 4)
Loop Until CheckBox1.Checked = False
End If
End Sub
Any ideas or solutions?
As the comments indicate, don't use Application.DoEvents() It's more trouble than it's worth. Instead, use a timer.
Drag a Timer control onto your form from the Toolbox. Set its Interval property to something suitable (like 100 ms). Add the Tick event and call your WriteDMAInteger method in that event. In your check box's changed event simply enable or disable the timer:
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
'Enables the time if the checkbox is checked
Timer1.Enabled = CheckBox1.Checked
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
WriteDMAInteger("Dishonored", GetModuleHandle("Dishonored", "Dishonored.exe") + &H100C810, {&H344}, 70, 1, 4)
End Sub
With the timer's interval set to 100 ms, the WriteDMAInteger method will be called 10 times per second. You can experiment with a smaller value than 100 for the interval, but the limit will be about 50ms.

Use timer to trigger an event in program at specific time

I have my timer code displaying the time correctly on my program, and I want to trigger an event to happen at a 6:31. How do I get the program to preform a button click or trigger the event that the button handles. The program works when I run and press the button, but I want it to happen automatically at 6.31 without me pressing it. Thanks!
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
Label1.Text = Date.Now.ToString("hh:mm:ss")
End Sub
In your Tick event:
Dim now As DateTime = DateTime.Now
If (18 = now.Hour) AndAlso (31 = now.Minute) Then
' Change 18 to 6 is you want AM instead of PM
' Do something here
End If
This is the naive version. Your question is lacking in details so I did not elaborate on the code.
At a minimum you may need to ensure that once the "event" happens it can't happen again.

Delaying in VB.net

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.