Visual studio 2022 как создать проект

от admin

Visual studio 2022 как создать проект

Чтобы облегчить написание, а также тестирование и отладку программного кода нередко используют специальные среды разработки, в частности, Visual Studio. Рассмотрим создание приложений на C# с помощью бесплатной и полнофункциональной среды Visual Studio Community 2022, которую можно загрузить по следующему адресу: Microsoft Visual Studio 2022

После загрузки запустим программу установщика. В открывшемся окне нам будет предложено выбрать те компоненты, которые мы хотим установить вместе Visual Studio. Стоит отметить, что Visual Studio — очень функциональная среда разработки и позволяет разрабатывать приложения с помощью множества языков и платформ. В нашем случае нам будет интересовать прежде всего C# и .NET.

Чтобы добавить в Visual Studio поддержку проектов для C# и .NET 7, в программе установки среди рабочих нагрузок можно выбрать только пункт ASP.NET и разработка веб-приложений . Можно выбрать и больше опций или вообще все опции, однако стоит учитывать свободный размер на жестком диске — чем больше опций будет выбрано, соответственно тем больше места на диске будет занято.

Установка Visual Studio 2022

И при инсталляции Visual Studio на ваш компьютер будут установлены все необходимые инструменты для разработки программ, в том числе фреймворк .NET 7.

После завершения установки создадим первую программу. Она будет простенькой. Вначале откроем Visual Studio. На стартовом экране выберем Create a new project (Создать новый проект)

Создание первого проекта в Visual Studio 2022

На следующем окне в качестве типа проекта выберем Console App , то есть мы будем создавать консольное приложение на языке C#

Проект консольного приложения на C# и .NET 7 в Visual Studio 2022

Чтобы проще было найти нужный тип проекта, в поле языков можно выбрать C# , а в поле типа проектов — Console .

Далее на следующем этапе нам будет предложено указать имя проекта и каталог, где будет располагаться проект.

Создание первого приложения на C#

В поле Project Name дадим проекту какое-либо название. В моем случае это HelloApp .

На следующем окне Visual Studio предложит нам выбрать версию .NET, которая будет использоваться для проекта. Выберем последнюю на данный момент верси. — .NET 7.0:

Установка C# 11 и .NET 7 в Visual Studio

Нажмен на кнопку Create (Создать) для создания проекта, и после этого Visual Studio создаст и откроет нам проект:

Первый проект на C#

В большом поле в центре, которое по сути представляет текстовый редактор, находится сгенерированный по умолчанию код C#. Впоследствии мы изменим его на свой.

Справа находится окно Solution Explorer, в котором можно увидеть структуру нашего проекта. В данном случае у нас сгенерированная по умолчанию структура: узел Dependencies — это узел содержит сборки dll, которые добавлены в проект по умолчанию. Эти сборки как раз содержат классы библиотеки .NET, которые будет использовать C#. Однако не всегда все сборки нужны. Ненужные потом можно удалить, в то же время если понадобится добавить какую-нибудь нужную библиотеку, то именно в этот узел она будет добавляться.

Далее идет непосредственно сам файл кода программы Program.cs , который по умолчанию открыт в центральном окне и который имеет всего две строки:

Первая строка предваряется символами // и представляет комментарии — пояснения к коду.

Вторая строка собственно представляет собой код программы: Console.WriteLine(«Hello World!»); . Эта строка выводит на консоль строку «Hello World!».

Несмотря на то, что программа содержит только одну строку кода, это уже некоторая программа, которую мы можем запустить. Запустить проект мы можем с помощью клавиши F5 или с панели инструментов, нажав на зеленую стрелку. И если вы все сделали правильно, то при запуске приложения на консоль будет выведена строка «Hello World!».

Первое приложение на C# и .NET 7

Теперь изменим весь этот код на следующий:

По сравнению с автоматически сгенерированным кодом я внес несколько изменений. Теперь первой строкой выводится приглашение к вводу.

Метод Console.Write() выводит на консоль некоторую строка. В данном случае это строка «Введите свое имя: «.

На второй строке определяется строковая переменная name, в которую пользователь вводит информацию с консоли:

Ключевое слово var указывает на определение переменной. В данном случае переменная называется name . И ей присваивается результат метода Console.ReadLine() , который позволяет считать с консоли введенную строку. То есть мы введем в консоли строку (точнее имя), и эта строка окажется в переменой name .

Затем введенное имя выводится на консоль:

Чтобы ввести значение переменной name внутрь выводимой на консоль строки, применяются фигурные скобки <>. То есть при выводе строки на консоль выражение будет заменяться на значение переменной name — введенное имя.

Однако чтобы можно было вводить таким образом значения переменных внутрь строки, перед строкой указывается знак доллара $.

Теперь протестируем проект, запустив его на выполнение, также нажав на F5 или зеленую стрелочку.

Первая программа на C#

