Common controls windows forms

Controls to Use on Windows Forms

The following is an alphabetic list of controls and components that can be used on Windows Forms. In addition to the Windows Forms controls covered in this section, you can add ActiveX and custom controls to Windows Forms. If you do not find the control you need listed here, you can also create your own. For details, see Developing Windows Forms Controls at Design Time. For more information about choosing the control you need, see Windows Forms Controls by Function.

Visual Basic controls are based on classes provided by the .NET Framework.

In This Section

Windows Forms Controls by Function
Lists and describes Windows Forms controls based on the .NET Framework.

Controls with Built-In Owner-Drawing Support
Describes how to alter aspects of a control’s appearance that are not available through properties.

BackgroundWorker Component
Enables a form or control to run an operation asynchronously.

BindingNavigator Control
Provides the navigation and manipulation user interface (UI) for controls that are bound to data.

BindingSource Component
Encapsulates a data source for binding to controls.

Button Control
Presents a standard button that the user can click to perform actions.

CheckBox Control
Indicates whether a condition is on or off.

CheckedListBox Control
Displays a list of items with a check box next to each item.

ColorDialog Component
Allows the user to select a color from a palette in a pre-configured dialog box and to add custom colors to that palette.

ComboBox Control
Displays data in a drop-down combo box.

ContextMenu Component
Provides users with an easily accessible menu of frequently used commands that are associated with the selected object. Although ContextMenuStrip replaces and adds functionality to the ContextMenu control of previous versions, ContextMenu is retained for both backward compatibility and future use if so desired.

ContextMenuStrip Control
Represents a shortcut menu. Although ContextMenuStrip replaces and adds functionality to the ContextMenu control of previous versions, ContextMenu is retained for both backward compatibility and future use if so desired.

DataGrid Control
Displays tabular data from a dataset and allows for updates to the data source.

DataGridView Control
Provides a flexible, extensible system for displaying and editing tabular data.

DateTimePicker Control
Allows the user to select a single item from a list of dates or times.

Dialog-Box Controls and Components
Describes a set of controls that allow users to perform standard interactions with the application or system.

DomainUpDown Control
Displays text strings that a user can browse through and select from.

ErrorProvider Component
Displays error information to the user in a non-intrusive way.

FileDialog Class Provides base-class functionality for file dialog boxes.

FlowLayoutPanel Control
Represents a panel that dynamically lays out its contents horizontally or vertically.

FolderBrowserDialog Component
Displays an interface with which users can browse and select a directory or create a new one.

FontDialog Component
Exposes the fonts that are currently installed on the system.

GroupBox Control
Provides an identifiable grouping for other controls.

HelpProvider Component
Associates an HTML Help file with a Windows-based application.

HScrollBar and VScrollBar Controls
Provide navigation through a list of items or a large amount of information by scrolling either horizontally or vertically within an application or control.

ImageList Component
Displays images on other controls.

Label Control
Displays text that cannot be edited by the user.

LinkLabel Control
Allows you to add Web-style links to Windows Forms applications.

ListBox Control
Allows the user to select one or more items from a predefined list.

ListView Control
Displays a list of items with icons, in the manner of Windows Explorer.

MainMenu Component
Displays a menu at run time. Although MenuStrip replaces and adds functionality to the MainMenu control of previous versions, MainMenu is retained for both backward compatibility and future use if you choose.

MaskedTextBox Control
Constrains the format of user input in a form.

MenuStrip Control
Provides a menu system for a form. Although MenuStrip replaces and adds functionality to the MainMenu control of previous versions, MainMenu is retained for both backward compatibility and future use if you choose.

MonthCalendar Control
Presents an intuitive graphical interface for users to view and set date information.

NotifyIcon Component
Displays icons for processes that run in the background and would not otherwise have user interfaces.

NumericUpDown Control
Displays numerals that a user can browse through and select from.

OpenFileDialog Component
Allows users to open files by using a pre-configured dialog box.

