- Практическое руководство. Загрузка изображения с помощью конструктора (Windows Form) How to: Load a Picture Using the Designer (Windows Forms)
- Отображение рисунка во время разработки To display a picture at design time
- Практическое руководство. Добавление и удаление изображений, выводимых с помощью компонента ImageList, в Windows Forms How to: Add or Remove Images with the Windows Forms ImageList Component
- Добавление образов программным способом To add images programmatically
- Для добавления изображений со значением ключа. To add images with a key value.
- Программное удаление всех образов To remove all images programmatically
- Удаление образов по ключу To remove images by key
- Image List Класс
- Определение
- Примеры
- Комментарии
- Конструкторы
- Свойства
- Методы
- События
- How to: Add or Remove Images with the Windows Forms ImageList Component
- To add images programmatically
- To add images with a key value.
- To remove all images programmatically
- To remove images by key
Практическое руководство. Загрузка изображения с помощью конструктора (Windows Form) How to: Load a Picture Using the Designer (Windows Forms)
С помощью PictureBox элемента управления Windows Forms можно загружать и отображать изображение в форме во время разработки, присвоив Image свойству допустимое изображение. With the Windows Forms PictureBox control, you can load and display a picture on a form at design time by setting the Image property to a valid picture. В следующей таблице приведены допустимые типы файлов. The following table shows the acceptable file types.
Тип Type | Расширение имени файла File name extension |
---|---|
Bitmap Bitmap | BMP .bmp |
Значок Icon | ICO .ico |
GIF GIF | .gif .gif |
Метафайл Metafile | . WMF .wmf |
JPEG JPEG | .jpg .jpg |
Отображение рисунка во время разработки To display a picture at design time
Рисование PictureBox элемента управления в форме. Draw a PictureBox control on a form.
В окне Свойства выберите Image свойство, а затем нажмите кнопку с многоточием, чтобы открыть диалоговое окно Открытие . In the Properties window, select the Image property, then select the ellipsis button to display the Open dialog box.
Если вы ищете конкретный тип файла (например, GIF-файлы), выберите его в поле файлы типа . If you’re looking for a specific file type (for example, .gif files), select it in the Files of type box.
Выберите файл, который требуется отобразить. Select the file you want to display.
Практическое руководство. Добавление и удаление изображений, выводимых с помощью компонента 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.
Image List Класс
Определение
Предоставляет методы для управления коллекцией объектов Image. Provides methods to manage a collection of Image objects. Этот класс не наследуется. This class cannot be inherited.
Примеры
В следующем примере кода показано, как выбирать, удалять и отображать изображения. The following code example shows how to select, remove, and display images.
Комментарии
ImageList обычно используется другими элементами управления, такими как ListView , TreeView или ToolBar . ImageList is typically used by other controls, such as the ListView, TreeView, or ToolBar. В можно добавлять растровые изображения или значки ImageList , а другие элементы управления могут использовать изображения по мере необходимости. You can add bitmaps or icons to the ImageList, and the other controls are able to use the images as they require.
ImageList использует маркер для управления списком образов. ImageList uses a handle to manage the list of images. HandleНе создается до тех пор, пока определенные операции, такие как получение Handle или вызов Draw , выполняются в списке изображений. The Handle is not created until certain operations, such as getting the Handle or calling Draw, are performed on the image list. Выполнение других операций, таких как установка ColorDepth или, ImageSize приведет к Handle повторному созданию. Performing other operations, such as setting the ColorDepth or ImageSize will cause the Handle to be recreated. Поэтому перед добавлением образов в необходимо выполнить эти операции ImageList . Therefore, you should perform these operations before you add images to the ImageList. Кроме того, при работе с формами, которые будут локализованы, всегда следует добавлять ImageList изображения и, если для свойства Language формы задано значение по умолчанию. 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.
Конструкторы
Инициализирует новый экземпляр класса ImageList, устанавливая значения по умолчанию для свойств ColorDepth, ImageSize и TransparentColor. Initializes a new instance of the ImageList class with default values for ColorDepth, ImageSize, and TransparentColor.
Инициализирует новый экземпляр класса ImageList, связывая его с контейнером. Initializes a new instance of the ImageList class, associating it with a container.
Свойства
Возвращает значение, показывающее, может ли компонент вызывать событие. Gets a value indicating whether the component can raise an event.
(Унаследовано от Component)
Получает глубину цвета для изображений в списке. Gets the color depth of the image list.
Возвращает объект IContainer, который содержит коллекцию Component. Gets the IContainer that contains the Component.
(Унаследовано от Component)
Возвращает значение, указывающее, находится ли данный компонент Component в режиме конструктора в настоящее время. Gets a value that indicates whether the Component is currently in design mode.
(Унаследовано от Component)
Возвращает список обработчиков событий, которые прикреплены к этому объекту Component. Gets the list of event handlers that are attached to this Component.
(Унаследовано от Component)
Получает дескриптор объекта списка изображений. Gets the handle of the image list object.
Получает значение, показывающее, создан ли основной дескриптор Win32. Gets a value indicating whether the underlying Win32 handle has been created.
Получает ImageList.ImageCollection для данного списка изображений. Gets the ImageList.ImageCollection for this image list.
Получает или задает размер изображений в списке изображений. Gets or sets the size of the images in the image list.
Получает объект ImageListStreamer, связанный с данным списком изображений. Gets the ImageListStreamer associated with this image list.
Получает или задает ISite объекта Component. Gets or sets the ISite of the Component.
(Унаследовано от Component)
Получает или задает объект, содержащий дополнительные данные о списке ImageList. Gets or sets an object that contains additional data about the ImageList.
Получает или задает цвет, обрабатываемый как прозрачный. Gets or sets the color to treat as transparent.
Методы
Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
(Унаследовано от MarshalByRefObject)
Освобождает все ресурсы, занятые модулем Component. Releases all resources used by the Component.
(Унаследовано от Component)
Освобождает неуправляемые ресурсы, используемые объектом Component, а при необходимости освобождает также управляемые ресурсы. Releases the unmanaged resources used by the Component and optionally releases the managed resources.
(Унаследовано от Component)
Рисует в заданном месте изображение согласно индексу, который определен в указанном объекте Graphics. Draws the image indicated by the given index on the specified Graphics at the specified location.
Рисует в заданном месте и с заданным размером изображение согласно индексу, который определен в указанном объекте Graphics. Draws the image indicated by the given index on the specified Graphics using the specified location and size.
Рисует в заданном месте изображение согласно индексу, который определен в указанном объекте Graphics. 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.
(Унаследовано от Object)
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра. Retrieves the current lifetime service object that controls the lifetime policy for this instance.
(Унаследовано от MarshalByRefObject)
Возвращает объект, представляющий службу, предоставляемую классом Component или классом Container. Returns an object that represents a service provided by the Component or by its Container.
(Унаследовано от Component)
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
(Унаследовано от Object)
Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. Obtains a lifetime service object to control the lifetime policy for this instance.
(Унаследовано от MarshalByRefObject)
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
Создает неполную копию текущего объекта MarshalByRefObject. Creates a shallow copy of the current MarshalByRefObject object.
(Унаследовано от MarshalByRefObject)
Возвращает строку, которая представляет текущий объект ImageList. Returns a string that represents the current ImageList.
События
Возникает при удалении компонента путем вызова метода Dispose(). Occurs when the component is disposed by a call to the Dispose() method.
(Унаследовано от Component)
Происходит при повторном создании Handle. Occurs when the Handle is recreated.
How to: Add or Remove Images with the Windows Forms ImageList Component
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.
When you remove images, verify that the ImageIndex property of any associated controls is still valid.
To add images programmatically
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. 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. The following code example requires that you have a form with an ImageList control already added.
To add images with a key value.
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. 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. The following code example requires that you have a form with an ImageList control already added.
To remove all images programmatically
Use the Remove method to remove a single image
Use the Clear method to clear all images in the image list.
To remove images by key
Use the RemoveByKey method to remove a single image by its key.