Скомпилированное приложение можно найти в папке проекта в каталоге bin\Debug\net7.0 . Оно будет называться по имени проекта и иметь расширение exe. И затем этот файл можно будет запускать без Visual Studio, а также переносить его на другие компьютеры, где установлен .NET 7.

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)

Buchcover C++ mit Visual Studio 2019 und Windows Forms Anwendungen

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:

Configure Project

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:

  1. 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).
  2. You write in C++ the instructions that should be done in response to user input (non-visual programming).
  3. 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)

Buchcover C++ mit Visual Studio 2019 und Windows Forms Anwendungen

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.

Visual studio 2022 как создать проект

Чтобы облегчить написание, а также тестирование и отладку программного кода нередко используют специальные среды разработки, в частности, Visual Studio. Рассмотрим создание приложений на C# с помощью бесплатной и полнофункциональной среды Visual Studio Community 2022, которую можно загрузить по следующему адресу: Microsoft Visual Studio 2022

Установка Visual Studio 2022

После загрузки запустим программу установщика. В открывшемся окне нам будет предложено выбрать те компоненты, которые мы хотим установить вместе Visual Studio. Стоит отметить, что Visual Studio — очень функциональная среда разработки и позволяет разрабатывать приложения с помощью множества языков и платформ. В нашем случае нам будет интересовать прежде всего C# и .NET.

Чтобы добавить в Visual Studio поддержку проектов для C# и .NET 7, в программе установки среди рабочих нагрузок можно выбрать только пункт ASP.NET и разработка веб-приложений . Можно выбрать и больше опций или вообще все опции, однако стоит учитывать свободный размер на жестком диске — чем больше опций будет выбрано, соответственно тем больше места на диске будет занято.

Установка Visual Studio 2022

И при инсталляции Visual Studio на ваш компьютер будут установлены все необходимые инструменты для разработки программ, в том числе фреймворк .NET 7.

После завершения установки создадим первую программу. Она будет простенькой. Вначале откроем Visual Studio. На стартовом экране выберем Create a new project (Создать новый проект)

Создание первого проекта в Visual Studio 2022

На следующем окне в качестве типа проекта выберем Console App , то есть мы будем создавать консольное приложение на языке C#

Проект консольного приложения на C# и .NET 7 в Visual Studio 2022

Чтобы проще было найти нужный тип проекта, в поле языков можно выбрать C# , а в поле типа проектов — Console .

Далее на следующем этапе нам будет предложено указать имя проекта и каталог, где будет располагаться проект.

Создание первого приложения на C#

В поле Project Name дадим проекту какое-либо название. В моем случае это HelloApp .

На следующем окне Visual Studio предложит нам выбрать версию .NET, которая будет использоваться для проекта. Выберем последнюю на данный момент верси. — .NET 7.0:

Установка C# 11 и .NET 7 в Visual Studio

Нажмен на кнопку Create (Создать) для создания проекта, и после этого Visual Studio создаст и откроет нам проект:

Первый проект на C#

В большом поле в центре, которое по сути представляет текстовый редактор, находится сгенерированный по умолчанию код C#. Впоследствии мы изменим его на свой.

Справа находится окно Solution Explorer, в котором можно увидеть структуру нашего проекта. В данном случае у нас сгенерированная по умолчанию структура: узел Dependencies — это узел содержит сборки dll, которые добавлены в проект по умолчанию. Эти сборки как раз содержат классы библиотеки .NET, которые будет использовать C#. Однако не всегда все сборки нужны. Ненужные потом можно удалить, в то же время если понадобится добавить какую-нибудь нужную библиотеку, то именно в этот узел она будет добавляться.

Далее идет непосредственно сам файл кода программы Program.cs , который по умолчанию открыт в центральном окне и который имеет всего две строки:

Первая строка предваряется символами // и представляет комментарии — пояснения к коду.

Вторая строка собственно представляет собой код программы: Console.WriteLine(«Hello World!»); . Эта строка выводит на консоль строку «Hello World!».

Несмотря на то, что программа содержит только одну строку кода, это уже некоторая программа, которую мы можем запустить. Запустить проект мы можем с помощью клавиши F5 или с панели инструментов, нажав на зеленую стрелку. И если вы все сделали правильно, то при запуске приложения на консоль будет выведена строка «Hello World!».

Первое приложение на C# и .NET 7

Теперь изменим весь этот код на следующий:

По сравнению с автоматически сгенерированным кодом я внес несколько изменений. Теперь первой строкой выводится приглашение к вводу.

Метод Console.Write() выводит на консоль некоторую строка. В данном случае это строка «Введите свое имя: «.

На второй строке определяется строковая переменная name, в которую пользователь вводит информацию с консоли:

Ключевое слово var указывает на определение переменной. В данном случае переменная называется name . И ей присваивается результат метода Console.ReadLine() , который позволяет считать с консоли введенную строку. То есть мы введем в консоли строку (точнее имя), и эта строка окажется в переменой name .

