200 Part II Programming Fundamentals
Using a Timer Object to Set a Time Limit
Another interesting use of a timer object is to set it to wait a given period of time before
either permitting or prohibiting an action. You can also use this timer technique to display
a welcome message or a copyright message on the screen or to repeat an event at a set
interval, such as saving a file every 10 minutes or backing up important files each night at
2:00 A .M. Again, this is a little like setting an egg timer in your program. You set the Interval
property with the delay you want, and then you start the clock ticking by setting the Enabled
property to True. So long as the program is still running, your timer object will be active.
The following exercise shows how you can use this approach to set a time limit for entering
a password. (The password for this program is “secret .”) The program uses a timer to close its
own program if a valid password isn’t entered in 15 seconds. (Normally, a program like this
would be one of the initial forms in a larger application .)
Set a password time limit
- On the File menu, click the New Project command, and create a new Windows Forms
Application project named My Timed Password.
The new project is created, and a blank form opens in the Designer. - Resize the form to a small rectangular window about the size of an input box.
- Click the TextBox control in the Toolbox, and then draw a text box for the password in
the middle of the form. - Click the Label control in the Toolbox, and then draw a long label above the text box.
- Click the Button control in the Toolbox, and then draw a button below the text box.
- Double-click the Timer control on the Components tab of the Toolbox.
Visual Studio adds a timer object to the component tray below the form.
- Set the properties for the program in the following table:
Object Property Setting
Label1 Text “Enter your password within 15 seconds”
TextBox1 PasswordChar “*”
Button1 Text “Try Password”
Timer1 Enabled
Interval
True
15000
Form1 Text “Password”
The PasswordChar setting displays asterisk (*) characters in the text box as the user enters
a password. Setting the timer Interval property to 15000 gives the user 15 seconds to
enter a password and click the Try Password button. Setting the Enabled property to