Step 10: Write Code for Additional Buttons and a Check Box

现在,您可以完成其他四个方法了。虽然您可以复制并粘贴此代码,但是若想从此教程中学些到最多的内容,那么请键入代码并使用 IntelliSense。

此代码将为您之前添加的按钮添加功能。如果不使用此代码,这些按钮将不执行任何操作。当您激活控件时,这些按钮将使用其 Click 事件(复选框使用 CheckChanged 事件)来执行不同的操作。例如,clearButton_Click 事件(当选择**“清除图片”**按钮时激活)会将其 Image 属性设置为 null(或 nothing),从而擦除当前的图像。代码中的每个事件都包括一些注释,用于解释代码所执行的操作。

链接到视频有关本主题的视频版本,请参阅教程 1:在 Visual Basic 中创建图片查看器 - 视频 5教程 1:在 C# 中创建图片查看器 - 视频 5。这些视频使用 Visual Studio 的早期版本,因此在一些菜单命令和其他用户界面元素上略有差异。但是,概念和过程与当前版本的 Visual Studio 大同小异。

说明说明

最佳做法是始终对您的代码进行注释。注释是供用户阅读的信息,花些时间使您的代码易于理解是值得的。程序会忽略注释行上的所有内容。在 Visual C# 中,通过在开头键入两个正斜杠 (//) 来注释一行;在 Visual Basic 中,通过以单引号 (') 开头来注释一行。

为其他按钮和复选框编码代码

  • 将以下代码添加到您的 Form1 代码文件(Form1.cs 或 Form1.vb)。选择**“VB”**选项卡以查看 Visual Basic 代码。

    Private Sub clearButton_Click() Handles clearButton.Click
        ' Clear the picture.
        PictureBox1.Image = Nothing 
    End Sub 
    
    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 
    
    Private Sub closeButton_Click() Handles closeButton.Click
        ' Close the form.
        Close()
    End Sub 
    
    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
    
    private void clearButton_Click(object sender, EventArgs e)
    {
        // Clear the picture.
        pictureBox1.Image = null;
    }
    
    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 void closeButton_Click(object sender, EventArgs e)
    {
        // Close the form. 
        this.Close();
    }
    
    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;
    }
    

继续或查看