Затем введенное имя выводится на консоль:

Чтобы ввести значение переменной name внутрь выводимой на консоль строки, применяются фигурные скобки <>. То есть при выводе строки на консоль выражение будет заменяться на значение переменной name — введенное имя.

Однако чтобы можно было вводить таким образом значения переменных внутрь строки, перед строкой указывается знак доллара $.

Теперь протестируем проект, запустив его на выполнение, также нажав на F5 или зеленую стрелочку.

Первая программа на C#

Скомпилированное приложение можно найти в папке проекта в каталоге bin\Debug\net7.0 . Оно будет называться по имени проекта и иметь расширение exe. И затем этот файл можно будет запускать без Visual Studio, а также переносить его на другие компьютеры, где установлен .NET 7.

Hello World C# | Первое приложение в Visual Studio

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

Перед началом данного урока рекомендую ознакомиться с предыдущим Преимущества и недостатки C#

Как работает компьютер

В начале мне хочется немного поговорить о том, как вообще работает компьютер, потому что это очень важно для понимания того, чем на самом деле мы занимаемся. Любой компьютер, насколько бы он ни был крутой, по сути является просто калькулятором на стеройдах. Он манипулирует двоичными данными 0 и 1, в которые закодирована используемая нами информация, и если очень утрировано может выполнять всего лишь несколько операций:

  • Записать значения в память
  • Прочитать значение из памяти
  • Выполнить операции сложения, умножения, отрицания

И именно так он на самом деле и работает – обрабатывает миллиарды единиц информации каждую секунду, чтобы ты мог погонять в дотку или порнушку посмотреть. Вот такая у компьютера незавидная участь, поэтому не обижай его, заботься о нем. Вот когда ты последний раз чистил его от пыли? А?

Опять работать?Как себя чувствует твой компьютер, когда ты запускаешь Visual Studio…

Так вот, по своей сути, любой компьютер — это очень примитивная машина, не способная воспринимать информацию в ни в каком другом формате, как в двоичном коде. К сожалению, мы люди не слишком часто используем бинарный код в повседневной жизни, и поэтому были придуманы языки программирования. Они являются промежуточной ступенью, адаптером, между человеком и машиной.

Что такое языки программирования

По своей сути, языки программирования — это более строго форматизированные человеческие языки (чаще всего английский). То есть, мы должны выражать свои мысли на бумаге (ну точнее на экране), так, как если бы мы писали письмо человеку, но при этом очень строго следуя правилам написания заданных регламентом. Именно к такому формату написания кода и нужно стремиться, чтобы твой код читался как книга.

И затем, написанный тобой текст по заданным правилам будет преобразован в машинные команды (язык ассемблер), которые уже могут восприниматься компьютером, ну и наконец начнется работа над нулями и единицами до тех пор, пока ни будет получен какой-либо результат.

Изначально программистам приходилось реализовывать свои мысли на языках низкого уровня. Это означает, что эти языки наиболее понятны компьютерам, но намного хуже воспринимаются людьми. Сейчас мы живем в эпоху языков высокого уровня, которые намного больше похожи на обычный текст и легко могут быть поняты даже человеком вообще ничего не понимающим в программировании (если, конечно, код написан не через жопу).

Золотые руки из жопыГерб большинства программистов

Инструмент создания приложений IDE

Таким образом, мы пришли к тому, что необходимы определенные инструменты, которые позволяют преобразовывать написанный текст на языке высокого уровня в машинные коды, которые будут понятны компьютеру. Такие приложения называются компиляторами. Но сейчас намного большей популярностью пользуются другие приложения, которые по сути являются основным инструментом современного программиста – это интегрированная среда разработки (Integrated Development Environment) IDE. По сути, это компилятор на стероидах. Это приложение, а иногда и набор инструментов, которые позволяют преобразовать исходный код, написанный программистом в готовое приложение, но содержащее в себе еще вагон и маленькую тележку дополнительных приблуд, которые делают жизнь программиста чуточку проще. Это и всевозможные статические анализаторы кода, которые находят ошибки еще до запуска приложения, а также указывают на так называемый код с душком. Это и системы тестирования, анализа и статистики по коду, инструменты для быстрого рефакторинга и выгрузки документации по коду. Короче, целая куча крутых фишек, которыми никто не пользуется.

Visual Studio

Так вот, основным инструментом C# программиста является интегрированная среда разработки Visual Studio 2017 на данный момент. Скачать ее можно по ссылке https://visualstudio.microsoft.com/ru/ Существует 3 основные версии

  • Community
  • Professional
  • Enterprise

Разница между ними только в количестве всех вот этих наворотов и цене. На начальном этапе я всем рекомендую использовать Community версию, которая является бесплатной с небольшими ограничениями:

— Visual Studio Community может использовать неограниченное число пользователей в учебных аудиториях, для научных исследований или участия в проектах с открытым кодом.

