共用方式為


步驟 10:撰寫其他按鈕和核取方塊的程式碼

現在,您可以準備完成其他四個方法。您可以複製及貼上此程式碼,但如果想要充分學習本教學課程,請輸入程式碼並使用 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;
    }
    

若要繼續或檢視