Visual c windows forms applications

Введение в Windows Forms

Для создания графических интерфейсов с помощью платформы .NET применяются разные технологии — Window Forms, WPF, приложения для магазина Windows Store (для ОС Windows 8/8.1/10). Однако наиболее простой и удобной платформой до сих пор остается Window Forms или формы. Данное руководство ставит своей целью дать понимание принципов создания графических интерфейсов с помощью технологии WinForms и работы основных элементов управления.

Создание графического приложения

Для создания графического проекта нам потребуется среда разработки Visual Studio. Поскольку наиболее распространенная пока версия Visual Studio 2013, то для данного руководства я буду использовать бесплатную версию данной среды Visual Studio Community 2013 которую можно найти на странице https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx.

После установки среды и всех ее компонентов, запустим Visual Studio и создадим проект графического приложения. Для этого в меню выберем пункт File (Файл) и в подменю выберем New — > Project (Создать — > Проект). После этого перед нами откроется диалоговое окно создания нового проекта:

В левой колонке выберем Windows Desktop , а в центральной части среди типов проектов — тип Windows Forms Application и дадим ему какое-нибудь имя в поле внизу. Например, назовем его HelloApp. После этого нажимаем OK.

После этого Visual Studio откроет наш проект с созданными по умолчанию файлами:

Большую часть пространства Visual Studio занимает графический дизайнер, который содержит форму будущего приложения. Пока она пуста и имеет только заголовок Form1. Справа находится окно файлов решения/проекта — Solution Explorer (Обозреватель решений). Там и находятся все связанные с нашим приложением файлы, в том числе файлы формы Form1.cs.

Внизу справа находится окно свойств — Properties. Так как у меня в данный момент выбрана форма как элемент управления, то в этом поле отображаются свойства, связанные с формой.

Теперь найдем в этом окне свойство формы Text и изменим его значение на любое другое:

Таким образом мы поменяли заголовок формы. Теперь перенесем на поле какой-нибудь элемент управления, например, кнопку. Для этого найдем в левой части Visual Studio вкладку Toolbox (Панель инструментов) . Нажмем на эту вкладку, и у нас откроется панель с элементами, откуда мы можем с помощью мыши перенести на форму любой элемент:

Найдем среди элементов кнопку и, захватив ее указателем мыши, перенесем на форму:

Это визуальная часть. Теперь приступим к самому программированию. Добавим простейший код на языке C#, который бы выводил сообщение по нажатию кнопки. Для этого мы должны перейти в файл кода, который связан с этой формой. Если у нас не открыт файл кода, мы можем нажать на форму правой кнопкой мыши и в появившемся меню выбрать View Code (Посмотреть файл кода):

Однако воспользуемся другим способом, чтобы не писать много лишнего кода. Наведем указатель мыши на кнопку и щелкнем по ней двойным щелчком. Мы автоматически попадаем в файл кода Form1.cs, который выглядит так:

Добавим вывод сообщения по нажатию кнопки, изменив код следующим образом:

Запуск приложения

Чтобы запустить приложение в режиме отладки, нажмем на клавишу F5 или на зеленую стрелочку на панели Visual Studio. После этого запустится наша форма с одинокой кнопкой. И если мы нажмем на кнопку на форме, то нам будет отображено сообщение с приветствием.

После запуска приложения студия компилирует его в файл с расширением exe. Найти данный файл можно, зайдя в папку проекта и далее в каталог bin/Debug или bin/Release

Рассмотрев вкратце создание проекта графического приложения, мы можем перейти к обзору основных компонентов и начнем мы с форм.

Create a Windows Forms app in Visual Studio with C#

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.

If you haven’t already installed Visual Studio, go to the Visual Studio downloads page to install it for free.

Читайте также:  Антивирус для слабых компьютеров windows

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.

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 2017.

From the top menu bar, choose File > New > Project.

In the New Project dialog box in the left pane, expand Visual C#, and then choose Windows Desktop. In the middle pane, choose Windows Forms App (.NET Framework). Then name the file HelloWorld .