— Для всех прочих сценариев использования: в некорпоративных организациях Visual Studio Community может использовать до 5 пользователей. В корпоративных организациях (в которых используется > 250 ПК или годовой доход которых > 1 млн долларов США) использование запрещено.

Таким образом, пока ты зарабатываешь меньше 1 млн долларов в год, ив твоей команде меньше 5 человек, можешь разрабатывать любое ПО в том числе и коммерческое.

Сейчас установка, обновление и изменение компонентов Visual Studio стало достаточно приятных и простым занятием, хотя раньше приносило достаточно много головной боли. Просто скачивай специальное приложение-установщик на свой компьютер и запускай установку. После скачивания необходимых компонентов, откроется окно выбора того, что тебе нужно установить.

Выбираем самые важные компоненты Visual StudioВыбираем самые важные компоненты для установки

Так как разработка на C# подразумевает универсальные приложения под любые платформы, то предоставляется over9000 компонентов, которые в большинстве своем совершенно тебе не нужны на данном этапе. Сейчас я покажу тебе необходимый минимум, а также мою рекомендуемую коллекцию компонентов.

  • Разработка классических приложений .NET — обязательно
  • ASP.NET и разработка веб-приложений
  • Кроссплатформенная разработка .NET Core

Самые нужные расширения для Visual Studio

После установки Вижуалки также очень рекомендую тебе установить несколько расширений, которые очень сильно помогут тебе работать в дальнейшем.

Для этого открываем меню Средства => Расширения и обновления

Расширения и обновления Visual StudioГде найти расширения Visual Studio

Выбрать В сети и в строке поиска ввести названия необходимых расширений

Устанавливаем нужные расширения для Visual StudioИнтерфейс установки расширений Visual Studio

ReSharper – суперкрутой статический анализатор кода. Может практически все, но некоторым (в том числе мне) не нравится, потому что бесит, и является платным. Но в целом очень полезен.

Web Essentials – mast have для веб программистов. Позволяет весьма упростить и ускорить процесс работы в интерфейсной частью приложения, упрощает и ускоряет верстку, но в других случаях он не нужен.

Productivity Power Tools 2017/2019 – целый набор небольших расширения, позволяющих сделать процесс написания кода комфортнее, код чище и красивее. Настоятельно рекомендую устанавливать каждому.

GitHub Extension for Visual Studio – очень удобное взаимодействие с популярным сервисом хранения кода и системой контроля версий. Каждому программисту нужно научиться и постоянно использовать любую подходящую систему контроля версий. А это расширение позволит форкать проекты и выполнять коммиты в пару кликов.

Visual Studio Spell Checker — позволяет избавиться от таких досадных ошибок, как опечатки в коде. Работает примерно как в ворде — подчеркивает красным не правильные слова. При этом он понимает различные нотации и без проблем понимает, что написанные слитно слова, но с заглавными буквами это не ошибка.

Важной функцией Visual Studio является встроенный помощник IntelliSense, который позволяет очень удобно обозревать классы, дополнять названия, показывать подсказки по улучшению кода. Обязательно научись им пользоваться и прислушивайся к его советам.

Создадим Hello World проект на C#

Создаем новый проект Visual StudioСоздаем новый проект

Открываем среду разработки Visual Studio и заходим в меню Файл => Создать => Проект

После этого выбираем Visual C# => Классическое приложение для Windows => Консольное приложение (.NET Framework), вводим имя проекта, указываем его расположение на диске и нажмем ОК.

Выбираем тип проекта Visual StudioВыбираем тип проекта — Консольное приложение

В открывшимся окне вводим следующий код приложения

После чего запускаем приложение, нажав сочетание клавишь Ctrl+F5 или зеленую клавишу Пуск и получаем следующий результат

Hello World C#Ваше первое приложение на C#

Поздравляю, вы создали свое первое приложение!

Подробно, весь процесс установки и настройки Visual Studio, а также создание первого приложения рассмотрен на моем видеоуроке.

Кроме того, рекомендую прочитать статью Объектно-ориентированное программирование C#. А также подписывайтесь на группу ВКонтакте, Telegram и YouTube-канал. Там еще больше полезного и интересного для программистов.

Get Started on Visual Studio 2022

This getting started will guide you through the creation of an Uno Platform App using C# and .NET, based in the WinUI 3 XAML.

This guide covers development on Windows using Visual Studio. If you want to use another environment or IDE, see our general getting started.

Important

To use Xamarin (as opposed to .NET 6 Mobile) with Visual Studio 2019, follow this guide.

Prerequisites

To create Uno Platform applications you will need Visual Studio 2022 17.3 or later:

ASP.NET and web workload installed, along with .NET 6.0 (for WebAssembly development)

visual-studio-installer-web

.NET Multi-platform App UI development workload installed.

visual-studio-installer-dotnet-mobile

.NET desktop development workload installed.

