Windows forms custom control

Varieties of Custom Controls

With the .NET Framework, you can develop and implement new controls. You can extend the functionality of the familiar user control as well as existing controls through inheritance. You can also write custom controls that perform their own painting.

Deciding which kind of control to create can be confusing. This topic highlights the differences among the various kinds of controls from which you can inherit, and provides you with information about how to choose a particular kind of control for your project.

For information about authoring a control to use on Web Forms, see Developing Custom ASP.NET Server Controls.

Base Control Class

The Control class is the base class for Windows Forms controls. It provides the infrastructure required for visual display in Windows Forms applications.

The Control class performs the following tasks to provide visual display in Windows Forms applications:

Exposes a window handle.

Manages message routing.

Provides mouse and keyboard events, and many other user interface events.

Provides advanced layout features.

Contains many properties specific to visual display, such as ForeColor, BackColor, Height, and Width.

Provides the security and threading support necessary for a Windows Forms control to act as a MicrosoftВ® ActiveXВ® control.

Because so much of the infrastructure is provided by the base class, it is relatively easy to develop your own Windows Forms controls.

Kinds of Controls

Windows Forms supports three kinds of user-defined controls: composite, extended, and custom. The following sections describe each kind of control and give recommendations for choosing the kind to use in your projects.

Composite Controls

A composite control is a collection of Windows Forms controls encapsulated in a common container. This kind of control is sometimes called a user control. The contained controls are called constituent controls.

A composite control holds all of the inherent functionality associated with each of the contained Windows Forms controls and enables you to selectively expose and bind their properties. A composite control also provides a great deal of default keyboard handling functionality with no extra development effort on your part.

For example, a composite control could be built to display customer address data from a database. This control could include a DataGridView control to display the database fields, a BindingSource to handle binding to a data source, and a BindingNavigator control to move through the records. You could selectively expose data binding properties, and you could package and reuse the entire control from application to application. For an example of this kind of composite control, see How to: Apply Attributes in Windows Forms Controls.

To author a composite control, derive from the UserControl class. The UserControl base class provides keyboard routing for child controls and enables child controls to work as a group. For more information, see Developing a Composite Windows Forms Control.

Recommendation

Inherit from the UserControl class if:

  • You want to combine the functionality of several Windows Forms controls into a single reusable unit.

Extended Controls

You can derive an inherited control from any existing Windows Forms control. With this approach, you can retain all of the inherent functionality of a Windows Forms control, and then extend that functionality by adding custom properties, methods, or other features. With this option, you can override the base control’s paint logic, and then extend its user interface by changing its appearance.

For example, you can create a control derived from the Button control that tracks how many times a user has clicked it.

In some controls, you can also add a custom appearance to the graphical user interface of your control by overriding the OnPaint method of the base class. For an extended button that tracks clicks, you can override the OnPaint method to call the base implementation of OnPaint, and then draw the click count in one corner of the Button control’s client area.

Recommendation

Inherit from a Windows Forms control if:

Most of the functionality you need is already identical to an existing Windows Forms control.

You do not need a custom graphical user interface, or you want to design a new graphical user interface for an existing control.

Читайте также:  Как поменять номер сети windows 10

Custom Controls

Another way to create a control is to create one substantially from the beginning by inheriting from Control. The Control class provides all of the basic functionality required by controls, including mouse and keyboard handling events, but no control-specific functionality or graphical interface.

Creating a control by inheriting from the Control class requires much more thought and effort than inheriting from UserControl or an existing Windows Forms control. Because a great deal of implementation is left for you, your control can have greater flexibility than a composite or extended control, and you can tailor your control to suit your exact needs.

To implement a custom control, you must write code for the OnPaint event of the control, as well as any feature-specific code you need. You can also override the WndProc method and handle windows messages directly. This is the most powerful way to create a control, but to use this technique effectively, you need to be familiar with the Microsoft Win32В® API.

