In visual basic, the Timer component is useful to raise an event repeatedly in our application based on the specified interval of time. The timer component is available with System.Timers
namespace. So, to work with the timer component in our application to raise an event after a set of interval we need to import the System.Timers namespace. Following is the example of defining the timer object that raises an elapsed event after a set of interval in visual basic. ‘ Create timer Dim timer As Timer = New Timer() timer.Interval = 2000 AddHandler timer.Elapsed, AddressOf TimerEvent timer.AutoReset = True timer.Enabled = True If you observe the above code, we created a timer object by using the Timer
class. Here, the Interval
property is used to specify the time interval to raise an Elapsed event (TimerEvent) and the Enabled
property is used to specify whether the timer object should raise an Elapsed event or not. The AutoReset
property is used to configure the timer object to raise an elapsed event repeatedly at the specified interval of time defined by the Interval
property. In case, if we want to raise the Elapsed event only once after the specified interval has elapsed, then we need to set the AutoReset
property to false
.
Visual Basic Timer Properties
The following table lists some of the most commonly used properties of Timer class in visual basic.
Property | Description |
---|---|
AutoReset | It is useful to get or set whether the Timer should raise the Elapsed event only once (false) or repeatedly (true). |
CanRaiseEvents | It will return a value that indicates whether the component can raise an event or not. |
DesignMode | It will return a value that indicates whether the component is in design mode or not. |
Enabled | It is useful to get or set a value to indicate whether the Timer should raise the Elapsed event or not. |
Interval | It is useful to get or set the interval in milliseconds at which to raise the Elapsed event. |
Visual Basic Timer Methods
The following table lists some of the most commonly used methods of Timer class in visual basic.
Method | Description |
---|---|
Start() | It is useful to start raise the Elapsed event by setting Enabled to true. |
Stop() | It will stop raising the Elapsed event by setting Enabled to false. |
Close() | It is useful to release the resources that are used by the Timer. |
Dispose() | It is useful to release all the resources used by the Component. |
MemberwiseClone() | It is useful to create a shallow copy of the current object. |
GetType() | It is useful to get the type of current instance. |
Visual Basic Timer Example
Following is the example of using Timer
class in visual basic to execute the Elapsed events repeatedly at a specified interval of time. Imports System.Timers ModuleModule1 Sub Main(ByVal args As String()) Console.WriteLine(«Present Enter Key to Exit the Application») ‘ Create timer Dim timer As Timer = New Timer() timer.Interval = 2000 AddHandler timer.Elapsed, AddressOf TimerEvent timer.AutoReset = True timer.Enabled = True Console.ReadLine() End Sub ‘ Elapsed Event Private Sub TimerEvent(ByVal source As Object, ByVal e As ElapsedEventArgs) Console.WriteLine(«Event Raised at {0:HH:mm:ss.fff}», e.SignalTime) End Sub End Module If you observe the above example, we imported System.Timers
namespace to create a timer object by using Timer
class. Here, we used Interval
property to specify the time interval to raise an Elapsed event (TimerEvent) and the Enabled
property to specify whether the timer object should raise an Elapsed event or not. When we execute the above visual basic program, we will get the result as shown below. Present Enter Key to Exit the Application Event Raised at 07:48:49.274 Event Raised at 07:48:51.275 Event Raised at 07:48:53.275 Event Raised at 07:48:55.275 If you observe the result, for every 2 seconds the Elapsed event (TimerEvent) is raising and executing the elapsed event code. This is how we can use the timer object to raise an event repeatedly at the specified interval of time based on our requirements. Skip to main content This browser is no longer supported. Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Tutorial: Add reference variables and a timer control to your matching game WinForms app
- Article
- 9 minutes to read
In this article
Applies to: Visual Studio
Visual Studio for Mac
Visual Studio Code In this series of four tutorials, you build a matching game, where the player matches pairs of hidden icons. Your Matching Game program needs to track which Label controls the player chooses.
After a player chooses the first label, the program should show the icon.
After the second label is chosen, the program should display both icons for a brief time.
Then it hides both icons. Your program keeps track of which Label you choose first and second by using reference variables.
A timer hides the icons and controls how long to show the icons
- Add label references.
- Add a timer.
Prerequisites
This tutorial builds on previous tutorials, Create a matching game application and Add icons to your matching game.
Do those tutorials first.
Add label references
In this section, you’ll add two reference variables to your code.
They keep track of, or refer to Label objects.
- Add label references to your form by using the following code.
- C#
- VB
public partial class Form1 : Form { // firstClicked points to the first Label control // that the player clicks, but it will be null // if the player hasn't clicked a label yet Label firstClicked = null; // secondClicked points to the second Label control // that the player clicks Label secondClicked = null;
Public Class Form1 ' firstClicked points to the first Label control ' that the player clicks, but it will be Nothing ' if the player hasn't clicked a label yet Private firstClicked As Label = Nothing ' secondClicked points to the second Label control ' that the player clicks Private secondClicked As Label = Nothing
Important Use the programming language control at the top right of this page to view either the C# code snippet or the Visual Basic code snippet. These statements don’t cause Label controls to appear on the form because there’s no
new
keyword.
When the program starts, both firstClicked
and secondClicked
are set to null
for C# or Nothing
for Visual Basic.
- Modify your Click event handler to use the new
firstClicked
reference variable.
Remove the last statement in thelabel1_Click()
event handler method (clickedLabel.ForeColor = Color.Black;
) and replace it with theif
statement as follows.- C#
- VB
/// <summary> /// Every label's Click event is handled by this event handler /// </summary> /// <param name="sender">The label that was clicked</param> /// <param name="e"></param> private void label1_Click(object sender, EventArgs e) { Label clickedLabel = sender as Label; if (clickedLabel != null) { // If the clicked label is black, the player clicked // an icon that's already been revealed -- // ignore the click if (clickedLabel.ForeColor == Color.Black) return; // If firstClicked is null, this is the first icon // in the pair that the player clicked, // so set firstClicked to the label that the player // clicked, change its color to black, and return if (firstClicked == null) { firstClicked = clickedLabel; firstClicked.ForeColor = Color.Black; return; } } }
''' <summary> ''' Every label's Click event is handled by this event handler ''' </summary> ''' <param name="sender">The label that was clicked</param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub label_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label9.Click, Label8.Click, Label7.Click, Label6.Click, Label5.Click, Label4.Click, Label3.Click, Label2.Click, Label16.Click, Label15.Click, Label14.Click, Label13.Click, Label12.Click, Label11.Click, Label10.Click, Label1.Click Dim clickedLabel = TryCast(sender, Label) If clickedLabel IsNot Nothing Then ' If the clicked label is black, the player clicked ' an icon that's already been revealed -- ' ignore the click If clickedLabel.ForeColor = Color.Black Then Exit Sub ' If firstClicked is Nothing, this is the first icon ' in the pair that the player clicked, ' so set firstClicked to the label that the player ' clicked, change its color to black, and return If firstClicked Is Nothing Then firstClicked = clickedLabel firstClicked.ForeColor = Color.Black Exit Sub End If End If End Sub
- Save and run your program. Choose one of the label controls, and its icon appears.
Choose the next label control, and notice that nothing happens.Only the first icon that’s chosen turns black.
The other icons are invisible.
The program is already keeping track of the first label that the player chose.
The reference firstClicked
isn’t null
in C# or Nothing
in Visual Basic.
When your if
statement finds that firstClicked
isn’t equal to null
or Nothing
, it runs the statements.
Add a timer
The Matching Game uses a Timer control the app.
A timer waits, and then fires an event, referred to as a tick.
A timer can start and action or repeat an action regularly. In your program, the timer enables a player to choose two icons.
If the icons don’t match, it hides the two icons again after a short period of time.
- Select the Toolbox tab, in the Components category, double-click or drag the Timer component to your form.
The timer icon, called timer1, appears in a space below the form. - Select the Timer1 icon to select the timer.
In the Properties window, select the Properties button to view properties. - Set the Interval property to 750, which is 750 milliseconds.The Interval property tells the timer how long to wait between ticks, when it triggers its Tick event.
Your program calls the Start() method to start the timer after the player chooses the second label. - Choose the timer control icon and then press Enter, or double-click the timer.
The IDE adds an empty Tick event handler.
Replace the code with the following code.- C#
- VB
/// <summary> /// This timer is started when the player clicks /// two icons that don't match, /// so it counts three quarters of a second /// and then turns itself off and hides both icons /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void timer1_Tick(object sender, EventArgs e) { // Stop the timer timer1.Stop(); // Hide both icons firstClicked.ForeColor = firstClicked.BackColor; secondClicked.ForeColor = secondClicked.BackColor; // Reset firstClicked and secondClicked // so the next time a label is // clicked, the program knows it's the first click firstClicked = null; secondClicked = null; }
''' <summary> ''' This timer is started when the player clicks ''' two icons that don't match, ''' so it counts three quarters of a second ''' and then turns itself off and hides both icons ''' </summary> ''' <remarks></remarks> Private Sub Timer1_Tick() Handles Timer1.Tick ' Stop the timer Timer1.Stop() ' Hide both icons firstClicked.ForeColor = firstClicked.BackColor secondClicked.ForeColor = secondClicked.BackColor ' Reset firstClicked and secondClicked ' so the next time a label is ' clicked, the program knows it's the first click firstClicked = Nothing secondClicked = Nothing End Sub
The Tick event handler does three things:
- It makes sure the timer isn’t running by calling the Stop() method.
- It uses two reference variables,
firstClicked
andsecondClicked
, to make the icons of the two labels that the player chose invisible again. - It resets the
firstClicked
andsecondClicked
reference variables tonull
in C# andNothing
in Visual Basic.
- Go to the code editor and add code to the top and bottom of the
label1_Click()
event handler method.
This code will check if the timer is enabled, set thesecondClicked
reference variable, and start the timer.
Thelabel1_Click()
event handler method now looks as follows:- C#
- VB
/// <summary> /// Every label's Click event is handled by this event handler /// </summary> /// <param name="sender">The label that was clicked</param> /// <param name="e"></param> private void label1_Click(object sender, EventArgs e) { // The timer is only on after two non-matching // icons have been shown to the player, // so ignore any clicks if the timer is running if (timer1.Enabled == true) return; Label clickedLabel = sender as Label; if (clickedLabel != null) { // If the clicked label is black, the player clicked // an icon that's already been revealed -- // ignore the click if (clickedLabel.ForeColor == Color.Black) return; // If firstClicked is null, this is the first icon // in the pair that the player clicked, // so set firstClicked to the label that the player // clicked, change its color to black, and return if (firstClicked == null) { firstClicked = clickedLabel; firstClicked.ForeColor = Color.Black; return; } // If the player gets this far, the timer isn't // running and firstClicked isn't null, // so this must be the second icon the player clicked // Set its color to black secondClicked = clickedLabel; secondClicked.ForeColor = Color.Black; // If the player gets this far, the player // clicked two different icons, so start the // timer (which will wait three quarters of // a second, and then hide the icons) timer1.Start(); } }
''' <summary> ''' Every label's Click event is handled by this event handler ''' </summary> ''' <param name="sender">The label that was clicked</param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub label_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label9.Click, Label8.Click, Label7.Click, Label6.Click, Label5.Click, Label4.Click, Label3.Click, Label2.Click, Label16.Click, Label15.Click, Label14.Click, Label13.Click, Label12.Click, Label11.Click, Label10.Click, Label1.Click ' The timer is only on after two non-matching ' icons have been shown to the player, ' so ignore any clicks if the timer is running If Timer1.Enabled Then Exit Sub Dim clickedLabel = TryCast(sender, Label) If clickedLabel IsNot Nothing Then ' If the clicked label is black, the player clicked ' an icon that's already been revealed -- ' ignore the click If clickedLabel.ForeColor = Color.Black Then Exit Sub ' If firstClicked is Nothing, this is the first icon ' in the pair that the player clicked, ' so set firstClicked to the label that the player ' clicked, change its color to black, and return If firstClicked Is Nothing Then firstClicked = clickedLabel firstClicked.ForeColor = Color.Black Exit Sub End If ' If the player gets this far, the timer isn't ' running and firstClicked isn't Nothing, ' so this must be the second icon the player clicked ' Set its color to black secondClicked = clickedLabel secondClicked.ForeColor = Color.Black ' If the player gets this far, the player ' clicked two different icons, so start the ' timer (which will wait three quarters of ' a second, and then hide the icons) Timer1.Start() End If End Sub
- The code at the top of the method checks whether the timer was started by checking the value of the Enabled property.
If the player chooses the first and second Label controls and the timer starts, choosing a third label won’t do anything. - The code at the bottom of the method sets the
secondClicked
reference variable to track the second Label control.
Then, it sets that label icon color to black to make it visible.
Then, it starts the timer in one-shot mode, so that it waits 750 milliseconds and then fires a single tick.
The timer’s Tick event handler hides the two icons and resets thefirstClicked
andsecondClicked
reference variables.
The form is ready for the player to choose another pair of icons.
Note If you copy and paste the label1_Click()
code block rather than entering the code manually, be sure to replace the existing label1_Click()
code.
Otherwise, you’ll end up with a duplicate code block.
- Save and run your program.
Select a square and the icon becomes visible.
Choose another square.
The icon appears briefly and then both icons disappear.
Your program now keeps track of the first and second icons that you choose.
It uses the timer to pause before making the icons disappear.
Next steps
Advance to the next tutorial to learn how to finish your Matching Game.
Feedback
Submit and view feedback for
next →
← prev The timer control is a looping control used to repeat any task in a given time interval. It is an important control used in Client-side and Server-side programming, also in Windows Services. Furthermore, if we want to execute an application after a specific amount of time, we can use the Timer Control. Once the timer is enabled, it generates a tick event handler to perform any defined task in its time interval property. It starts when the start() method of timer control is called, and it repeats the defined task continuously until the timer stops. Let’s create a Timer control in the VB.NET Windows form by using the following steps. Step 1: Drag and drop the Timer control onto the window form, as shown below. Step 2: Once the Timer is added to the form, we can set various properties of the Timer by clicking on the Timer control.
Timer Control Properties
There are following properties of the VB.NET Timer control.
Properties | Description |
---|---|
Name | The Name property is used to set the name of the control. |
Enabled | The Enables property is used to enable or disable the timer control. By default, it is True. |
Interval | An Interval property is used to set or obtain the iteration interval in milliseconds to raise the timer control’s elapsed event. According to the interval, a timer repeats the task. |
AutoReset | The AutoReset property is used to obtain or set a Boolean value that determines whether the timer raises the elapsed event only once. |
Events | Events property are used to get the list of event handler that is associated with Event Component. |
CanRaiseEvents | It is used to get a value that represents whether the component can raise an event. |
Events of Timer Control
Events | Description |
---|---|
Disposed | When control or component is terminated by calling the Dispose method, a Dispose event occurs. |
Elapsed | When the interval elapses in timer control, the Elapsed event has occurred. |
Tick | A tick event is used to repeat the task according to the time set in the Interval property. It is the default event of a timer control that repeats the task between the Start() and Stop() methods. |
Methods of Timer Control
Methods | Description |
---|---|
BeginInt() | The BeginInt() method is used to start run time initialization of a timer control used on a form or by another component. |
Dispose() | The Dispose() method is used to free all resources used by the Timer Control or component. |
Dispose(Boolean) | It is used to release all resources used by the current Timer control. |
Close() | The Close() method is used to release the resource used by the Timer Control. |
Start() | The Start() method is used to begin the Timer control’s elapsed event by setting the Enabled property to true. |
EndInt() | The EndInt() method is used to end the run time initialization of timer control that is used on a form or by another component. |
Stop() | The Stop() method is used to stop the timer control’s elapsed event by setting Enabled property to false. |
Let’s create a simple program to understand the use of Timer Control in the VB.NET Windows Forms. TimerProgram.vb Output: When the program executes, it starts blinking the WELCOME TO JAVATPOINT.COM statement and counting the number to 1, as shown above. When the number is odd, the color of the statement is Red, and when the number is even, the color of the statement is Blue, as shown below.
Next TopicHow to keep a Form on top of others in VB.NET ← prev
next →
title | description | ms.custom | dev_langs | ms.date | ms.topic | author | ms.author | manager | ms.technology | ms.workload | ||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Tutorial: Add a timer to a Windows Forms app | Learn how to use the Visual Studio IDE to add a Timer control and event handler to the math quiz Windows Forms app. | vs-acquisition |
|
01/20/2022 | tutorial | anandme | meghaanand | jmartens | vs-ide-general | multiple |
Tutorial: Add a Timer control to a math quiz WinForms app
[!INCLUDE Visual Studio]
In this series of four tutorials, you’ll build a math quiz. The quiz contains four random math problems that a quiz taker tries to answer within a specified time.
The quiz uses a Timer control. The code behind this control tracks the elapsed time and checks the quiz taker’s answers.
In this third tutorial, you learn how to:
[!div]
- Add a Timer control.
- Add an event handler for the timer.
- Write code to check the user’s answers, display messages, and fill in the correct answers.
Prerequisites
This tutorial builds on previous tutorials, starting with Create a math quiz WinForms app. If you haven’t completed those tutorials, go through them first.
Add a countdown timer
To keep track of time during the quiz, you use a timer component. You also need a variable to store the amount of time that’s left.
-
Add an integer variable that’s named timeLeft in the same way that you declared variables in previous tutorials. Put the timeLeft declaration right after the other declarations. Your code should look like the following sample.
C#
:::code language=»csharp» source=»../../snippets/csharp/VS_Snippets_VBCSharp/vbexpresstutorial3step7/cs/form1.cs»:::
VB
:::code language=»vb» source=»../../snippets/visualbasic/VS_Snippets_VBCSharp/vbexpresstutorial3step7/vb/form1.vb»:::
[!INCLUDE devlang-control-csharp-vb]
-
In Windows Forms Designer, move a xref:System.Windows.Forms.Timer control from the Components category of the Toolbox to your form. The control appears in the gray area at the bottom of the design window.
-
On the form, select the timer1 icon that you just added, and set its Interval property to 1000. Because this interval is in milliseconds, a value of 1000 causes the timer to raise a xref:System.Windows.Forms.Timer.Tick event every second.
Check the answers
Because the timer raises a Tick event every second, it makes sense to check the elapsed time in a Tick event handler. It’s also practical to check the answers in that event handler. If time has run out, or if the answers are correct, the quiz should end.
Before you write that event handler, add a method called CheckTheAnswer()
to determine whether the answers to the math problems are correct. This method should be in line with the other methods, such as StartTheQuiz()
. Your code should look like the following sample.
C#
:::code language=»csharp» source=»../../snippets/csharp/VS_Snippets_VBCSharp/vbexpresstutorial3step7/cs/form1.cs»:::
VB
:::code language=»vb» source=»../../snippets/visualbasic/VS_Snippets_VBCSharp/vbexpresstutorial3step7/vb/form1.vb»:::
This method determines the answers to the math problems and compares the results to the values in the xref:System.Windows.Forms.NumericUpDown controls. In this code:
-
The Visual Basic version uses the
Function
keyword instead of the usualSub
keyword because this method returns a value. -
You can’t easily enter the multiplication sign (×) and the division sign (÷) by using the keyboard, so C# and Visual Basic accept an asterisk (*) for multiplication and a slash mark (/) for division.
-
In C#,
&&
is thelogical and
operator. In Visual Basic, the equivalent operator isAndAlso
. You use thelogical and
operator to check whether more than one condition is true. In this case, if the values are all correct, the method returns a value oftrue
. Otherwise, the method returns a value offalse
. -
The
if
statement uses the Value property of a NumericUpDown control to access the control’s current value. In the next section, you use the same property to display the correct answer in each control.
Add an event handler to the timer
Now that you have a way to check the answers, you can write the code for the Tick event handler. This code runs every second, after the timer raises a Tick event. This event handler checks the quiz taker’s answers by calling CheckTheAnswer()
. It also checks how much time has elapsed in the quiz.
-
On the form, double-click the Timer control, or select it and then select Enter. These actions add a Tick event handler to the timer. The code editor appears and displays the Tick handler’s method.
-
Add the following statements to the new event handler method.
C#
:::code language=»csharp» source=»../../snippets/csharp/VS_Snippets_VBCSharp/vbexpresstutorial3step3/cs/form1.cs»:::
VB
:::code language=»vb» source=»../../snippets/visualbasic/VS_Snippets_VBCSharp/vbexpresstutorial3step3/vb/form1.vb»:::
Each second of the quiz, this method runs. The code first checks the value that
CheckTheAnswer()
returns.-
If all answers are correct, that value is
true
, and the quiz ends:- The timer stops.
- A congratulatory message appears.
- The Enabled property of the startButton control is set to
true
so that the quiz taker can start another quiz.
-
If
CheckTheAnswer()
returnsfalse
, the code checks the value of timeLeft:- If this variable is greater than 0, the timer subtracts 1 from timeLeft. It also updates the Text property of the timeLabel control to show the quiz taker how many seconds remain.
- If no time remains, the timer stops and changes the timeLabel text to Time’s up! A message box announces that the quiz is over, and the answers are revealed. The start button becomes available again.
-
Start the timer
To start the timer when the quiz starts, add three lines to the end of the StartTheQuiz()
method, as the following sample shows.
C#
:::code language=»csharp» source=»../../snippets/csharp/VS_Snippets_VBCSharp/vbexpresstutorial3step3/cs/form1.cs»:::
VB
:::code language=»vb» source=»../../snippets/visualbasic/VS_Snippets_VBCSharp/vbexpresstutorial3step3/vb/form1.vb»:::
When your quiz starts, this code sets the timeLeft variable to 30 and the Text property of the timeLabel control to 30 seconds. Then the xref:System.Windows.Forms.Timer.Start method of the Timer control starts the countdown.
Run your app
-
Save your program and run it.
-
Select Start the quiz. The timer starts to count down. When time runs out, the quiz ends, and the answers appear.
-
Start another quiz, and provide correct answers to the math problems. When you answer correctly within the time limit, a message box opens, the start button becomes available, and the timer stops.
:::image type=»content» source=»../media/tutorial-windows-forms-timed-math-quiz/quiz-end.png» alt-text=»Screenshot that shows a completed quiz with 19 seconds remaining. The Start the quiz button is available.»:::
Next steps
Advance to the next tutorial to learn how to customize your math quiz.
[!div]
Tutorial part 4: Customize a math quiz WinForms app
- How to open a djvu file
- How to unlock the lost in the binding of isaac rebirth
- How to tell if a girl is trying to steal your boyfriend
- How to copy text that cannot be copied
- How to find a boyfriend (teen guys)