visual-studio-installer-dotnet

Universal Windows Platform workload installed.

visual-studio-installer-uwp

Important

To build Xamarin-based projects in Visual Studio 2022, in Visual Studio’s installer Individual components tab, search for Xamarin and select Xamarin and Xamarin Remoted Simulator . See this section on migrating Xamarin projects to .NET 6.

For information about connecting Visual Studio to a Mac build host to build iOS apps, see Pairing to a Mac for Xamarin.iOS development.

Important

To build .NET 7 projects, you will need to install Visual Studio 17.4 Preview 5 or later.

Finalize your environment

Open a command-line prompt, Windows Terminal if you have it installed, or else Command Prompt or Windows Powershell from the Start menu.

a. Install the tool by running the following command from the command prompt:

b. To update the tool, if you already have an existing one:

Run the tool from the command prompt with the following command:

Follow the instructions indicated by the tool

To build .NET 7 apps, you will need to run uno-check —pre .

You can find additional information about uno-check here.

Install the Solution Templates

Launch Visual Studio 2022, then click Continue without code . Click Extensions -> Manage Extensions from the Menu Bar.

In the Extension Manager expand the Online node and search for Uno , install the Uno Platform Solution Templates extension or download it from the Visual Studio Marketplace, then restart Visual Studio.

Create an application

To create an Uno Platform app:

Create a new C# solution using the Uno Platform App template, from Visual Studio’s Start Page

Choose the list of targets platforms you want to be generated

If you do not select platforms, you still can add them later.

visual-studio-installer-web

Wait for the projects to be created, and their dependencies to be restored

To debug the Windows head:

  • Right click on the MyApp.Windows project, select Set as startup project
  • Select the Debug|x86 configuration
  • Press the MyApp.Windows button to deploy the app
  • If you’ve not enabled Developer Mode, the Settings app should open to the appropriate page. Turn on Developer Mode and accept the disclaimer.

To run the WebAssembly (Wasm) head:

  • Right click on the MyApp.Wasm project, select Set as startup project
  • Press the MyApp.Wasm button to deploy the app

To run the ASP.NET Hosted WebAssembly (Server) head:

  • Right click on the MyApp.Server project, select Set as startup project
  • Press the MyApp.Server button to deploy the app

To debug for iOS:

Right click on the MyApp.Mobile project, select Set as startup project

In the "Debug toolbar" drop down, select framework net6.0-ios :

visual-studio-installer-web

Select an active device

To debug the Android platform:

  • Right click on the MyApp.Mobile project, select Set as startup project
  • In the Debug toolbar drop down, select framework net6.0-android
  • Select an active device in "Device" sub-menu

You’re all set! You can now head to our tutorials on how to work on your Uno Platform app.

Debugging either the macOS and macCatalyst targets is not supported from Visual Studio on Windows.

Troubleshooting Installation Issues

You may encounter installation and/or post-installation Visual Studio issues for which workarounds exist. Please see Common Issues we have documented.

Getting Help

If you continue experiencing issues with Uno Platform, please visit our GitHub Discussions or Discord — #uno-platform channel where our engineering team and community will be able to help you.

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)

Buchcover C++ mit Visual Studio 2019 und Windows Forms Anwendungen

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:

Configure Project

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 „ “ 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:

  1. 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).
  2. You write in C++ the instructions that should be done in response to user input (non-visual programming).
  3. 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 for the first value after the string, 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)

Buchcover C++ mit Visual Studio 2019 und Windows Forms Anwendungen

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.

Name already in use

cpp-docs / docs / windows / walkthrough-deploying-a-visual-cpp-application-by-using-a-setup-project.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Walkthrough: Deploy a Visual C++ application by using a setup project

In this walkthrough, you’ll create a sample app in Visual Studio, then create a setup project to deploy your app to another computer.

Instructions for creating a new project vary depending on which version of Visual Studio you’ve installed. To see the documentation for your preferred version of Visual Studio, use the Version selector control. It’s found at the top of the table of contents on this page.

You need the following components to complete this walkthrough:

A computer with Visual Studio 2022 installed. The installation must include the Desktop development with C++ workload, and the C++ MFC for latest v143 build tools (x86 & x64) optional component.

The Microsoft Visual Studio Installer Projects extension. The extension is free for Visual Studio developers and adds the functionality of the setup and deployment project templates to Visual Studio.

To test your deployment, another computer that doesn’t have the Visual C++ libraries installed.

To install C++ and MFC in Visual Studio 2022

If you have Visual Studio installed, but you don’t have the C++ or MFC components installed, you can add them now.

Launch the Visual Studio Installer program from the Windows Start menu.

In Visual Studio Installer, choose the Modify button next to your installed version of Visual Studio.

In the Modifying dialog, under the Workloads tab, scroll down to the Desktop Development with C++ tile. If the tile checkbox isn’t checked, check the checkbox.

To the side of the dialog under Installation details, expand the Desktop Development with C++ node, then expand the Optional node. If it isn’t already checked, add a check to the C++ MFC for latest v143 build tools (x86 & x64) component.

Choose the Modify button to modify your Visual Studio installation. When installation completes, exit the Visual Studio installer.

To install the Installer Projects extension

In Visual Studio, select the Extensions > Manage Extensions menu item.

In the Manage Extensions dialog, expand Online > Visual Studio Marketplace > Tools and select Setup & Deployment.

The Manage Extensions dialog showing the Visual Studio setup project extension.

In the list of extensions, select Microsoft Visual Studio Installer Projects 2022. Choose the Download button.

A notification appears at the bottom of the dialog that tells you the modification will begin when all Microsoft Visual Studio windows are closed. Close the dialog.

Close Visual Studio. The download and install process begins. You may need to accept a User Account Control elevation prompt to allow the installer to change Visual Studio.

In the VSIX Installer dialog, choose Modify to install the extension. When the modifications complete, choose Close to dismiss the dialog.

A computer with Visual Studio 2019 installed. The installation must include the Desktop development with C++ workload, and the C++ MFC for latest v142 build tools (x86 & x64) optional component.

The Microsoft Visual Studio Installer Projects extension. The extension is free for Visual Studio developers and adds the functionality of the setup and deployment project templates to Visual Studio.

To test your deployment, another computer that doesn’t have the Visual C++ libraries installed.

To install C++ and MFC in Visual Studio 2019

If you have Visual Studio installed, but you don’t have the C++ or MFC components installed, you can add them now.

Launch the Visual Studio Installer program from the Windows Start menu.

In Visual Studio Installer, choose the Modify button next to your installed version of Visual Studio.

In the Modifying dialog, under the Workloads tab, scroll down to the Desktop Development with C++ tile. If the tile checkbox isn’t checked, check the checkbox.

To the side of the dialog under Installation details, expand the Desktop Development with C++ node, then expand the Optional node. If it isn’t already checked, add a check to the C++ MFC for latest v142 build tools (x86 & x64) component.

Choose the Modify button to modify your Visual Studio installation. When installation completes, exit the Visual Studio installer.

To install the Installer Projects extension

In Visual Studio, select the Extensions > Manage Extensions menu item.

In the Manage Extensions dialog, expand Online > Visual Studio Marketplace > Tools and select Setup & Deployment.

The Manage Extensions dialog showing the Visual Studio setup project extension.

In the list of extensions, select Microsoft Visual Studio Installer Projects. Choose the Download button.

A notification appears at the bottom of the dialog that tells you the modification will begin when all Microsoft Visual Studio windows are closed. Close the dialog.

Close Visual Studio. The download and install process begins. You may need to accept a User Account Control elevation prompt to allow the installer to change Visual Studio.

In the VSIX Installer dialog, choose Modify to install the extension. When the modifications complete, choose Close to dismiss the dialog.

A computer with Visual Studio 2017 installed. The installation must include the Desktop development with C++ workload, and the Visual C++ MFC for x86 and x64 optional component.

The Microsoft Visual Studio Installer Projects extension. The extension is free for Visual Studio developers and adds the functionality of the setup and deployment project templates to Visual Studio.

To test your deployment, another computer that doesn’t have the Visual C++ libraries installed.

To install C++ and MFC in Visual Studio 2017

If you have Visual Studio 2017 installed, but you don’t have the C++ or MFC components installed, you can add them now.

Launch the Visual Studio Installer program from the Windows Start menu.

In Visual Studio Installer, choose the Modify button next to your installed version of Visual Studio 2017.

In the Modifying dialog, under the Workloads tab, scroll down to the Desktop Development with C++ tile. If the tile checkbox isn’t checked, check the checkbox.

To the side of the dialog under Installation details, expand the Desktop Development with C++ node, then expand the Optional node. If it isn’t already checked, add a check to the Visual C++ MFC for x86 and x64 component.

Choose the Modify button to modify your Visual Studio installation. When installation completes, exit the Visual Studio installer.

To install the Installer Projects extension

In Visual Studio, select the Tools > Extensions and Updates menu item.

In the Extensions and Updates dialog, expand Online > Visual Studio Marketplace > Tools and select Setup & Deployment. Set the Sort by dropdown to Most Downloads.

The Manage Extensions dialog showing the Visual Studio setup project extension.

In the list of extensions, select Microsoft Visual Studio Installer Projects. Choose the Download button.

A notification appears at the bottom of the dialog that tells you the modification will begin when all Microsoft Visual Studio windows are closed. Close the dialog.

Close Visual Studio. The download and install process begins. You may need to accept a User Account Control elevation prompt to allow the installer to change Visual Studio.

In the VSIX Installer dialog, choose Modify to install the extension. When the modifications complete, choose Close to dismiss the dialog.

