Tutorial: Add reference variables and a timer control to your matching game WinForms app

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

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.

  1. Add label references to your form by using the following code.

    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
    
    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;
    

    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.

    Programming language control for Docs.Microsoft.com

    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.

  2. Modify your Click event handler to use the new firstClicked reference variable. Remove the last statement in the label1_Click() event handler method (clickedLabel.ForeColor = Color.Black;) and replace it with the if statement as follows.

    ''' <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
    
    /// <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;
            }
        }
    }
    
  3. 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.

    Screenshot shows the Matching Game showing one icon.

    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.

  1. 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.

    Screenshot shows the timer icon below the form.

  2. Select the Timer1 icon to select the timer. In the Properties window, select the Properties button to view properties.

  3. 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.

  4. 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.

    /// <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 and secondClicked, to make the icons of the two labels that the player chose invisible again.
    • It resets the firstClicked and secondClicked reference variables to null in C# and Nothing in Visual Basic.
  5. 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 the secondClicked reference variable, and start the timer. The label1_Click() event handler method now looks as follows:

    /// <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 the firstClicked and secondClicked 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.

  6. 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.