An example of a custom control is a clock control that duplicates the appearance and behavior of an analog clock. Custom painting is invoked to cause the hands of the clock to move in response to Tick events from an internal Timer component. For more information, see How to: Develop a Simple Windows Forms Control.

Recommendation

Inherit from the Control class if:

You want to provide a custom graphical representation of your control.

You need to implement custom functionality that is not available through standard controls.

ActiveX Controls

Although the Windows Forms infrastructure has been optimized to host Windows Forms controls, you can still use ActiveX controls. There is support for this task in Visual Studio. For more information, see How to: Add ActiveX Controls to Windows Forms.

Windowless Controls

The Microsoft Visual BasicВ® 6.0and ActiveX technologies support windowless controls. Windowless controls are not supported in Windows Forms.

Custom Design Experience

If you need to implement a custom design-time experience, you can author your own designer. For composite controls, derive your custom designer class from the ParentControlDesigner or the DocumentDesigner classes. For extended and custom controls, derive your custom designer class from the ControlDesigner class.

Типы пользовательских элементов управления (Windows Forms .NET) Types of custom controls (Windows Forms .NET)

С помощью Windows Forms можно разрабатывать и реализовывать новые элементы управления. With Windows Forms, you can develop and implement new controls. Можно создать новый пользовательский элемент управления, изменить существующие элементы управления с помощью наследования, а также написать пользовательский элемент управления, который выполняет собственное рисование. You can create a new user control, modify existing controls through inheritance, and write a custom control that does its own painting.

Документация для Руководства по рабочему столу по .NET 5 (и .NET Core) находится в разработке. The Desktop Guide documentation for .NET 5 (and .NET Core) is under construction.

Выбор типа создаваемого элемента управления может быть затруднителен. Deciding which kind of control to create can be confusing. В этой статье описываются различия между типами элементов управления, которые можно использовать для наследования, и рассказывается, как выбрать тип элемента управления для конкретного проекта. This article highlights the differences among the various kinds of controls from which you can inherit, and provides you with information about how to choose a particular type of control for your project.

Если. If . Создайте. Create a .
  • — если нужно объединить функциональные возможности нескольких элементов управления Windows Forms в один блок для повторного использования. You want to combine the functionality of several Windows Forms controls into a single reusable unit.
Составной элемент управления путем наследования от System.Windows.Forms.UserControl. Composite control by inheriting from System.Windows.Forms.UserControl.
  • — если большинство необходимых функций аналогичны функциям уже существующего элемента управления Windows Forms; Most of the functionality you need is already identical to an existing Windows Forms control.
  • — если нестандартный графический интерфейс не требуется или необходимо разработать новый интерфейс для существующего элемента управления. You don’t need a custom graphical user interface, or you want to design a new graphical user interface for an existing control.
Расширенный элемент управления путем наследования от конкретного элемента управления Windows Forms. Extended control by inheriting from a specific Windows Forms control.
  • — если требуется создать пользовательское графическое представление элемента управления; You want to provide a custom graphical representation of your control.
  • — если требуется реализовать пользовательские функциональные возможности, которые недоступны в стандартных элементах управления. You need to implement custom functionality that isn’t available through standard controls.
Пользовательский элемент управления путем наследования от System.Windows.Forms.Control. Custom control by inheriting from System.Windows.Forms.Control.

Базовый класс элемента управления Base Control Class

Класс Control является базовым классом для элементов управления Windows Forms. The Control class is the base class for Windows Forms controls. Он обеспечивает инфраструктуру, необходимую для визуального отображения элементов управления в приложениях Windows Forms и предоставляет следующие возможности. It provides the infrastructure required for visual display in Windows Forms applications and provides the following capabilities:

  • Обеспечивает обработку окон. Exposes a window handle.
  • Управляет маршрутизацией сообщений. Manages message routing.
  • Предоставляет события мыши и клавиатуры, а также многие другие события пользовательского интерфейса. Provides mouse and keyboard events, and many other user interface events.
  • Предоставляет расширенные функции размещения. Provides advanced layout features.
  • Содержит множество свойств, характерных для визуального отображения, таких как ForeColor, BackColor, Height и Width. Contains many properties specific to visual display, such as ForeColor, BackColor, Height, and Width.
  • Обеспечивает безопасность и поддержку потоков, необходимые для того, чтобы элемент управления Windows Forms действовал как элемент управления Microsoft® ActiveX®. Provides the security and threading support necessary for a Windows Forms control to act as a Microsoft® ActiveX® control.