A computer with Visual Studio installed. The installation must include the Visual C++ programming language tools, and the Microsoft Foundation Classes for C++ optional component.

The Microsoft Visual Studio Installer Projects extension. The extension is free for Visual Studio developers and adds the functionality of the setup and deployment project templates to Visual Studio.

To test your deployment, another computer that doesn’t have the Visual C++ libraries installed.

To install C++ and MFC in Visual Studio 2015

The Visual Studio 2015 setup program doesn’t install Visual C++ and MFC by default. If you have Visual Studio 2015 installed, but you don’t have the C++ or MFC components installed, you can add them now.

Open the Windows Start menu and enter Add Remove Programs. Open the control panel app from the results list.

Find your Microsoft Visual Studio 2015 installation in the list of installed programs. Find the Modify option for Microsoft Visual Studio 2015 and choose it to launch the Visual Studio setup program.

In the Visual Studio setup program, choose the Modify button.

Under the Features tab, expand Programming Languages > Visual C++. Select Common Tools for Visual C++ 2015 and Microsoft Foundation Classes for C++. Choose the Next button to continue.

On the Selected Features page, choose the UPDATE button to install the required components. When the update is complete, choose Close to dismiss the setup program.

To install the Installer Projects extension

In Visual Studio, select the Tools > Extensions and Updates menu item.

In the Extensions and Updates dialog, expand Online > Visual Studio Gallery > Tools and select Setup & Deployment. Set the Sort by dropdown to Most Downloads.

In the list of extensions, select Microsoft Visual Studio 2015 Installer Projects. Choose the Download button.

When the download completes, close the Extensions and Updates dialog, then close Visual Studio.

Open the downloaded VSI_bundle.exe file. Choose Install in the Visual Studio setup program. You may need to accept a User Account Control elevation prompt to allow the installer to change Visual Studio. Choose Close when the installer completes to dismiss the dialog.

Create the sample app project

To create a deployable application setup, first you’ll create a sample app to deploy.

To create the app project in Visual Studio 2022

Launch Visual Studio. By default, it opens the Create a New Project dialog box. If Visual Studio is already open, on the menu bar, choose File > New > Project to open the Create a New Project dialog box.

Screenshot of the Create a new project dialog showing an MFC App project template.

At the top of the dialog, type MFC in the search box and then choose MFC App from the results list. (If the MFC App template is missing, see To install C++ and MFC in Visual Studio 2022.) Choose the Next button to continue.

In the Configure your new project page, enter a name for the project, such as MyMFCApp. Choose the Create button.

In the MFC Application Wizard dialog, choose Finish to create the default MFC app project. The wizard creates your MFC app and opens the project in Visual Studio.

In Visual Studio, change the active solution configuration to Release and the Active solution platform to x86. On the Build menu, select Configuration Manager. In the Configuration Manager dialog box, select Release from the Active solution configuration drop-down box. Choose Close to save your changes.

Select the Build > Build Solution menu item to build the solution. The setup project uses the output of this MFC application project.

To create the app project in Visual Studio 2019

On the menu bar, choose File > New > Project to open the Create a New Project dialog box.

Screenshot of the Create a new project dialog showing an MFC App project template.

At the top of the dialog, type MFC in the search box and then choose MFC App from the results list. (If the MFC App template is missing, see To install C++ and MFC in Visual Studio 2019.) Choose the Next button to continue.

In the Configure your new project page, enter a name for the project, such as MyMFCApp. Choose the Create button.

In the MFC Application Wizard dialog, choose Finish to create the default MFC app project. The wizard creates your MFC app and opens the project in Visual Studio.

In Visual Studio, change the active solution configuration to Release. On the Build menu, select Configuration Manager. In the Configuration Manager dialog box, select Release from the Active solution configuration drop-down box. Choose Close to save your changes.

Select the Build > Build Solution menu item to build the solution. The setup project uses the output of this MFC application project.

To create the app project in Visual Studio 2017

On the menu bar, choose File > New > Project to open the New Project dialog box.

In the New Project dialog tree view control, select Installed > Visual C++ > MFC/ATL.

In the center pane, select the MFC App template. (If the MFC App template is missing, see To install C++ and MFC in Visual Studio 2017.) Change the Name to MyMFCApp. Choose OK to launch the MFC Application wizard.

In the MFC Application Wizard dialog, choose Finish to create the default MFC app project. The wizard creates your MFC app and opens the project in Visual Studio.

In Visual Studio, change the active solution configuration to Release. On the Build menu, select Configuration Manager. In the Configuration Manager dialog box, select Release from the Active solution configuration drop-down box. Choose Close to save your changes.

Select the Build > Build Solution menu item to build the solution. The setup project uses the output of this MFC application project.

To create the app project in Visual Studio 2015

On the menu bar, choose File > New > Project to open the New Project dialog box.

In the New Project dialog tree view control, select Installed > Templates > Visual C++ > MFC.

In the center pane, select the MFC Application template. (If the MFC Application template is missing, see To install C++ and MFC in Visual Studio 2015.) Change the Name to MyMFCApp. Choose OK to launch the MFC Application wizard.

In the MFC Application Wizard dialog, choose Finish to create the default MFC app project. The wizard creates your MFC app and opens the project in Visual Studio.

In Visual Studio, change the active solution configuration to Release. On the Build menu, select Configuration Manager. In the Configuration Manager dialog box, select Release from the Active solution configuration drop-down box. Choose Close to save your changes.

Select the Build > Build Solution menu item to build the solution. The setup project uses the output of this MFC application project.

Create the app setup project

Now that you’ve created a sample app to deploy, next you’ll create a setup project to build the deployment package for your app.

To create the setup project in Visual Studio 2022

In Visual Studio, with your sample app solution loaded, choose File > New > Project to open the Create a New Project dialog box.

In the search box above the template list, enter Setup. In the resulting list of templates, choose Setup Project. (If the Setup Project template is missing, see To install the Installer Projects extension.)

Enter a name for the setup project in the Name box, such as MyMFCAppSetup. In the Solution drop-down list, select Add to solution. Choose the OK button to create the setup project. A File System (MyMFCAppSetup) tab opens in the editor window.

To create the setup project in Visual Studio 2019

In Visual Studio, with your sample app solution loaded, choose File > New > Project to open the Create a New Project dialog box.

In the search box above the template list, enter Setup. In the resulting list of templates, choose Setup Project. (If the Setup Project template is missing, see To install the Installer Projects extension.)

Enter a name for the setup project in the Name box, such as MyMFCAppSetup. In the Solution drop-down list, select Add to solution. Choose the OK button to create the setup project. A File System (MyMFCAppSetup) tab opens in the editor window.

To create the setup project in Visual Studio 2017

In Visual Studio, with your sample app solution loaded, choose File > New > Project to open the New Project dialog box.

In the New Project dialog box, select the Installed > Other Project Types > Visual Studio Installer node. In the center pane, select Setup Project. (If the Setup Project template is missing, see To install the Installer Projects extension.)

Enter a name for the setup project in the Name box, such as MyMFCAppSetup. In the Solution drop-down list, select Add to solution. Choose the OK button to create the setup project. A File System (MyMFCAppSetup) tab opens in the editor window.

To create the setup project in Visual Studio 2015

In Visual Studio, with your sample app solution loaded, choose File > New > Project to open the New Project dialog box.

In the New Project dialog box, select the Installed > Templates > Other Project Types > Visual Studio Installer node. In the center pane, select Setup Project. (If the Setup Project template is missing, see To install the Installer Projects extension.)

Enter a name for the setup project in the Name box, such as MyMFCAppSetup. In the Solution drop-down list, select Add to solution. Choose the OK button to create the setup project. A File System (MyMFCAppSetup) tab opens in the editor window.

Add items to the setup project

The setup project lets you specify where the components of your app are installed when deployed on a target machine.

To add app components to the setup project

In the File System (MyMFCAppSetup) editor window, select the File System or Target Machine > Application Folder node.

On the menu bar, select Project > Add > Project Output to open the Add Project Output Group dialog box.

In the dialog box, select Primary Output and choose OK. A new item named Primary Output from ProjectName (Active) appears in the File System window.

Right-click the Application Folder node and select Add > Assembly to open the Select Component dialog box. Select and add any required DLLs needed by the program. For more information about how to identify required libraries, see Determining which DLLs to redistribute.

In the list of items in the Application Folder, right-click Primary Output from ProjectName (Active) and choose Create Shortcut to Primary Output from ProjectName (Active). A new item named Shortcut to Primary Output from ProjectName (Active) appears. You may rename the shortcut item, then drag and drop the item into the User’s Programs Menu node on the left side of the window. This item causes the setup to create a shortcut to the app in the Start menu.

On the menu bar, choose Build > Configuration Manager to open the Configuration Manager dialog.

In the Configuration Manager dialog, in the Project table under the Build column, check the box for the deployment project. Choose Close to save your changes and close the dialog.

On the menu bar, choose Build > Build Solution to build the MFC project and the deployment project.

In the solution folder, locate the setup.exe program that was built by the deployment project. You can copy this file (and the .msi file) to install the application and its required library files on another computer.

Test your deployment

To test your deployment, copy the deployment files to a second computer that doesn’t have the Visual C++ libraries installed. Run the setup program. If your app loads and runs normally, and you don’t get a runtime error about missing libraries or components, then your deployment is successful.

For application testing, you can create a deployment setup program that installs a debug version of your app, along with debug libraries, on machines you control. Debug apps and debug libraries aren’t licensed for redistribution, and can’t be deployed to customer machines. For more information, see Preparing a test machine to run a debug executable.

Читать:
Аттачмент что это в программировании

Похожие статьи