Icon Класс
Определение
Представляет значок Windows, который является точечным рисунком небольшого размера и используется для представления объекта.Represents a Windows icon, which is a small bitmap image that is used to represent an object. Значки можно считать прозрачными точечными рисунками, хотя их размер определяется системой.Icons can be thought of as transparent bitmaps, although their size is determined by the system.
public ref class Icon sealed : MarshalByRefObject, ICloneable, IDisposable, System::Runtime::Serialization::ISerializable
[System.ComponentModel.TypeConverter(typeof(System.Drawing.IconConverter))]
[System.Runtime.InteropServices.ComVisible(false)]
[System.Serializable]
[System.ComponentModel.TypeConverter("System.Drawing.IconConverter, System.Windows.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")]
public sealed class Icon : MarshalByRefObject, ICloneable, IDisposable, System.Runtime.Serialization.ISerializable
type Icon = class
inherit MarshalByRefObject
interface ISerializable
interface ICloneable
interface IDisposable
Public NotInheritable Class Icon
Inherits MarshalByRefObject
Implements ICloneable, IDisposable, ISerializable
- Наследование
- Атрибуты
- Реализации
Примеры
В следующем примере кода показано, как использовать метод ToBitmap.The following code example demonstrates how to use the ToBitmap method. Этот пример предназначен для использования с Windows Forms.This example is designed to be used with Windows Forms. Создайте форму и вставьте в нее следующий код.Create a form and paste the following code into it. Вызовите IconToBitmap
метод в обработчике Paint событий формы, передав e
его как PaintEventArgs.Call the IconToBitmap
method in the form's Paint event handler, passing e
as PaintEventArgs.
private:
void IconToBitmap( PaintEventArgs^ e )
{
// Construct an Icon.
System::Drawing::Icon^ icon1 = gcnew System::Drawing::Icon( SystemIcons::Exclamation,40,40 );
// Call ToBitmap to convert it.
Bitmap^ bmp = icon1->ToBitmap();
// Draw the bitmap.
e->Graphics->DrawImage( bmp, Point(30,30) );
}
private void IconToBitmap(PaintEventArgs e)
{
// Construct an Icon.
Icon icon1 = new Icon(SystemIcons.Exclamation, 40, 40);
// Call ToBitmap to convert it.
Bitmap bmp = icon1.ToBitmap();
// Draw the bitmap.
e.Graphics.DrawImage(bmp, new Point(30, 30));
}
Private Sub IconToBitmap(ByVal e As PaintEventArgs)
' Construct an Icon.
Dim icon1 As New Icon(SystemIcons.Exclamation, 40, 40)
' Call ToBitmap to convert it.
Dim bmp As Bitmap = icon1.ToBitmap()
' Draw the bitmap.
e.Graphics.DrawImage(bmp, New Point(30, 30))
End Sub
Комментарии
Можно создавать Icon объекты из файлов, потоков или внедренных ресурсов.You can construct Icon objects from files, streams, or embedded resources. Список конструкторов см. в разделе Icon.For a list of constructors, see Icon. Также можно преобразовать Icon в растровое изображение с ToBitmap помощью метода.You can also convert an Icon to a bitmap by using the ToBitmap method.
Ресурс значка может содержать несколько изображений значков.An icon resource can contain multiple icon images. Один файл значка может содержать изображения с несколькими размерами и глубиной цвета.One icon file may contain images in several sizes and color depths. Образ, используемый в приложении, зависит от операционной системы и параметров.The image that is used in an application depends on the operating system and settings. В следующем списке приведены типичные размеры значка.The following list details the typical sizes for an icon:
16 пикселей x 16 пикселей16 pixels x 16 pixels
32 пикселей x 32 пикселей32 pixels x 32 pixels
48 пикселей x 48 пикселей48 pixels x 48 pixels
Конструкторы
Icon(Icon, Int32, Int32) |
Инициализирует новый экземпляр класса Icon и предпринимает попытку поиска версии значка, соответствующей требуемому размеру.Initializes a new instance of the Icon class and attempts to find a version of the icon that matches the requested size. |
Icon(Icon, Size) |
Инициализирует новый экземпляр класса Icon и предпринимает попытку поиска версии значка, соответствующей требуемому размеру.Initializes a new instance of the Icon class and attempts to find a version of the icon that matches the requested size. |
Icon(Stream) |
Инициализирует новый экземпляр класса Icon из указанного потока данных.Initializes a new instance of the Icon class from the specified data stream. |
Icon(Stream, Int32, Int32) |
Инициализирует новый экземпляр класса Icon из указанного потока данных с заданными шириной и высотой.Initializes a new instance of the Icon class from the specified data stream and with the specified width and height. |
Icon(Stream, Size) |
Инициализирует новый экземпляр класса Icon заданного размера из указанного потока данных.Initializes a new instance of the Icon class of the specified size from the specified stream. |
Icon(String) |
Инициализация нового экземпляра класса Icon из указанного имени файла.Initializes a new instance of the Icon class from the specified file name. |
Icon(String, Int32, Int32) |
Инициализирует новый экземпляр класса Icon с заданными шириной и высотой из указанного файла.Initializes a new instance of the Icon class with the specified width and height from the specified file. |
Icon(String, Size) |
Инициализирует новый экземпляр класса Icon заданного размера из указанного файла.Initializes a new instance of the Icon class of the specified size from the specified file. |
Icon(Type, String) |
Инициализирует новый экземпляр класса Icon из ресурса в указанной сборке.Initializes a new instance of the Icon class from a resource in the specified assembly. |
Свойства
Handle |
Получает дескриптор Windows для данного объекта Icon.Gets the Windows handle for this Icon. Данный дескриптор не является копией дескриптора, поэтому освобождать его не следует.This is not a copy of the handle; do not free it. |
Height | |
Size | |
Width |
Методы
Clone() |
Копирует объект Icon, создавая идентичное изображение.Clones the Icon, creating a duplicate image. |
CreateObjRef(Type) |
Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Унаследовано от MarshalByRefObject) |
Dispose() |
Освобождает все ресурсы, используемые этим объектом Icon.Releases all resources used by this Icon. |
Equals(Object) |
Определяет, равен ли указанный объект текущему объекту.Determines whether the specified object is equal to the current object. (Унаследовано от Object) |
ExtractAssociatedIcon(String) |
Возвращает представление изображения, содержащегося в заданном файле, в виде значка.Returns an icon representation of an image that is contained in the specified file. |
Finalize() |
Позволяет объекту попытаться освободить ресурсы и выполнить другие операции очистки, перед тем как он будет уничтожен во время сборки мусора.Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. |
FromHandle(IntPtr) |
Создает объект GDI+ Icon из указанного дескриптора Windows для значка ( |
GetHashCode() |
Служит в качестве хэш-функции по умолчанию.Serves as the default hash function. (Унаследовано от Object) |
GetLifetimeService() |
Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра.Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Унаследовано от MarshalByRefObject) |
GetType() |
Возвращает объект Type для текущего экземпляра.Gets the Type of the current instance. (Унаследовано от Object) |
InitializeLifetimeService() |
Получает объект службы времени существования для управления политикой времени существования для этого экземпляра.Obtains a lifetime service object to control the lifetime policy for this instance. (Унаследовано от MarshalByRefObject) |
MemberwiseClone() |
Создает неполную копию текущего объекта Object.Creates a shallow copy of the current Object. (Унаследовано от Object) |
MemberwiseClone(Boolean) |
Создает неполную копию текущего объекта MarshalByRefObject.Creates a shallow copy of the current MarshalByRefObject object. (Унаследовано от MarshalByRefObject) |
Save(Stream) |
Сохраняет этот объект Icon в заданном потоке вывода Stream.Saves this Icon to the specified output Stream. |
ToBitmap() |
Преобразует этот объект Icon в объект GDI+ Bitmap.Converts this Icon to a GDI+ Bitmap. |
ToString() |
Получает легко читаемую пользователем строку, описывающую объект Icon.Gets a human-readable string that describes the Icon. |
Явные реализации интерфейса
ISerializable.GetObjectData(SerializationInfo, StreamingContext) |
Заполняет объект SerializationInfo данными, необходимыми для сериализации целевого объекта.Populates a SerializationInfo with the data that is required to serialize the target object. |