- Controls to Use on Windows Forms
- In This Section
- Related Sections
- Добавление UserControl В Windows Form
- Windows Forms overview (Общие сведения о Windows Forms) Windows Forms overview
- Windows Forms и интеллектуальные клиентские приложения Windows Forms and smart client apps
- Создание многофункциональных интерактивных пользовательских интерфейсов Build rich, interactive user interfaces
- Создание форм и элементов управления Create forms and controls
- Отображение данных и работа с ними Display and manipulate data
- Отображение данных и работа с ними Display and manipulate data
- Развертывание приложений на клиентских компьютерах Deploy apps to client computers
- Развертывание приложений ClickOnce Deploy ClickOnce apps
- Другие элементы управления и функции Other controls and features
- Реализация других элементов управления и функций Implement other controls and features
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.
Добавление UserControl В Windows Form
Добавление UserControl в Form
Создал UserControl, которую мне надо добавить на форму. Использовал Controls, но я не знаю как при.
Добавление кнопки в всплывающие окно Windows Form
Всем привет.Я в С# не очень, и у меня возникла проблема.Как можно в всплывающие окно, например.
UserControl vs CheckBox or RadioButton Win Form
Помогите в следующем вопросе. Из Json/Xml Извлекаются данные, в виде вопрос и варианты ответа.
Form.Size и UserControl
Доброго времени суток! Ребята вопрос! Есть UserControl (на рис. помечен цифрой 1) Но при.
Тематические курсы и обучение профессиям онлайн Профессия С#-разработчик (Skillbox) Архитектор ПО (Skillbox) Профессия Тестировщик (Skillbox) |
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Передача события (Event) между UserControl и Form
Ситуация такая: Делаю UserControl, из него вызывается форма Form. Вопрос: 1. Как передать в.
Создать win form, используя шаблон windows form в clr, однако такого шаблона на моей студии 2013 нет
есть необходимость создать win form используя шаблон windows form в clr, однако такого шаблона на.
Динамическое добавление UserControl-ов
Всем привет. Мне нужно динамически выводить на экран данные в виде написанных мною UserControl-ов.
Добавление в MainWindow UserControl
Помогите разобраться, как в пустое поле Главного окна программы добавить пользовательский элемент.
Windows Forms overview (Общие сведения о Windows Forms) Windows Forms overview
В этом обзоре рассматриваются преимущества интеллектуальных клиентских приложений, основные возможности программирования Windows Forms, а также использование Windows Forms для разработки интеллектуальных клиентов, удовлетворяющих запросам современных предприятий и конечных пользователей. The following overview discusses the advantages of smart client applications, the main features of Windows Forms programming, and how you can use Windows Forms to build smart clients that meet the needs of today’s enterprises and end users.
Windows Forms и интеллектуальные клиентские приложения Windows Forms and smart client apps
Windows Forms позволяет разрабатывать интеллектуальные клиенты. With Windows Forms you develop smart clients. Интеллектуальный клиент — это приложение с полнофункциональным графическим интерфейсом, простое в развертывании и обновлении, способное работать при наличии или отсутствии подключения к Интернету и использующее более безопасный доступ к ресурсам на локальном компьютере по сравнению с традиционными приложениями Windows. Smart clients are graphically rich applications that are easy to deploy and update, can work when they are connected to or disconnected from the Internet, and can access resources on the local computer in a more secure manner than traditional Windows-based applications.
Создание многофункциональных интерактивных пользовательских интерфейсов Build rich, interactive user interfaces
Windows Forms — это технология интеллектуальных клиентов для NET Framework. Она представляет собой набор управляемых библиотек, упрощающих выполнение стандартных задач, таких как чтение из файловой системы и запись в нее. Windows Forms is a smart client technology for the .NET Framework, a set of managed libraries that simplify common application tasks such as reading and writing to the file system. С помощью такой среды разработки, как Visual Studio, можно создавать интеллектуальные клиентские приложения Windows Forms, которые отображают информацию, запрашивают ввод от пользователей и обмениваются данными с удаленными компьютерами по сети. When you use a development environment like Visual Studio, you can create Windows Forms smart-client applications that display information, request input from users, and communicate with remote computers over a network.
В Windows Forms форма — это визуальная поверхность, на которой отображаются сведения для пользователя. In Windows Forms, a form is a visual surface on which you display information to the user. Обычно приложение Windows Forms строится путем помещения элементов управления на форму и написания кода для реагирования на действия пользователя, такие как щелчки мыши или нажатия клавиш. You ordinarily build Windows Forms applications by adding controls to forms and developing responses to user actions, such as mouse clicks or key presses. Элемент управления — это отдельный элемент пользовательского интерфейса, предназначенный для отображения или ввода данных. A control is a discrete user interface (UI) element that displays data or accepts data input.
При выполнении пользователем какого-либо действия с формой или одним из ее элементов управления создается событие. When a user does something to your form or one of its controls, the action generates an event. Приложение реагирует на эти события с помощью кода и обрабатывает события при их возникновении. Your application reacts to these events by using code, and processes the events when they occur. Подробнее см. в разделе Создание обработчиков событий в Windows Forms. For more information, see Creating Event Handlers in Windows Forms.
Windows Forms включает широкий набор элементов управления, которые можно добавлять на формы: текстовые поля, кнопки, раскрывающиеся списки, переключатели и даже веб-страницы. Windows Forms contains a variety of controls that you can add to forms: controls that display text boxes, buttons, drop-down boxes, radio buttons, and even Web pages. Список всех элементов управления, которые можно использовать в форме, представлены в разделе Элементы управления для использования в формах Windows Forms. For a list of all the controls you can use on a form, see Controls to Use on Windows Forms. Если существующий элемент управления не удовлетворяет потребностям, в Windows Forms можно создать пользовательские элементы управления с помощью класса UserControl. If an existing control does not meet your needs, Windows Forms also supports creating your own custom controls using the UserControl class.
В состав Windows Forms входят многофункциональные элементы пользовательского интерфейса, позволяющие воссоздавать возможности таких сложных приложений, как Microsoft Office. Windows Forms has rich UI controls that emulate features in high-end applications like Microsoft Office. Используя элементы управления ToolStrip и MenuStrip, можно создавать панели инструментов и меню, содержащие текст и рисунки, подменю и другие элементы управления, такие как текстовые поля и поля со списками. When you use the ToolStrip and MenuStrip control, you can create toolbars and menus that contain text and images, display submenus, and host other controls such as text boxes and combo boxes.
С помощью конструктор Windows Forms перетаскивания в Visual Studio можно легко создавать Windows Forms приложения. With the drag-and-drop Windows Forms Designer in Visual Studio, you can easily create Windows Forms applications. Достаточно выделить элемент управления курсором и поместить его в нужное место на форме. Just select the controls with your cursor and add them where you want on the form. Для преодоления трудностей, связанных с выравниванием элементов управления, конструктор предоставляет такие средства, как линии сетки и линии привязки. The designer provides tools such as gridlines and snap lines to take the hassle out of aligning controls. А также при использовании Visual Studio или компиляции из командной строки можно использовать FlowLayoutPanel TableLayoutPanel SplitContainer элементы управления, и для создания расширенных макетов форм за меньшее время. And whether you use Visual Studio or compile at the command line, you can use the FlowLayoutPanel, TableLayoutPanel and SplitContainer controls to create advanced form layouts in less time.
Наконец, если нужно создать свои собственные элементы пользовательского интерфейса, пространство имен System.Drawing содержит широкий набор классов, необходимых для отрисовки линий, кругов и других фигур непосредственно на форме. Finally, if you must create your own custom UI elements, the System.Drawing namespace contains a large selection of classes to render lines, circles, and other shapes directly on a form.
Элементы управления Windows Forms не предназначены для маршалинга между доменами приложений. Windows Forms controls are not designed to be marshaled across application domains. По этой причине технологии Майкрософт не поддерживают передачу элементов управления Windows Forms через границы AppDomain, хотя на первый взгляд базовый тип Control класса MarshalByRefObject подразумевает такую возможность. For this reason, Microsoft does not support passing a Windows Forms control across an AppDomain boundary, even though the Control base type of MarshalByRefObject would seem to indicate that this is possible. Приложения Windows Forms с несколькими доменами приложений поддерживаются только при условии, что элементы управления Windows Forms не передаются через границы доменов приложения. Windows Forms applications that have multiple application domains are supported as long as no Windows Forms controls are passed across application domain boundaries.
Создание форм и элементов управления Create forms and controls
Пошаговые инструкции по использованию этих возможностей можно найти в приведенных ниже разделах справки. For step-by-step information about how to use these features, see the following Help topics.
Описание Description | Раздел справки Help topic |
---|---|
Использование элементов управления в формах Using controls on forms | Практическое руководство. Добавление элементов управления в Windows Forms How to: Add Controls to Windows Forms |
Использование элемента управления ToolStrip Using the ToolStrip Control | Практическое руководство. Создание базового элемента управления ToolStrip со стандартными элементами с помощью конструктора How to: Create a Basic ToolStrip with Standard Items Using the Designer |
Создание графических элементов с помощью System.Drawing Creating graphics with System.Drawing | Приступая к программированию графики Getting Started with Graphics Programming |
Создание пользовательских элементов управления Creating custom controls | Практическое руководство. Наследование класса UserControl How to: Inherit from the UserControl Class |
Отображение данных и работа с ними Display and manipulate data
Во многих приложениях нужно отображать данные из базы данных, XML-файла, веб-службы XML или другого источника данных. Many applications must display data from a database, XML file, XML Web service, or other data source. Windows Forms предоставляет гибкий элемент управления с именем DataGridView для отображения таких табличных данных в традиционном формате строк и столбцов так, что каждый фрагмент данных занимает свою собственную ячейку. Windows Forms provides a flexible control that is named the DataGridView control for displaying such tabular data in a traditional row and column format, so that every piece of data occupies its own cell. С помощью DataGridView можно, помимо прочего, настроить внешний вид отдельных ячеек, зафиксировать строки и столбцы на своем месте, а также обеспечить отображение сложных элементов управления внутри ячеек. When you use DataGridView, you can customize the appearance of individual cells, lock arbitrary rows and columns in place, and display complex controls inside cells, among other features.
При использовании интеллектуальных клиентов Windows Forms можно легко подключаться к источникам данных по сети. Connecting to data sources over a network is a simple task with Windows Forms smart clients. BindingSourceКомпонент представляет соединение с источником данных и предоставляет методы для привязки данных к элементам управления, перехода к предыдущим и следующим записям, изменения записей и сохранения изменений в исходном источнике. The BindingSource component represents a connection to a data source, and exposes methods for binding data to controls, navigating to the previous and next records, editing records, and saving changes back to the original source. Элемент управления BindingNavigator предоставляет простой интерфейс на основе компонента BindingSource для перехода между записями. The BindingNavigator control provides a simple interface over the BindingSource component for users to navigate between records.
Вы можете легко создавать элементы управления с привязкой к данным с помощью окна «Источники данных». You can create data-bound controls easily by using the Data Sources window. В нем приводятся имеющиеся в проекте источники данных, такие как базы данных, веб-службы и объекты. The window displays data sources such as databases, Web services, and objects in your project. Создавать элементы управления с привязкой к данным можно путем перетаскивания объектов из этого окна в формы проекта. You can create data-bound controls by dragging items from this window onto forms in your project. Также можно связывать существующие элементы управления с данными, перетаскивая объекты из окна «Источники данных» в существующие элементы управления. You can also data-bind existing controls to data by dragging objects from the Data Sources window onto existing controls.
Другой тип привязки данных, который можно управлять в Windows Forms — это Параметры. Another type of data binding you can manage in Windows Forms is settings. Большинство интеллектуальных клиентских приложений должны сохранять некоторые сведения о своем состоянии во время выполнения, такие как последние известные размеры форм, а также сохранять пользовательские предпочтения, например место сохранения файлов по умолчанию. Most smart client applications must retain some information about their run-time state, such as the last-known size of forms, and retain user preference data, such as default locations for saved files. Параметры приложения отвечает этим требованиям, предоставляя простой способ хранения обоих типов сведений на клиентском компьютере. The Application Settings feature addresses these requirements by providing an easy way to store both types of settings on the client computer. После определения этих параметров с помощью Visual Studio или редактора кода параметры сохраняются в формате XML и автоматически считываются обратно в память во время выполнения. After you define these settings by using either Visual Studio or a code editor, the settings are persisted as XML and automatically read back into memory at run time.
Отображение данных и работа с ними Display and manipulate data
Пошаговые инструкции по использованию этих возможностей можно найти в приведенных ниже разделах справки. For step-by-step information about how to use these features, see the following Help topics.
Описание Description | Раздел справки Help topic |
---|---|
Использование компонента BindingSource Using the BindingSource component | Практическое руководство. Связывание элементов управления Windows Forms с компонентом BindingSource с помощью конструктора How to: Bind Windows Forms Controls with the BindingSource Component Using the Designer |
Работа с источниками данных ADO.NET Working with ADO.NET data sources | Практическое руководство. Сортировка и фильтрация данных ADO.NET с помощью компонента BindingSource в Windows Forms How to: Sort and Filter ADO.NET Data with the Windows Forms BindingSource Component |
Использование окна «Источники данных» Using the Data Sources window | Привязка элементов управления Windows Forms к данным в Visual Studio Bind Windows Forms controls to data in Visual Studio |
Работа с параметрами приложения Using application settings | Практическое руководство. Создание параметров приложения How to: Create Application Settings |
Развертывание приложений на клиентских компьютерах Deploy apps to client computers
После создания приложения необходимо отправить его пользователям, чтобы они могли установить и запустить его на своих клиентских компьютерах. After you have written your application, you must send the application to your users so that they can install and run it on their own client computers. При использовании технологии ClickOnce можно развертывать приложения в Visual Studio, используя всего несколько щелчков мышью, и предоставить пользователям URL-адрес, указывающий на ваше приложение в Интернете. When you use the ClickOnce technology, you can deploy your applications from within Visual Studio by using just a few clicks, and provide your users with a URL pointing to your application on the Web. Технология ClickOnce управляет всеми элементами и зависимостями в приложении и обеспечивает правильную установку приложения на клиентском компьютере. ClickOnce manages all the elements and dependencies in your application, and ensures that the application is correctly installed on the client computer.
Приложения ClickOnce можно настроить так, чтобы они работали только при подключении к сети или как в сетевом, так и в автономном режиме. ClickOnce applications can be configured to run only when the user is connected to the network, or to run both online and offline. При указании того, что приложение должно поддерживать автономную работу, ClickOnce добавляет ссылку на приложение в меню » Пуск » пользователя. When you specify that an application should support offline operation, ClickOnce adds a link to your application in the user’s Start menu. Пользователь может открыть приложение без использования URL-адреса. The user can then open the application without using the URL.
Когда вы обновляете приложение, на веб-сервере публикуется новый манифест развертывания и новая копия приложения. When you update your application, you publish a new deployment manifest and a new copy of your application to your Web server. ClickOnce обнаружит, что доступно обновление, и обновите установку пользователя. для обновления старых сборок не требуется пользовательское программирование. ClickOnce will detect that there is an update available and upgrade the user’s installation; no custom programming is required to update old assemblies.
Развертывание приложений ClickOnce Deploy ClickOnce apps
Общие сведения о ClickOnce можно найти в разделе Развертывание и безопасность технологии ClickOnce. For a full introduction to ClickOnce, see ClickOnce Security and Deployment. Пошаговые инструкции по использованию этих возможностей можно найти в приведенных ниже разделах справки. For step-by-step information about how to use these features, see the following Help topics,
Описание Description | Раздел справки Help topic |
---|---|
Развертывание приложения с помощью ClickOnce Deploying an application by using ClickOnce | Практическое руководство. Публикация приложения ClickOnce с помощью мастера публикации How to: Publish a ClickOnce Application using the Publish Wizard Пошаговое руководство: Развертывание вручную приложения ClickOnce Walkthrough: Manually Deploying a ClickOnce Application |
Обновление развертывания ClickOnce Updating a ClickOnce deployment | Практическое руководство. Управление обновлениями для ClickOnce-приложения How to: Manage Updates for a ClickOnce Application |
Управление безопасностью с помощью ClickOnce Managing security with ClickOnce | Практическое руководство. Включение параметров безопасности ClickOnce-приложений How to: Enable ClickOnce Security Settings |
Другие элементы управления и функции Other controls and features
В Windows Forms имеется множество других возможностей, которые упрощают и ускоряют реализацию общих задач, таких как создание диалоговых окон, печать, добавление справки и документации, а также локализация приложений на различных языках. There are many other features in Windows Forms that make implementing common tasks fast and easy, such as support for creating dialog boxes, printing, adding Help and documentation, and localizing your application to multiple languages. Кроме того, Windows Forms полагается на надежную систему безопасности .NET Framework. Additionally, Windows Forms relies on the robust security system of the .NET Framework. Благодаря ей можно создавать более надежные приложения. With this system, you can release more secure applications to your customers.
Реализация других элементов управления и функций Implement other controls and features
Пошаговые инструкции по использованию этих возможностей можно найти в приведенных ниже разделах справки. For step-by-step information about how to use these features, see the following Help topics.