Поскольку существенная часть инфраструктуры предоставляется базовым классом, разрабатывать собственные элементы управления Windows Forms довольно просто. Because so much of the infrastructure is provided by the base class, it’s relatively easy to develop your own Windows Forms controls.

Составные элементы управления Composite Controls

Составной элемент управления — это коллекция элементов управления Windows Forms, инкапсулированных в общий контейнер. A composite control is a collection of Windows Forms controls encapsulated in a common container. Этот тип элементов управления иногда называют пользовательским элементом управления. This kind of control is sometimes called a user control. Элементы, входящие в составной элемент управления, называются составляющими. The contained controls are called constituent controls.

Составной элементе управления содержит все унаследованные функциональные возможности, связанные с каждым входящим в него элементом управления Windows Forms, и позволяет выборочно представлять и связывать их свойства. A composite control holds all of the inherent functionality associated with each of the contained Windows Forms controls and enables you to selectively expose and bind their properties. Кроме того, составной элемент управления предоставляет немало функций для обработки событий клавиатуры по умолчанию, не требуя дополнительной разработки с вашей стороны. A composite control also provides a great deal of default keyboard handling functionality with no extra development effort on your part.

Например, составной элемент управления можно собрать таким образом, чтобы он отображал данные адреса клиента из базы данных. For example, a composite control could be built to display customer address data from a database. Этот элемент управления включает элемент управления DataGridView для отображения полей базы данных, BindingSource для управления привязкой к источнику данных, а также BindingNavigator для перемещения по записям. This control would include a DataGridView control to display the database fields, a BindingSource to handle binding to a data source, and a BindingNavigator control to move through the records. Вы можете выборочно предоставить свойства привязки данных, а также упаковать и повторно использовать весь элемент управления в других приложениях. You could selectively expose data binding properties, and you could package and reuse the entire control from application to application.

Для создания составного элемента следует выполнить наследование от класса UserControl. To author a composite control, derive from the UserControl class. Базовый класс UserControl обеспечивает маршрутизацию клавиатуры для дочерних элементов управления и позволяет им работать сообща. The UserControl base class provides keyboard routing for child controls and enables child controls to work as a group.

Расширенные элементы управления Extended Controls

Элемент управления можно унаследовать от любого существующего элемента управления Windows Forms. You can derive an inherited control from any existing Windows Forms control. Такой подход позволяет сохранить все функциональные возможности, унаследованные от элемента управления Windows Forms, и расширить их путем добавления пользовательских свойств, методов или других функций. With this approach, you can keep all of the inherent functionality of a Windows Forms control, and then extend that functionality by adding custom properties, methods, or other features. С помощью этого параметра можно переопределить логику отрисовки базового элемента управления, а затем расширить его пользовательский интерфейс, изменив его внешний вид. With this option, you can override the base control’s paint logic, and then extend its user interface by changing its appearance.

Например, можно создать элемент управления, производный от элемента управления Button, который будет отслеживать, сколько раз пользователь на него нажал. For example, you can create a control derived from the Button control that tracks how many times a user has clicked it.

В некоторых элементах управления к графическому пользовательскому интерфейсу можно добавить пользовательское оформление путем переопределения метода OnPaint базового класса. In some controls, you can also add a custom appearance to the graphical user interface of your control by overriding the OnPaint method of the base class. Для расширенной кнопки, отслеживающей щелчки, можно переопределить метод OnPaint, чтобы вызвать базовую реализацию OnPaint, а затем отобразить число щелчков в одном углу клиентской области элемента управления Button. For an extended button that tracks clicks, you can override the OnPaint method to call the base implementation of OnPaint, and then draw the click count in one corner of the Button control’s client area.