PageSetupDialog Component
Sets page details for printing through a pre-configured dialog box.

Panel Control
Provide an identifiable grouping for other controls, and allows for scrolling.

PictureBox Control
Displays graphics in bitmap, GIF, JPEG, metafile, or icon format.

Читайте также:  Диспетчер устройств администратор заблокировал выполнение этого приложения windows 10 home

PrintDialog Component
Selects a printer, chooses the pages to print, and determines other print-related settings.

PrintDocument Component
Sets the properties that describe what to print, and prints the document in Windows-based applications.

PrintPreviewControl Control
Allows you to create your own PrintPreview component or dialog box instead of using the pre-configured version.

PrintPreviewDialog Control
Displays a document as it will appear when it is printed.

ProgressBar Control
Graphically indicates the progress of an action towards completion.

RadioButton Control
Presents a set of two or more mutually exclusive options to the user.

RichTextBox Control
Allows users to enter, display, and manipulate text with formatting.

SaveFileDialog Component
Selects files to save and where to save them.

SoundPlayer Class Enables you to easily include sounds in your applications.

SplitContainer Control
Allows the user to resize a docked control.

Splitter Control
Allows the user to resize a docked control (.NET Framework version 1.x).

StatusBar Control
Displays status information related to the control that has focus. Although StatusStrip replaces and extends the StatusBar control of previous versions, StatusBar is retained for both backward compatibility and future use if you choose.

StatusStrip Control
Represents a Windows status bar control. Although StatusStrip replaces and extends the StatusBar control of previous versions, StatusBar is retained for both backward compatibility and future use if you choose.

TabControl Control
Displays multiple tabs that can contain pictures or other controls.

TableLayoutPanel Control
Represents a panel that dynamically lays out its contents in a grid composed of rows and columns.

TextBox Control
Allows editable, multiline input from the user.

Timer Component
Raises an event at regular intervals.

ToolBar Control
Displays menus and bitmapped buttons that activate commands. You can extend the functionality of the control and modify its appearance and behavior. Although ToolStrip replaces and adds functionality to the ToolBar control of previous versions, ToolBar is retained for both backward compatibility and future use if you choose.

ToolStrip Control
Creates custom toolbars and menus in your Windows Forms applications. Although ToolStrip replaces and adds functionality to the ToolBar control of previous versions, ToolBar is retained for both backward compatibility and future use if you choose.

ToolStripContainer Control
Provides panels on each side of a form for docking, rafting, and arranging ToolStrip controls, and a central ToolStripContentPanel for traditional controls.

ToolStripPanel Control
Provides one panel for docking, rafting and arranging ToolStrip controls.

ToolStripProgressBar Control Overview
Graphically indicates the progress of an action towards completion. The ToolStripProgressBar is typically contained in a StatusStrip.

ToolTip Component
Displays text when the user points at other controls.

TrackBar Control
Allows navigation through a large amount of information or visually adjusting a numeric setting.

TreeView Control
Displays a hierarchy of nodes that can be expanded or collapsed.

WebBrowser Control
Hosts Web pages and provides Internet Web browsing capabilities to your application.

Windows Forms Controls Used to List Options
Describes a set of controls used to provide users with a list of options to choose from.

Windows Forms Controls
Explains the use of Windows Forms controls, and describes important concepts for working with them.

Developing Windows Forms Controls at Design Time
Provides links to step-by-step topics, recommendations for which kind of control to create, and other information about creating your own control.

Controls and Programmable Objects Compared in Various Languages and Libraries
Provides a table that maps controls in Visual Basic 6.0 to the corresponding control in Visual Basic .NET. Note that controls are now classes in the .NET Framework.

How to: Add ActiveX Controls to Windows Forms
Describes how to use ActiveX controls on Windows Forms.

Типы пользовательских элементов управления (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.

Читайте также:  Способы завершения работы с приложениями windows
Оцените статью