If you don’t see the Windows Forms App (.NET Framework) project template, cancel out of the New Project dialog box and from the top menu bar, choose Tools > Get Tools and Features. The Visual Studio Installer launches. Choose the .NET desktop development workload, then choose Modify.

Open Visual Studio 2019.

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 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.

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.

Читайте также:  Почему компьютер не воспроизводит звук windows 10

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:

Учебник. Создание нового приложения WinForms (Windows Forms .NET) Tutorial: Create a new WinForms app (Windows Forms .NET)

Из этого краткого руководства вы узнаете, как создать новое приложение Windows Forms (WinForms) с помощью Visual Studio. In this short tutorial, you’ll learn how to create a new Windows Forms (WinForms) app with Visual Studio. После создания первоначального приложения вы научитесь добавлять элементы управления и обрабатывать события. Once the initial app has been generated, you’ll learn how to add controls and how to handle events. По завершении работы с этим руководством у вас будет простое приложение, добавляющее имена в список. By the end of this tutorial, you’ll have a simple app that adds names to a list box.

Документация для Руководства по рабочему столу по .NET 5 (и .NET Core) находится в разработке. The Desktop Guide documentation for .NET 5 (and .NET Core) is under construction.

В этом руководстве описано следующее: In this tutorial, you learn how to:

  • Создание нового приложения WinForms Create a new WinForms app
  • Добавление элементов управления на форму Add controls to a form
  • Обработка событий элемента управления для предоставления функциональных возможностей приложения Handle control events to provide app functionality
  • Запустите приложение Run the app

Предварительные требования Prerequisites

  • Visual Studio 2019 версии 16.8 или более поздней Visual Studio 2019 version 16.8 or later versions
    • Выберите рабочую нагрузку «Рабочий стол Visual Studio» Select the Visual Studio Desktop workload
    • Выберите Отдельные компоненты .NET 5 Select the .NET 5 individual component

Создание приложения WinForms Create a WinForms app

Первым шагом в создании нового приложения является запуск Visual Studio и создание приложения на основе шаблона. The first step to creating a new app is opening Visual Studio and generating the app from a template.

Запустите Visual Studio. Open Visual Studio.

Выберите Создать новый проект. Select Create a new project.

В поле Поиск шаблонов введите winforms и нажмите клавишу ВВОД . In the Search for templates box, type winforms, and then press Enter .

В раскрывающемся списке язык кода выберите C# или Visual Basic. In the code language dropdown, choose C# or Visual Basic.

В списке шаблонов выберите Приложение Windows Forms (.NET) и затем щелкните Далее. In the templates list, select Windows Forms App (.NET) and then click Next.

Не выбирайте шаблон Приложение Windows Forms (.NET Framework) . Don’t select the Windows Forms App (.NET Framework) template.

В окне Настроить новый проект задайте в качестве имени проекта значение Names и щелкните Создать. In the Configure your new project window, set the Project name to Names and click Create.

Вы также можете сохранить проект в другую папку, изменив параметр Расположение. You can also save your project to a different folder by adjusting the Location setting.

После создания приложения Visual Studio должен открыть панель конструктора для формы по умолчанию Form1. Once the app is generated, Visual Studio should open the designer pane for the default form, Form1. Если конструктор форм не отображается, дважды щелкните форму в области Обозреватель решений, чтобы открыть окно конструктора. If the form designer isn’t visible, double-click on the form in the Solution Explorer pane to open the designer window.

Важные элементы среды Visual Studio Important parts of Visual Studio

Поддержка WinForms в Visual Studio состоит из четырех важных компонентов, с которыми вы будете взаимодействовать при создании приложения. Support for WinForms in Visual Studio has four important components that you’ll interact with as you create an app:

обозреватель решений Solution Explorer

Все файлы проекта, код, формы и ресурсы отображаются в этой области. All if your project files, code, forms, resources, will appear in this pane.

Properties (Свойства) Properties

На этой панели отображаются параметры свойств, которые можно настроить в зависимости от выбранного элемента. This pane shows property settings you can configure based on the item selected. Например, если выбрать элемент в Обозревателе решений, отобразятся параметры свойств, связанные с файлом. For example, if you select an item from Solution Explorer, you’ll see property settings related to the file. Если выбрать объект в конструкторе, отобразятся параметры элемента управления или формы. If you select an object in the Designer, you’ll see settings for the control or form.

