
108
LESSON 9 Creating and displaying new Forms
The following code demonstrates this technique. The main form’s Load event handler creates and dis-
plays a new
ColorForm. When the user clicks the main form’s Red button, its event handler changes the
remote form’s
BackColor and ForeColor properties. The startup form also contains green and blue
buttons that have similar event handlers.
// The remote form we will manipulate.
ColorForm remoteColorForm;
// Create and display the remote form.
private void Form1_Load(object sender, EventArgs e)
{
remoteColorForm = new ColorForm();
remoteColorForm.Show();
}
// Make the color form red.
private void redButton_Click(object sender, EventArgs e)
{
remoteColorForm.BackColor = Color.Red;
remoteColorForm.ForeColor = Color.Pink;
}
Here the remoteColorForm variable is declared outside of the event handlers. The form’s Load event
handler initializes the variable and displays the remote form. The
redButton_Click event handler
uses it. Because the variable is declared outside of the event handlers, they can all use it. (Lesson 13
has more to say about when and where variables are available to the code.)
In the previous example, I moved the code that creates the ColorForm into the
main form’s
Load event handler. If that code stayed in a Button’s Click event
handler, the user could click it a bunch of times and create many different
forms. Each time the prog