- Учебник. Создание нового приложения WinForms (Windows Forms .NET) Tutorial: Create a new WinForms app (Windows Forms .NET)
- Предварительные требования Prerequisites
- Создание приложения WinForms Create a WinForms app
- Важные элементы среды Visual Studio Important parts of Visual Studio
- Добавление элементов управления на форму Add controls to the form
- Обработка событий Handle events
- Запустите приложение Run the app
- 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
Учебник. Создание нового приложения WinForms (Windows Forms .NET) Tutorial: Create a new WinForms app (Windows Forms .NET)
Из этого краткого руководства вы узнаете, как создать новое приложение Windows Forms (WinForms) с помощью Visual Studio. In this short tutorial, you’ll learn how to create a new Windows Forms (WinForms) app with Visual Studio. После создания первоначального приложения вы научитесь добавлять элементы управления и обрабатывать события. Once the initial app has been generated, you’ll learn how to add controls and how to handle events. По завершении работы с этим руководством у вас будет простое приложение, добавляющее имена в список. By the end of this tutorial, you’ll have a simple app that adds names to a list box.
Документация для Руководства по рабочему столу по .NET 5 (и .NET Core) находится в разработке. The Desktop Guide documentation for .NET 5 (and .NET Core) is under construction.
В этом руководстве описано следующее: In this tutorial, you learn how to:
- Создание нового приложения WinForms Create a new WinForms app
- Добавление элементов управления на форму Add controls to a form
- Обработка событий элемента управления для предоставления функциональных возможностей приложения Handle control events to provide app functionality
- Запустите приложение Run the app
Предварительные требования Prerequisites
- Visual Studio 2019 версии 16.8 или более поздней Visual Studio 2019 version 16.8 or later versions
- Выберите рабочую нагрузку «Рабочий стол Visual Studio» Select the Visual Studio Desktop workload
- Выберите Отдельные компоненты .NET 5 Select the .NET 5 individual component
Создание приложения WinForms Create a WinForms app
Первым шагом в создании нового приложения является запуск Visual Studio и создание приложения на основе шаблона. The first step to creating a new app is opening Visual Studio and generating the app from a template.
Запустите Visual Studio. Open Visual Studio.
Выберите Создать новый проект. Select Create a new project.
В поле Поиск шаблонов введите winforms и нажмите клавишу ВВОД . In the Search for templates box, type winforms, and then press Enter .
В раскрывающемся списке язык кода выберите C# или Visual Basic. In the code language dropdown, choose C# or Visual Basic.
В списке шаблонов выберите Приложение Windows Forms (.NET) и затем щелкните Далее. In the templates list, select Windows Forms App (.NET) and then click Next.
Не выбирайте шаблон Приложение Windows Forms (.NET Framework) . Don’t select the Windows Forms App (.NET Framework) template.
В окне Настроить новый проект задайте в качестве имени проекта значение Names и щелкните Создать. In the Configure your new project window, set the Project name to Names and click Create.
Вы также можете сохранить проект в другую папку, изменив параметр Расположение. You can also save your project to a different folder by adjusting the Location setting.
После создания приложения Visual Studio должен открыть панель конструктора для формы по умолчанию Form1. Once the app is generated, Visual Studio should open the designer pane for the default form, Form1. Если конструктор форм не отображается, дважды щелкните форму в области Обозреватель решений, чтобы открыть окно конструктора. If the form designer isn’t visible, double-click on the form in the Solution Explorer pane to open the designer window.
Важные элементы среды Visual Studio Important parts of Visual Studio
Поддержка WinForms в Visual Studio состоит из четырех важных компонентов, с которыми вы будете взаимодействовать при создании приложения. Support for WinForms in Visual Studio has four important components that you’ll interact with as you create an app:
обозреватель решений Solution Explorer
Все файлы проекта, код, формы и ресурсы отображаются в этой области. All if your project files, code, forms, resources, will appear in this pane.
Properties (Свойства) Properties
На этой панели отображаются параметры свойств, которые можно настроить в зависимости от выбранного элемента. This pane shows property settings you can configure based on the item selected. Например, если выбрать элемент в Обозревателе решений, отобразятся параметры свойств, связанные с файлом. For example, if you select an item from Solution Explorer, you’ll see property settings related to the file. Если выбрать объект в конструкторе, отобразятся параметры элемента управления или формы. If you select an object in the Designer, you’ll see settings for the control or form.
Конструктор форм Form Designer
Это конструктор для формы. This is the designer for the form. Он является интерактивным, и на него можно перетаскивать объекты из панели элементов. It’s interactive and you can drag-and-drop objects from the Toolbox. Выбирая и перемещая элементы в конструкторе, можно визуально создавать пользовательский интерфейс для приложения. By selecting and moving items in the designer, you can visually compose the user interface (UI) for your app.
Панель элементов Toolbox
Панель элементов содержит все элементы управления, которые можно добавить на форму. The toolbox contains all of the controls you can add to a form. Чтобы добавить элемент управления на текущую форму, дважды щелкните элемент управления или перетащите его. To add a control to the current form, double-click a control or drag-and-drop the control.
Добавление элементов управления на форму Add controls to the form
Открыв конструктор форм Form1, используйте панель Область элементов, чтобы добавить на форму следующие элементы управления: With the Form1 form designer open, use the Toolbox pane to add the following controls to the form:
- Метка Label
- Кнопка Button
- Listbox Listbox
- Текстовое поле Textbox
Вы можете расположить и изменить размер элементов управления в соответствии со следующими настройками. You can position and size the controls according to the following settings. Либо визуально перенесите их, чтобы они соответствовали следующему снимку экрана, либо щелкните каждый элемент управления и настройте параметры в области Свойства. Either visually move them to match the screenshot that follows, or click on each control and configure the settings in the Properties pane. Можно также щелкнуть область заголовка формы, чтобы выбрать форму. You can also click on the form title area to select the form:
Объект Object | Параметр Setting | Значение Value |
---|---|---|
Form Form | Текст Text | Names |
Размер Size | 268, 180 | |
Label Label | Расположение Location | 12, 9 |
Текст Text | Names | |
Listbox Listbox | Имя Name | lstNames |
Расположение Location | 12, 27 | |
Размер Size | 120, 94 | |
текстовое поле; Textbox | Имя Name | txtName |
Расположение Location | 138, 26 | |
Размер Size | 100, 23 | |
Button Button | Имя Name | btnAdd |
Расположение Location | 138, 55 | |
Размер Size | 100, 23 | |
Текст Text | Add Name |
Вы должны получить в конструкторе форму, которая выглядит следующим образом. You should have a form in the designer that looks similar to the following:
Обработка событий Handle events
Теперь, когда в форме есть все элементы управления, необходимо обрабатывать события элементов управления, чтобы реагировать на вводимые пользователем данные. Now that the form has all of its controls laid out, you need to handle the events of the controls to respond to user input. Открыв конструктор форм, выполните следующие действия. With the form designer still open, perform the following steps:
Выберите в форме элемент управления «Кнопка». Select the button control on the form.
В области Свойства щелкните значок события , чтобы вывести список событий кнопки.
Найдите событие Click и дважды щелкните его, чтобы создать обработчик событий. Find the Click event and double-click it to generate an event handler.
Это действие добавляет следующий код в форму: This action adds the following code to the the form:
Код, помещаемый в этот обработчик, будет добавлять имя, заданное элементом управления TextBox txtName , в элемент управления ListBox lstNames . The code we’ll put in this handler will add the name specified by the txtName textbox control to the lstNames listbox control. Однако мы хотим, чтобы имя удовлетворяло двум условиям: указанное имя не должно быть пустым, и его еще не должно быть в списке. However, we want there to be two conditions to adding the name: the name provided must not be blank, and the name must not already exist.
В следующем примере кода показано добавление имени в элемент управления lstNames . The following code demonstrates adding a name to the lstNames control:
Запустите приложение Run the app
Теперь, когда у нас есть код события, можно запустить приложение, нажав клавишу F5 или выбрав пункт меню Отладка > Начать отладку. Now that the event has been coded, you can run the app by pressing the F5 key or by selecting Debug > Start Debugging from the menu. Отобразится форма, и вы можете ввести имя в текстовое поле, а затем добавить его, нажав кнопку. The form displays and you can enter a name in the textbox and then add it by clicking the button.
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.