- Элементы управления
- Кнопка
- Оформление кнопки
- Изображение на кнопке
- Клавиши быстрого доступа
- Кнопки по умолчанию
- Create a Windows Forms app in Visual Studio with C#
- Create a project
- Create the application
- Add a button to the form
- Add a label to the form
- Add code to the form
- Run the application
- Create the application
- Add a button to the form
- Add a label to the form
- Add code to the form
- Run the application
- Next steps
Элементы управления
Элементы управления представляют собой визуальные классы, которые получают введенные пользователем данные и могут инициировать различные события. Все элементы управления наследуются от класса Control и поэтому имеют ряд общих свойств:
Anchor : Определяет, как элемент будет растягиваться
BackColor : Определяет фоновый цвет элемента
BackgroundImage : Определяет фоновое изображение элемента
ContextMenu : Контекстное меню, которое открывается при нажатии на элемент правой кнопкой мыши. Задается с помощью элемента ContextMenu
Cursor : Представляет, как будет отображаться курсор мыши при наведении на элемент
Dock : Задает расположение элемента на форме
Enabled : Определяет, будет ли доступен элемент для использования. Если это свойство имеет значение False, то элемент блокируется.
Font : Устанавливает шрифт текста для элемента
ForeColor : Определяет цвет шрифта
Location : Определяет координаты верхнего левого угла элемента управления
Name : Имя элемента управления
Size : Определяет размер элемента
Width : ширина элемента
Height : высота элемента
TabIndex : Определяет порядок обхода элемента по нажатию на клавишу Tab
Tag : Позволяет сохранять значение, ассоциированное с этим элементом управления
Кнопка
Наиболее часто используемым элементом управления является кнопка. Обрабатывая событие нажатия кнопки, мы может производить те или иные действия.
При нажатии на кнопку на форме в редакторе Visual Studio мы по умолчанию попадаем в код обработчика события Click , который будет выполняться при нажатии:
Оформление кнопки
Чтобы управлять внешним отображением кнопки, можно использовать свойство FlatStyle. Оно может принимать следующие значения:
Flat — Кнопка имеет плоский вид
Popup — Кнопка приобретает объемный вид при наведении на нее указателя, в иных случаях она имеет плоский вид
Standard — Кнопка имеет объемный вид (используется по умолчанию)
System — Вид кнопки зависит от операционной системы
Изображение на кнопке
Как и для многих элементов управления, для кнопки можно задавать изображение с помощью свойства BackgroundImage. Однако мы можем также управлять размещением текста и изображения на кнопки. Для этого надо использовать свойство TextImageRelation . Оно приобретает следующие значения:
Overlay : текст накладывается на изображение
ImageAboveText : изображение располагается над текстом
TextAboveImage : текст располагается над изображением
ImageBeforeText : изображение располагается перед текстом
TextBeforeImage : текст располагается перед изображением
Например, установим для кнопки изображение. Для этого выберем кнопку и в окне Свойств нажмем на поле Image (не путать с BackgroundImage). Нам откроется диалоговое окно установи изображения:
В этом окне выберем опцию Local Resource и нажмем на кнопку Import , после чего нам откроется диалоговое окно для выбора файла изображения.
После выбора изображения мы можем установить свойство ImageAlign , которое управляет позиционированием изображения на кнопке:
Нам доступны 9 вариантов, с помощью которых мы можем прикрепить изображение к определенной стороне кнопки. Оставим здесь значение по умолчанию — MiddleCenter , то есть позиционирование по центру.
Затем перейдем к свойству TextImageRelation и установим для него значение ImageBeforeText . В итоге мы получим кнопку, где сразу после изображения идет надпись на кнопке:
Клавиши быстрого доступа
При работе с формами при использовании клавиатуры очень удобно пользоваться клавишами быстрого доступа. При нажатии на клавиатуре комбинации клавиш At+некоторый символ, будет вызываться определенная кнопка. Например, зададим для некоторой кнопки свойство Text равное &Аватар . Первый знак — амперсанд — определяет ту букву, которая будет подчеркнута. В данном случае надпись будет выглядеть как А ватар. И теперь чтобы вызвать событие Click, нам достаточно нажать на комбинацию клавиш Alt+А.
Кнопки по умолчанию
Форма, на которой размещаются все элементы управления, имеет свойства, позволяющие назначать кнопку по умолчанию и кнопку отмены.
Так, свойство формы AcceptButton позволяет назначать кнопку по умолчанию, которая будет срабатывать по нажатию на клавишу Enter.
Аналогично работает свойство формы CancelButton , которое назначает кнопку отмены. Назначив такую кнопку, мы можем вызвать ее нажатие, нажав на клавишу Esc.
Create a Windows Forms app in Visual Studio with C#
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this short introduction to the Visual Studio integrated development environment (IDE), 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.
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.)
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.
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.)
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.
Next, in the Visual Studio Installer, select the .NET desktop development workload.
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.
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.
(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.)
Select the Pin icon to dock the Toolbox window.
Select 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, 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.
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:
Run the application
Select 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.
Select 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.
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.
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:
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.
Next steps
To learn more, continue with the following tutorial: