Share via


HOW TO:在執行階段設定圖片 (Windows Form)

更新:2007 年 11 月

您可以程式設計的方式,設定 Windows Form PictureBox 控制項所顯示的影像。

若要以程式設計的方式設定圖片

  • 使用 Image 類別的 FromFile 方法,設定 Image 屬性。

    在以下範例中,為影像位置所設定的路徑為 [我的文件] 資料夾。這是可以做到的,因為您可假設大部分執行 Windows 作業系統的電腦都會包含這個目錄。這也可讓使用者以最基本的系統存取層級,便可安全執行應用程式。下列範例假設已加入使用 PictureBox 控制項的表單。

    Private Sub LoadNewPict()
       ' You should replace the bold image 
       ' in the sample below with an icon of your own choosing.
       PictureBox1.Image = Image.FromFile _
       (System.Environment.GetFolderPath _
       (System.Environment.SpecialFolder.Personal) _
       & "\Image.gif")
    End Sub
    
    private void LoadNewPict(){
       // You should replace the bold image 
       // in the sample below with an icon of your own choosing.
       // Note the escape character used (@) when specifying the path.
       pictureBox1.Image = Image.FromFile
       (System.Environment.GetFolderPath
       (System.Environment.SpecialFolder.Personal)
       + @"\Image.gif");
    }
    
    private void LoadNewPict(){
       // You should replace the bold image 
       // in the sample below with an icon of your own choosing.
       pictureBox1.get_Image().FromFile
       (System.Environment.GetFolderPath
       (System.Environment.SpecialFolder.Personal)
       + "\\Image.gif");
    
    private:
       void LoadNewPict()
       {
          // You should replace the bold image 
          // in the sample below with an icon of your own choosing.
          pictureBox1->Image = Image::FromFile(String::Concat(
             System::Environment::GetFolderPath(
             System::Environment::SpecialFolder::Personal),
             "\\Image.gif"));
       }
    

若要清除圖形

  • 首先,釋放正由影像使用的記憶體,然後再清除圖形。如果記憶體管理成為問題,則記憶體回收稍後將會釋放記憶體。

    If Not (PictureBox1.Image Is Nothing) Then
       PictureBox1.Image.Dispose()
       PictureBox1.Image = Nothing
    End If
    
    if (pictureBox1.Image != null) 
    {
       pictureBox1.Image.Dispose();
       pictureBox1.Image = null;
    }
    
    if (pictureBox1->Image != nullptr)
    {
       pictureBox1->Image->Dispose();
       pictureBox1->Image = nullptr;
    }
    
    注意事項:

    如需為何要以這種方式使用 Dispose 方法的詳細資訊,請參閱清除 Unmanaged 資源

    即使圖形是在設計階段時載入控制項,此程式碼也會清除影像。

請參閱

工作

HOW TO:使用設計工具載入圖片 (Windows Form)

HOW TO:於執行階段修改圖片的大小或位置 (Windows Form)

參考

PictureBox 控制項概觀 (Windows Form)

PictureBox

Image.FromFile

其他資源

PictureBox 控制項 (Windows Form)