Windows forms application tutorial

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.

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.

Читайте также:  Mac os big sur для старых mac

(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:

Step 1: Create a Windows Forms App project

When you create a picture viewer, the first step is to create a Windows Forms App project.

Open Visual Studio 2017

On the menu bar, choose File > New > Project. The dialog box should look similar to the following screenshot.


New project dialog box

On the left side of the New Project dialog box, choose either Visual C# or Visual Basic, and then choose Windows Desktop.

In the project templates list, choose Windows Forms App (.NET Framework). Name the new form PictureViewer, and then choose the OK button.

If you don’t see the Windows Forms App (.NET Framework) template, use the Visual Studio Installer to install the .NET desktop development workload.

For more information, see the Install Visual Studio page.

Open Visual Studio 2019

On the start window, choose Create a new project.

On the Create a new project window, enter or type Windows Forms in the search box. Next, choose Desktop from the Project type list.

After you apply the Project type filter, choose the Windows Forms App (.NET Framework) template for either C# or Visual Basic, and then choose Next.

If you don’t see the Windows Forms App (.NET Framework) template, you can install it from the Create a new project window. In the Not finding what you’re looking for? message, choose the Install more tools and features link.

Читайте также:  Total war napoleon windows 10

Next, in the Visual Studio Installer, choose the Choose the .NET desktop development workload.

After that, choose the Modify button in the Visual Studio Installer. You might be prompted to save your work; if so, do so. Next, choose Continue to install the workload.

In the Configure your new project window, type or enter PictureViewer in the Project name box. Then, choose Create.

Visual Studio creates a solution for your app. A solution acts as a container for all of the projects and files needed by your app. These terms will be explained in more detail later in this tutorial.

About the Windows Forms App project

The development environment contains three windows: a main window, Solution Explorer, and the Properties window.

If any of these windows are missing, you can restore the default window layout. On the menu bar, choose Window > Reset Window Layout.

You can also display windows by using menu commands. On the menu bar, choose View > Properties Window or Solution Explorer.

If any other windows are open, close them by choosing the Close (x) button in their upper-right corners.

  • Main window In this window, you’ll do most of your work, such as working with forms and editing code. The window shows a form in the Form Editor. At the top of the window, the Start Page tab and the Form1.cs [Design] tab appear. (In Visual Basic, the tab name ends with .vb instead of .cs.)
  • Main window In this window, you’ll do most of your work, such as working with forms and editing code. The window shows a form in the Form Editor.
  • Solution Explorer window In this window, you can view and navigate to all items in your solution.

If you choose a file, the contents of the Properties window changes. If you open a code file (which ends in .cs in C# and .vb in Visual Basic), the code file or a designer for the code file appears. A designer is a visual surface onto which you can add controls such as buttons and lists. For Visual Studio forms, the designer is called the Windows Forms Designer.

Properties window In this window, you can change the properties of items that you choose in the other windows. For example, if you choose Form1, you can change its title by setting the Text property, and you can change the background color by setting the Backcolor property.

The top line in Solution Explorer shows Solution ‘PictureViewer’ (1 project), which means that Visual Studio created a solution for you. A solution can contain more than one project, but for now, you’ll work with solutions that contain only one project.

On the menu bar, choose File > Save All.

As an alternative, choose the Save All button on the toolbar, which the following image shows.

Save All toolbar button

Visual Studio automatically fills in the folder name and the project name and then saves the project in your projects folder.

Next steps

To go to the next tutorial step, see Step 2: Run your app.

To return to the overview topic, see Tutorial 1: Create a picture viewer.

Читайте также:  Хорошая антивирусная утилита для windows 10

Введение в 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

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

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