Tuesday, October 30, 2012

Insert a Timer without the form Designer

Insert a Timer without the form Designer

On a previous post [How to use a Timer], we show you how to use a Timer from the System.Windows.Forms.
But you could also make it without the form designer.  This gives you the advantage to control your code. Visual Basic Express or Visual Studio will always try to write your code base on the windows design form. The biggest problem is when Visual Basic is mess up and starts building garbage line or duplicate objects. It happen most the ContextMenu and StripMenus.

Typing your own code will also help you gather your stuff. Check this sample:

''' <summary>
''' put a Timer without the Visual Basic form Designer
''' </summary>
''' <remarks></remarks>
Public Class Form1
    Private WithEvents oTimer As System.Windows.Forms.Timer

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        oTimer = New System.Windows.Forms.Timer
        oTimer.Interval = 1000
        oTimer.Enabled = True
    End Sub

    Private Sub timerTicks() Handles oTimer.Tick
        Me.Text = Date.Now
    End Sub

End Class

The most important line is this one:

    Private WithEvents oTimer As System.Windows.Forms.Timer

Is important for you to place it inside your class and mostly important to put the WithEvents. The WithEvents make the oTimer1 to activate the Tick function:

    Private Sub timerTicks() Handles oTimer.Tick
        Me.Text = Date.Now
    End Sub

How you name your function is really not important. I called it timerTicks without parameters. Well in fact, in this case, it works and lucky for us. All matter is at the end of your function, your put Handle and the event of the object. In this case, is oTimer.Tick

What does this program do?

The first function initiates the oTimer1 and set some values. The interval is the period.  If the interval is a 1000, the interval is set a 1 seconds. You see? The units are in milliseconds.
Then, make sure to enable your timer. By default, is set to false. Make sure is set to true if you want the timer to work.
Finally, use the start method to start the count down.

At 1000 milliseconds, the program triggers the event and calls the function timerTicks. Inside that function, place anything you want.

In this example, I made a simple clock.

This is very interesting if you need a timer in a little code in MS-Excel or MS-Word with Visual Basic for Application (VBA). Use it for simple program too.

The program I love to use:

Sample Code :

1 comment: