
FIGURE 96
You can improve this program by making all four PictureBoxes use the same event han-
dler and making the event handler figure out which image to use.
The event handler’s
sender parameter is the control that raised the event, in this case, the
PictureBox that the user clicked. The data type of that parameter is object, but you can get
a variable of type
PictureBox that refers to the same object by using the as keyword. The
as keyword tells the program to treat some value (in this case the sender parameter) as if it
were some other type (in this case a
PictureBox). The following code shows how you can
get a variable that treats the
sender parameter as a PictureBox.
PictureBox selectedPictureBox;
selectedPictureBox = sender as PictureBox;
Copy the program you built for Exercise 4. Modify the first event handler so it uses the
as keyword to get a reference to the PictureBox that the user clicked, and then uses that
PictureBox to set the PictureForm’s background. Delete the other event handlers and
make all the
PictureBoxes share the modified one.
You can download the solutions to these exercises from the book’s web page at
www.wrox.com or www.CSharpHelper.com/24hour.html. You can find them in
the Lesson09 folder in the download.
596906c09.indd 113 4/7/10 12:32:21 PM
Click here to Play