- Обзор конструктора Windows Forms Windows Forms Designer overview
- функциональное назначение; Functionality
- Step 1: Create a Windows Forms App project
- Open Visual Studio 2017
- Open Visual Studio 2019
- About the Windows Forms App project
- Next steps
- Шаг 1. Создание проекта приложения Windows Forms Step 1: Create a Windows Forms App project
- Откройте Visual Studio 2017. Open Visual Studio 2017
- Запустите Visual Studio 2019. Open Visual Studio 2019
- Сведения о проекте приложения Windows Forms About the Windows Forms App project
- Дальнейшие действия Next steps
Обзор конструктора Windows Forms Windows Forms Designer overview
Конструктор Windows Forms в Visual Studio — это решение для быстрого создания приложений на основе Windows Forms. Windows Forms Designer in Visual Studio provides a rapid development solution for creating Windows Forms-based applications. Конструктор Windows Forms позволяет легко добавлять элементы управления в форму, упорядочивать их и писать код для их событий. Windows Forms Designer lets you easily add controls to a form, arrange them, and write code for their events. Дополнительные сведения о Windows Forms см. в обзорной статье об этом решении. For more information about Windows Forms, see Windows Forms overview.
функциональное назначение; Functionality
Конструктор позволяет выполнять такие задачи: Using the designer you can:
Добавлять в форму компоненты, элементы управления данными или элементы управления для Windows. Add components, data controls, or Windows-based controls to a form.
Дважды щелкнув форму в конструкторе, создавать код в событии Load этой формы или, дважды щелкнув элемент управления в форме, создавать код для события по умолчанию этого элемента управления. Double-click the form in the designer and write code in the Load event for that form, or double-click a control on the form and write code for the control’s default event.
Изменять свойство Text элемента управления, выбрав элемент управления и введя имя. Edit a control’s Text property by selecting the control and typing a name.
Изменять положение выбранного элемента управления, перемещая его с помощью мыши или клавиш со стрелками. Adjust the placement of the selected control by moving it with the mouse or the arrow keys. Таким же образом задавать точное положение элемента с помощью клавиши CTRL и клавиш со стрелками. Similarly, adjust the placement more precisely using the Ctrl and arrow keys. Наконец, изменять размер элемента управления с помощью клавиши SHIFT и клавиш со стрелками. Finally, adjust the size of the control by using the Shift and arrow keys.
Одновременно выбирать несколько элементов управления, нажимая клавишу SHIFT или CTRL при щелчке. Select multiple controls by selecting either Shift or Ctrl while you click. Если использовать клавишу SHIFT в сочетании со щелчком, первый выбранный элемент управления становится главным при выравнивании или изменении размера. When using sing Shift+click, the first control selected is the dominant control when aligning or manipulating size. Если использовать клавишу CTRL в сочетании со щелчком, главным становится последний выбранный элемент, поэтому главный элемент управления меняется при добавлении нового элемента. When using Ctrl+click, the last control selected is dominant, so the dominant control changes with every new control added. Кроме того, можно выбрать несколько элементов управления, очертив требуемые элементы управления прямоугольником выделения. Alternatively, you can select multiple controls by dragging a selection rectangle around the controls that you want to select.
Для внесения изменений в файл ресурсов формы (RESX) используйте конструктор Windows Forms, а не редактор ресурсов. Use Windows Forms Designer, and not the Resource Editor, to make changes to a form’s resource (.resx) file. При редактировании файла RESX, связанного с формой, отображается предупреждение о том, что изменения, внесенные в редакторе ресурсов, могут быть потеряны. If you edit a form-based .resx file, you’ll see a warning that changes you make in the Resource Editor may be lost. Это происходит потому, что конструктор Windows Forms создает файл RESX. This is because the Windows Forms Designer generates the .resx file.
Step 1: Create a Windows Forms App project
When you create a picture viewer, the first step is to create a Windows Forms App project.
Open Visual Studio 2017
On the menu bar, choose File > New > Project. The dialog box should look similar to the following screenshot.
New project dialog box
On the left side of the New Project dialog box, choose either Visual C# or Visual Basic, and then choose Windows Desktop.
In the project templates list, choose Windows Forms App (.NET Framework). Name the new form PictureViewer, and then choose the OK button.
If you don’t see the Windows Forms App (.NET Framework) template, use the Visual Studio Installer to install the .NET desktop development workload.
For more information, see the Install Visual Studio page.
Open Visual Studio 2019
On the start window, choose Create a new project.
On the Create a new project window, enter or type Windows Forms in the search box. Next, choose Desktop from the Project type list.
After you apply the Project type filter, choose the Windows Forms App (.NET Framework) template for either C# or Visual Basic, and then choose Next.
If you don’t see the Windows Forms App (.NET Framework) template, you can install it from the Create a new project window. In the Not finding what you’re looking for? message, choose the Install more tools and features link.
Next, in the Visual Studio Installer, choose the Choose the .NET desktop development workload.
After that, choose the Modify button in the Visual Studio Installer. You might be prompted to save your work; if so, do so. Next, choose Continue to install the workload.
In the Configure your new project window, type or enter PictureViewer in the Project name box. Then, choose Create.
Visual Studio creates a solution for your app. A solution acts as a container for all of the projects and files needed by your app. These terms will be explained in more detail later in this tutorial.
About the Windows Forms App project
The development environment contains three windows: a main window, Solution Explorer, and the Properties window.
If any of these windows are missing, you can restore the default window layout. On the menu bar, choose Window > Reset Window Layout.
You can also display windows by using menu commands. On the menu bar, choose View > Properties Window or Solution Explorer.
If any other windows are open, close them by choosing the Close (x) button in their upper-right corners.
- Main window In this window, you’ll do most of your work, such as working with forms and editing code. The window shows a form in the Form Editor. At the top of the window, the Start Page tab and the Form1.cs [Design] tab appear. (In Visual Basic, the tab name ends with .vb instead of .cs.)
- Main window In this window, you’ll do most of your work, such as working with forms and editing code. The window shows a form in the Form Editor.
- Solution Explorer window In this window, you can view and navigate to all items in your solution.
If you choose a file, the contents of the Properties window changes. If you open a code file (which ends in .cs in C# and .vb in Visual Basic), the code file or a designer for the code file appears. A designer is a visual surface onto which you can add controls such as buttons and lists. For Visual Studio forms, the designer is called the Windows Forms Designer.
Properties window In this window, you can change the properties of items that you choose in the other windows. For example, if you choose Form1, you can change its title by setting the Text property, and you can change the background color by setting the Backcolor property.
The top line in Solution Explorer shows Solution ‘PictureViewer’ (1 project), which means that Visual Studio created a solution for you. A solution can contain more than one project, but for now, you’ll work with solutions that contain only one project.
On the menu bar, choose File > Save All.
As an alternative, choose the Save All button on the toolbar, which the following image shows.
Save All toolbar button
Visual Studio automatically fills in the folder name and the project name and then saves the project in your projects folder.
Next steps
To go to the next tutorial step, see Step 2: Run your app.
To return to the overview topic, see Tutorial 1: Create a picture viewer.
Шаг 1. Создание проекта приложения Windows Forms Step 1: Create a Windows Forms App project
Первый шаг в создании программы для просмотра изображений — это создание проекта приложения Windows Forms. When you create a picture viewer, the first step is to create a Windows Forms App project.
Откройте Visual Studio 2017. Open Visual Studio 2017
В строке меню выберите Файл > Создать > Проект. On the menu bar, choose File > New > Project. Диалоговое окно должно выглядеть так же, как на следующем снимке экрана. The dialog box should look similar to the following screenshot.
Диалоговое окно _ _»Новый проект» New project _ _dialog box
В левой части диалогового окна Новый проект выберите Visual C# или Visual Basic, а затем — Классическое приложение Windows. On the left side of the New Project dialog box, choose either Visual C# or Visual Basic, and then choose Windows Desktop.
В списке шаблонов проектов выберите Приложение Windows Forms (.NET Framework). In the project templates list, choose Windows Forms App (.NET Framework). Назовите новую форму PictureViewer и нажмите кнопку ОК. Name the new form PictureViewer, and then choose the OK button.
Если вы не видите шаблон Приложение Windows Forms (.NET Framework), используйте Visual Studio Installer, чтобы установить рабочую нагрузку Разработка классических приложений .NET. If you don’t see the Windows Forms App (.NET Framework) template, use the Visual Studio Installer to install the .NET desktop development workload.
Дополнительные сведения см. в разделе Установка Visual Studio. For more information, see the Install Visual Studio page.
Запустите Visual Studio 2019. Open Visual Studio 2019
На начальном экране выберите Создать проект. On the start window, choose Create a new project.
В поле поиска окна Создание проекта введите Windows Forms. On the Create a new project window, enter or type Windows Forms in the search box. Затем в списке Тип проекта выберите Рабочий стол. Next, choose Desktop from the Project type list.
Применив фильтр Тип проекта, выберите шаблон Приложение Windows Forms (.NET Framework) для C# или Visual Basic и нажмите кнопку Далее. After you apply the Project type filter, choose the Windows Forms App (.NET Framework) template for either C# or Visual Basic, and then choose Next.
Если шаблон Приложение Windows Forms (.NET Framework) отсутствует, его можно установить из окна Создание проекта. If you don’t see the Windows Forms App (.NET Framework) template, you can install it from the Create a new project window. В сообщении Не нашли то, что искали? выберите ссылку Установка других средств и компонентов. In the Not finding what you’re looking for? message, choose the Install more tools and features link.
После этого в Visual Studio Installer выберите рабочую нагрузку Разработка классических приложений .NET. Next, in the Visual Studio Installer, choose the Choose the .NET desktop development workload.
Затем нажмите кнопку Изменить в Visual Studio Installer. After that, choose the Modify button in the Visual Studio Installer. Вам может быть предложено сохранить результаты работы; в таком случае сделайте это. You might be prompted to save your work; if so, do so. Выберите Продолжить, чтобы установить рабочую нагрузку. Next, choose Continue to install the workload.
В поле Имя проекта окна Настроить новый проект введите PictureViewer. In the Configure your new project window, type or enter PictureViewer in the Project name box. Затем нажмите Создать. Then, choose Create.
Visual Studio создает решение для приложения. Visual Studio creates a solution for your app. Решение играет роль контейнера для всех проектов и файлов, необходимых приложению. A solution acts as a container for all of the projects and files needed by your app. Более подробно эти термины поясняются далее в этом учебнике. These terms will be explained in more detail later in this tutorial.
Сведения о проекте приложения Windows Forms About the Windows Forms App project
Среда разработки содержит три окна: главное окно, Обозреватель решений и окно Свойства. The development environment contains three windows: a main window, Solution Explorer, and the Properties window.
Если какое-либо из этих окон отсутствует, можно восстановить макет окон по умолчанию. If any of these windows are missing, you can restore the default window layout. В строке меню выберите Окно > Сброс макета окна. On the menu bar, choose Window > Reset Window Layout.
Можно также отобразить окна с помощью команд меню. You can also display windows by using menu commands. В строке меню выберите Вид > Окно «Свойства» или Обозреватель решений. On the menu bar, choose View > Properties Window or Solution Explorer.
Если открыты какие-либо другие окна, закройте их с помощью кнопки Закрыть (x) в верхнем правом углу. If any other windows are open, close them by choosing the Close (x) button in their upper-right corners.
- Главное окно. В этом окне выполняется основная часть работы, например работа с формами и редактирование кода. Main window In this window, you’ll do most of your work, such as working with forms and editing code. В окне показана форма в редакторе форм. The window shows a form in the Form Editor. В верхней части окна находятся две вкладки — вкладка Начальная страница и вкладка Form1.cs [Design]. At the top of the window, the Start Page tab and the Form1.cs [Design] tab appear. (В Visual Basic имя вкладки заканчивается на .vb, а не на .cs.) (In Visual Basic, the tab name ends with .vb instead of .cs.)
- Главное окно. В этом окне выполняется основная часть работы, например работа с формами и редактирование кода. Main window In this window, you’ll do most of your work, such as working with forms and editing code. В окне показана форма в редакторе форм. The window shows a form in the Form Editor.
- Окно «Обозреватель решений». В этом окне можно просматривать все элементы, входящие в решение, и переходить к ним. Solution Explorer window In this window, you can view and navigate to all items in your solution.
Если выбрать файл, содержимое в окне Свойства изменится. If you choose a file, the contents of the Properties window changes. Если открыть файл кода (с расширением .cs в C# и .vb в Visual Basic), откроется сам файл кода или конструктор для него. If you open a code file (which ends in .cs in C# and .vb in Visual Basic), the code file or a designer for the code file appears. Конструктор — это визуальная поверхность, на которую можно добавлять элементы управления, такие как кнопки и списки. A designer is a visual surface onto which you can add controls such as buttons and lists. При работе с формами Visual Studio такая поверхность называется конструктор Windows Forms. For Visual Studio forms, the designer is called the Windows Forms Designer.
Окно «Свойства». В этом окне производится изменение свойств элементов, выбранных в других окнах. Properties window In this window, you can change the properties of items that you choose in the other windows. Например, выбрав форму Form1, можно изменить ее название путем задания свойства Text, а также изменить цвет фона путем задания свойства Backcolor. For example, if you choose Form1, you can change its title by setting the Text property, and you can change the background color by setting the Backcolor property.
В верхней строке в обозревателе решений отображается текст Решение «PictureViewer» (1 проект). Это означает, что Visual Studio автоматически создала для вас решение. The top line in Solution Explorer shows Solution ‘PictureViewer’ (1 project), which means that Visual Studio created a solution for you. Решение может содержать несколько проектов, но пока что вы будете работать с решениями, которые содержат только один проект. A solution can contain more than one project, but for now, you’ll work with solutions that contain only one project.
В строке меню выберите Файл > Сохранить все. On the menu bar, choose File > Save All.
Другой вариант — нажать кнопку Сохранить все на панели инструментов, как показано на рисунке ниже. As an alternative, choose the Save All button on the toolbar, which the following image shows.
Кнопка «Сохранить все» _ _на панели инструментов Save All _ _toolbar button
Visual Studio автоматически заполняет имя папки и имя проекта, а затем сохраняет проект в папке проектов. Visual Studio automatically fills in the folder name and the project name and then saves the project in your projects folder.
Дальнейшие действия Next steps
Следующий раздел руководства: Шаг 2. Запуск приложения . To go to the next tutorial step, see Step 2: Run your app.