Displaying date and time in the UI - vb.net

My program displays the current date and time and must be accurate, and I need to prevent users from changing the time. Here's what I tried.
On form load I query the current date and time of the server and change the local system time to what I got.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cmd = New SqlCommand("Select getdate()", con)
serverdatetime = cmd.ExecuteScalar
Microsoft.VisualBasic.TimeOfDay = serverdatetime
Microsoft.VisualBasic.DateAndTime.Today = serverdatetime
TimeKeeper.Start()
End Sub
Now I tried 2 ways of displaying the time, the first one, since I adjusted the system time to what I got from the server, I just get my time from the local system. But the time on my program can easily be changed by changing the system time.
Private Sub TimeKeeper_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimeKeeper.Tick
lblDate.Text = DateTime.Now.Date()
lblTime.Text = DateTime.Now().ToString("HH:mm:ss")
End SUb
Second thing, I just take the time I got from the server and increment it every second.
Private Sub TimeKeeper_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimeKeeper.Tick
serverdatetime = serverdatetime.AddSeconds(1)
lblDate.Text = serverdatetime.Date()
lblTime.Text = serverdatetime.ToString("HH:mm:ss")
End SUb
I thought it worked great except it seems to get delayed once I do some operations in the system(I guess because some other code is running, my timer doesn't execute its code) and the more I do the more it gets delayed, after a few testing of the program the server time was already 10 seconds ahead of the time I have in my program.
So, how can I achieve what I need?

You cannot rely on Tick event of the Timer. I would use the StopWatch class to get duration passed (since when server time is read) independent from the system time adjustments.
Dim stopWatch As StopWatch = new StopWatch()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cmd = New SqlCommand("Select getdate()", con)
serverdatetime = cmd.ExecuteScalar
stopWatch.Start()
TimeKeeper.Start()
End Sub
Private Sub TimeKeeper_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimeKeeper.Tick
Dim currentDate As DateTime = serverdatetime.Add(stopWatch.Elapsed)
lblDate.Text = currentDate.Date()
lblTime.Text = currentDate.ToString("HH:mm:ss")
End SUb

Related

add sound with time interval in vb.net

I created a vb.net app
In the form 2 text box and one button
Textbox1 displays current system time and textbox2, 1 hour later.
So when i press the button , sound should play exactly after 1 hour of time i pressed button.
So if I press button for 5 different time in half an hour, the sound should play after 1 hour starting from that button press.
I have following code to play sound and to display two different time in text box.
Private Sub ESREntry_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim mytime As System.DateTime
Dim hours As Double = 1
mytime = Now.ToShortTimeString
StartTimetxt.Text = mytime
EndTimeTxt.Text = mytime.AddHours(+hours)
Timer1.Start()
End sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim hours As Double = 1
Me.StartTimetxt.Text = TimeOfDay
Me.EndTimeTxt.Text = TimeOfDay.AddHours(+hours).ToShortTimeString
End Sub
I used this code for this
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Console.Beep()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Console.Beep()
End Sub

Set start time of Timer Interval

how do i set the starting time of the time interval, let's say i would like to start the 5 sec interval counting after 10 seconds. I'm having a problem with my logic can you help me with this? this is my code:
This is my timer in my Form1
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
If DateTime.Now = Form3.DateTimePicker1.Value Then
Timer2.Stop()
MsgBox("hey")
Timer2.Start()
End If
This is the OK button in my Form3
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Form1.Timer2.Interval = New TimeSpan(CInt(NumericUpDown3.Value), CInt(NumericUpDown2.Value), CInt(NumericUpDown1.Value)).TotalMilliseconds
Form1.Timer2.Start()
End If
It seems to work successfully with the intervals without setting the start of the interval, But if i add the start time of the interval, it doesn't seem to work. with this code If DateTime.Now = Form3.DateTimePicker1.Value Then what could be wrong?
This seems to be bad idea:
If DateTime.Now = Form3.DateTimePicker1.Value Then
Because it is extremely hard for you to catch the time exactly as you specify. Simply change = to >=
If DateTime.Now >= Form3.DateTimePicker1.Value Then
Then when you reach the time or later, you would show your message box.

Timer and updating label text

im trying to make an app to show when there is somthing "new". So i made Label1 and Timer. I want every secound to check if in status.txt text is 0 to show nothing, if its 1 to show text from text.txt. This is what try so far:
Public Class Form1
Dim client As WebClient = New WebClient()
Dim status As String = client.DownloadString("http://force-play.com/launcher/status.txt")
Dim information As String = client.DownloadString("http://force-play.com/launcher/text.txt")
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1.Start()
Timer1.Interval = 1000
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If status = 0 Then
Label1.Text = "No New Info"
End If
If status = 1 Then
Label1.Text = information
End If
End Sub
End Class
Try setting the status string at the beginning of your Timer1_Tick method.

Showing time on label according to selected time zone from combobox (VB)

I wonder how to display the time in a label according to the selected UTC time zone from the list of a combobox. Thanks in advance. This is what have so far.
Private Sub frmClock_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Label2.Text = TimeOfDay
Dim tzCollection As ReadOnlyCollection(Of TimeZoneInfo)
tzCollection = TimeZoneInfo.GetSystemTimeZones()
Me.ComboBox1.DataSource = tzCollection
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim selectedTimeZone As TimeZoneInfo = DirectCast(Me.ComboBox1.SelectedValue(), TimeZoneInfo)
MsgBox("You selected the " & selectedTimeZone.ToString() & " time zone.")
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim dt As Date = TimeOfDay
Label2.Text = dt.ToString()
End Sub
The TimeZoneInfo class provides several shared methods which can be used to convert times from one time-zone to another. For instance, if the time from which you want to convert is UTC, you can use the ConvertTimeFromUtc method, like this:
Dim convertedTime As Date = TimeZoneInfo.ConvertTimeFromUtc(Date.UtcNow, selectedTimeZone)
Or, if the time to convert is in the current local time-zone, then you can use the ConvertTime method, like this:
Dim convertedTime As Date = TimeZoneInfo.ConvertTime(Date.Now, selectedTimeZone)
Alternatively, if the source time is in another time-zone (not UTC nor local), you can use another overload of the ConvertTime method which takes both the source time-zone and the destination time-zone, like this:
Dim convertedTime As Date = TimeZoneInfo.ConvertTime(sourceTime, sourceTimeZoneInfo, destinationTimeZoneInfo)

How to use timer for for next loop in visual basic 2008

I have a case where i need to generate millions of unique codes. For this I have created a generate function where the random number is generated. I call this function from a for loop and add the generated number on a list box. my code is as follow
for i=1 to val(txtnumber.txt)
mynum=generate()
next
I have created a lable on form where i wanted to display the no of secs elapsed while processing the loop. I used timer control as
timer1.start()
for i=1 to val(txtnumber.text)
mynum=generate()
listbox1.items.add(mynum)
next
timer1.stop
and on timer1_tick function
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Label1.Text = Val(Label1.Text) + 1
End Sub
but when i click generate button, all numbers are generated, but timer doesnot shows time elapsed.
I may have missed something, so please help me out
This is probably best handled in a BackgroundWorker. Place one on the form and set its WorkerReportsProgress=True. Also, placing a million numbers in a ListBox probably isn't a good idea, so I omitted that.
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Button1.Enabled = False
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim started As DateTime = Now
For i As Integer = 1 To val(txtnumber.txt)
mynum=generate()
BackgroundWorker1.ReportProgress(i, Nothing)
Next
Dim ended As TimeSpan = Now.Subtract(started)
BackgroundWorker1.ReportProgress(0, ended.TotalSeconds.ToString)
End Sub
Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
If e.UserState IsNot Nothing Then
Label1.Text = e.UserState.ToString()
Else
Label1.Text = e.ProgressPercentage.ToString
End If
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Button1.Enabled = True
End Sub
Your label should be updating correctly when the worker reports the ProgressChanged event.
What you're encountering is a threading issue. The work you are doing to generate the numbers is being executing by the UI thread, so it never gets a chance to update the screen. Take a look here: How to prevent UI from freezing during lengthy process?
This one might also have good information for you: Updating UI from another thread
Try this:
Private _Counter As Integer = 0
Private _StartTime As Date = Now
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
_StartTime = Now
_Counter = CInt(Val(txtnumber.Text))
ListBox1.Items.Clear()
Label1.Text = "0"
Timer1.Interval = 50
Timer1.Start()
End Sub
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
ListBox1.Items.Add(generate())
Label1.Text = New Date((Now - _StartTime).Ticks).ToString("HH:mm:ss.ff")
_Counter -= 1
If (_Counter <= 0) Then
Timer1.Stop()
End If
End Sub
Or you can research actual Threading.