- Controls to Use on Windows Forms
- In This Section
- Related Sections
- Программное добавление элементов управления в Windows Forms во время выполнения с помощью Visual C#
- Сводка
- Требования
- Создание приложения Windows Forms
- Настройка свойств формы и элемента управления
- Добавление элементов управления в форму
- Проверка работы
- Ссылки
- Menu Класс
- Определение
- Примеры
- Комментарии
- Конструкторы
- Свойства
- Методы
- События
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.
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.
Related Sections
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 во время выполнения с помощью Visual C#
Эта статья поможет программным способом добавлять и настраивать элементы управления в форме Windows Forms с помощью Visual C#.
Исходная версия продукта: Visual C #
Исходный номер статьи базы знаний: 319266
Сводка
В этой статье приведены пошаговые инструкции по добавлению и настройке нескольких часто используемых элементов управления в форме Windows Forms. В примере кода отсутствует обработка событий.
Пакет средств разработки программного обеспечения (SDK) Microsoft .NET Framework предоставляет множество визуальных элементов управления, которые можно использовать для создания приложения Windows Forms. Вы можете добавлять и настраивать элементы управления во время конструирования в Visual Studio .NET или в Visual Studio. Вы можете добавлять и настраивать элементы управления программным способом во время выполнения.
Требования
В этой статье предполагается, что вы знакомы со следующими разделами:
- Синтаксис Visual C#
- Среда Visual Studio .NET, среда Visual Studio
- Назначение распространенных элементов управления Visual C#
Создание приложения Windows Forms
Запустите Visual Studio .NET или Visual Studio и создайте новый проект приложения Visual C# для Windows с именем винконтролс. По умолчанию форма Form1 добавляется в проект.
Дважды щелкните Form1, чтобы создать и просмотреть Form1_Load процедуру обработки события.
Добавьте в класс переменные частных экземпляров Form1 для работы с общими элементами управления Windows. Form1 Класс запускается следующим образом:
Код должен быть изменен в Visual Studio. Когда вы создаете проект Windows Forms, Visual C# добавляет по умолчанию одну форму в проект. Эта форма называется Form1. Два файла, представляющие форму, называются Form1.CS и Form1.Designer.CS. Вы пишете свой код в Form1.CS. Файл Designer.CS — это место, в котором конструктор Windows Forms записывает код, который реализует все действия, выполненные путем добавления элементов управления. Дополнительные сведения о конструкторе Windows Forms в Visual C# приведены в статье Создание проекта (Visual c#).
Настройка свойств формы и элемента управления
Нахождение Form1_Load процедуры обработки события и добавление в процедуру следующего кода для настройки внешнего вида элемента управления формы:
Добавьте следующий код в Form1_Load процедуру обработки события для настройки внешнего вида элемента управления «Кнопка»:
Добавьте следующий код для настройки внешнего вида элемента управления TextBox в Form1_Load :
Добавьте следующий код для настройки внешнего вида элемента управления ListBox в Form1_Load :
Добавьте следующий код, чтобы настроить внешний вид элемента управления CheckBox в Form1_Load :
Добавьте следующий код, чтобы настроить внешний вид элемента управления Label в Form1_Load :
Добавление элементов управления в форму
Добавьте следующий код, чтобы добавить каждый объект в Controls массив формы в конце Form1_Load :
Проверка работы
Чтобы убедиться, что пример работает, выберите команду начать в меню Отладка .
- Хотя отображаются форма и элементы управления, в настоящее время они не выполняют никаких действий, так как вы не записали обработчики событий.
- Помните, что позиции этих элементов управления являются статическими. Чтобы сделать их более надежными при растяжении формы, сделайте точки динамическими относительно положения формы. Если элементы управления статичны, растягивание формы может помешать отображению других элементов управления в форме.
Ссылки
Дополнительные сведения об использовании элементов управления программным способом можно найти в разделе приложения Windows в разделе Visual C# справочной документации по Visual Studio .NET Online или в справочной документации по Visual Studio Online.
Menu Класс
Определение
Представляет базовые возможности всех меню. Represents the base functionality for all menus.
Этот класс недоступен в .NET Core 3.1 и более поздних версиях. This class is not available in .NET Core 3.1 and later versions. Вместо него следует использовать ToolStripDropDown и ToolStripDropDownMenu, которые заменяют и расширяют элемент управления Menu. Use ToolStripDropDown and ToolStripDropDownMenu instead, which replace and extend the Menu control.
Примеры
В следующем примере кода производный класс используется MenuItem для создания структуры меню для формы. The following code example uses the derived class, MenuItem, to create a menu structure for a form. В примере кода добавляется MenuItem для представления пункта меню верхнего уровня, добавляется к нему элемент подменю для выбора размера шрифта, а затем в этот пункт меню добавляются два элемента подменю, представляющие крупные и малые шрифты в приложении. The example code adds a MenuItem to represent the top-level menu item, adds a submenu item to it for selecting a font size, and then adds two submenu items to that menu item that represent large and small font choices in an application. В этом примере требуется наличие MainMenu объекта с именем mainMenu1 и четырех MenuItem объектов с именами menuItem1 , menuItem2 , menuItem3 и menuItem4 . The example requires that there is a MainMenu object named mainMenu1 and four MenuItem objects named menuItem1 , menuItem2 , menuItem3 , and menuItem4 .
Комментарии
Этот класс недоступен в .NET Core 3.1 и более поздних версиях. This class is not available in .NET Core 3.1 and later versions. Взамен используйте и . Use and instead.
Этот класс является базовым классом для MainMenu MenuItem классов, и ContextMenu . This class is the base class for the MainMenu, MenuItem, and ContextMenu classes. Нельзя создать экземпляр этого класса. You cannot create an instance of this class. Меню приложения состоит из MenuItem объектов. The menus for an application consist of MenuItem objects. Они могут содержать другие MenuItem объекты, представляющие элементы подменю. These can contain other MenuItem objects, representing submenu items. MenuItemОбъекты могут храниться в MainMenu для вывода в виде всей структуры меню формы или ContextMenu , которая используется для вывода контекстных меню. The MenuItem objects can be stored in a MainMenu for display as an entire menu structure for a form or a ContextMenu that is used to display shortcut menus. Этот класс предоставляет функциональные возможности, общие для всех классов меню. This class provides functionality that is common for all the menu classes.
В отличие от многих базовых классов, Menu класс использует производные классы для определения многих его свойств. Unlike many base classes, the Menu class uses its derived classes to define many of its properties. Если вы используете меню в приложении многодокументного интерфейса (MDI), можно использовать MdiListItem свойство, чтобы указать MenuItem , который отображает список открытых дочерних форм MDI в приложении. If you are using your menu in a multiple-document interface (MDI) application, you can use the MdiListItem property to specify a MenuItem that displays a list of open MDI child forms in your application. MenuItemsСвойство содержит список MenuItem объектов, хранящихся в классе меню. The MenuItems property contains a list of MenuItem objects stored in the menu class. Для MainMenu или ContextMenu это свойство содержит все MenuItem отображаемые объекты. For a MainMenu or ContextMenu, this property contains all the MenuItem objects that are displayed. Для MenuItem MenuItems свойство представляет связанные с ним элементы вложенного меню. For a MenuItem, the MenuItems property represents the submenu items associated with it.
Помимо свойств, предоставляемых для всех производных классов меню, Menu класс также предоставляет методы, такие как CloneMenu и MergeMenu , которые позволяют создавать новые меню из существующих меню, а также объединять две структуры меню. In addition to the properties that are provided for all the derived menu classes, the Menu class also provides methods, such as CloneMenu and MergeMenu, that enable you to create new menus from existing menus, and also merge two menu structures together.
MenuКласс также определяет вложенный класс Menu.MenuItemCollection . The Menu class also defines the nested class Menu.MenuItemCollection. Этот класс определяет коллекцию объектов, MenuItem используемых MenuItems свойством. This class defines the collection of MenuItem objects used by the MenuItems property. Методы класса можно использовать Menu.MenuItemCollection для добавления и удаления пунктов меню из MainMenu , ContextMenu или MenuItem . You can use the methods of the Menu.MenuItemCollection class to add and remove menu items from a MainMenu, ContextMenu, or MenuItem.
Конструкторы
Инициализирует новый экземпляр класса Menu. Initializes a new instance of the Menu class.
Указывает, что метод FindMenuItem(Int32, IntPtr) должен выполнять поиск дескриптора. Specifies that the FindMenuItem(Int32, IntPtr) method should search for a handle.
Указывает, что метод FindMenuItem(Int32, IntPtr) должен выполнять поиск ярлыка. Specifies that the FindMenuItem(Int32, IntPtr) method should search for a shortcut.
Свойства
Возвращает значение, показывающее, может ли компонент вызывать событие. Gets a value indicating whether the component can raise an event.
(Унаследовано от Component)
Возвращает объект 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 a value representing the window handle for the menu.
Получает значение, показывающее, содержит ли это меню какие-нибудь элементы меню. Gets a value indicating whether this menu contains any menu items. Это свойство доступно только для чтения. This property is read-only.
Получает значение, указывающее объект MenuItem, используемый для отображения списка дочерних форм многодокументного интерфейса (MDI). Gets a value indicating the MenuItem that is used to display a list of multiple document interface (MDI) child forms.
Получает значение, показывающее коллекцию объектов MenuItem, связанных с данным меню. Gets a value indicating the collection of MenuItem objects associated with the menu.
Возвращает или задает имя таблицы для объекта Menu. Gets or sets the name of the Menu.
Получает или задает ISite объекта Component. Gets or sets the ISite of the Component.
(Унаследовано от Component)
Получает или задает определяемые пользователем данные, связанные с элементом управления. Gets or sets user-defined data associated with the control.
Методы
Копирует объект Menu, передаваемый в качестве параметра в текущий объект Menu. Copies the Menu that is passed as a parameter to the current Menu.
Создает новый дескриптор для объекта Menu. Creates a new handle to the Menu.
Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. 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)
Уничтожает ресурсы (кроме памяти), используемые классом Menu. Disposes of the resources, other than memory, used by the Menu.
Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.
(Унаследовано от Object)
Получает объект MenuItem, содержащий указываемое значение. Gets the MenuItem that contains the value specified.
Возвращает позицию меню, в которую должен быть вставлен элемент меню. Returns the position at which a menu item should be inserted into the menu.
Получает объект ContextMenu, содержащий это меню. Gets the ContextMenu that contains this menu.
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра. Retrieves the current lifetime service object that controls the lifetime policy for this instance.
(Унаследовано от MarshalByRefObject)
Получает объект MainMenu, содержащий это меню. Gets the MainMenu that contains this menu.
Возвращает объект, представляющий службу, предоставляемую классом 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)
Объединяет объекты MenuItem одного меню с текущим меню. Merges the MenuItem objects of one menu with the current menu.
Обрабатывает клавишу для команд. Processes a command key.
Возвращает объект String, который представляет элемент управления Menu. Returns a String that represents the Menu control.
События
Возникает при удалении компонента путем вызова метода Dispose(). Occurs when the component is disposed by a call to the Dispose() method.