Последнее обновление: 28.01.2023
-
Глава 1. Введение в Windows Forms
-
Первое приложение с .NET CLI
-
Первое приложение в Visual Studio
-
Создание графического приложения
-
-
Глава 2. Работа с формами
-
Основы форм
-
Основные свойства форм
-
Добавление форм. Взаимодействие между формами
-
События в Windows Forms. События формы
-
Создание непрямоугольных форм. Закрытие формы
-
-
Глава 3. Контейнеры в Windows Forms
-
Динамическое добавление элементов
-
Элементы GroupBox, Panel и FlowLayoutPanel
-
TableLayoutPanel
-
Размеры элементов и их позиционирование в контейнере
-
Панель вкладок TabControl и SplitContainer
-
-
Глава 4. Элементы управления
-
Кнопка
-
Метки и ссылки
-
Текстовое поле TextBox
-
Элемент MaskedTextBox
-
Элементы Radiobutton и CheckBox
-
ListBox
-
Элемент ComboBox
-
Привязка данных в ListBox и ComboBox
-
Элемент CheckedListBox
-
Элементы NumericUpDown и DomainUpDown
-
ImageList
-
ListView
-
TreeView
-
TrackBar, Timer и ProgressBar
-
DateTimePicker и MonthCalendar
-
PictureBox
-
WebBrowser
-
Элемент NotifyIcon
-
Окно сообщения MessageBox
-
OpenFileDialog и SaveFileDialog
-
FontDialog и ColorDialog
-
ErrorProvider
-
-
Глава 5. Меню и панели инструментов
-
Панель инструментов ToolStrip
-
Создание меню MenuStrip
-
Строка состояния StatusStrip
-
Контекстное меню ContextMenuStrip
-
-
Глава 6. Привязка и паттерн Model-View-ViewModel
-
Введение в привязку. Форматирование значения привязки
-
Привязка объектов. Интерфейс INotifyPropertyChanged
-
DataContext
-
Паттерн Model-View-ViewModel
-
Команды и взаимодействие с пользователем в MVVM
-
Параметры команды
-
- Глава 1. Введение в Windows Forms
- Первое приложение с .NET CLI
- Первое приложение в Visual Studio
- Создание графического приложения
- Глава 2. Работа с формами
- Основы форм
- Основные свойства форм
- Добавление форм. Взаимодействие между формами
- События в Windows Forms. События формы
- Создание непрямоугольных форм. Закрытие формы
- Глава 3. Контейнеры в Windows Forms
- Динамическое добавление элементов
- Элементы GroupBox, Panel и FlowLayoutPanel
- TableLayoutPanel
- Размеры элементов и их позиционирование в контейнере
- Панель вкладок TabControl и SplitContainer
- Глава 4. Элементы управления
- Кнопка
- Метки и ссылки
- Текстовое поле TextBox
- Элемент MaskedTextBox
- Элементы Radiobutton и CheckBox
- ListBox
- Элемент ComboBox
- Привязка данных в ListBox и ComboBox
- Элемент CheckedListBox
- Элементы NumericUpDown и DomainUpDown
- ImageList
- ListView
- TreeView
- TrackBar, Timer и ProgressBar
- DateTimePicker и MonthCalendar
- PictureBox
- WebBrowser
- Элемент NotifyIcon
- Окно сообщения MessageBox
- OpenFileDialog и SaveFileDialog
- FontDialog и ColorDialog
- ErrorProvider
- Глава 5. Меню и панели инструментов
- Панель инструментов ToolStrip
- Создание меню MenuStrip
- Строка состояния StatusStrip
- Контекстное меню ContextMenuStrip
- Глава 6. Привязка и паттерн Model-View-ViewModel
- Введение в привязку. Форматирование значения привязки
- Привязка объектов. Интерфейс INotifyPropertyChanged
- DataContext
- Паттерн Model-View-ViewModel
- Команды и взаимодействие с пользователем в MVVM
- Параметры команды
Помощь сайту
YooMoney:
410011174743222
Перевод на карту
Номер карты:
4048415020898850
Getting started with Windows Forms for .NET
This document describes the experience of using Windows Forms on .NET. The Developer Guide describes how to develop features and fixes for Windows Forms.
Installation
Choose one of these options:
-
.NET 7.0 SDK (recommended)
-
.NET 8.0 daily build (latest changes, could be less stable)
Creating new applications
You can create a new WinForms application with dotnet new command, using the following commands:
dotnet new winforms -o MyWinFormsApp
cd MyWinFormsApp
dotnet run
Designing Forms
You can try the Windows Forms Core Designer Visual Studio extension, see Windows Forms Designer documentation. As an alternative, you can use this workaround.
Samples
Check out the .NET Windows Forms samples for both basic and advanced scenarios. Additionally, there is a collection of Windows Forms sample applications on Microsoft Learn.
Porting existing applications
To port your existing Windows Forms application from .NET Framework to .NET 6 or .NET 7, refer to our porting guidelines.
So far we have seen how to work with C# to create console based applications. But in a real-life scenario team normally use Visual Studio and C# to create either Windows Forms or Web-based applications.
A windows form application is an application, which is designed to run on a computer. It will not run on web browser because then it becomes a web application.
This Tutorial will focus on how we can create Windows-based applications. We will also learn some basics on how to work with the various elements of C# Windows application.
In this Windows tutorial, you will learn-
- Windows Forms Basics
- Hello World in Windows Forms
- Adding Controls to a form
- Event Handling for Controls
- Tree and PictureBox Control
Windows Forms Basics
A Windows forms application is one that runs on the desktop computer. A Windows forms application will normally have a collection of controls such as labels, textboxes, list boxes, etc.
Below is an example of a simple Windows form application C#. It shows a simple Login screen, which is accessible by the user. The user will enter the required credentials and then will click the Login button to proceed.
So an example of the controls available in the above application
- This is a collection of label controls which are normally used to describe adjacent controls. So in our case, we have 2 textboxes, and the labels are used to tell the user that one textbox is for entering the user name and the other for the password.
- The 2 textboxes are used to hold the username and password which will be entered by the user.
- Finally, we have the button control. The button control will normally have some code attached to perform a certain set of actions. So for example in the above case, we could have the button perform an action of validating the user name and password which is entered by the user.
C# Hello World
Now let’s look at an example of how we can implement a simple ‘hello world’ application in Visual Studio. For this, we would need to implement the below-mentioned steps
Step 1) The first step involves the creation of a new project in Visual Studio. After launching Visual Studio, you need to choose the menu option New->Project.
Step 2) The next step is to choose the project type as a Windows Forms application. Here we also need to mention the name and location of our project.
- In the project dialog box, we can see various options for creating different types of projects in Visual Studio. Click the Windows option on the left-hand side.
- When we click the Windows options in the previous step, we will be able to see an option for Windows Forms Application. Click this option.
- We will give a name for the application. In our case, it is DemoApplication. We will also provide a location to store our application.
- Finally, we click the ‘OK’ button to let Visual Studio create our project.
If the above steps are followed, you will get the below output in Visual Studio.
Output:-
You will see a Form Designer displayed in Visual Studio. It’s in this Form Designer that you will start building your Windows Forms application.
In the Solution Explorer, you will also be able to see the DemoApplication Solution. This solution will contain the below 2 project files
- A Form application called Forms1.cs. This file will contain all of the code for the Windows Form application.
- The Main program called Program.cs is default code file which is created when a new application is created in Visual Studio. This code will contain the startup code for the application as a whole.
On the left-hand side of Visual Studio, you will also see a ToolBox. The toolbox contains all the controls which can be added to a Windows Forms. Controls like a text box or a label are just some of the controls which can be added to a Windows Forms.
Below is a screenshot of how the Toolbox looks like.
Step 3) In this step, we will now add a label to the Form which will display “Hello World.” From the toolbox, you will need to choose the Label control and simply drag it onto the Form.
Once you drag the label to the form, you can see the label embedded on the form as shown below.
Step 4) The next step is to go to the properties of the control and Change the text to ‘Hello World’.
To go to the properties of a control, you need to right-click the control and choose the Properties menu option
- The properties panel also shows up in Visual Studio. So for the label control, in the properties control, go to the Text section and enter “Hello World”.
- Each Control has a set of properties which describe the control.
If you follow all of the above steps and run your program in Visual Studio, you will get the following output
Output:-
In the output, you can see that the Windows Form is displayed. You can also see ‘Hello World’ is displayed on the form.
Adding Controls to a form
We had already seen how to add a control to a form when we added the label control in the earlier section to display “Hello World.”
Let’s look at the other controls available for Windows forms and see some of their common properties.
In our Windows form application in C# examples, we will create one form which will have the following functionality.
- The ability for the user to enter name and address.
- An option to choose the city in which the user resides in
- The ability for the user to enter an option for the gender.
- An option to choose a course which the user wants to learn. There will make choices for both C# and ASP.Net
So let’s look at each control in detail and add them to build the form with the above-mentioned functionality.
Group Box
A group box is used for logical grouping controls into a section. Let’s take an example if you had a collection of controls for entering details such as name and address of a person. Ideally, these are details of a person, so you would want to have these details in a separate section on the Form. For this purpose, you can have a group box. Let’s see how we can implement this with an example shown below
Step 1) The first step is to drag the Groupbox control onto the Windows Form from the toolbox as shown below
Step 2) Once the groupbox has been added, go to the properties window by clicking on the groupbox control. In the properties window, go to the Text property and change it to “User Details”.
Once you make the above changes, you will see the following output
Output:-
In the output, you can clearly see that the Groupbox was added to the form. You can also see that the text of the groupbox was changed to “User Details.”
Label Control
Next comes the Label Control. The label control is used to display a text or a message to the user on the form. The label control is normally used along with other controls. Common examples are wherein a label is added along with the textbox control.
The label indicates to the user on what is expected to fill up in the textbox. Let’s see how we can implement this with an example shown below. We will add 2 labels, one which will be called ‘name’ and the other called ‘address.’ They will be used in conjunction with the textbox controls which will be added in the later section.
Step 1) The first step is to drag the label control on to the Windows Form from the toolbox as shown below. Make sure you drag the label control 2 times so that you can have one for the ‘name’ and the other for the ‘address’.
Step 2) Once the label has been added, go to the properties window by clicking on the label control. In the properties window, go to the Text property of each label control.
Once you make the above changes, you will see the following output
Output:-
You can see the label controls added to the form.
Textbox
A textbox is used for allowing a user to enter some text on the Windows application in C#. Let’s see how we can implement this with an example shown below. We will add 2 textboxes to the form, one for the Name and the other for the address to be entered for the user
Step 1) The first step is to drag the textbox control onto the Windows Form from the toolbox as shown below
Step 2) Once the text boxes have been added, go to the properties window by clicking on the textbox control. In the properties window, go to the Name property and add a meaningful name to each textbox. For example, name the textbox for the user as txtName and that for the address as txtAddress. A naming convention and standard should be made for controls because it becomes easier to add extra functionality to these controls, which we will see later on.
Once you make the above changes, you will see the following output
Output:-
In the output, you can clearly see that the Textboxes was added to the form.
List box
A Listbox is used to showcase a list of items on the Windows form. Let’s see how we can implement this with an example shown below. We will add a list box to the form to store some city locations.
Step 1) The first step is to drag the list box control onto the Windows Form from the toolbox as shown below
Step 2) Once the list box has been added, go to the properties window by clicking on the list box control.
- First, change the property of the Listbox box control, in our case, we have changed this to lstCity
- Click on the Items property. This will allow you to add different items which can show up in the list box. In our case, we have selected items “collection”.
- In the String Collection Editor, which pops up, enter the city names. In our case, we have entered “Mumbai”, “Bangalore” and “Hyderabad”.
- Finally, click on the ‘OK’ button.
Once you make the above changes, you will see the following output
Output:-
In the output, you can see that the Listbox was added to the form. You can also see that the list box has been populated with the city values.
RadioButton
A Radiobutton is used to showcase a list of items out of which the user can choose one. Let’s see how we can implement this with an example shown below. We will add a radio button for a male/female option.
Step 1) The first step is to drag the ‘radiobutton’ control onto the Windows Form from the toolbox as shown below.
Step 2) Once the Radiobutton has been added, go to the properties window by clicking on the Radiobutton control.
- First, you need to change the text property of both Radio controls. Go the properties windows and change the text to a male of one radiobutton and the text of the other to female.
- Similarly, change the name property of both Radio controls. Go the properties windows and change the name to ‘rdMale’ of one radiobutton and to ‘rdfemale’ for the other one.
One you make the above changes, you will see the following output
Output:-
You will see the Radio buttons added to the Windows form.
Checkbox
A checkbox is used to provide a list of options in which the user can choose multiple choices. Let’s see how we can implement this with an example shown below. We will add 2 checkboxes to our Windows forms. These checkboxes will provide an option to the user on whether they want to learn C# or ASP.Net.
Step 1) The first step is to drag the checkbox control onto the Windows Form from the toolbox as shown below
Step 2) Once the checkbox has been added, go to the properties window by clicking on the Checkbox control.
In the properties window,
- First, you need to change the text property of both checkbox controls. Go the properties windows and change the text to C# and ASP.Net.
- Similarly, change the name property of both Radio controls. Go the properties windows and change the name to chkC of one checkbox and to chkASP for the other one.
Once you make the above changes, you will see the following output
Output:-
Button
A button is used to allow the user to click on a button which would then start the processing of the form. Let’s see how we can implement this with an example shown below. We will add a simple button called ‘Submit’ which will be used to submit all the information on the form.
Step 1) The first step is to drag the button control onto the Windows Form from the toolbox as shown below
Step 2) Once the Button has been added, go to the properties window by clicking on the Button control.
- First, you need to change the text property of the button control. Go the properties windows and change the text to ‘submit’.
- Similarly, change the name property of the control. Go the properties windows and change the name to ‘btnSubmit’.
Once you make the above changes, you will see the following output
Output:-
Congrats, you now have your first basic Windows Form in place. Let’s now go to the next topic to see how we can do Event handling for Controls.
C# Event Handling for Controls
When working with windows form, you can add events to controls. An event is something that happens when an action is performed. Probably the most common action is the clicking of a button on a form. In C# Windows Forms, you can add code which can be used to perform certain actions when a button is pressed on the form.
Normally when a button is pressed on a form, it means that some processing should take place.
Let’s take a look at one of the event and how it can be handled before we go to the button event scenario.
The below example will showcase an event for the Listbox control. So whenever an item is selected in the listbox control, a message box should pop up which shows the item selected. Let’s perform the following steps to achieve this.
Step 1) Double click on the Listbox in the form designer. By doing this, Visual Studio will automatically open up the code file for the form. And it will automatically add an event method to the code. This event method will be triggered, whenever any item in the listbox is selected.
Above is the snippet of code which is automatically added by Visual Studio, when you double-click the List box control on the form. Now let’s add the below section of code to this snippet of code, to add the required functionality to the listbox event.
- This is the event handler method which is automatically created by Visual Studio when you double-click the List box control. You don’t need to worry about the complexity of the method name or the parameters passed to the method.
- Here we are getting the SelectedItem through the lstCity.SelectedItem property. Remember that lstCity is the name of our Listbox control. We then use the GetItemText method to get the actual value of the selected item. We then assign this value to the text variable.
- Finally, we use the MessageBox method to display the text variable value to the user.
One you make the above changes, and run the program in Visual Studio you will see the following output
Output:-
From the output, you can see that when any item from the list box is selected, a message box will pops up. This will show the selected item from the listbox.
Now let’s look at the final control which is the button click Method. Again this follows the same philosophy. Just double click the button in the Forms Designer and it will automatically add the method for the button event handler. Then you just need to add the below code.
- This is the event handler method which is automatically created by Visual Studio when you double click the button control. You don’t need to worry on the complexity of the method name or the parameters passed to the method.
- Here we are getting values entered in the name and address textbox. The values can be taken from the text property of the textbox. We then assign the values to 2 variables, name, and address accordingly.
- Finally, we use the MessageBox method to display the name and address values to the user.
One you make the above changes, and run the program in Visual Studio you will see the following output
Output:-
- First, enter a value in the name and address field.
- Then click on the Submit button
Once you click the Submit button, a message box will pop, and it will correctly show you what you entered in the user details section.
Tree and PictureBox Control
There are 2 further controls we can look at, one is the ‘Tree Control’ and the other is the ‘Image control’. Let’s look at examples of how we can implement these controls
Tree Control
– The tree control is used to list down items in a tree like fashion. Probably the best example is when we see the Windows Explorer itself. The folder structure in Windows Explorer is like a tree-like structure.
Let’s see how we can implement this with an example shown below.
Step 1) The first step is to drag the Tree control onto the Windows Form from the toolbox as shown below
Step 2) The next step is to start adding nodes to the tree collection so that it can come up in the tree accordingly. First, let’s follow the below sub-steps to add a root node to the tree collection.
- Go to the properties toolbox for the tree view control. Click on the Node’s property. This will bring up the TreeNode Editor
- In the TreeNode Editor click on the Add Root button to add a root node to the tree collection.
- Next, change the text of the Root node and provide the text as Root and click ‘OK’ button. This will add Root node.
Step 3) The next step is to start adding the child nodes to the tree collection. Let’s follow the below sub-steps to add child root node to the tree collection.
- First, click on the Add child button. This will allow you to add child nodes to the Tree collection.
- For each child node, change the text property. Keep on repeating the previous step and this step and add 2 additional nodes. In the end, you will have 3 nodes as shown above, with the text as Label, Button, and Checkbox respectively.
- Click on the OK button
Once you have made the above changes, you will see the following output.
Output:-
You will be able to see the Tree view added to the form. When you run the Windows form application, you can expand the root node and see the child nodes in the list.
PictureBox Control
This control is used to add images to the Winforms C#. Let’s see how we can implement this with an example shown below.
Step 1) The first step is to drag the PictureBox control onto the C# Windows Form from the toolbox as shown below
Step 2) The next step is to actually attach an image to the picture box control. This can be done by following the below steps.
- First, click on the Image property for the PictureBox control. A new window will pops out.
- In this window, click on the Import button. This will be used to attach an image to the picturebox control.
- A dialog box will pop up in which you will be able to choose the image to attach the picturebox
- Click on the OK button
One you make the above changes, you will see the following output
Output:-
From the output, you can see that an image is displayed on the form.
Summary
- A Windows form in C# application is one that runs on the desktop of a computer. Visual Studio Form along with C# can be used to create a Windows Forms application.
- Controls can be added to the Windows forms C# via the Toolbox in Visual Studio. Controls such as labels, checkboxes, radio buttons, etc. can be added to the form via the toolbox.
- One can also use advanced controls like the tree view control and the PictureBox control.
- Event handlers are used to respond to events generated from controls. The most common one is the one added for the button clicked event.
На чтение 7 мин Просмотров 4.2к. Опубликовано 07.04.2022
Освойте Microsoft Visual Studio и разрабатывайте собственные приложения с помощью Windows Forms практически без написания кода.
Windows Forms — это платформа, доступная в Visual Studio, которая позволяет создавать настольные приложения с помощью графического пользовательского интерфейса. Это позволяет вам щелкать и перетаскивать виджеты, такие как кнопки или метки, прямо на холст и управлять свойствами каждого виджета, такими как размер шрифта, цвет или граница.
В этой статье простой конвертер градусов Цельсия в градусы Фаренгейта будет использоваться в качестве примера для изучения основ настройки приложения Windows Form. В этом руководстве используется Visual Studio 2019 Community Edition.
Содержание
- Как создать проект Windows Forms в Visual Studio
- Как добавить элементы на холст проекта
- Как обрабатывать события и писать код в коде программной части
- Как запускать и отлаживать программу Windows Forms
- Отладка программы Windows Forms
- Запуск программы с помощью исполняемого файла
- Добавление дополнительных элементов в форму Windows
Как создать проект Windows Forms в Visual Studio
Сначала создайте проект в Visual Studio.
- Откройте Visual Studio и выберите Создать новый проект.
- Visual Studio предоставит вам список шаблонов проектов, из которых вы можете выбрать.
- Чтобы создать приложение Windows Forms, найдите приложение Windows Formи выберите его из списка шаблонов. Как только это будет выбрано, нажмите » Далее».
- Добавьте имя и местоположение для проекта и нажмите » Далее». Расположение — это каталог, в котором будут храниться файлы кода.
- На следующем экране сохраните выбор по умолчанию.NET Core 3.1.
- Щелкните Создать.
- Когда Visual Studio завершит создание проекта, он откроется.
Как добавить элементы на холст проекта
Холст — это белая область, расположенная в верхнем левом углу экрана. Нажмите и перетащите точки в нижней, правой или нижней правой части холста, чтобы изменить его размер, если это необходимо.
Чтобы создать пользовательский интерфейс приложения, добавьте на холст такие виджеты, как кнопки или текстовые поля.
- Откройте вкладку «Вид» в верхней части окна и выберите » Панель инструментов «.
- Это добавит панель инструментов в левую часть приложения. Выберите значок булавкив правом верхнем углу панели инструментов, чтобы закрепить его там навсегда.
- Здесь вы можете перетащить любой виджет из панели инструментов на холст. Выделите кнопку на панели инструментов и перетащите ее на холст.
- Перетащите на холст еще два текстовых поля вместе с тремя метками (две метки для каждого текстового поля и одна метка для заголовка в верхней части приложения).
- Каждый виджет на холсте имеет связанные с ним свойства. Выделите виджет, чтобы отобразить окно свойствв правом нижнем углу Visual Studio, в котором перечислены все свойства этого виджета. Эти свойства могут включать текст, имя, размер шрифта, границу или выравнивание выделенного виджета.
- На данный момент текст этих виджетов по-прежнему говорит label1, label2или button1. Выберите виджет label1и отредактируйте свойство Text в окне свойств, указав «Цельсий в Фаренгейт». Измените размер шрифта на 22pt.
- Аналогичным образом отредактируйте свойства других виджетов на холсте, чтобы они были следующими:
|
Виджет |
Имущество |
Новое значение |
| метка2 | Текст | Цельсия |
| этикетка3 | Текст | по Фаренгейту |
| кнопка | Текст | Рассчитать |
| Текстовое поле Фаренгейта | Только для чтения | Истинный |
Как обрабатывать события и писать код в коде программной части
Виджеты на холсте можно привязывать к событиям. События могут включать в себя такие вещи, как нажатие кнопки, изменение текста внутри текстового поля или выбор определенного переключателя. Когда происходят эти события, это может привести к срабатыванию части кода в программном коде.
C# — это язык, используемый при создании Windows Forms. Если вы еще не использовали C#, есть много практических причин для изучения программирования на C#.
Для этого конкретного приложения добавьте событие к кнопке » Рассчитать «, чтобы инициировать выполнение части кода при нажатии этой кнопки.
1. Дважды щелкните кнопку » Рассчитать«, чтобы автоматически открыть Form1.cs с новым методом Event:
private void calculateButton_Click(object sender, EventArgs e)
2. Здесь вы добавите код, который будет выполнять расчет градусов Цельсия по Фаренгейту и отображать результат в текстовом поле Фаренгейта. Для этого вам нужно иметь возможность прочитать значение из текстового поля Цельсия и изменить текстовое поле Фаренгейта, чтобы отобразить результат.
3. Вернитесь на холст и повторно отредактируйте свойства, как показано ранее. На этот раз отредактируйте свойство Nameдля текстовых полей Цельсия и Фаренгейта. Эти имена можно использовать для ссылки на текстовые поля в коде.
| Виджет | Имущество | Новое значение |
| Текстовое поле Цельсия | Имя | ЦельсияTextBox |
| Текстовое поле Фаренгейта | Имя | по ФаренгейтуTextBox |
4. Вернитесь к функции calculateButton_Click в Form1.cs.
5. Теперь на текстовое поле Celsius можно ссылаться в коде, используя имя «celsiusTextBox». Введенное пользователем значение Цельсия сохраняется в его свойстве Text. Однако, поскольку это строка, разберите ее на двойную, чтобы включить ее в будущие расчеты по Фаренгейту.
private void calculateButton_Click(object sender, EventArgs e)
{
// Get the value that the user entered in the Celsius Text Box
double celsiusValue = Double.Parse(celsiusTextBox.Text);
}
6. Переменная celsiusValue теперь хранит значение, введенное пользователем в текстовом поле Celsius. Формула для преобразования градусов Цельсия в градусы Фаренгейта: (celsiusValue * 9 / 5) + 32.Таким образом, результат теперь можно рассчитать и сохранить в текстовом поле Фаренгейта.
private void calculateButton_Click(object sender, EventArgs e)
{
// Get the value that the user entered in the Celsius Text Box
double celsiusValue = Double.Parse(celsiusTextBox.Text);
// Apply the calculation
double result = (celsiusValue * 9 / 5) + 32;
// Store the result in the Fahrenheit Textbox
fahrenheitTextBox.Text = result.ToString();
}
Как запускать и отлаживать программу Windows Forms
Запуск программы Windows Forms в Visual Studio
Теперь, когда пользовательский интерфейс и логика кода настроены, запустите программу, чтобы увидеть, как она работает.
1. Чтобы запустить программу, выберите зеленую стрелку вверху панели инструментов в Visual Studio.
2. После загрузки проекта добавьте значение в текстовое поле Цельсия и нажмите кнопку » Рассчитать». Это добавит результат в текстовое поле по Фаренгейту.
3 Если программа размыта во время выполнения, вероятно, ваше приложение не поддерживает DPI. Это может вызвать проблемы с масштабированием и разрешением, поэтому его необходимо включить.
4. Щелкните правой кнопкой мыши проект TemperatureConverterв обозревателе решений. Выберите Добавить, затем выберите Новый элемент.
5. Найдите файл манифеста приложения и нажмите » Добавить «.
6. Скопируйте следующий код в новый файл app.manifest как дочерний элемент тега сборки (если код уже сгенерирован, просто раскомментируйте его).
<application xmlns=»urn:schemas-microsoft-com:asm.v3″>
<windowsSettings>
<dpiAware xmlns=»http://schemas.microsoft.com/SMI/2005/WindowsSettings«>true</dpiAware>
<longPathAware xmlns=»http://schemas.microsoft.com/SMI/2016/WindowsSettings«>true</longPathAware>
</windowsSettings>
</application>
7. Чтобы это изменение вступило в силу, перезапустите программу. Нажмите красную кнопку остановки в верхней части панели инструментов, затем снова нажмите зеленую кнопку воспроизведения.
Отладка программы Windows Forms
Вы можете отладить программу, если логика вашего приложения Windows Forms не работает должным образом.
- Вернитесь к функции calculateButton_Click в Form1.cs и щелкните в любом месте серой полосы в крайнем левом углу экрана. Это добавит точку останова, которая обозначена красным кружком.
- Нажмите кнопку «Рассчитать» еще раз, чтобы запустить этот метод. Программа приостановится, когда достигнет точки останова, чтобы показать все значения, хранящиеся в переменных в этой точке.
- Чтобы продолжить работу программы, нажмите зеленую стрелку » Продолжить» в верхней части панели инструментов.
Запуск программы с помощью исполняемого файла
Если вы не хотите запускать свою программу через Visual Studio, используйте автономный исполняемый файл для программы. Это автоматически генерируется.
Перейдите к исполняемому файлу, который можно найти здесь:
<your-project-folder>/bin/Debug/netcoreapp3.1/TemperatureConverter.exe
Нажмите на исполняемый файл, чтобы запустить программу напрямую.
Добавление дополнительных элементов в форму Windows
Надеюсь, теперь у вас есть общее представление об основной структуре приложения Windows Form. Вы можете продолжить изучение дополнительных функций Windows Forms, поэкспериментировав с новыми виджетами и углубившись в другие различные события, которые можно обрабатывать.
Как только вы лучше познакомитесь с Windows Forms, вы сможете приступить к созданию более сложных приложений. Вы также можете изучить многие другие способы создания приложений на рабочем столе Windows.
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
Windows Forms is a Graphical User Interface(GUI) class library which is bundled in .Net Framework. Its main purpose is to provide an easier interface to develop the applications for desktop, tablet, PCs. It is also termed as the WinForms. The applications which are developed by using Windows Forms or WinForms are known as the Windows Forms Applications that runs on the desktop computer. WinForms can be used only to develop the Windows Forms Applications not web applications. WinForms applications can contain the different type of controls like labels, list boxes, tooltip etc.
Creating a Windows Forms Application Using Visual Studio 2017
- First, open the Visual Studio then Go to File -> New -> Project to create a new project and then select the language as Visual C# from the left menu. Click on Windows Forms App(.NET Framework) in the middle of current window. After that give the project name and Click OK.
Here the solution is like a container which contains the projects and files that may be required by the program.
- After that following window will display which will be divided into three parts as follows:
- Editor Window or Main Window: Here, you will work with forms and code editing. You can notice the layout of form which is now blank. You will double click the form then it will open the code for that.
- Solution Explorer Window: It is used to navigate between all items in solution. For example, if you will select a file form this window then particular information will be display in the property window.
- Properties Window: This window is used to change the different properties of the selected item in the Solution Explorer. Also, you can change the properties of components or controls that you will add to the forms.
You can also reset the window layout by setting it to default. To set the default layout, go to Window -> Reset Window Layout in Visual Studio Menu.
- Now to add the controls to your WinForms application go to Toolbox tab present in the extreme left side of Visual Studio. Here, you can see a list of controls. To access the most commonly used controls go to Common Controls present in Toolbox tab.
- Now drag and drop the controls that you needed on created Form. For example, if you can add TextBox, ListBox, Button etc. as shown below. By clicking on the particular dropped control you can see and change its properties present in the right most corner of Visual Studio.
In the above image, you can see the TextBox is selected and its properties like TextAlign, MaxLength etc. are opened in right most corner. You can change its properties’ values as per the application need. The code of controls will be automatically added in the background. You can check the Form1.Designer.cs file present in the Solution Explorer Window.
- To run the program you can use an F5 key or Play button present in the toolbar of Visual Studio. To stop the program you can use pause button present in the ToolBar. You can also run the program by going to Debug->Start Debugging menu in the menubar.
Last Updated :
27 Jan, 2019
Like Article
Save Article





























































