Edit

Share via


Tutorial: Add code to the picture viewer Windows Forms App (.NET Framework)

In this series of three tutorials, you create a Windows Forms application that loads a picture and displays it. The Visual Studio Integrated Design Environment (IDE) provides the tools you need to create the app.

Controls use C# or Visual Basic code to take the actions associated with them.

In this third tutorial, you learn how to:

  • Add event handlers for your controls
  • Write code to open a dialog box
  • Write code for the other controls
  • Run your application

To create a new Windows Forms App with .NET, follow the tutorial Create a Windows Forms app with .NET. See the Desktop Guide on Windows Forms .NET to learn more.

Prerequisites

Add event handlers for your controls

In this section, add event handlers for the controls that you added in the second tutorial, Add controls to a picture viewer application. Your application calls an event handler when an action takes place, such as selecting a button.

  1. Open Visual Studio. Your Picture Viewer project appears under Open recent.

  2. In the Windows Forms Designer, double-click the Show a picture button. You can instead select the Show a picture button on the form, and then press Enter.

    The Visual Studio IDE opens a tab in the main window. For C#, the tab is named Form1.cs. If you're using Visual Basic, the tab is named Form1.vb.

    This tab displays the code file behind the form.

    Screenshot shows the Form1.cs tab with Visual C sharp code.

    Note

    Your Form1.vb tab might display showButton as ShowButton.

  3. Focus on this part of the code.

    private void showButton_Click(object sender, EventArgs e)
    {
    }
    
  4. Choose the Windows Forms Designer tab again, and then double-click the Clear the picture button to open its code. Repeat for the remaining two buttons. Each time, the Visual Studio IDE adds a new method to the form's code file.

  5. Double-click the CheckBox control in Windows Forms Designer to add a checkBox1_CheckedChanged() method. When you select or clear the check box, it calls this method.

    The following snippet shows the new code that you see in the code editor.

    private void clearButton_Click(object sender, EventArgs e)
    {
    }
    
    private void backgroundButton_Click(object sender, EventArgs e)
    {
    }
    
    private void closeButton_Click(object sender, EventArgs e)
    {
    }
    
    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
    }
    

Methods, including event handlers, can have any name that you want. When you add an event handler with the IDE, it creates a name based on the control's name and the event being handled.

For example, the Click event for a button named showButton is called showButton_Click() or ShowButton_Click(). If you want to change a code variable name, right-click the variable in the code and then choose Refactor > Rename. This action renames all instances of that variable in the code. For more information, see Rename refactoring.

Write code to open a dialog box

The Show a picture button uses the OpenFileDialog component to display a picture file. This procedure adds the code used to call that component.

The Visual Studio IDE offers a powerful tool called IntelliSense. As you type, IntelliSense suggests possible code.

  1. In Windows Forms Designer, double-click the Show a picture button. The IDE moves your cursor inside the showButton_Click() or ShowButton_Click() method.

  2. Type an i on the empty line between the two braces { }or between Private Sub... and End Sub. An IntelliSense window opens.

    Screenshot shows IntelliSense with Visual C sharp code.

  3. The IntelliSense window should highlight the word if. Select the Tab key twice to insert the if snippet.

  4. Select true and then type op to overwrite it for C# or Op for Visual Basic.

    Screenshot shows the event handler for the show button with the value true selected.

    IntelliSense displays openFileDialog1.

  5. Select Tab to add openFileDialog1.

  6. Type a period (.) or dot, right after openFileDialog1. IntelliSense provides all of the OpenFileDialog component's properties and methods. Start to type ShowDialog and select Tab. The ShowDialog() method shows the Open File dialog box.

  7. Add parentheses () immediately after the "g" in ShowDialog. Your code should be openFileDialog1.ShowDialog().

  8. For C#, add a space, and then add two equal signs (==). For Visual Basic, add a space, and then use a single equal sign (=).

  9. Add another space. Use IntelliSense to enter DialogResult.

  10. Type a dot to open the DialogResult value in the IntelliSense window. Enter the letter O and choose the Tab key to insert OK.

    Note

    The first line of code should be complete. For C#, it should be similar to the following.

    if (openFileDialog1.ShowDialog() == DialogResult.OK)

    For Visual Basic, it should be the following.

    If OpenFileDialog1.ShowDialog() = DialogResult.OK Then

  11. Add the following line of code.

    pictureBox1.Load(openFileDialog1.FileName);  
    

    You can copy and paste or use IntelliSense to add it. Your final showButton_Click() method should look similar to the following code.

    private void showButton_Click(object sender, EventArgs e)
    {
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            pictureBox1.Load(openFileDialog1.FileName);  
        }
    }
    

  1. Add the following comment to your code.

    private void showButton_Click(object sender, EventArgs e)
    {
        // Show the Open File dialog. If the user clicks OK, load the
        // picture that the user chose.
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            pictureBox1.Load(openFileDialog1.FileName);
        }
    }
    

It's the best practice to always comment your code. Code comments make it easier to understand and maintain your code in the future.

Write code for the other controls

If you run your application now, you can select Show a picture. Picture Viewer opens the Open File dialog box, where you can select a picture to display.

In this section, add the code for the other event handlers.

  1. In Windows Forms Designer, double-click the Clear the picture button. For C#, add the code in braces. For Visual Basic, add the code between Private Sub and End Sub.

    private void clearButton_Click(object sender, EventArgs e)
    {
        // Clear the picture.
        pictureBox1.Image = null;
    }
    
  2. Double-click the Set the background color button and add the code.

    private void backgroundButton_Click(object sender, EventArgs e)
    {
        // Show the color dialog box. If the user clicks OK, change the
        // PictureBox control's background to the color the user chose.
        if (colorDialog1.ShowDialog() == DialogResult.OK)
            pictureBox1.BackColor = colorDialog1.Color;
    }
    
  3. Double-click the Close button and add the code.

    private void closeButton_Click(object sender, EventArgs e)
    {
        // Close the form.
        this.Close();
    }
    
    
  4. Double-click the Stretch checkbox and add the code.

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        // If the user selects the Stretch check box, 
        // change the PictureBox's
        // SizeMode property to "Stretch". If the user clears 
        // the check box, change it to "Normal".
        if (checkBox1.Checked)
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
        else
            pictureBox1.SizeMode = PictureBoxSizeMode.Normal;
    }
    

Run your application

You can run your application at any time while you're writing it. After you add the code in the previous section, the Picture Viewer is complete. As in the previous tutorials, use one of the following methods to run your application:

  • Select the F5 key.
  • On the menu bar, select Debug > Start Debugging.
  • On the toolbar, select the Start button.

A window with the title Picture Viewer appears. Test all the controls.

  1. Select the Set the background color button. The Color dialog box opens.

    Screenshot shows your app with the Color dialog box.

  2. Choose a color to set the background color.

  3. Select Show a picture to display a picture.

    Screenshot shows the Picture Viewer app with a picture displayed.

  4. Select and unselect Stretch.

  5. Select the Clear the picture button to make sure the display clears.

  6. Select Close to exit the app.

Congratulations! You completed this series of tutorials. You accomplished these programming and design tasks in the Visual Studio IDE:

  • Created a Visual Studio project that uses Windows Forms
  • Added layout for the picture viewing application
  • Added buttons and a checkbox
  • Added dialog boxes
  • Added event handlers for your controls
  • Written C# or Visual Basic code to handle the events

Next step

Continue learning with another tutorial series on how to create a timed math quiz.