- Практическое руководство. Добавление и удаление изображений, выводимых с помощью компонента 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
- 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. Image Collection. Add Метод
- Определение
- Перегрузки
- Add(Icon)
- Параметры
- Исключения
- Примеры
- Комментарии
- Применяется к
- Add(Image)
- Параметры
- Исключения
- Применяется к
- Add(Image, Color)
- Параметры
- Возвращаемое значение
- Исключения
- Практическое руководство. Загрузка изображения с помощью конструктора (Windows Form) How to: Load a Picture Using the Designer (Windows Forms)
- Отображение рисунка во время разработки To display a picture at design time
- Add image to windows form
- Answered by:
- Question
- Answers
Практическое руководство. Добавление и удаление изображений, выводимых с помощью компонента 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.
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.
Image List. Image Collection. Add Метод
Определение
Добавляет указанный объект к объекту ImageList. Adds the specified object to the ImageList.
Перегрузки
Добавляет заданный значок в объект ImageList. Adds the specified icon to the ImageList.
Добавляет указанное изображение в ImageList. Adds the specified image to the ImageList.
Добавляет заданное изображение в 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.
Add(Icon)
Добавляет заданный значок в объект ImageList. Adds the specified icon to the ImageList.
Параметры
Объект Icon, который требуется добавить в список. An Icon to add to the list.
Исключения
value равно null value is null
-или- -or- значение свойства не равно Icon. value is not an Icon.
Примеры
В следующем примере кода демонстрируется создание ImageList , добавление изображений в Images свойство, установка ImageSize Свойства и использование Draw метода. The following code example demonstrates constructing an ImageList, adding images to the Images property, setting the ImageSize property, and using the Draw method. Чтобы выполнить этот пример, поместите его в форму, содержащую кнопку с именем Button1 . To run this example, place it in a form that contains a button named Button1 . В примере предполагается наличие FeatherTexture.bmp и прошедшей Fishing.bmp в c:\Windows \ . The example assumes the existence of FeatherTexture.bmp and Gone Fishing.bmp at c:\Windows\. Измените пример соответствующим образом, если точечные рисунки не существуют в системе или существуют в другом расположении. Change the example accordingly if the bitmaps do not exist on your system or exist at another location.
Комментарии
IconПреобразуется в Bitmap перед добавлением в список. The Icon is converted to a Bitmap before it is added to the list.
Применяется к
Add(Image)
Добавляет указанное изображение в ImageList. Adds the specified image to the ImageList.
Параметры
Объект Bitmap изображения, который требуется добавить в список. A Bitmap of the image to add to the list.
Исключения
Добавляемое изображение является null . The image being added is null .
Добавляемое изображение не является Bitmap. The image being added is not a Bitmap.
Применяется к
Add(Image, Color)
Добавляет заданное изображение в ImageList, используя для создания маски указанный цвет. Adds the specified image to the ImageList, using the specified color to generate the mask.
Параметры
Объект Bitmap изображения, который требуется добавить в список. A Bitmap of the image to add to the list.
Объект Color, используемый в качестве маски для данного изображения. The Color to mask this image.
Возвращаемое значение
Индекс добавляемого изображения или -1, если добавить изображение не удалось. The index of the newly added image, or -1 if the image cannot be added.
Исключения
Добавляемое изображение является null . The image being added is null .
Добавляемое изображение не является Bitmap. The image being added is not a Bitmap.
Практическое руководство. Загрузка изображения с помощью конструктора (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.
Add image to windows form
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
how do i add an image or icon to my winform form ?
Answers
not really, e.g. in a webform you add the image control and then specify the path for the image.
Likewise in the webform, I dont see any image control in the toolbox to add .
Its simply just to make it fancy, nothing more.
Welcome to the MSDN Forum.
Maybe you want to draw the picture without any control, but show it as a background and you don’t want to set the background-Image, than you can do like the following sample:
And you can add a property with set method so that you can change the image.
On the other hand, you can also add the BackgroundImage by using the Visual Studio.
Neddy Ren[MSFT]
MSDN Community Support | Feedback to us