Tutorial: Add code to the picture viewer Windows Forms app in Visual Studio

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

In this series of three tutorials, you'll 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. To learn more, see Welcome to the Visual Studio IDE.

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

Prerequisites

This tutorial builds on the previous tutorials, Create a picture viewer application and Add UI controls to the picture viewer. If you haven't done those tutorials, go through them first.

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)
    {
    }
    
    Private Sub showButton_Click() Handles showButton.Click
    
    End Sub
    

    Important

    Use the programming language control at the top right of this page to view either the C# code snippet or the Visual Basic code snippet.

    Programming language control for Docs.Microsoft.com

  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)
    {
    }
    
    Private Sub clearButton_Click() Handles clearButton.Click
    
    End Sub
    
    Private Sub backgroundButton_Click() Handles backgroundButton.Click
    
    End Sub
    
    Private Sub closeButton_Click() Handles closeButton.Click
    
    End Sub
    
    Private Sub CheckBox1_CheckedChanged() Handles CheckBox1.CheckedChanged
    
    End Sub
    

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. All instances of that variable in the code are renamed. 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 to insert if.

  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 will show 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);  
    
    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);  
        }
    }
    
    Private Sub showButton_Click() Handles showButton.Click
        If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
            PictureBox1.Load(OpenFileDialog1.FileName)
        End If
    
    End Sub
    
  12. 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);
        }
    }
    
    Private Sub showButton_Click() Handles showButton.Click
    
        ' Show the Open File dialog. If the user clicks OK, load the
        ' picture that the user chose.
        If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
            PictureBox1.Load(OpenFileDialog1.FileName)
        End If
    
    End Sub
    

    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. Add the code in the braces.

    private void clearButton_Click(object sender, EventArgs e)
    {
        // Clear the picture.
        pictureBox1.Image = null;
    }
    
    Private Sub clearButton_Click() Handles clearButton.Click
        ' Clear the picture.
        PictureBox1.Image = Nothing
    End Sub   
    
  2. Double-click the Set the background color button and add the code in braces.

    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;
    }
    
    Private Sub backgroundButton_Click() Handles backgroundButton.Click
        ' 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 Then
            PictureBox1.BackColor = ColorDialog1.Color
        End If
    End Sub
    
  3. Double-click the Close button and add the code in braces.

    private void closeButton_Click(object sender, EventArgs e)
    {
        // Close the form.
        this.Close();
    }
    
    
    Private Sub closeButton_Click() Handles closeButton.Click
        ' Close the form.
        Close()
    End Sub  
    
  4. Double-click the Stretch checkbox and add the code in braces.

    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;
    }
    
    Private Sub CheckBox1_CheckedChanged() Handles CheckBox1.CheckedChanged
        ' 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 Then
            PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
        Else
            PictureBox1.SizeMode = PictureBoxSizeMode.Normal
        End If
    End Sub   
    

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 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.

Next steps

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

  • Created a Visual Studio project that uses Windows Forms
  • Done 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

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