System windows forms imagelist

Практическое руководство. Добавление и удаление изображений, выводимых с помощью компонента ImageList, в Windows Forms How to: Add or Remove Images with the Windows Forms ImageList Component

Windows Forms ImageList компонент обычно заполняется образами, прежде чем он будет связан с элементом управления. The Windows Forms ImageList component is typically populated with images before it is associated with a control. Однако можно добавлять и удалять изображения после связывания списка изображений с элементом управления. However, you can add and remove images after associating the image list with a control.

При удалении образов убедитесь, что ImageIndex свойство всех связанных элементов управления по-прежнему допустимо. When you remove images, verify that the ImageIndex property of any associated controls is still valid.

Добавление образов программным способом To add images programmatically

Используйте Add метод свойства списка изображений Images . Use the Add method of the image list’s Images property.

В следующем примере кода путь, заданный для расположения изображения, является папкой » Мои документы «. In the following code example, the path set for the location of the image is the My Documents folder. Это расположение используется, поскольку можно предположить, что большинство компьютеров, работающих под управлением операционной системы Windows, будут содержать эту папку. This location is used because you can assume that most computers that are running the Windows operating system will include this folder. Выбор этого расположения также позволяет пользователям с минимальными уровнями доступа к системе более безопасно запускать приложение. Choosing this location also lets users who have minimal system access levels more safely run the application. В следующем примере кода требуется форма с ImageList уже добавленным элементом управления. The following code example requires that you have a form with an ImageList control already added.

Для добавления изображений со значением ключа. To add images with a key value.

Используйте один из Add методов свойства списка изображений Images , который принимает значение ключа. Use one of the Add methods of the image list’s Images property that takes a key value.

В следующем примере кода путь, заданный для расположения изображения, является папкой » Мои документы «. In the following code example, the path set for the location of the image is the My Documents folder. Это расположение используется, поскольку можно предположить, что большинство компьютеров, работающих под управлением операционной системы Windows, будут содержать эту папку. This location is used because you can assume that most computers that are running the Windows operating system will include this folder. Выбор этого расположения также позволяет пользователям с минимальными уровнями доступа к системе более безопасно запускать приложение. Choosing this location also lets users who have minimal system access levels more safely run the application. В следующем примере кода требуется форма с ImageList уже добавленным элементом управления. The following code example requires that you have a form with an ImageList control already added.

Читайте также:  Как сделать мультизагрузочную флешку для линукс

Программное удаление всех образов To remove all images programmatically

Использование Remove метода для удаления одного образа Use the Remove method to remove a single image

Используйте Clear метод, чтобы очистить все изображения в списке изображений. Use the Clear method to clear all images in the image list.

Удаление образов по ключу To remove images by key

Используйте RemoveByKey метод, чтобы удалить одно изображение по ключу. Use the RemoveByKey method to remove a single image by its key.

Общие сведения о компоненте ImageList (Windows Forms) ImageList Component Overview (Windows Forms)

Компонент ImageList в Windows Forms используется для хранения изображений, которые затем будут отображаться элементами управления. The Windows Forms ImageList component is used to store images, which can then be displayed by controls. Список изображений позволяет написать код для создания единого согласованного каталога изображений. An image list allows you to write code for a single, consistent catalog of images. Например, можно поворачивать изображения, отображаемые элементом управления Button, просто изменив свойство ImageIndex или ImageKey кнопки. For example, you can rotate images displayed by a Button control simply by changing the button’s ImageIndex or ImageKey property. Кроме того, можно связать один список изображений с несколькими элементами управления. You can also associate the same image list with multiple controls. Например, если вы используете оба элемента управления, ListView и TreeView, для отображения одного списка файлов, при изменении значка файла в списке изображений новый значок будет отображаться в обоих представлениях. For example, if you are using both a ListView control and a TreeView control to display the same list of files, changing a file’s icon in the image list will cause the new icon to appear in both views.

Использование компонента ImageList с элементами управления Using ImageList with Controls

Список изображений можно использовать с любым элементом управления, который имеет свойство ImageList (или свойства SmallImageList и LargeImageList, если используется элемент управления ListView). You can use an image list with any control that has an ImageList property — or in the case of the ListView control, SmallImageList and LargeImageList properties. Элементы управления, которые могут быть связаны со списком изображений, включают: ListView, TreeView, ToolBar, TabControl, Button, CheckBox, RadioButton и Label. The controls that can be associated with an image list include: the ListView, TreeView, ToolBar, TabControl, Button, CheckBox, RadioButton, and Label controls. Чтобы связать список изображений с элементом управления, задайте для свойства ImageList элемента управления имя компонента ImageList. To associate the image list with a control, set the control’s ImageList property to the name of the ImageList component.

Ключевые свойства Key Properties

Основным свойством компонента ImageList является Images, которое содержит изображения для использования связанным элементом управления. The key property of the ImageList component is Images, which contains the pictures to be used by the associated control. Доступ к каждому отдельному изображению может осуществляться по значению индекса или ключу. Each individual image can be accessed by its index value or by its key. Свойство ColorDepth определяет количество цветов, которые используются для отрисовки изображений. The ColorDepth property determines the number of colors that the images are rendered with. Размер всех отображаемых изображений будет одинаковым (задается свойством ImageSize). The images will all be displayed at the same size, set by the ImageSize property. Изображения, размер которых больше заданного, масштабируются. Images that are larger will be scaled to fit.

Image List. Image Collection Class

Definition

