How do I add a Real Time Clock to my Application?

I am very much a newb to VB but want to get started on an Alarm Clock program, I have viewed the first 6 videos here http://msdn.microsoft.com/vstudio/express/vb/learning/default.aspx

So thats about as fars as my knowledge goes. I havent been able to find a Clock controll to add to my project, so how do I add a Real Time Clock to my project so that I can perform different functions based on what time it is



Answer this question

How do I add a Real Time Clock to my Application?

  • dstock

    VB 2005 is acting very wierd, I know I am not an expert at VB, but I think this version of VB has issues!

    First take a look at this Picture I have here> http://www.clannbs.com/nbs/modules.php name=Forums&file=viewtopic&p=554#554 and click on the picture to see it better. Or you can go here to view it directly> http://www.clannbs.com/nbs/modules.php name=Forums&file=download&id=50

    In this picture, it is still the same program, I just manually put the labels and timers in there so I dont have to mess around with a bunch of code to make it simpler. I labeled the objects and circled them with a red border so you can see what ther are named instead of guessing.

    Ok, first of all the Clock object is working fine. The object I have labeled "HH" is working fine also. I have HH there, as you can see from my code; to display only hours in the 24hr format. I have it like this so I can use it as a reference to change the AMPM.text to to AM or PM respectively.

    If HH.text = Format(Now, "0H" Then

    AMPM.text = "AM"

    Else

    AMPM.text = "PM"

    This is the code that was working for the most part, before I added the code you see in the picture. The code that is commented out isnt exactly working or at least thats what I thought untill I noticed issues with VB 2005.

    Before I explain my program any further and what issues im having, I have to explain why I think this version of VB is has issues.

    Ok, I finally re wrote the program to what you see in the picture because before when I was playing around with the code trying to get it to work the way I want it to, it stopped showing any new controll I put on the form, when I run the project that is; Buttons, Textboxes, Listboxes, you name it and it wouldnt show it when I ran the program. I thought I did something wrong to make this happen but I copied all the controlls in my form (the ones that would show) so I didnt have to remake them and I closed the project down and started a fresh one and pasted the controlls back in the new project. I rewrote the code and added the controlls that I wanted to use with my project and they still wouldnt show when I ran the project, I then added more controlls just to see if they would show and those didnt show. I checked the properties and there were no issues there, also the Visible property was set to True.

    I then closed down VB 2005 Express and reopened it, started a new project, added all the controlls I wanted, and reprogrammed to what you see in the picture except I didnt add the HH and AMPM yet, I then ran the program and the Clock works fine, So I decide to add the HH and AMPM objects, before I programmed them I ran it and they showed in my form just fine. (Now I am back to explaining my project further, this is also part of where VB has issues though) I tried different code to get the AMPM label to display accordingly, but had some issues.

    NOTE: That the code I wrote above is the code I had working somewhat, before I start noticing issues with VB2005. Then I wrote the code you see in its place because I thought it was my code that I may have writen incorectly.

    The code above will make the AMPM label display "AM" when the HH label displays 00 through 09, except when the HH label displayed 02 for some reason it displayed PM on the AMPM label. This is the start of the issued with VB 2005.

    I tried many different logical things in the code to get it to working the way I wanted to but it still didnt work properly.

    Then with the code I wrote above i commented out this code>

    Else

    AMPM.text = "PM"

    because AMPM label was displaying PM at the weirdest times when rad the program. Even when the code was written like this>, between the lines are the different code I tried to use to get the AMPM to display properly but nothing worked, I changed my system clock to test out different times.

  • Aqsa

    How can I turn;

    Clock.Text = Format(Now, "HH:mm:ss")

    into a 12hr format instead of 24hr


  • R102oy

    Add a timer control to your form, in the toolbox under "Components", which fires at least once a second, or whenever you want your clock to update. Then you can find out the current time and date from the system clock using the Now built in property.

  • guy kolbis

    This is helpfull for me to know, but I want to display the current time in my project, like either a textbox or label that displays the currect time to the second.
  • LoicBaroux

    By the way, you may have to widen your clock textbox in your design window... almost forgot, i missed out on that at first n then it still didnt show my added AM/PM which kinda defeated the purpose of makin it in the first place.

  • Shailesh_rathi

    Hi

    I'm sorry you can't get it to work. It seemed from your previous post that you needed a bit more help than you got in the previous answer and I thought that this might have provided it.

    Firstly let's make sure you have the code as written.

    Highlight the code written above and copy it to the clipboard.

    Open a new windows application project in VB Express.

    Double click the empty form to open up the code editor which should contain something like:

    Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    End Class

    Delete all of this and then paste in what you copied above.

    Hit F5 and it should run.

    Regarding your queries above I have posted the code again but this time with comments which may resolve some of your queries.

    Public Class Form1
    ' Create a label to act as the clock display
    ' by creating a new instance of the label class called Clock
    ' This could also be done in the form designer
    Dim Clock As New Label
    ' Define a timer to update the display
    ' Again this could be done in the form designer
    Dim WithEvents Ticker As New Timer
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    ' Set the width and height of the form
    Me.Width = 300 : Me.Height = 200
    ' Set size and position of the clock display
    Clock.Width = 225 : Clock.Height = 55 : Clock.Left = 35 : Clock.Top = 50
    ' Set the font to be used in the display
    Clock.Font = New Font("Arial", 36, FontStyle.Bold)
    ' Add the display to the form controls collection
    ' otherwise it won't be seen

    Me.Controls.Add(Clock)
    ' Set the update interval to 1 second (interval is set in msecs)
    Ticker.Interval = 1000
    ' This line is not essential but simply calls the timer_tick event handler
    ' to write the current time to the clock display as soon as the application starts,
    ' otherwise there could be a delay of up to a second between the form appearing and
    ' the time being displayed

    Tick(Nothing, Nothing)
    ' start the timer
    Ticker.Start()
    End Sub
    Private Sub Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Ticker.Tick
    ' every time the timer fires (i.e. every second)
    ' update the display

    Clock.Text = Format(Now, "HH:mm:ss")
    End Sub
    End Class


    If you still can't get it working it may be best if you e-mail me (see my profile) rather than continue the discussion in the forum

    Good Luck

    Dave


  • Reinhold_Fischer

    I have a couple questions and one about logical placement of code I write in general.

    I just notices that I can move pieces of code around into different classed and it will still work like I planned. Except for like the Clock code has to be in the "sub timer1_tick".

    But I can take, for instance, the code for an Alarm Event, that shows a messagebox or plays a sound when its the right time, I can take that code (which I originally written it under "Private Sub TextBox1_TextChanged") and put it under "Private Sub Tick" (which is where it is now) and it still works, although I can put under "Private Sub Form1_Load" and this works also.

    I know if I am writing a button event it must be under the "Private Sub Button_Click", but how do I know if I am writing the code in the right place in general That is, if there is a right place for the code (which im sure there is), but what are the general "logical" rules behind issue

    The other question is about playing a sound and looping it untill a button is clicked or a extra form or messagebox closes. I just learned how to play a audio file when an event happens by using "My.Computer.Audio.Play("C:\TheAudioFile.FormatPrefix")".

    I tryed playing around with the "Do While/Untill Loop" statement that I researched on MSDN, but I couldnt figure out how to get it working properly.

    For example, when I have my alarm event, a messagebox shows, I got it to play the sound and show the messagebox after but couldnt get the sound to loop untill the messagebox was closed, It either didnt play the sound at all or it kept opening a new msgbox and playing the sound once after I closed it then opened a nother msgbox and playing the soung after I closed it and stayed in that loop.

    I since changed my code to open a new form I created, but this "Do Loop" statement doesnt work the same with the form as it did with the mesagebox, I just get an error.

    ** Ok, I just accidentally found another way for it to loop the sound apon an alram event. By taking out the "ss" format it will loop the sound untill the nect minute as shown in the code below. **

    If CheckBox1.Checked And TextBox1.Text = Format(Now, "h:mm") Then

    AlarmEventForm1.Show()

    My.Computer.Audio.Play("C:\Documents and Settings\Ronald C. Stone\My Documents\My Music\WAV samples\ringin.wav")

    End If

    But I would like to have more controll over it than just this. Plus I am having fun learning programming with VB Express :)

    Thanks!


  • dirose

    this is the whole of the code:

    Public Class Form1
    Dim Clock As New Label
    Dim WithEvents Ticker As New Timer
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Me.Width = 300 : Me.Height = 200
    Clock.Width = 225 : Clock.Height = 55 : Clock.Left = 35 : Clock.Top = 50
    Clock.Font = New Font("Arial", 36, FontStyle.Bold)
    Me.Controls.Add(Clock)
    Ticker.Interval = 1000
    Tick(Nothing, Nothing)
    Ticker.Start()
    End Sub
    Private Sub Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Ticker.Tick
    Clock.Text = Format(Now, "hh:mm:ss")
    If Clock.Text = "13:13:40" Then
    MessageBox.Show("ALARM")
    End If
    End Sub
    End Class

    including everything...

    but what you need is really:

    Private Sub Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Ticker.Tick
    Clock.Text = Format(Now, "hh:mm:ss")
    If Clock.Text = "13:13:40" Then
    MessageBox.Show("ALARM")
    End If
    End Sub


    so you see, inside your
    Private Sub Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Ticker.Tick


    End Sub

    you must have your if statement.
    else it wont check it. I dont know if it was this or if you missed the End If, but this works.
    Also, the 12hr clock is given by non-capital "hh" in "hh:mm:ss" if you use "HH:mm:ss" you get 24 hr clock :)
    lol, made my first application yesterday... in VB... dont work proberly yet, but this does...

    hope this does it, else:
    you might know this, but if now, you may replace the string " "ALARM" " by any variable string which you can give a value at another point, thus giving different messages in your MessageBox than just "ALARM" or whatever you might want.

  • Marcelius

    ok, i did it a slightly bit different, you can keep the change or you can do as you did with the AMPM box, but this works too:

    Private Sub Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Ticker.Tick

    Clock.Text = Format(Now, "hh:mm:ss")
    If (Format(Now, "HH") < 12) Then
    Clock.Text = Clock.Text + " AM"
    Else
    Clock.Text = Clock.Text + " PM"
    End If


    End Sub

    if you dont like it, dont use it, you can just change Clock.Text = Clock.Text + " AM" or "PM
    to your AMPM.Text = "AM"
    or
    AMPM.Text ="PM"

    your problem could arise from the AMPM.Text with non-capital T in text no idea really, just a suggestion, but this worked so far with me.
    VB will not recognise your string "12" as a number 12, therefore, no "".

    Oh, n i believe that you call it PM when its 12:00 on a 12 hour clock... AM is for 00:00 thats y i put < 12 only.

    Best regards...

  • Thomas van der Heijden

    A few suggestions you may find useful:

    1. Turn on Option Strict, either through Tools - Options - Projects and Solutions - VB Defaults where you can make it a default for all of your projects, or by adding Option Strict On at the top of your code, above the class declaration.

    This will tell the code editor to warn you when you are attempting to use expressions which require narrowing type conversions. Although VB will generally do such conversions for you it is better if you are warned about this and have to do it yourself as it will force you to think about the data types you are using and eventually lead to a better understanding of them.

    2. Rather than mess about with your system clock to do your testing put a datetime picker on your form and set it to show the time using its format property. When you click on it you can then change the displayed time using the up/down and left/right keys. Use this to set your alarm time with code such as

    Dim AlarmTime As Date
    Private Sub DateTimePicker1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateTimePicker1.ValueChanged
    AlarmTime = DateTimePicker1.Value
    End Sub

    3. Don't use an equality check for your alarm function but rather check whether the current time is > or = to the alarm time

    4. Don't use the text property of the clock label for the check but use the value you used to write to the label instead.

    5. Don't make repeated accesses of the Now property, it may change between one access and the next. For instance you are going to write the current time to the clock label, check whether it is AM or PM and then check whether the alarm time has passed. This would hardly be critical in this application but could be in others so only make one read of the property and assign it to a variable. Then use the variable for your display and checks. e.g.

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Dim CurrentTime As Date = Now
    Label1.Text = Format(CurrentTime, "HH:mm:ss")
    If CurrentTime >= AlarmTime Then
    Textbox1.Text = "ALARM"
    Else
    Textbox1.Text = ""
    End If
    If CurrentTime.Hour < 12 Then
    Textbox2.Text = "AM"
    Else
    Textbox2.Text = "PM"
    End If
    End Sub


    Dave


  • michael.wu

    I cant get this to work, ill analyze it from my point of view from what I think I know, but just remember I am a beginner :), If I am wrong somewhere please correct me, thanks.

    Public Class Form1
    Dim Clock As New Label
    Dim WithEvents Ticker As New Timer

    'Here you are globally declaring two variables (Clock and Ticker), I am not sure what the "WithEvents" and "New" keywords are for, I am thinking that they add those controlls (Label and Timer) to my form so I dont have to add them manually

  • Ams

       Thank you very much, this works!

    Now I am trying to raise an event based on the value in the clock variable. I "basically" know how to raise events based on text and number formats inside text boxes and labels and such, but I am having trouble raising them using the time  "HH:mm:ss" format.

    What I tried is this under the (Private Sub Form1_Load);

       If Clock.Text = ("08:03:00") Then

       MessageBox.Show("Alarm Event!")

    I also tried;

       If Clock.Text = ("080300") Then

       MessageBox.Show("Alarm Event!")

    I am sure you see what I am trying to do here, I just cant get it working. So I guess my question is, How do I raise events using the Time Format (HH:mm:ss)

    Thanks.

     

    I am editing this because I just answered the event question myself.

    I found that the code;

       If Clock.Text = ("08:03:00") Then

       MessageBox.Show("Alarm Event!")

     needed to be under the; (Private Sub Tick).

    So I guess ill play around with for a while, Thanks alot for the help :)

     


  • MoMad

    A couple of comments....

    Dave "Dim"ed the member variables that were "with events", I would have declared them "Protected".

    You asked what WithEvents means. It means to define this object in such a way denoting that it has events and it likely to have event handlers. Intellisense will show the event handlers for the declared object.



  • Oliver Foehr

    You may find the following useful just to get you going

    Public Class Form1
    Dim Clock As New Label
    Dim WithEvents Ticker As New Timer
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Me.Width = 300 : Me.Height = 200
    Clock.Width = 225 : Clock.Height = 55 : Clock.Left = 35 : Clock.Top = 50
    Clock.Font = New Font("Arial", 36, FontStyle.Bold)
    Me.Controls.Add(Clock)
    Ticker.Interval = 1000
    Tick(Nothing, Nothing)
    Ticker.Start()
    End Sub
    Private Sub Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Ticker.Tick
    Clock.Text = Format(Now, "HH:mm:ss")
    End Sub
    End Class

    Dave


  • How do I add a Real Time Clock to my Application?