使用 ImageList 组件添加或删除图像 - Windows Forms

2025-07-26 16:51:50
Windows 窗体 ImageList 组件通常在与控件关联之前填充图像。 但是,在将图像列表与控件关联后,可以添加和删除图像。 注释 删除图像时,请验证...

Windows 窗体 ImageList 组件通常在与控件关联之前填充图像。 但是,在将图像列表与控件关联后,可以添加和删除图像。

注释

删除图像时,请验证任何关联控件的 ImageIndex 属性是否仍然有效。

以编程方式添加图像

使用图像列表的 Add 属性的 Images 方法。

在以下代码示例中,为图像位置设置的路径是“我的文档” 文件夹 。 之所以使用此位置,是因为你可以假定运行 Windows 操作系统的大多数计算机将包含此文件夹。 选择此位置还使具有最小系统访问级别的用户能够更安全地运行应用程序。 下面的代码示例要求你已具有一个已添加 ImageList 控件的表单。

Public Sub LoadImage()

Dim myImage As System.Drawing.Image = _

Image.FromFile _

(System.Environment.GetFolderPath _

(System.Environment.SpecialFolder.Personal) _

& "\Image.gif")

ImageList1.Images.Add(myImage)

End Sub

public void addImage()

{

// Be sure that you use an appropriate escape sequence (such as the

// @) when specifying the location of the file.

System.Drawing.Image myImage =

Image.FromFile

(System.Environment.GetFolderPath

(System.Environment.SpecialFolder.Personal)

+ @"\Image.gif");

imageList1.Images.Add(myImage);

}

public:

void addImage()

{

// Replace the bold image in the following sample

// with your own icon.

// Be sure that you use an appropriate escape sequence (such as

// \\) when specifying the location of the file.

System::Drawing::Image ^ myImage =

Image::FromFile(String::Concat(

System::Environment::GetFolderPath(

System::Environment::SpecialFolder::Personal),

"\\Image.gif"));

imageList1->Images->Add(myImage);

}

使用键值添加图像。

使用图像列表采用键值的 Add 属性的 Images 方法之一。

在以下代码示例中,为图像位置设置的路径是“我的文档” 文件夹 。 之所以使用此位置,是因为你可以假定运行 Windows 操作系统的大多数计算机将包含此文件夹。 选择此位置还使具有最小系统访问级别的用户能够更安全地运行应用程序。 下面的代码示例要求你已具有一个已添加 ImageList 控件的表单。

Public Sub LoadImage()

Dim myImage As System.Drawing.Image = _

Image.FromFile _

(System.Environment.GetFolderPath _

(System.Environment.SpecialFolder.Personal) _

& "\Image.gif")

ImageList1.Images.Add("myPhoto", myImage)

End Sub

public void addImage()

{

// Be sure that you use an appropriate escape sequence (such as the

// @) when specifying the location of the file.

System.Drawing.Image myImage =

Image.FromFile

(System.Environment.GetFolderPath

(System.Environment.SpecialFolder.Personal)

+ @"\Image.gif");

imageList1.Images.Add("myPhoto", myImage);

}

以编程方式删除所有图片

使用 Remove 方法删除单个图像

,或

使用 Clear 方法清除图像列表中的所有图像。

' Removes the first image in the image list

ImageList1.Images.Remove(myImage)

' Clears all images in the image list

ImageList1.Images.Clear()

// Removes the first image in the image list.

imageList1.Images.Remove(myImage);

// Clears all images in the image list.

imageList1.Images.Clear();

按键删除图像

使用 RemoveByKey 方法按键删除单个图像。

' Removes the image named "myPhoto" from the list.

ImageList1.Images.RemoveByKey("myPhoto")

// Removes the image named "myPhoto" from the list.

imageList1.Images.RemoveByKey("myPhoto");

另请参阅

ImageList 组件

ImageList 组件概述

图像、位图和图元文件