Encapsulates the collection of Image objects in an ImageList.

Examples

The following code example shows how to select, remove, and display images, from the Images property of the ImageList class, which is an ImageList.ImageCollection type.

Читайте также:  Локальная политика безопасности windows 10 cmd

Remarks

This is used to manage the images in the ImageList programmatically, providing methods to add and remove image objects.

Properties

Gets the number of images currently in the list.

Gets a value indicating whether the ImageList has any images.

Gets a value indicating whether the list is read-only.

Gets or sets an Image at the specified index within the collection.

Gets an Image with the specified key from the collection.

Gets the collection of keys associated with the images in the ImageList.ImageCollection.

Methods

Adds the specified icon to the ImageList.

Adds the specified image to the ImageList.

Adds the specified image to the ImageList, using the specified color to generate the mask.

Adds an icon with the specified key to the end of the collection.

Adds an image with the specified key to the end of the collection.

Adds an array of images to the collection.

Adds an image strip for the specified image to the ImageList.

Removes all the images and masks from the ImageList.

Not supported. The Contains(Object) method indicates whether a specified object is contained in the list.

Determines if the collection contains an image with the specified key.

Determines whether the specified object is equal to the current object.

(Inherited from Object) GetEnumerator()

Returns an enumerator that can be used to iterate through the item collection.

Serves as the default hash function.

(Inherited from Object) GetType()

Gets the Type of the current instance.

(Inherited from Object) IndexOf(Image)

Not supported. The IndexOf(Object) method returns the index of a specified object in the list.

Determines the index of the first occurrence of an image with the specified key in the collection.

Creates a shallow copy of the current Object.

(Inherited from Object) Remove(Image)

Not supported. The Remove(Object) method removes a specified object from the list.

Removes an image from the list.

Removes the image with the specified key from the collection.

Sets the key for an image in the collection.

Returns a string that represents the current object.

(Inherited from Object)

Explicit Interface Implementations

Copies the items in this collection to a compatible one-dimensional array, starting at the specified index of the target array.

Gets a value indicating whether access to the collection is synchronized (thread safe).

Gets an object that can be used to synchronize access to the collection.

Adds the specified image to the ImageList.

This API supports the product infrastructure and is not intended to be used directly from your code.

Implements the Contains(Object) method. Throws a NotSupportedException in all cases.

This API supports the product infrastructure and is not intended to be used directly from your code.

Implements the IndexOf(Object) method. Throws a NotSupportedException in all cases.

Implements the Insert(Int32, Object) method. Throws a NotSupportedException in all cases.

Gets a value indicating whether the ImageList.ImageCollection has a fixed size.

Gets or sets an image in an existing ImageList.ImageCollection.

Implements the Remove(Object). Throws a NotSupportedException in all cases.

Extension Methods

Casts the elements of an IEnumerable to the specified type.

Filters the elements of an IEnumerable based on a specified type.

Image List Class

Definition

Provides methods to manage a collection of Image objects. This class cannot be inherited.

Examples

The following code example shows how to select, remove, and display images.

Remarks

ImageList is typically used by other controls, such as the ListView, TreeView, or ToolBar. You can add bitmaps or icons to the ImageList, and the other controls are able to use the images as they require.

Читайте также:  Обработка команд windows что это

ImageList uses a handle to manage the list of images. The Handle is not created until certain operations, such as getting the Handle or calling Draw, are performed on the image list. Performing other operations, such as setting the ColorDepth or ImageSize will cause the Handle to be recreated. Therefore, you should perform these operations before you add images to the ImageList. In addition, when you work with forms that will be localized, you should always add an ImageList and images when the Language property of a form is set to Default. Changing the form’s language before you add images will corrupt the application resource files.

Constructors

Initializes a new instance of the ImageList class with default values for ColorDepth, ImageSize, and TransparentColor.

Initializes a new instance of the ImageList class, associating it with a container.

Properties

Gets a value indicating whether the component can raise an event.

(Inherited from Component) ColorDepth

Gets the color depth of the image list.

Gets the IContainer that contains the Component.

(Inherited from Component) DesignMode

Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component) Events

Gets the list of event handlers that are attached to this Component.

(Inherited from Component) Handle

Gets the handle of the image list object.

Gets a value indicating whether the underlying Win32 handle has been created.

Gets the ImageList.ImageCollection for this image list.

Gets or sets the size of the images in the image list.

Gets the ImageListStreamer associated with this image list.

Gets or sets the ISite of the Component.

(Inherited from Component) Tag

Gets or sets an object that contains additional data about the ImageList.

Gets or sets the color to treat as transparent.

Methods

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject) Dispose()

Releases all resources used by the Component.

(Inherited from Component) Dispose(Boolean)

Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(Inherited from Component) Draw(Graphics, Int32, Int32, Int32)

Draws the image indicated by the given index on the specified Graphics at the specified location.

Draws the image indicated by the given index on the specified Graphics using the specified location and size.

Draws the image indicated by the specified index on the specified Graphics at the given location.

Determines whether the specified object is equal to the current object.

(Inherited from Object) GetHashCode()

Serves as the default hash function.

(Inherited from Object) GetLifetimeService()

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject) GetService(Type)

Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component) GetType()

Gets the Type of the current instance.

(Inherited from Object) InitializeLifetimeService()

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject) MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object) MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject) ToString()

Returns a string that represents the current ImageList.

Events

Occurs when the component is disposed by a call to the Dispose() method.

Оцените статью