Читайте также:  Windows сам закрывает приложения

Конструктор форм Form Designer

Это конструктор для формы. This is the designer for the form. Он является интерактивным, и на него можно перетаскивать объекты из панели элементов. It’s interactive and you can drag-and-drop objects from the Toolbox. Выбирая и перемещая элементы в конструкторе, можно визуально создавать пользовательский интерфейс для приложения. By selecting and moving items in the designer, you can visually compose the user interface (UI) for your app.

Панель элементов Toolbox

Панель элементов содержит все элементы управления, которые можно добавить на форму. The toolbox contains all of the controls you can add to a form. Чтобы добавить элемент управления на текущую форму, дважды щелкните элемент управления или перетащите его. To add a control to the current form, double-click a control or drag-and-drop the control.

Добавление элементов управления на форму Add controls to the form

Открыв конструктор форм Form1, используйте панель Область элементов, чтобы добавить на форму следующие элементы управления: With the Form1 form designer open, use the Toolbox pane to add the following controls to the form:

  • Метка Label
  • Кнопка Button
  • Listbox Listbox
  • Текстовое поле Textbox

Вы можете расположить и изменить размер элементов управления в соответствии со следующими настройками. You can position and size the controls according to the following settings. Либо визуально перенесите их, чтобы они соответствовали следующему снимку экрана, либо щелкните каждый элемент управления и настройте параметры в области Свойства. Either visually move them to match the screenshot that follows, or click on each control and configure the settings in the Properties pane. Можно также щелкнуть область заголовка формы, чтобы выбрать форму. You can also click on the form title area to select the form:

Объект Object Параметр Setting Значение Value
Form Form Текст Text Names
Размер Size 268, 180
Label Label Расположение Location 12, 9
Текст Text Names
Listbox Listbox Имя Name lstNames
Расположение Location 12, 27
Размер Size 120, 94
текстовое поле; Textbox Имя Name txtName
Расположение Location 138, 26
Размер Size 100, 23
Button Button Имя Name btnAdd
Расположение Location 138, 55
Размер Size 100, 23
Текст Text Add Name

Вы должны получить в конструкторе форму, которая выглядит следующим образом. You should have a form in the designer that looks similar to the following:

Обработка событий Handle events

Теперь, когда в форме есть все элементы управления, необходимо обрабатывать события элементов управления, чтобы реагировать на вводимые пользователем данные. Now that the form has all of its controls laid out, you need to handle the events of the controls to respond to user input. Открыв конструктор форм, выполните следующие действия. With the form designer still open, perform the following steps:

Выберите в форме элемент управления «Кнопка». Select the button control on the form.

В области Свойства щелкните значок события , чтобы вывести список событий кнопки.

Найдите событие Click и дважды щелкните его, чтобы создать обработчик событий. Find the Click event and double-click it to generate an event handler.

Это действие добавляет следующий код в форму: This action adds the following code to the the form:

Код, помещаемый в этот обработчик, будет добавлять имя, заданное элементом управления TextBox txtName , в элемент управления ListBox lstNames . The code we’ll put in this handler will add the name specified by the txtName textbox control to the lstNames listbox control. Однако мы хотим, чтобы имя удовлетворяло двум условиям: указанное имя не должно быть пустым, и его еще не должно быть в списке. However, we want there to be two conditions to adding the name: the name provided must not be blank, and the name must not already exist.

В следующем примере кода показано добавление имени в элемент управления lstNames . The following code demonstrates adding a name to the lstNames control:

Запустите приложение Run the app

Теперь, когда у нас есть код события, можно запустить приложение, нажав клавишу F5 или выбрав пункт меню Отладка > Начать отладку. Now that the event has been coded, you can run the app by pressing the F5 key or by selecting Debug > Start Debugging from the menu. Отобразится форма, и вы можете ввести имя в текстовое поле, а затем добавить его, нажав кнопку. The form displays and you can enter a name in the textbox and then add it by clicking the button.

Оцените статью