Name already in use
visualstudio-docs / docs / ide / create-csharp-winform-visual-studio.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
10 contributors
Users who have contributed to this file
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Create a Windows Forms app in Visual Studio with C#
In this tutorial, you’ll create a simple C# application that has a Windows-based user interface (UI).
If you haven’t already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
[!NOTE] Some of the screenshots in this tutorial use the dark theme. If you aren’t using the dark theme but would like to, see the Personalize the Visual Studio IDE and Editor page to learn how.
If you haven’t already installed Visual Studio, go to the Visual Studio 2022 downloads page to install it for free.
Create a project
First, you’ll create a C# application project. The project type comes with all the template files you’ll need, before you’ve even added anything.
Open Visual Studio.
On the start window, choose Create a new project.

On the Create a new project window, choose the Windows Forms App (.NET Framework) template for C#.
(If you prefer, you can refine your search to quickly get to the template you want. For example, enter or type Windows Forms App in the search box. Next, choose C# from the Language list, and then choose Windows from the Platform list.)

[!NOTE] If you do not 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 .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. Then, return to step 2 in this «Create a project» procedure.
In the Configure your new project window, type or enter HelloWorld in the Project name box. Then, choose Create.

Visual Studio opens your new project.
Open Visual Studio.
On the start window, select Create a new project.
. image type=»content» source=»media/vs-2022/create-new-project-dark-theme.png» alt-text=»Screenshot to show the Create a new project window.».
On the Create a new project window, select the Windows Forms App (.NET Framework) template for C#.
(If you prefer, you can refine your search to quickly get to the template you want. For example, enter or type Windows Forms App in the search box. Next, select C# from the Language list, and then select Windows from the Platform list.)
. image type=»content» source=»media/vs-2022/csharp-winform-create-a-new-project.png» alt-text=»Screenshot to select the C# template for the Windows Forms App (.NET Framework).».
[!NOTE] If you do not 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, select the Install more tools and features link.
. image type=»content» source=»../get-started/media/vs-2019/not-finding-what-looking-for.png» alt-text=»Screenshot to show the The ‘Install more tools and features’ link from the ‘Not finding what you’re looking for’ message in the ‘Create a new project’ window.».
Next, in the Visual Studio Installer, select the .NET desktop development workload.
. image type=»content» source=»media/vs-2022/install-dot-net-desktop-env.png» alt-text=»Screenshot to show the .NET Core workload in the Visual Studio Installer.».
After that, select the Modify button in the Visual Studio Installer. You might be prompted to save your work; if so, do so. Next, select Continue to install the workload. Then, return to step 2 in this «Create a project» procedure.
In the Configure your new project window, type or enter HelloWorld in the Project name box. Then, select Create.
. image type=»content» source=»media/vs-2022/csharp-winform-configure-new-project.png» alt-text=»Screenshot to show the ‘Configure your new project’ window and name your project ‘HelloWorld’.».
Visual Studio opens your new project.
Create the application
After you select your C# project template and name your file, Visual Studio opens a form for you. A form is a Windows user interface. We’ll create a «Hello World» application by adding controls to the form, and then we’ll run the app.
Add a button to the form
Select Toolbox to open the Toolbox fly-out window.
. image type=»content» source=»media/vs-2022/csharp-winform-hello-world-project-toolbox.png» alt-text=»Screenshot to select the Toolbox to open the Toolbox window.».
(If you don’t see the Toolbox fly-out option, you can open it from the menu bar. To do so, View > Toolbox. Or, press Ctrl+Alt+X.)
Expand Common Controls and select the Pin icon to dock the Toolbox window.
. image type=»content» source=»media/vs-2022/csharp-winform-toolbox-flyout-pin.png» alt-text=»Screenshot to select the Pin icon to pin the Toolbox window to the IDE.».
Select the Button control and then drag it onto the form.
. image type=»content» source=»media/vs-2022/csharp-winform-add-button-on-form.png» alt-text=»Screenshot to add a button to the form.».
In the Properties window, locate Text, change the name from button1 to Click this , and then press Enter.
. image type=»content» source=»media/vs-2022/csharp-winform-button-properties-text.png» alt-text=»Screenshot to add text to the button on the form by using the Properties window.».
(If you don’t see the Properties window, you can open it from the menu bar. To do so, select View > Properties Window. Or, press F4.)
In the Design section of the Properties window, change the name from button1 to btnClickThis , and then press Enter.
. image type=»content» source=»media/vs-2022/csharp-winform-button-properties-design-name.png» alt-text=»Screenshot to add a function to the button on the form by using the Properties window.».
[!NOTE] If you’ve alphabetized the list in the Properties window, button1 appears in the (DataBindings) section, instead.
Add a label to the form
Now that we’ve added a button control to create an action, let’s add a label control to send text to.
Select the Label control from the Toolbox window, and then drag it onto the form and drop it beneath the Click this button.
In either the Design section or the (DataBindings) section of the Properties window, change the name of label1 to lblHelloWorld , and then press Enter.
Add code to the form
In the Form1.cs [Design] window, double-click the Click this button to open the Form1.cs window.
(Alternatively, you can expand Form1.cs in Solution Explorer, and then choose Form1.)
In the Form1.cs window, after the private void line, type or enter lblHelloWorld.Text = «Hello World!»; as shown in the following screenshot:
. image type=»content» source=»media/vs-2022/csharp-winform-button-click-code.png» alt-text=»Screenshot to add code to the form».
Run the application
Select the Start button to run the application.
. image type=»content» source=»media/vs-2022/csharp-winform-visual-studio-start-run-program.png» alt-text=»Screenshot to select Start to debug and run the app.».
Several things will happen. In the Visual Studio IDE, the Diagnostics Tools window will open, and an Output window will open, too. But outside of the IDE, a Form1 dialog box appears. It will include your Click this button and text that says label1.
Select the Click this button in the Form1 dialog box. Notice that the label1 text changes to Hello World!.
. image type=»content» source=»media/vs-2022/csharp-winform-form.png» alt-text=»Screenshot to show a Form1 dialog box that includes label1 text.».
Close the Form1 dialog box to stop running the app.
Create the application
After you select your C# project template and name your file, Visual Studio opens a form for you. A form is a Windows user interface. We’ll create a «Hello World» application by adding controls to the form, and then we’ll run the app.
Add a button to the form
Choose Toolbox to open the Toolbox fly-out window.

(If you don’t see the Toolbox fly-out option, you can open it from the menu bar. To do so, View > Toolbox. Or, press Ctrl+Alt+X.)
Choose the Pin icon to dock the Toolbox window.

Choose the Button control and then drag it onto the form.
In the Properties window, locate Text, change the name from Button1 to Click this , and then press Enter.
(If you don’t see the Properties window, you can open it from the menu bar. To do so, choose View > Properties Window. Or, press F4.)
In the Design section of the Properties window, change the name from Button1 to btnClickThis , and then press Enter.
[!NOTE] If you’ve alphabetized the list in the Properties window, Button1 appears in the (DataBindings) section, instead.
Add a label to the form
Now that we’ve added a button control to create an action, let’s add a label control to send text to.
Select the Label control from the Toolbox window, and then drag it onto the form and drop it beneath the Click this button.
In either the Design section or the (DataBindings) section of the Properties window, change the name of Label1 to lblHelloWorld , and then press Enter.
Add code to the form
In the Form1.cs [Design] window, double-click the Click this button to open the Form1.cs window.
(Alternatively, you can expand Form1.cs in Solution Explorer, and then choose View Code(or press F7) from the right-click menu on Form1.cs.)
In the Form1.cs window, after the private void line, type or enter lblHelloWorld.Text = «Hello World!»; as shown in the following screenshot:

Run the application
Choose the Start button to run the application.

Several things will happen. In the Visual Studio IDE, the Diagnostics Tools window will open, and an Output window will open, too. But outside of the IDE, a Form1 dialog box appears. It will include your Click this button and text that says Label1.
Choose the Click this button in the Form1 dialog box. Notice that the Label1 text changes to Hello World!.

Close the Form1 dialog box to stop running the app.
Congratulations on completing this tutorial. To learn more, continue with the following tutorial:
visual studio windows forms как открыть конструктор
Из этого краткого руководства вы узнаете, как создать новое приложение Windows Forms (WinForms) с помощью Visual Studio. После создания первоначального приложения вы научитесь добавлять элементы управления и обрабатывать события. По завершении работы с этим руководством у вас будет простое приложение, добавляющее имена в список.
В этом руководстве описано следующее:
Предварительные требования
Создание приложения WinForms
Первым шагом в создании нового приложения является запуск Visual Studio и создание приложения на основе шаблона.
Запустите Visual Studio.
Выберите Создать новый проект.

В раскрывающемся списке язык кода выберите C# или Visual Basic.
В списке шаблонов выберите Приложение Windows Forms (.NET) и затем щелкните Далее.

В окне Настроить новый проект задайте в качестве имени проекта значение Names и щелкните Создать.
Вы также можете сохранить проект в другую папку, изменив параметр Расположение.

После создания приложения Visual Studio должен открыть панель конструктора для формы по умолчанию Form1. Если конструктор форм не отображается, дважды щелкните форму в области Обозреватель решений, чтобы открыть окно конструктора.
Важные элементы среды Visual Studio
Поддержка WinForms в Visual Studio состоит из четырех важных компонентов, с которыми вы будете взаимодействовать при создании приложения.

Все файлы проекта, код, формы и ресурсы отображаются в этой области.
На этой панели отображаются параметры свойств, которые можно настроить в зависимости от выбранного элемента. Например, если выбрать элемент в Обозревателе решений, отобразятся параметры свойств, связанные с файлом. Если выбрать объект в конструкторе, отобразятся параметры элемента управления или формы.
Это конструктор для формы. Он является интерактивным, и на него можно перетаскивать объекты из панели элементов. Выбирая и перемещая элементы в конструкторе, можно визуально создавать пользовательский интерфейс для приложения.
Панель элементов содержит все элементы управления, которые можно добавить на форму. Чтобы добавить элемент управления на текущую форму, дважды щелкните элемент управления или перетащите его.
Добавление элементов управления на форму
Открыв конструктор форм Form1, используйте панель Область элементов, чтобы добавить на форму следующие элементы управления:
Вы можете расположить и изменить размер элементов управления в соответствии со следующими настройками. Либо визуально перенесите их, чтобы они соответствовали следующему снимку экрана, либо щелкните каждый элемент управления и настройте параметры в области Свойства. Можно также щелкнуть область заголовка формы, чтобы выбрать форму.
| Объект | Параметр | Значение |
|---|---|---|
| Form | Текст | Names |
| Размер | 268, 180 | |
| Label | Расположение | 12, 9 |
| Текст | Names | |
| Listbox | Имя | lstNames |
| Расположение | 12, 27 | |
| Размер | 120, 94 | |
| текстовое поле; | Имя | txtName |
| Расположение | 138, 26 | |
| Размер | 100, 23 | |
| Button | Имя | btnAdd |
| Расположение | 138, 55 | |
| Размер | 100, 23 | |
| Текст | Add Name |
Вы должны получить в конструкторе форму, которая выглядит следующим образом.

Обработка событий
Теперь, когда в форме есть все элементы управления, необходимо обрабатывать события элементов управления, чтобы реагировать на вводимые пользователем данные. Открыв конструктор форм, выполните следующие действия.
Выберите в форме элемент управления «Кнопка».
Найдите событие Click и дважды щелкните его, чтобы создать обработчик событий.
Это действие добавляет следующий код в форму:
Запустите приложение
Теперь, когда у нас есть код события, можно запустить приложение, нажав клавишу F5 или выбрав пункт меню Отладка > Начать отладку. Отобразится форма, и вы можете ввести имя в текстовое поле, а затем добавить его, нажав кнопку.
Шаг 1. Создание проекта приложения Windows Forms
Первый шаг в создании программы для просмотра изображений — это создание проекта приложения Windows Forms.
Откройте Visual Studio 2017.
В строке меню выберите Файл > Создать > Проект. Диалоговое окно должно выглядеть так же, как на следующем снимке экрана.

Диалоговое окно _ _»Новый проект»
В левой части диалогового окна Новый проект выберите Visual C# или Visual Basic, а затем — Классическое приложение Windows.
В списке шаблонов проектов выберите Приложение Windows Forms (.NET Framework). Назовите новую форму PictureViewer и нажмите кнопку ОК.

Дополнительные сведения см. в разделе Установка Visual Studio.
Открытие Visual Studio
На начальном экране выберите Создать проект.

В поле поиска окна Создание проекта введите Windows Forms. Затем в списке Тип проекта выберите Рабочий стол.
Применив фильтр Тип проекта, выберите шаблон Приложение Windows Forms (.NET Framework) для C# или Visual Basic и нажмите кнопку Далее.

Если шаблон Приложение Windows Forms (.NET Framework) отсутствует, его можно установить из окна Создание проекта. В сообщении Не нашли то, что искали? выберите ссылку Установка других средств и компонентов.


Затем нажмите кнопку Изменить в Visual Studio Installer. Вам может быть предложено сохранить результаты работы; в таком случае сделайте это. Выберите Продолжить, чтобы установить рабочую нагрузку.
В поле Имя проекта окна Настроить новый проект введите PictureViewer. Затем нажмите Создать.
Visual Studio создает решение для приложения. Решение играет роль контейнера для всех проектов и файлов, необходимых приложению. Более подробно эти термины поясняются далее в этом учебнике.
Сведения о проекте приложения Windows Forms
Среда разработки содержит три окна: главное окно, Обозреватель решений и окно Свойства.
Если какое-либо из этих окон отсутствует, можно восстановить макет окон по умолчанию. В строке меню выберите Окно > Сброс макета окна.
Можно также отобразить окна с помощью команд меню. В строке меню выберите Вид > Окно «Свойства» или Обозреватель решений.
Если открыты какие-либо другие окна, закройте их с помощью кнопки Закрыть (x) в верхнем правом углу.
Если выбрать файл, содержимое в окне Свойства изменится. Если открыть файл кода (с расширением .cs в C# и .vb в Visual Basic), откроется сам файл кода или конструктор для него. Конструктор — это визуальная поверхность, на которую можно добавлять элементы управления, такие как кнопки и списки. При работе с формами Visual Studio такая поверхность называется конструктор Windows Forms.
Окно «Свойства». В этом окне производится изменение свойств элементов, выбранных в других окнах. Например, выбрав форму Form1, можно изменить ее название путем задания свойства Text, а также изменить цвет фона путем задания свойства Backcolor.
В верхней строке в обозревателе решений отображается текст Решение «PictureViewer» (1 проект). Это означает, что Visual Studio автоматически создала для вас решение. Решение может содержать несколько проектов, но пока что вы будете работать с решениями, которые содержат только один проект.
В строке меню выберите Файл > Сохранить все.
Другой вариант — нажать кнопку Сохранить все на панели инструментов, как показано на рисунке ниже.
Visual Studio автоматически заполняет имя папки и имя проекта, а затем сохраняет проект в папке проектов.
Дальнейшие действия
Учебник. Начало работы с конструктором Windows Forms
Конструктор Windows Forms предоставляет множество средств для создания приложений Windows Forms. В этой статье показано, как создать приложение с помощью различных средств, предоставляемых конструктором, и выполнять такие задачи:
В итоге вы создадите пользовательский элемент управления, используя разнообразные функции макета, которые доступны в конструкторе Windows Forms. Этот элемент управления реализует пользовательский интерфейс для простого калькулятора. На следующем изображении показан общий макет элемента управления калькулятора.
Создание проекта пользовательского элемента управления
Первым шагом является создание проекта элемента управления DemoCalculator.
Откройте Visual Studio и создайте проект категории Библиотека элементов управления Windows Forms. Задайте проекту имя DemoCalculatorLib.

Чтобы переименовать файл, в обозревателе решений щелкните правой кнопкой мыши элемент UserControl1.vb или UserControl1.cs, выберите Переименовать и замените имя файла на DemoCalculator.vb или DemoCalculator.cs. Чтобы переименовать все ссылки на элемент кода UserControl1, в соответствующем запросе выберите Да.
В конструктор Windows Forms отображается поверхность конструктора для элемента управления DemoCalculator. В этом представлении можно графически спроектировать внешний вид элемента управления, выбрав элементы управления и компоненты на панели элементов и поместив их на поверхности конструктора. Дополнительные сведения см. в статье о разновидностях пользовательских элементов управления.
Разработка макета элемента управления
Элемент управления DemoCalculator содержит несколько элементов управления Windows Forms. На этом этапе вы зададите расположение элементов управления с помощью конструктора Windows Forms.
В конструкторе Windows Forms увеличьте размер элемента управления DemoCalculator, выбрав маркер изменения размера в правом нижнем углу и перетащив его вниз и вправо. В правом нижнем углу Visual Studio просмотрите сведения о размере и расположении элементов управления. Задайте элементу управления ширину 500 и высоту 400, наблюдая за сведениями о размере при изменении размера элемента управления.
На панели элементов выберите узел Контейнеры, чтобы открыть его. Выберите элемент управления SplitContainer и перетащите его на поверхность конструктора.
Элемент SplitContainer появится на поверхности конструктора элемента управления DemoCalculator.
Элемент управления SplitContainer уменьшится до размера по умолчанию и больше не будет меняться при изменении размера элемента управления DemoCalculator.
Элемент управления SplitContainer закрепится по границам элемента управления DemoCalculator.
Для некоторых элементов управления доступны смарт-теги, упрощающие проектирование. Дополнительные сведения см. в разделе Пошаговое руководство: выполнение типичных задач с помощью смарт-тегов в элементах управления Windows Forms.
Выберите вертикальную границу между панелями и перетащите ее вправо, так чтобы большую часть заняла левая панель.
SplitContainer разделяет элемент управления DemoCalculator на две панели с разделяющей их границей, которую можно перемещать. На левой панели будут находиться кнопки калькулятора и экран, а на правой будет отображаться запись арифметических операций, выполненных пользователем.
На панели смарт-тегов выберите Изменить столбцы.
Откроется диалоговое окно Редактор коллекции ColumnHeader.
На панели смарт-тегов выберите Закрепить в родительском контейнере, а затем щелкните глиф смарт-тега, чтобы закрыть панель смарт-тегов.
Элемент управления TableLayoutPanel отобразится на поверхности конструктора с открытой панелью смарт-тегов. Элемент управления TableLayoutPanel упорядочивает свои дочерние элементы управления в сетке. Элемент управления TableLayoutPanel будет содержать экран и кнопки элемента управления DemoCalculator. Дополнительные сведения см. в разделе Пошаговое руководство: упорядочение элементов управления в формах Windows Forms с помощью элемента TableLayoutPanel.
На панели смарт-тегов выберите Правка строк и столбцов.
Откроется диалоговое окно Стили столбцов и строк.
Нажимайте кнопку Добавить, пока не добавятся пять столбцов. Выберите все пять столбцов, а затем в поле Тип размера выберите Процент. Параметру Процент задайте значение 20. При этом каждому столбцу задается одинаковая ширина.
В разделе Показать выберите Строки.
Нажимайте кнопку Добавить, пока не добавятся пять строк. Выберите все пять строк, а затем в поле Тип размера выберите Процент. Параметру Процент задайте значение 20. При этом каждой строке задается одинаковая высота.
Нажмите кнопку ОК, чтобы применить изменения, и щелкните глиф смарт-тега, чтобы закрыть панель смарт-тегов.
Заполнение элемента управления
Теперь, когда макет элемента управления настроен, можно добавить в элемент управления DemoCalculator кнопки и экран.
В окне Свойства замените значение свойства ColumnSpan элемента управления TextBox на 5.
Элемент управления TextBox переместится в центр своей строки.
Элемент управления TextBox расширится по горизонтали, заняв все пять столбцов.
Все элементы управления Button закрепятся в своих ячейках.
Всем элементам управления Button задается меньший размер, чтобы увеличить поля между ними.
Выберите button10 и button20, после чего нажмите клавишу DELETE, чтобы удалить их из макета.
Выберите button5 и button15, после чего замените значение их свойства RowSpan на 2. Это будут кнопки очистки и = для элемента управления DemoCalculator.
Использование окна структуры документа
Если в элементе управления или форме присутствует несколько элементов управления, перемещаться по макету удобнее с помощью окна «Структура документа».
В строке меню выберите Вид > Другие окна > Структура документа.
В окне Структура документа щелкните правой кнопкой мыши элемент button1, чтобы выбрать его, после чего щелкните Переименовать. Замените его имя на sevenButton.
button1 на sevenButton;
button2 на eightButton;
button3 на nineButton;
button4 на divisionButton;
button5 на clearButton;
button6 на fourButton;
button7 на fiveButton;
button8 на sixButton;
button9 на multiplicationButton;
button11 на oneButton;
button12 на twoButton;
button13 на threeButton;
button14 на subtractionButton;
button15 на equalsButton;
button16 на zeroButton;
button17 на changeSignButton;
button18 на decimalButton;
button19 на additionButton;
С помощью окон Структура документа и Свойства измените значения свойства Text для каждого имени элемента управления Button согласно следующему списку:
для элемента управления sevenButton замените свойство текста на 7;
для элемента управления eightButton замените свойство текста на 8;
для элемента управления nineButton замените свойство текста на 9;
для элемента управления divisionButton замените свойство текста на / (косая черта);
для элемента управления clearButton замените свойство текста на Clear;
для элемента управления fourButton замените свойство текста на 4;
для элемента управления fiveButton замените свойство текста на 5;
для элемента управления sixButton замените свойство текста на 6;
для элемента управления multiplicationButton замените свойство текста на * (звездочка);
для элемента управления oneButton замените свойство текста на 1;
для элемента управления twoButton замените свойство текста на 2;
для элемента управления threeButton замените свойство текста на 3;
для элемента управления subtractionButton замените свойство текста на — (дефис);
для элемента управления equalsButton замените свойство текста на = (знак равенства);
для элемента управления zeroButton замените свойство текста на 0;
для элемента управления changeSignButton замените свойство текста на +/- ;
для элемента управления decimalButton замените свойство текста на . (точка);
для элемента управления additionButton замените свойство текста на + (знак «плюс»);
На этом разработка элемента управления DemoCalculator завершена. Остается только добавить логику калькулятора.
Добавление обработчиков событий
Кнопки в элементе управления DemoCalculator имеют обработчики событий, которые можно использовать для реализации большей части логики калькулятора. Конструктор Windows Forms позволяет реализовать заглушки всех обработчиков событий для всех кнопок одним выбором.
В редакторе кода откроются обработчики событий, созданные конструктором.
Тестирование элемента управления
Поскольку элемент управления DemoCalculator наследуется от класса UserControl, его поведение можно проверить с помощью Контейнера для тестирования пользовательских элементов управления. Дополнительные сведения см. в разделе Практическое руководство. Тестирование поведения элемента UserControl во время выполнения.
Нажмите клавишу F5, чтобы собрать и запустить элемент управления DemoCalculator в Контейнере для тестирования пользовательских элементов управления.
Выберите границу между панелями SplitContainer и перетащите ее влево и вправо. Размеры элемента TableLayoutPanel и всех его дочерних элементов управления будут изменяться в соответствии с доступным пространством.
Завершив тестирование элемента управления, нажмите кнопку Закрыть.
Использование элемента управления в форме
Элемент управления DemoCalculator можно использовать в других составных элементах управления или в форме. Ниже описано, как это сделать.
Создание проекта
Первым шагом является создание проекта приложения. В этом проекте выполняется сборка приложения, демонстрирующего работу пользовательского элемента управления.
Создайте проект Приложение Windows Forms с именем DemoCalculatorTest.
В обозревателе решений щелкните правой кнопкой мыши проект DemoCalculatorTest и выберите Добавить ссылку, чтобы открыть диалоговое окно Добавление ссылки.
Перейдите на вкладку Проекты и выберите проект DemoCalculatorLib, чтобы добавить ссылку на тестовый проект.
В обозревателе решений щелкните правой кнопкой мыши DemoCalculatorTest и выберите пункт Назначить запускаемым проектом.
В конструкторе Windows Forms увеличьте размер формы примерно до 700 x 500.
Использование элемента управления в макете формы
Чтобы использовать элемент управления DemoCalculator в приложении, его необходимо поместить в форму.
На панели элементов разверните узел Компоненты DemoCalculatorLib.
Перетащите элемент управления DemoCalculator с панели элементов в форму. Переместите элемент управления в левый верхний угол формы. Когда элемент управления расположен близко к границам формы, отображаются линии привязки. Линии привязки указывают расстояние свойства Padding формы и свойства Margin элемента управления. Поместите элемент управления в расположение, указанное линиями привязки.
Перетащите элемент управления Button с панели элементов и поместите его в форму.
Щелкните правой кнопкой мыши элемент управления DemoCalculator и выберите пункт Свойства.
Измените размер формы, перетаскивая различные маркеры изменения размера в разные положения. Обратите внимание на то, как размер элемента управления DemoCalculator пропорционально изменяется.
Следующие шаги
В этой статье было показано, как создать пользовательский интерфейс для простого калькулятора. В дальнейшем можно расширить его функциональность, реализовав логику калькулятора, а затем опубликовать приложение с помощью ClickOnce. Вы также можете ознакомиться с руководством по созданию средства просмотра рисунков с помощью Windows Forms.
Как войти в конструктор формы
Помощь в написании контрольных, курсовых и дипломных работ здесь.
Как связать формы для ввода логина и пароля с кнопкой войти
Итак, друзья, есть у меня два text.Box (login:password), как это все связать с кнопкой войти, что.
Как переоткрыть конструктор CLR формы
Добрый день! Помогите, пожалуйста, не могу никак вернуть конструктор формы. Создаю CLR пустой.
Как связать элементы формы и конструктор класса?
Доброго времени суток. Подскажите пожалуйста, вот у меня есть форма, на ней есть TextBox. как.
В обозревателе решений написано проектов 0. Может кто-либо на пальцах объсянить можно ли вернуть эту форму и как. Зайти туда-то поставить галочку там-то
Добавлено через 4 минуты
Я не знаю что это такое (ПКМ и View Designer).
moland, так это не форма пропала, а проект. Интересно где ты нажимал Shift+F7 в таком случае.
Если файлы проекта не были удалены, то нужно заново добавить проект в решение. Для начала посмотри есть ли рядом с решением папка проекта или его файлы. Ориентиром будет *.csproj файл. Если файлов нет, то значит ты переместил их куда-то (вспоминай куда) или удалил (тогда всё пропало шеф). Если файлы проекта есть, то выбери в контекстом меню решения «Add Existing Project».
How to open form designer in Visual Studio?
Unfortunately, it only opens up the code for the file.

![]()
12 Answers 12
Have the same issue when placing another class before the form class (in this case my ImageContainer class).
By just moving the internal class ImageContainer after the public partial class Form1 : Form < >the VS2019 drag&drop designer could load my Form1 class.
Also symbol in Solution Explorer changed back to a dialog icon.
![]()
You are in the Folder view.
Change to the Solution (Project) view.
This icon
at the top of Solution Explorer.
![]()
The associations between the files must have gotten broken somehow. You can manually edit the .csproj file and correct it. Search for Form1 . You should have entries for each file that look something like this:
Notice the SubType and DependentUpon . Those are the important pieces.
In my case right-click on Form1.cs (with correct Form icon) and select «View Designer» still showing code.
I found this thread and realized I accidentally choose .Net Core instead of .NET Framework when creating new project:

I should able see this long xml inside .csproj file (.NET Framework) of Solution Explorer panel, which the TargetFrameworkVersion showing v<Number> :
, instead of short xml below (*.Net Core), which the TargetFramework showing netcoreapp<Number> :
To check project type, can refer this answer.
Microsoft devlogs stated that Designer with .Net Core is not shipped by default yet:
If you want to work with .NET Core project, don’t forget to install the .NET Core Windows Forms Designer, since it isn’t yet shipped inside Visual Studio by default. See the previous “Enabling the designer” section.
C++ Winforms Tutorial

Windows Forms Projects with C++ in Visual Studio 2022
In Visual Studio up to version 2010, Templates for Windows Forms projects are pre-installed, but not as of Visual Studio 2012. For these newer versions of Visual Studio you have to install an extension.
This tutorial is for Visual Studio 2022, but applies essentially the same to other versions of Visual Studio (2019, 2017, 2015 and earlier).
Installing the extension for Windows Forms projects with C++
This extension is installed in Visual Studio 2022 under Extensions|Manage Extensions
After clicking Download at “C++ Windows Forms for Visual Studio 2022 .NET Framework”
and closing Visual Studio you get the message
Click Modify to install the extension.
After the next start of Visual Studio under File|New|Project you will find the CppCLR_WinformsProject template:
With this template you can create Windows Forms projects written in C++. Such a project creates a Windows application with a graphical user interface (buttons, menus, etc.), for example:
Standard C++ (including almost all extensions of C++11, C++14, C++17) is used as programming language for the business logic. Only for accessing Windows controls C++/CLI is necessary. This is a simple C++ dialect for the .NET Framework.
The book „C++ mit Visual Studio 2019 und Windows Forms-Anwendungen“
The following is a brief excerpt from my book (in German)
which is still up to date with Visual Studio 2022. All examples and projects can be created and compiled in Visual Studio 2022 as in Visual Studio 2019.
Installing Visual Studio for Windows Forms Projects
In order to create Windows Forms projects in Visual Studio, particular components must be installed during the installation of Visual Studio. If this was forgotten during the installation, start the Visual Studio Installer either under Windows|Start
or in Visual Studio under File|New|Project|Create new project (at the end of the project list)
In the installer, check .NET desktop development, desktop development with C++ and C++/CLI support:
Create a Windows Forms project
After restarting Visual Studio, Windows Forms projects are available under Create New Project or File|New|Project:
Click the Next button. Then you will be prompted to enter the name of the project and a directory:
After clicking the Create button, Visual Studio looks something like this:
If you now click on Form1.h in the Solution Explorer, the form is displayed:
Normally, everything is done and you can continue with the next section. However, if you get something like this
you have clicked Form1.h too fast. Close this window
and click again on Form1.h in the Solution Explorer.
Visual Programming: A first small program
Now, before we get started with our first little program, let’s rearrange Visual Studio a bit to make it easier to use.
After installing Visual Studio, the Toolbox is offered at the left margin.
To prevent the toolbox from covering the form, drag the toolbox to the frame with the Solution Explorer (press the left mouse button on the title bar of the toolbox, then move to the title bar of the Solution Explorer with the mouse button pressed and release the mouse button).
Drag the properties window analogously to the Solution Explorer.
Since we initially only need the Toolbox, Solution Explorer and Properties window, you can close all other windows here (e.g. Git Explorer, etc.). Then the right frame looks something like this:
With the Windows Forms project from Section 1.4, Visual Studio then looks like this:
Next, we will now write a first small program.
The form (here Form1) is the starting point for all Windows Forms applications. It corresponds to the window that is displayed when the program is started:
Controls from the Toolbox can be placed on a form. The Toolbox contains essentially all the controls commonly used in Windows. They are located in various groups (e.g. General Controls, Containers, etc.), which can be expanded and collapsed. Most of these controls (such as a button) are displayed on the form while the program is running. If you stop with the mouse pointer briefly on a line of the toolbox, a small hint appears with a short description:
To place an element from the toolbox on the form, simply drag it from the toolbox onto the form. Or click on it in the toolbox first and then click on the position in the form where you want the upper left corner to be.
Example: After placing a Label (line seven in Common Controls, with the capital A), a TextBox (fourth line from the bottom, labelled ab) and a Button (second line labelled ab) on the form, it looks something like this:
By playing around like this, you have already created a real Windows program – not a particularly useful one, but still. You can start it as follows:
- with Debug|Start Debugging from the menu, or
- with F5 from any window in Visual Studio or
- by starting the exe file generated by the compiler.
This program already has many features that you would expect from a Windows program: You can move it with the mouse, resize and close it.
Do not forget to close your program before you continue editing it. As long as the program is still running, you cannot restart the compiler or modify the form.
This way of programming is called visual programming. While conventional programming means developing a program solely by writing instructions (text) in a programming language, visual programming means composing it wholly or in part from out-of-the-box graphical controls.
With Visual Studio, the user interface of a Windows Forms program can be designed visually. This allows you to see how the program will look later at runtime as soon as you design it. The instructions that are to take place as a response to user input (mouse clicks, etc.), on the other hand, are written conventionally in a programming language (e.g. C++).
The Properties Window
The control that was clicked last on a form (or in the pull-down menu of the Properties window) is called the currently selected control. You can identify it by the small squares on its edges, the so-called drag handles. You can drag them with the mouse to change to resize the control. A form becomes the currently selected control by clicking on a free position in the form.
Example: In the last example, button1 is the currently selected control.
In the Properties window (context menu of the control on the form, or View|Properties window – do not confuse with View|Property pages).
the properties of the currently selected control are displayed. The left column contains the names and the right column contains the values of the properties. With F1 you get a description of the property.
The value of a property can be changed via the right column. For some properties, you can type the new value using the keyboard. For others, after clicking on the right column, a small triangle is displayed for a pull-down menu, through which a value can be selected. Or an icon with three dots „…“ is displayed, which can be used to enter values.
- For the Text property, you can enter a text with the keyboard. For a button this text is the inscription on the button (e.g. „OK“), and for a form the title line (e.g. „My first C++ program“).
- For the BackColor property (e.g. from a button) you can select the background color via a pull-down menu.
- If you click the right column of the Font property and then the „…“ icon, you can select the font of the Text property.
A control on the form is not only adjusted to its properties in the Properties panel, but also vice versa: if you resize it by dragging the drag handles on the form, the values of the corresponding properties (Location and Size in the Layout section) in the Properties panel are automatically updated.
First steps in C++
Next, the program from Section 1.5 is to be extended so that instructions are executed in response to user input (e.g., a button click).
Windows programs can receive user input in the form of mouse clicks or keyboard input. All inputs are received centrally by Windows and passed on to the program. This triggers a so-called event in the program.
Such an event can be assigned a function that is called when the event occurs. This function is also called an event handler.
For the time being, our program should only react to the clicking of a button. The easiest way to get the function called for this event is to double-click on the button in the form. The cursor is then placed at the beginning of the function. This causes Visual Studio to generate the following function and display it in the editor:
Between the curly brackets „<“ and „>“ you then write the statements to be executed when the Click event occurs.
Essentially all instructions of C++ are possible here. In the context of this simple tutorial, only some elementary instructions are to be introduced, which is necessary for the basic understanding of Visual Studio. If terms like „variables“ etc. are new to you, read on anyway – from the context you will surely get an intuitive idea which is sufficient for the time being.
A frequently used instruction in programming is the assignment (with the operator „=“), which is used to assign a value to a variable. Initially, only those properties of controls that are also displayed in the properties window are to be used as variables. These variables can then be assigned the values that are also offered in the properties window in the right column of the properties.
For the BackColor property, the allowed values are offered after the pull-down menu is expanded:
These values can be used in the program by specifying them after Color::. If you now write the statement
between the curly brackets
the BackColor property of textBox1 gets the value Color::Yellow, which stands for the color yellow, when button1 is clicked during the execution of the program. If you now start the program with F5 and then click button1, the TextBox actually gets the background color yellow.
Even if this program is not yet much more useful than the first one, you have seen how Visual Studio is used to develop applications for Windows. This development process always consists of the following activities:
- You design the user interface by placing controls from the Toolbox on the form (drag and drop) and adjusting their properties in the Properties window or the layout with the mouse (visual programming).
- You write in C++ the instructions that should be done in response to user input (non-visual programming).
- You start the program and test whether it really behaves as it should.
The period of program development (activities 1. and 2.) is called design time. In contrast, the time during which a program runs is called the runtime of a program.
A simple Winforms application
Next, a simple Winforms application is to be created based on the previous explanations. It contains a button and TextBoxes for input and output:
However, you do not have to create this project yourself. If you install the Visual Studio extension
a project template with exactly this project is available in Visual Studio:
You can use this project as a basis for many applications by adding more controls and functions.
The main purpose of this project is to show how the application logic is separated from the user interface:
- The functions, classes, etc. of the application logic are written in standard C++ and are contained in a header file that is added to the project.
- The instructions for the user interface, on the other hand, are written primarily in C++/CLI and are often included in the form class in Form1..
- The functions of the header file are called when clicking a button.
The following is a simplified version of chapter 2.11 from my book „C++ mit Visual Studio 2019 und Windows Forms-Anwendungen“. There I recommend such a project for the solutions of the exercises. In the header file of such a project you can include the solutions of several exercises or distribute them to different header files. For each subtask you can put a button (or menu options) on the form. This way you don’t have to create a new project for each subtask.
Of course, outsourcing your own instructions to an extra file (as in 3.) and accessing the controls via function parameters is somewhat cumbersome: however, it leads to clearer programs than if all instructions are located in the form file within the Form1 class. This saves many programming errors that lead to obscure error messages, and makes it easier to search for errors.
1. Create the project
Create a new project with File|New|Project|CppCLR_WinformsProject (see section 1.1).
The following examples assume a project named CppCLR_Winforms_GUI.
2. Design the user interface (the form)
The form is then designed to contain all the controls needed to input and output information and start actions. This is done by dragging appropriate controls from the toolbox onto the form.
For many projects (e.g. the exercises from my book) the following controls are sufficient:
- A multiline TextBox (see Section 2.3.2 of my book) to display the results.
- A single-line TextBox for entering data
- One or more buttons (or menu options, etc.) to start the instructions
A TextBox becomes multiline TextBox by the value true of the MultiLine property. The TextBox for output is to be named out_textBox:
The TextBox for entering data will be named in_textBox:
Since the function plus_1 is called when the button is clicked, it is given the caption „plus 1“ and the name button_plus1:
3. A header file for the application logic
The functions, declarations, classes etc. of the so-called application logic are placed in a separate header file, which is added to the project with Project|Add new element|Visual C++|Code as header file(.h) with the name Header1.h. In practice, however, you should group functions and classes that belong together conceptually in a header file, and then give the header file a more meaningful name than Header.h.
The application logic is then included in the header file. These are mostly functions, classes, etc. written in C++. In our first example, this should be a function with the name plus_1, which returns the value of the argument increased by 1:
In a C++ Windows Forms project, the application logic consists primarily of functions, classes, etc. written in C++, without C++/CLI language elements. In our first example, this should be a function named plus_1, which returns the value of the argument incremented by 1:
Diese Datei wird dann vor dem namespace des Projekts mit einer #include-Anweisung in die Formulardatei (z.B. Form1.h) aufgenommen:
This file is then included in the form file (e.g. Form1.h) before the namespace of the project with an #include statement:
4. Calling the functions
By double-clicking the button on the form, Visual Studio creates the function (the event handler) that will be called when the button is clicked when the program is running:
In this event handler you then call the corresponding function. In this simple tutorial this is the function plus_1 from the file Header.h.
- If this function uses user input, you read it in via a TextBox. In this simple tutorial, it will be a number that is read from the in_TextBox.
- If a parameter of the called function does not have type String (the type of the property in_textBox->Text), the string must be converted to the type of the parameter. This is possible with one of the Convert:: functions.
- The results are to be displayed in the out_textBox. This can be done with the function out_textBox->AppendText. The string that AppendText expects can be created with String::Format. In the first argument (a string) you specify <0>for the first value after the string, <1>for the second and so on.
If you enter a number in the input field after starting this program with F5 and then click on the button, the value incremented by 1 is displayed in the output text box:
For each further function whose result is to be displayed, a button is placed on the form and given a suitable name (Name property) and a suitable label (Text property). This function is then called in the associated event handler.
With this all relevant parts of the . CppCLR_Winforms_GUI are presented. You can enhance it as you like with additional controls (buttons, menus, etc.). See chapter 2 of my book for more information.
5. GUI and application logic not so strictly separated
In the version created under 1. to 4. the application logic is strictly separated from the user interface: The access to the user interface with C++/CLI is exclusively done in Form1.h. In Header1.h, however, only standard C++ is used. This has in particular the advantage that one can use this header also in other platforms (e.g. console applications, Qt, Mac).
However, in the early stages of a project, when there is still a lot of experimenting going on, it can be a bit cumbersome if you have to change the calls in another file every time you change a parameter list. And for applications that are not intended to be used for other platforms at all, this strict separation doesn’t help much. This often applies to exercise tasks as well.
This jumping back and forth between different files can be avoided by relaxing the strict separation between the application logic and the user interface by including access to the controls in the header file as well.
Accessing controls in a header file is enabled by inserting
into the header file at the beginning. Then you can also use the types of the controls in the header file (e.g. as parameters) and include the statements that were in the buttonClick function in Form1.h under 4.
This procedure is implemented in the Header2.h file:
Here you pass a parameter for the control to the function. Please note that you must specify a ^ after the name of a .NET type (e.g. TextBox, Button). In the function you then address the control under the name of the parameter.
This function can be called when a button is clicked:
6. Analogy to console applications
Comparing of this Windows Forms project with a corresponding console application shows the analogy of the two types of projects. This analogy shows how to convert a console application into a forms application: If you have a console program like
Excerpt from the preface to my book „C++ mit Visual Studio 2019 und Windows Forms-Anwendungen“
The preface to my book (in German)
teaches C++ with Windows Forms applications in more detail.
Preface
The starting point for this book was the desire for a C++ textbook in which programs for a graphical user interface (Windows) are developed from the beginning, and not console applications as is usually the case. Programs in which inputs and outputs are done via a console are like stone-aged DOS programs for many beginners and discourage them from wanting to deal with C++ at all.
Windows Forms applications are an ideal framework for C++ programs with an attractive user interface: access to Windows controls (Buttons, TextBoxes etc.) is easy. The difference to a standard C++ program is mostly only that inputs and outputs are done via a Windows control (mostly a TextBox)
while in standard C++ the console is used with cout:
But not only students can benefit from C++ with a graphical user interface. With Windows Forms projects, existing C or C++ programs can be enhanced with a graphical user interface without much effort. And those who know C or C++ and do not want to learn a new language for a GUI can make their existing programs more beautiful and easier to use with simple means.
C++ has developed rapidly in recent years: The innovations of C++11, C++14, C++17 and C++20 have brought many improvements and new possibilities. Much of what was good and recommended in 2010 can be made better and safer today.
As a book author and trainer who has accompanied this whole evolution, you notice this particularly clearly: many things that have been written in the past should be done differently today. True, it would still be compiled. But it is no longer modern C++, which corresponds to the current state of the art and uses all the advantages.
This book introduces C++ at the Visual Studio 2019 level in May 2020. This is the scope of C++17.