Пользовательские элементы управления Custom Controls

Другим способом разработки элемента управления является создание его практически с нуля путем наследования от класса Control. Another way to create a control is to create one substantially from the beginning by inheriting from Control. Класс Control обеспечивает всю основную функциональность, необходимую элементам управления (включая обработку событий мыши и клавиатуры), однако не имеет функциональных возможностей для отдельных элементов управления и лишен графического интерфейса. The Control class provides all of the basic functionality required by controls, including mouse and keyboard handling events, but no control-specific functionality or graphical interface.

Создание элемента управления путем наследования от класса Control — гораздо более сложная задача, чем наследование от UserControl или существующего элемента управления Windows Forms. Creating a control by inheriting from the Control class requires much more thought and effort than inheriting from UserControl or an existing Windows Forms control. Поскольку значительную часть реализации вы выполняете сами, ваш элемент управления может быть более гибким, чем составной или расширенный, и вы можете его адаптировать к конкретным задачам. Because a great deal of implementation is left for you, your control can have greater flexibility than a composite or extended control, and you can tailor your control to suit your exact needs.

Для реализации настраиваемого элемента управления необходимо написать код для события OnPaint элемента управления, а также код для нужных вам функций. To implement a custom control, you must write code for the OnPaint event of the control, as well as any feature-specific code you need. Можно также переопределить метод WndProc и обрабатывать сообщения Windows напрямую. You can also override the WndProc method and handle windows messages directly. Это самый эффективный способ создания элементов управления, однако для того, чтобы использовать его эффективно, необходимо знание API Microsoft Win32®. This is the most powerful way to create a control, but to use this technique effectively, you need to be familiar with the Microsoft Win32® API.

Примером нестандартного элемента управления служит элемент управления «Часы», который выглядит и действует как часы со стрелками. An example of a custom control is a clock control that duplicates the appearance and behavior of an analog clock. Вы можете применить пользовательское оформление, чтобы заставить стрелки часов двигаться при наступлении событий Tick внутреннего компонента Timer. Custom painting is invoked to cause the hands of the clock to move in response to Tick events from an internal Timer component.

Элементы управления ActiveX ActiveX Controls

Несмотря на то что инфраструктура Windows Forms оптимизирована для размещения элементов управления Windows Forms, элементы управления ActiveX также можно использовать. Although the Windows Forms infrastructure has been optimized to host Windows Forms controls, you can still use ActiveX controls. Эта задача поддерживается в Visual Studio. There’s support for this task in Visual Studio.

Элементы управления без окон Windowless Controls

Технологии Microsoft Visual Basic® 6.0 и ActiveX поддерживают элементы управления без окон. The Microsoft Visual Basic® 6.0 and ActiveX technologies support windowless controls. В Windows Forms элементы управления без окон не поддерживаются. Windowless controls aren’t supported in Windows Forms.

Пользовательская среда разработки Custom Design Experience

Если вам требуется пользовательская среда разработки, вы можете создать свой собственный конструктор. If you need to implement a custom design-time experience, you can author your own designer. Для составных элементов управления следует наследовать класс пользовательского конструктора от классов ParentControlDesigner или DocumentDesigner. For composite controls, derive your custom designer class from the ParentControlDesigner or the DocumentDesigner classes. Для расширенных и настраиваемых элементов управления создайте класс пользовательского конструктора из класса ControlDesigner. For extended and custom controls, derive your custom designer class from the ControlDesigner class.

Используйте DesignerAttribute, чтобы связать элемент управления с конструктором. Use the DesignerAttribute to associate your control with your designer.

Следующие сведения устарели, но могут помочь вам. The following information is out of date but may help you.

Читайте также:  Как удалить переменную среды linux
Оцените статью