- Общие сведения о событиях (Windows Forms) Events Overview (Windows Forms)
- Делегаты и их роли Delegates and Their Role
- Порядок событий в формах Windows Forms Order of Events in Windows Forms
- События запуска и завершения работы приложения Application Startup and Shutdown Events
- События, связанные с фокусом и проверками Focus and Validation Events
- Создание обработчиков событий в Windows Forms Creating Event Handlers in Windows Forms
- в этом разделе In This Section
- Связанные разделы Related Sections
- Desktop Guide (Windows Forms .NET)
- Introduction
- Why migrate from .NET Framework
- Build rich, interactive user interfaces
- Create forms and controls
- Display and manipulate data
- Deploy apps to client computers
Общие сведения о событиях (Windows Forms) Events Overview (Windows Forms)
Событие — это действие, требующее реагирования или «обработки» в коде. An event is an action which you can respond to, or «handle,» in code. События могут генерироваться действиями пользователя (например, нажатием кнопки мыши или клавиши на клавиатуре), программным кодом или системой. Events can be generated by a user action, such as clicking the mouse or pressing a key; by program code; or by the system.
Приложения, управляемые событиями, выполняют код в ответ на событие. Event-driven applications execute code in response to an event. Каждая форма и элемент управления имеют предопределенный набор событий, который можно запрограммировать. Each form and control exposes a predefined set of events that you can program against. Если возникает такое событие, а в соответствующем обработчике событий имеется код, этот код выполняется. If one of these events occurs and there is code in the associated event handler, that code is invoked.
Типы порождаемых объектом событий могут варьироваться, но многие их них стандартны для большинства элементов управления. The types of events raised by an object vary, but many types are common to most controls. Например, большинство объектов обработают событие Click. For example, most objects will handle a Click event. Если пользователь откроет форму, в форме сработает код обработчика события Click. If a user clicks a form, code in the form’s Click event handler is executed.
Многие события возникают вместе с другими событиями. Many events occur in conjunction with other events. Например, при возникновении события DoubleClick возникают также события MouseDown, MouseUp и Click. For example, in the course of the DoubleClick event occurring, the MouseDown, MouseUp, and Click events occur.
Сведения о том, как вызывать и использовать событие, см. в разделе события. For information about how to raise and consume an event, see Events.
Делегаты и их роли Delegates and Their Role
Делегаты — это классы, обычно используемые в .NET Framework для создания механизмов обработки событий. Delegates are classes commonly used within the .NET Framework to build event-handling mechanisms. Делегаты приблизительно соответствуют указателям на функции, обычно используемым в Visual C++ и других объектно-ориентированных языках. Delegates roughly equate to function pointers, commonly used in Visual C++ and other object-oriented languages. В отличие от указателей функций делегаты объектно-ориентированы, типобезопасны и безопасны. Unlike function pointers however, delegates are object-oriented, type-safe, and secure. К тому же, если указатель функций содержит только ссылку на определенную функцию, то делегат содержит ссылку на объект и ссылки на один или несколько методов в этом объекте. In addition, where a function pointer contains only a reference to a particular function, a delegate consists of a reference to an object, and references to one or more methods within the object.
Эта модель событий использует делегаты для привязки событий к методам, которые используются для их обработки. This event model uses delegates to bind events to the methods that are used to handle them. Делегаты позволяют другим классам записывать уведомление о событии, определяя метод обработки. The delegate enables other classes to register for event notification by specifying a handler method. При возникновении события делегат вызывает соответствующий метод. When the event occurs, the delegate calls the bound method. Дополнительные сведения об определении делегатов см. в разделе события. For more information about how to define delegates, see Events.
Делегаты можно связать с одним или несколькими методами, создав так называемую многоадресную рассылку. Delegates can be bound to a single method or to multiple methods, referred to as multicasting. При создании делегата для события обычно создается многоадресное событие (или Windows). When creating a delegate for an event, you (or the Windows) typically create a multicast event. Редким исключением является событие, вызывающее выполнение определенной процедуры (например, отображение диалогового окна), которая не будет логически повторяться несколько раз за событие. A rare exception might be an event that results in a specific procedure (such as displaying a dialog box) that would not logically repeat multiple times per event. Сведения о создании делегата многоадресной рассылки см. в разделе Объединение делегатов (многоадресные делегаты). For information about how to create a multicast delegate, see How to combine delegates (Multicast Delegates).
Делегат многоадресной рассылки поддерживает список вызова методов, к которым он привязан. A multicast delegate maintains an invocation list of the methods it is bound to. Делегат многоадресной рассылки поддерживает метод Combine, позволяющий добавить метод в список вызова, и метод Remove, позволяющий его удалить. The multicast delegate supports a Combine method to add a method to the invocation list and a Remove method to remove it.
Когда приложение регистрирует событие, элемент управления порождает это событие, вызывая для него делегат. When an event is recorded by the application, the control raises the event by invoking the delegate for that event. Делегат, в свою очередь, вызывает соответствующий метод. The delegate in turn calls the bound method. В самом распространенном случае (делегат многоадресной рассылки) делегат вызывает каждый метод связки из списка вызова по очереди, что обеспечивает уведомление один-ко-многим. In the most common case (a multicast delegate) the delegate calls each bound method in the invocation list in turn, which provides a one-to-many notification. Данная стратегия означает, что элементу управления не нужно вести список целевых объектов для уведомления о событии, поскольку записью и уведомлением занимается делегат. This strategy means that the control does not need to maintain a list of target objects for event notification—the delegate handles all registration and notification.
Делегаты также позволяют связать с одним методом несколько событий, чтобы использовать уведомление по типу многие-к-одному. Delegates also enable multiple events to be bound to the same method, allowing a many-to-one notification. Например, событие нажатия на кнопку и событие выбора команды в меню вызывают один и тот же делегат, который вызывает один и тот же метод, обрабатывающий эти события одинаковым образом. For example, a button-click event and a menu-command–click event can both invoke the same delegate, which then calls a single method to handle these separate events the same way.
В делегатах используется динамический механизм связки: во время выполнения делегат может быть связан с любым методом, подпись которого совпадает с подписью обработчика событий. The binding mechanism used with delegates is dynamic: a delegate can be bound at run time to any method whose signature matches that of the event handler. С помощью этой функции можно устанавливать или изменять метод связки в зависимости от условий и динамически привязывать обработчик событий к элементу управления. With this feature, you can set up or change the bound method depending on a condition and to dynamically attach an event handler to a control.
Порядок событий в формах Windows Forms Order of Events in Windows Forms
Особый интерес для разработчиков представляет порядок, в котором вызываются события в приложениях Windows Forms, для обеспечения обработки каждого из этих событий в свою очередь. The order in which events are raised in Windows Forms applications is of particular interest to developers concerned with handling each of these events in turn. Если ситуация требует аккуратной обработки событий, например когда производится перерисовка части формы, то необходимо знать точный порядок, в котором вызываются события во время выполнения. When a situation calls for meticulous handling of events, such as when you are redrawing parts of the form, an awareness of the precise order in which events are raised at run time is necessary. В этом разделе приведены некоторые сведения о порядке событий, возникающих на нескольких важных этапах жизненного цикла приложений и элементов управления. This topic provides some details on the order of events during several important stages in the lifetime of applications and controls. Конкретные сведения о порядке событий ввода мыши см. в разделе события мыши в Windows Forms. For specific details about the order of mouse input events, see Mouse Events in Windows Forms. Общие сведения о событиях в Windows Forms см. в разделе Общие сведения о событиях. For an overview of events in Windows Forms, see Events Overview. Дополнительные сведения о описывающего обработчиков событий см. в разделе Общие сведения об обработчиках событий. For details about the makeup of event handlers, see Event Handlers Overview.
События запуска и завершения работы приложения Application Startup and Shutdown Events
Классы Form и Control предоставляют набор событий, связанных с запуском и завершением приложения. The Form and Control classes expose a set of events related to application startup and shutdown. При запуске приложения Windows Forms события запуска главной формы вызываются в следующем порядке: When a Windows Forms application starts, the startup events of the main form are raised in the following order:
При закрытии приложения события запуска главной формы вызываются в следующем порядке: When an application closes, the shutdown events of the main form are raised in the following order:
Событие ApplicationExit класса Application вызывается после событий завершения работы основной формы. The ApplicationExit event of the Application class is raised after the shutdown events of the main form.
В Visual Basic 2005 содержатся дополнительные события приложений, такие как WindowsFormsApplicationBase.Startup и WindowsFormsApplicationBase.Shutdown. Visual Basic 2005 includes additional application events, such as WindowsFormsApplicationBase.Startup and WindowsFormsApplicationBase.Shutdown.
События, связанные с фокусом и проверками Focus and Validation Events
При изменении фокуса с помощью клавиатуры (при нажатии клавиш TAB, SHIFT+TAB и так далее), путем вызова методов Select или SelectNextControl, либо присвоением свойства ActiveControl текущей форме, события фокуса ввода класса Control происходят в следующем порядке: When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ActiveControl property to the current form, focus events of the Control class occur in the following order:
При изменении фокуса ввода с помощью мыши или путем вызова метода Focus события фокуса класса Control происходят в следующем порядке. When you change the focus by using the mouse or by calling the Focus method, focus events of the Control class occur in the following order:
Создание обработчиков событий в Windows Forms Creating Event Handlers in Windows Forms
Обработчик событий — это процедура в коде, определяющая, какие действия должны выполняться при возникновении тех или иных событий, например, если пользователь нажимает кнопку или сообщение поступает в очередь. An event handler is a procedure in your code that determines what actions are performed when an event occurs, such as when the user clicks a button or a message queue receives a message. При порождении события запускается получивший его обработчик или несколько обработчиков. When an event is raised, the event handler or handlers that receive the event are executed. События могут назначаться сразу нескольким обработчикам, а методы, которые управляют конкретными событиями, можно изменять динамически. Events can be assigned to multiple handlers, and the methods that handle particular events can be changed dynamically. Для создания обработчиков событий также можно использовать конструктор Windows Forms в Visual Studio. You can also use the Windows Forms Designer in Visual Studio to create event handlers.
в этом разделе In This Section
Общие сведения о событиях Events Overview
Объясняет модель событий и роли делегатов. Explains the event model and the role of delegates.
Общие сведения об обработчиках событий Event Handlers Overview
Описывает порядок обработки событий. Describes how to handle events.
Практические руководства. Создание обработчиков событий во время выполнения для Windows Forms How to: Create Event Handlers at Run Time for Windows Forms
Динамически выдает инструкции по реагированию на системные или пользовательские события. Gives directions for responding to system or user events dynamically.
Как подключить несколько событий к одному обработчику событий в Windows Forms How to: Connect Multiple Events to a Single Event Handler in Windows Forms
Выдает инструкции по назначению одной и той же функциональности нескольким элементам управления с помощью событий. Gives directions for assigning the same functionality to multiple controls through events.
Порядок событий в Windows Forms Order of Events in Windows Forms
Описывает порядок порождения событий в элементах управления Windows Forms. Describes the order in which events are raised in Windows Forms controls.
Инструкции. Создание обработчиков событий с помощью конструктора Описывает, как использовать конструктор Windows Forms для создания обработчиков событий. How to: Create Event Handlers Using the Designer Describes how to use the Windows Forms Designer to create event handlers.
Связанные разделы Related Sections
Событиях Events
Содержит ссылки на разделы, посвященные обработке и вызову событий с помощью .NET Framework. Provides links to topics on handling and raising events using the .NET Framework.
Устранение неполадок унаследованных обработчиков событий в Visual Basic Troubleshooting Inherited Event Handlers in Visual Basic
Представляет распространенные проблемы, возникающие у обработчиков событий в наследуемых компонентах. Lists common issues that occur with event handlers in inherited components.
Desktop Guide (Windows Forms .NET)
Welcome to the Desktop Guide for Windows Forms, a UI framework that creates rich desktop client apps for Windows. The Windows Forms development platform supports a broad set of app development features, including controls, graphics, data binding, and user input. Windows Forms features a drag-and-drop visual designer in Visual Studio to easily create Windows Forms apps.
The Desktop Guide documentation for .NET 5 (and .NET Core) is under construction.
There are two implementations of Windows Forms:
The open-source implementation hosted on GitHub.
This version runs on .NET 5 and .NET Core 3.1. The Windows Forms Visual Designer requires, at a minimum, Visual Studio 2019 version 16.8 Preview.
The .NET Framework 4 implementation that’s supported by Visual Studio 2019 and Visual Studio 2017.
.NET Framework 4 is a Windows-only version of .NET and is considered a Windows Operating System component. This version of Windows Forms is distributed with .NET Framework.
This Desktop Guide is written for Windows Forms on .NET 5. For more information about the .NET Framework version of Windows Forms, see Windows Forms for .NET Framework.
Introduction
Windows Forms is a UI framework for building Windows desktop apps. It provides one of the most productive ways to create desktop apps based on the visual designer provided in Visual Studio. Functionality such as drag-and-drop placement of visual controls makes it easy to build desktop apps.
With Windows Forms, you develop graphically rich apps that are easy to deploy, update, and work while offline or while connected to the internet. Windows Forms apps can access the local hardware and file system of the computer where the app is running.
Why migrate from .NET Framework
Windows Forms for .NET 5.0 provides new features and enhancements over .NET Framework. For more information, see What’s new in Windows Forms for .NET 5. To learn how to migrate an app, see How to migrate a Windows Forms desktop app to .NET 5.
Build rich, interactive user interfaces
Windows Forms is a UI technology for .NET, a set of managed libraries that simplify common app tasks such as reading and writing to the file system. When you use a development environment like Visual Studio, you can create Windows Forms smart-client apps that display information, request input from users, and communicate with remote computers over a network.
In Windows Forms, a form is a visual surface on which you display information to the user. You ordinarily build Windows Forms apps by adding controls to forms and developing responses to user actions, such as mouse clicks or key presses. A control is a discrete 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 app reacts to these events with code, and processes the events when they occur.
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 webpages. If an existing control doesn’t meet your needs, Windows Forms also supports creating your own custom controls using the UserControl class.
Windows Forms has rich UI controls that emulate features in high-end apps like Microsoft Office. When you use the ToolStrip and MenuStrip controls, you can create toolbars and menus that contain text and images, display submenus, and host other controls such as text boxes and combo boxes.
With the drag-and-drop Windows Forms Designer in Visual Studio, you can easily create Windows Forms apps. Just select the controls with your cursor and place 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. You can use the FlowLayoutPanel, TableLayoutPanel, and SplitContainer controls to create advanced form layouts in less time.
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.
Create forms and controls
For step-by-step information about how to use these features, see the following Help topics.
- How to add a form to a project
- How to add Controls to to a form
Control | [How to: Create a Basic ToolStrip with Standard Items Using the Designer](./controls/create-a-basic-wf-toolstrip-with-standard-items-using-the-designer.md) | | Creating graphics with | [Getting Started with Graphics Programming](./advanced/getting-started-with-graphics-programming.md) | | Creating custom controls | [How to: Inherit from the UserControl Class](./controls/how-to-inherit-from-the-usercontrol-class.md) | —>
Display and manipulate data
Many apps must display data from a database, XML or JSON file, web service, or other data source. 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. 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.
Connecting to data sources over a network is a simple task with Windows Forms. 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. 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 in Visual Studio. 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.
Another type of data binding you can manage in Windows Forms is settings. Most apps 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. 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.
component | [How to: Bind Windows Forms Controls with the BindingSource Component Using the Designer](./controls/bind-wf-controls-with-the-bindingsource.md) | | Working with ADO.NET data sources | [How to: Sort and Filter ADO.NET Data with the Windows Forms BindingSource Component](./controls/sort-and-filter-ado-net-data-with-wf-bindingsource-component.md) | | Using the Data Sources window | [Bind Windows Forms controls to data in Visual Studio](/visualstudio/data-tools/bind-windows-forms-controls-to-data-in-visual-studio) | | Using app settings | [How to: Create Application Settings](./advanced/how-to-create-application-settings.md) | —>
Deploy apps to client computers
After you have written your app, you must send the app to your users so that they can install and run it on their own client computers. When you use the ClickOnce technology, you can deploy your apps from within Visual Studio by using just a few clicks, and provide your users with a URL pointing to your app on the web. ClickOnce manages all the elements and dependencies in your app, and ensures that the app is correctly installed on the client computer.
ClickOnce apps can be configured to run only when the user is connected to the network, or to run both online and offline. When you specify that an app should support offline operation, ClickOnce adds a link to your app in the user’s Start menu. The user can then open the app without using the URL.
When you update your app, you publish a new deployment manifest and a new copy of your app to your web server. ClickOnce will detect that there is an update available and upgrade the user’s installation. No custom programming is required to update old apps.