382 Part III Designing the User Interface
To perform a relative movement using the Location property, the Location.X and Location.Y
properties are needed. For example, the program statement:
PictureBox1.Location = New Point(PictureBox1.Location.X - 50, _
PictureBox1.Location.Y - 40)
moves the picture box object 50 pixels left and 40 pixels up on the form. Although this
construction seems a bit unwieldy, it’s the recommended way to relocate objects in relative
movements on your form at run time.
Creating Animation by Using a Timer Object
The trick to creating animation in a program is placing one or more Location property
updates in a timer event procedure so that at set intervals the timer causes one or more
objects to drift across the screen. In Chapter 7, “Using Loops and Timers,” you learned how
to use a timer object to update a simple clock utility every second so that it displayed the
correct time. When you create animation, you set the Interval property of the timer to
a much faster rate—1/5 second (200 milliseconds), 1/10 second (100 milliseconds), or less.
The exact rate that you choose depends on how fast you want the animation to run.
Another trick is to use the Top and Left properties and the size of the form to “sense” the
edges of the form. By using these values in an event procedure, you can stop the animation
(disable the timer) when an object reaches the edge of the form. And by using the Top
property, the Left property, form size properties, and an If... Then or Select... Case decision
structure, you can make an object appear to bounce off one or more edges of the form.
The following exercise demonstrates how you can animate a picture box containing a Sun
icon (Sun .ico) by using the Location property and a timer object. In this exercise, you’ll use
the Top property to detect the top edge of the form, and you’ll use the Size.Height property
to detect the bottom edge. The Sun icon will move back and forth between these extremes
each time you click a button.
Animate a Sun icon on your form
- Click the Close Project command on the File menu, and then create a new Windows
Forms Application project named My Moving Icon. - Using the Button control, draw two button objects in the lower-left corner of the form.
- Using the PictureBox control, draw a small rectangular picture box object in the
lower-right corner of the form.
This is the object that you’ll animate in the program. - Click the Image property in the Properties window, and then click the ellipsis button in
the second column.
The Select Resource dialog box appears. - Click the Local Resource radio button, and then click the Import button.