Последнее обновление: 11.11.2022
Для создания графических приложений на C# можно использовать .NET CLI, но также можно
использовать бесплатную и полнофункциональную среду разработки — Visual Studio Community 2022, которая в ряде случаев облегчает проектирование
приложения. Так, загрузим установщик Visual Studio по адресу:
https://www.visualstudio.com/en-us/downloads.
Чтобы добавить в Visual Studio поддержку проектов для Windows Forms и C# и .NET 7, в программе установки среди рабочих нагрузок нужно
выбрать только пункт Разработка классических приложений .NET. Можно выбрать и больше опций или вообще все опции, однако стоит
учитывать свободный размер на жестком диске — чем больше опций будет выбрано, соответственно тем больше места на диске будет занято.
После установки среды и всех ее компонентов, запустим Visual Studio и создадим проект графического приложения.
На стартовом экране выберем Create a new project (Создать новый проект)
На следующем окне в качестве типа проекта выберем Windows Forms App:
Стоит отметить, что среди шаблонов можно увидеть еще тип Windows Forms App (.NET Framework) — его НЕ надо выбирать, необходим именно тип
Windows Forms App.
Далее на следующем этапе нам будет предложено указать имя проекта и каталог, где будет располагаться проект.
В поле Project Name дадим проекту какое-либо название. В моем случае это HelloApp.
На следующем окне Visual Studio предложит нам выбрать версию .NET, которая будет использоваться для проекта. Выберем последнюю на данный момент версию — .NET 7.0 и нажмен на кнопку Create (Создать) для создания проекта.
После этого Visual Studio откроет наш проект с созданными по умолчанию файлами:
Справа находится окно Solution Explorer, в котором можно увидеть структуру нашего проекта. Практически этот тот же проект, который создается с
помощью .NET CLI:
-
Dependencies — это узел содержит сборки dll, которые добавлены в проект по умолчанию.
Эти сборки как раз содержат классы библиотеки .NET, которые будет использовать C# -
Form1.Designer.cs: он содержит определение компонентов формы, добавленных
на форму в графическом дизайнере -
Далее идет файл единственной в проекте формы — Form1.cs, который по умолчанию открыт в центральном окне.
-
Program.cs определяет точку входа в приложение
Запуск приложения
Чтобы запустить приложение в режиме отладки, нажмем на клавишу F5 или на зеленую стрелочку на панели Visual Studio.
После этого запустится пустая форма Form1 по умолчанию.
После запуска приложения студия компилирует его в файл с расширением exe. Найти данный файл можно, зайдя в папку проекта и далее в каталог
\bin\Debug\net7.0-windows
Рассмотрев вкратце создание проекта графического приложения, мы можем перейти к обзору основных компонентов и начнем мы с форм.
Search code, repositories, users, issues, pull requests…
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
So far we have seen how to work with C# to create console based applications. But in a real-life scenario team normally use Visual Studio and C# to create either Windows Forms or Web-based applications.
A windows form application is an application, which is designed to run on a computer. It will not run on web browser because then it becomes a web application.
This Tutorial will focus on how we can create Windows-based applications. We will also learn some basics on how to work with the various elements of C# Windows application.
Windows Forms Basics
A Windows forms application is one that runs on the desktop computer. A Windows forms application will normally have a collection of controls such as labels, textboxes, list boxes, etc.
Below is an example of a simple Windows form application C#. It shows a simple Login screen, which is accessible by the user. The user will enter the required credentials and then will click the Login button to proceed.
So an example of the controls available in the above application
- This is a collection of label controls which are normally used to describe adjacent controls. So in our case, we have 2 textboxes, and the labels are used to tell the user that one textbox is for entering the user name and the other for the password.
- The 2 textboxes are used to hold the username and password which will be entered by the user.
- Finally, we have the button control. The button control will normally have some code attached to perform a certain set of actions. So for example in the above case, we could have the button perform an action of validating the user name and password which is entered by the user.
C# Hello World
Now let’s look at an example of how we can implement a simple ‘hello world’ application in Visual Studio. For this, we would need to implement the below-mentioned steps
Step 1) The first step involves the creation of a new project in Visual Studio. After launching Visual Studio, you need to choose the menu option New->Project.
Step 2) The next step is to choose the project type as a Windows Forms application. Here we also need to mention the name and location of our project.
- In the project dialog box, we can see various options for creating different types of projects in Visual Studio. Click the Windows option on the left-hand side.
- When we click the Windows options in the previous step, we will be able to see an option for Windows Forms Application. Click this option.
- We will give a name for the application. In our case, it is DemoApplication. We will also provide a location to store our application.
- Finally, we click the ‘OK’ button to let Visual Studio create our project.
If the above steps are followed, you will get the below output in Visual Studio.
Output:-
You will see a Form Designer displayed in Visual Studio. It’s in this Form Designer that you will start building your Windows Forms application.
In the Solution Explorer, you will also be able to see the DemoApplication Solution. This solution will contain the below 2 project files
- A Form application called Forms1.cs. This file will contain all of the code for the Windows Form application.
- The Main program called Program.cs is default code file which is created when a new application is created in Visual Studio. This code will contain the startup code for the application as a whole.
On the left-hand side of Visual Studio, you will also see a ToolBox. The toolbox contains all the controls which can be added to a Windows Forms. Controls like a text box or a label are just some of the controls which can be added to a Windows Forms.
Below is a screenshot of how the Toolbox looks like.
Step 3) In this step, we will now add a label to the Form which will display “Hello World.” From the toolbox, you will need to choose the Label control and simply drag it onto the Form.
Once you drag the label to the form, you can see the label embedded on the form as shown below.
Step 4) The next step is to go to the properties of the control and Change the text to ‘Hello World’.
To go to the properties of a control, you need to right-click the control and choose the Properties menu option
- The properties panel also shows up in Visual Studio. So for the label control, in the properties control, go to the Text section and enter “Hello World”.
- Each Control has a set of properties which describe the control.
If you follow all of the above steps and run your program in Visual Studio, you will get the following output
Output:-
In the output, you can see that the Windows Form is displayed. You can also see ‘Hello World’ is displayed on the form.
Adding Controls to a form
We had already seen how to add a control to a form when we added the label control in the earlier section to display “Hello World.”
Let’s look at the other controls available for Windows forms and see some of their common properties.
In our Windows form application in C# examples, we will create one form which will have the following functionality.
- The ability for the user to enter name and address.
- An option to choose the city in which the user resides in
- The ability for the user to enter an option for the gender.
- An option to choose a course which the user wants to learn. There will make choices for both C# and ASP.Net
So let’s look at each control in detail and add them to build the form with the above-mentioned functionality.
Group Box
A group box is used for logical grouping controls into a section. Let’s take an example if you had a collection of controls for entering details such as name and address of a person. Ideally, these are details of a person, so you would want to have these details in a separate section on the Form. For this purpose, you can have a group box. Let’s see how we can implement this with an example shown below
Step 1) The first step is to drag the Groupbox control onto the Windows Form from the toolbox as shown below
Step 2) Once the groupbox has been added, go to the properties window by clicking on the groupbox control. In the properties window, go to the Text property and change it to “User Details”.
Once you make the above changes, you will see the following output
Output:-
In the output, you can clearly see that the Groupbox was added to the form. You can also see that the text of the groupbox was changed to “User Details.”
Label Control
Next comes the Label Control. The label control is used to display a text or a message to the user on the form. The label control is normally used along with other controls. Common examples are wherein a label is added along with the textbox control.
The label indicates to the user on what is expected to fill up in the textbox. Let’s see how we can implement this with an example shown below. We will add 2 labels, one which will be called ‘name’ and the other called ‘address.’ They will be used in conjunction with the textbox controls which will be added in the later section.
Step 1) The first step is to drag the label control on to the Windows Form from the toolbox as shown below. Make sure you drag the label control 2 times so that you can have one for the ‘name’ and the other for the ‘address’.
Step 2) Once the label has been added, go to the properties window by clicking on the label control. In the properties window, go to the Text property of each label control.
Once you make the above changes, you will see the following output
Output:-
You can see the label controls added to the form.
Textbox
A textbox is used for allowing a user to enter some text on the Windows application in C#. Let’s see how we can implement this with an example shown below. We will add 2 textboxes to the form, one for the Name and the other for the address to be entered for the user
Step 1) The first step is to drag the textbox control onto the Windows Form from the toolbox as shown below
Step 2) Once the text boxes have been added, go to the properties window by clicking on the textbox control. In the properties window, go to the Name property and add a meaningful name to each textbox. For example, name the textbox for the user as txtName and that for the address as txtAddress. A naming convention and standard should be made for controls because it becomes easier to add extra functionality to these controls, which we will see later on.
Once you make the above changes, you will see the following output
Output:-
In the output, you can clearly see that the Textboxes was added to the form.
List box
A Listbox is used to showcase a list of items on the Windows form. Let’s see how we can implement this with an example shown below. We will add a list box to the form to store some city locations.
Step 1) The first step is to drag the list box control onto the Windows Form from the toolbox as shown below
Step 2) Once the list box has been added, go to the properties window by clicking on the list box control.
- First, change the property of the Listbox box control, in our case, we have changed this to lstCity
- Click on the Items property. This will allow you to add different items which can show up in the list box. In our case, we have selected items “collection”.
- In the String Collection Editor, which pops up, enter the city names. In our case, we have entered “Mumbai”, “Bangalore” and “Hyderabad”.
- Finally, click on the ‘OK’ button.
Once you make the above changes, you will see the following output
Output:-
In the output, you can see that the Listbox was added to the form. You can also see that the list box has been populated with the city values.
RadioButton
A Radiobutton is used to showcase a list of items out of which the user can choose one. Let’s see how we can implement this with an example shown below. We will add a radio button for a male/female option.
Step 1) The first step is to drag the ‘radiobutton’ control onto the Windows Form from the toolbox as shown below.
Step 2) Once the Radiobutton has been added, go to the properties window by clicking on the Radiobutton control.
- First, you need to change the text property of both Radio controls. Go the properties windows and change the text to a male of one radiobutton and the text of the other to female.
- Similarly, change the name property of both Radio controls. Go the properties windows and change the name to ‘rdMale’ of one radiobutton and to ‘rdfemale’ for the other one.
One you make the above changes, you will see the following output
Output:-
You will see the Radio buttons added to the Windows form.
Checkbox
A checkbox is used to provide a list of options in which the user can choose multiple choices. Let’s see how we can implement this with an example shown below. We will add 2 checkboxes to our Windows forms. These checkboxes will provide an option to the user on whether they want to learn C# or ASP.Net.
Step 1) The first step is to drag the checkbox control onto the Windows Form from the toolbox as shown below
Step 2) Once the checkbox has been added, go to the properties window by clicking on the Checkbox control.
In the properties window,
- First, you need to change the text property of both checkbox controls. Go the properties windows and change the text to C# and ASP.Net.
- Similarly, change the name property of both Radio controls. Go the properties windows and change the name to chkC of one checkbox and to chkASP for the other one.
Once you make the above changes, you will see the following output
Output:-
Button
A button is used to allow the user to click on a button which would then start the processing of the form. Let’s see how we can implement this with an example shown below. We will add a simple button called ‘Submit’ which will be used to submit all the information on the form.
Step 1) The first step is to drag the button control onto the Windows Form from the toolbox as shown below
Step 2) Once the Button has been added, go to the properties window by clicking on the Button control.
- First, you need to change the text property of the button control. Go the properties windows and change the text to ‘submit’.
- Similarly, change the name property of the control. Go the properties windows and change the name to ‘btnSubmit’.
Once you make the above changes, you will see the following output
Output:-
Congrats, you now have your first basic Windows Form in place. Let’s now go to the next topic to see how we can do Event handling for Controls.
C# Event Handling for Controls
When working with windows form, you can add events to controls. An event is something that happens when an action is performed. Probably the most common action is the clicking of a button on a form. In C# Windows Forms, you can add code which can be used to perform certain actions when a button is pressed on the form.
Normally when a button is pressed on a form, it means that some processing should take place.
Let’s take a look at one of the event and how it can be handled before we go to the button event scenario.
The below example will showcase an event for the Listbox control. So whenever an item is selected in the listbox control, a message box should pop up which shows the item selected. Let’s perform the following steps to achieve this.
Step 1) Double click on the Listbox in the form designer. By doing this, Visual Studio will automatically open up the code file for the form. And it will automatically add an event method to the code. This event method will be triggered, whenever any item in the listbox is selected.
Above is the snippet of code which is automatically added by Visual Studio, when you double-click the List box control on the form. Now let’s add the below section of code to this snippet of code, to add the required functionality to the listbox event.
- This is the event handler method which is automatically created by Visual Studio when you double-click the List box control. You don’t need to worry about the complexity of the method name or the parameters passed to the method.
- Here we are getting the SelectedItem through the lstCity.SelectedItem property. Remember that lstCity is the name of our Listbox control. We then use the GetItemText method to get the actual value of the selected item. We then assign this value to the text variable.
- Finally, we use the MessageBox method to display the text variable value to the user.
One you make the above changes, and run the program in Visual Studio you will see the following output
Output:-
From the output, you can see that when any item from the list box is selected, a message box will pops up. This will show the selected item from the listbox.
Now let’s look at the final control which is the button click Method. Again this follows the same philosophy. Just double click the button in the Forms Designer and it will automatically add the method for the button event handler. Then you just need to add the below code.
- This is the event handler method which is automatically created by Visual Studio when you double click the button control. You don’t need to worry on the complexity of the method name or the parameters passed to the method.
- Here we are getting values entered in the name and address textbox. The values can be taken from the text property of the textbox. We then assign the values to 2 variables, name, and address accordingly.
- Finally, we use the MessageBox method to display the name and address values to the user.
One you make the above changes, and run the program in Visual Studio you will see the following output
Output:-
- First, enter a value in the name and address field.
- Then click on the Submit button
Once you click the Submit button, a message box will pop, and it will correctly show you what you entered in the user details section.
Tree and PictureBox Control
There are 2 further controls we can look at, one is the ‘Tree Control’ and the other is the ‘Image control’. Let’s look at examples of how we can implement these controls
Tree Control
– The tree control is used to list down items in a tree like fashion. Probably the best example is when we see the Windows Explorer itself. The folder structure in Windows Explorer is like a tree-like structure.
Let’s see how we can implement this with an example shown below.
Step 1) The first step is to drag the Tree control onto the Windows Form from the toolbox as shown below
Step 2) The next step is to start adding nodes to the tree collection so that it can come up in the tree accordingly. First, let’s follow the below sub-steps to add a root node to the tree collection.
- Go to the properties toolbox for the tree view control. Click on the Node’s property. This will bring up the TreeNode Editor
- In the TreeNode Editor click on the Add Root button to add a root node to the tree collection.
- Next, change the text of the Root node and provide the text as Root and click ‘OK’ button. This will add Root node.
Step 3) The next step is to start adding the child nodes to the tree collection. Let’s follow the below sub-steps to add child root node to the tree collection.
- First, click on the Add child button. This will allow you to add child nodes to the Tree collection.
- For each child node, change the text property. Keep on repeating the previous step and this step and add 2 additional nodes. In the end, you will have 3 nodes as shown above, with the text as Label, Button, and Checkbox respectively.
- Click on the OK button
Once you have made the above changes, you will see the following output.
Output:-
You will be able to see the Tree view added to the form. When you run the Windows form application, you can expand the root node and see the child nodes in the list.
PictureBox Control
This control is used to add images to the Winforms C#. Let’s see how we can implement this with an example shown below.
Step 1) The first step is to drag the PictureBox control onto the C# Windows Form from the toolbox as shown below
Step 2) The next step is to actually attach an image to the picture box control. This can be done by following the below steps.
- First, click on the Image property for the PictureBox control. A new window will pops out.
- In this window, click on the Import button. This will be used to attach an image to the picturebox control.
- A dialog box will pop up in which you will be able to choose the image to attach the picturebox
- Click on the OK button
One you make the above changes, you will see the following output
Output:-
From the output, you can see that an image is displayed on the form.
Summary
- A Windows form in C# application is one that runs on the desktop of a computer. Visual Studio Form along with C# can be used to create a Windows Forms application.
- Controls can be added to the Windows forms C# via the Toolbox in Visual Studio. Controls such as labels, checkboxes, radio buttons, etc. can be added to the form via the toolbox.
- One can also use advanced controls like the tree view control and the PictureBox control.
- Event handlers are used to respond to events generated from controls. The most common one is the one added for the button clicked event.
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)
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:
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.
Example:
- 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
textBox1->BackColor = Color::Yellow;
between the curly brackets
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
textBox1->BackColor = Color::Yellow;
}
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:
- 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).
- You write in C++ the instructions that should be done in response to user input (non-visual programming).
- 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:
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:
int plus_1(int x)
{
return x + 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:
#pragma once
#include "Header1.h" // <-- manuell einfügen. nach dem Eintippen von
// "#include " bietet Visual Studio die Datei an.
namespace CppCLRWinFormsProject {
using namespace System;
...
}
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:
private: System::Void button_plus_1_Click(System::Object^ sender, System::EventArgs^ e)
{
}
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.
private: System::Void button_plus_1_Click(System::Object^ sender, System::EventArgs^ e)
{
int n = Convert::ToInt32(in_textBox->Text);
int result = plus_1(n);
out_textBox->AppendText(String::Format("plus_1({0})={1}\r\n",n,result));
}
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
using namespace System;
using namespace System::Windows::Forms;
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:
#pragma once
using namespace System;
using namespace System::Windows::Forms;
int plus_2(int x)
{
return x + 2;
}
void plus_2_Click(TextBox^ in_textBox, TextBox^ out_textBox)
{
int n = Convert::ToInt32(in_textBox->Text);
int result = plus_2(n);
out_textBox->AppendText(String::Format("plus_2({0})={1}\r\n", n, result));
}
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:
private: System::Void button_plus_1_Click(System::Object^ sender, System::EventArgs^ e)
{
plus_2_Click(in_textBox, out_textBox);
}
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
#include<iostream>
int main()
{
int n;
std::cin >> n;
int result = plus_2(n);
std::cout << "plus_2(" << n << ") = " << result << std::endl;
return 0;
}
you can port it to a form application with relatively little effort. You just need to replace the I/O statements and call the functions in response to a ButtonClick, etc:
private: System::Void button_plus_1_Click(System::Object^ sender, System::EventArgs^ e)
{
int n = Convert::ToInt32(in_textBox->Text);
int result = plus_1(n);
out_textBox->AppendText(String::Format("plus_1({0})={1}\r\n",n,result));
}
Excerpt from the preface to my book „C++ mit Visual Studio 2019 und Windows Forms-Anwendungen“
The preface to my book (in German)
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)
textBox1->AppendText(„Hello World“);
while in standard C++ the console is used with cout:
cout << "Hello world" << endl;
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.
In this article, we’ll achieve numerous goals. First of all, we’ll learn through a step-by-step process to create the project in Visual Studio 2019 and create a windows form application. Within the application, we’ll use the features of the drag and drop low code approach supported for the Designer in Visual Studio 2019. A small part of gamification has been creatively put in to make it interesting for beginners. Later, we run the application and look at the prospective possibilities with the windows from the application.
The previous article, C# Connect to MySQL in Visual Studio 2019 will help you connect to the database for applications in C# and the .NET framework from Visual Studio itself.
Step 1
Let us start with the installation of Visual Studio 2019. The Community edition is free for use. Once installed, the following screen will pop up. Click on Launch.
Step 2
To start a new project, click on Create a new project.
Step 3
Now, as we are making a Windows Forms App, we choose the Windows Forms App (.NET Framework).
If you don’t find the options available, it’s probably not installed yet. You can select the Install more tools and features and then choose the .NET desktop development workload which supports console application building, windows forms application, and WPF.
Step 4
Fill in the project name, the location where the solutions repository will be saved, the solution name, and the .NET framework of your choice. After that, Click on Create.
Step 5
The Visual Studio Solution will be created and the window will look similar to as shown below.
Step 6
In caset he Toolbox is not there, you can opt for it from the View section in Menu.
Step 7
The Toolbox should look similar to the following image.
Now, let us start our project. Choose the Button and then drag and top on the Designer.
I’ve created three buttons here, button1, button2, and button3.
The properties of the button can be seen in the Properties section. The Text shows the displayed name of the button — the first button.
Let us change the text to Press Here.
Moreover, the Name of the Design is the one that will call functions for in the program. Here, we name it btnPresshere.
Step 8
Let us go back to Toolbox and search for labels by typing in the search bar. Select the Label and drag and drop one in the designer.
Step 9
The new label i.e. label1 is placed below the button Press Here.
The reason for the label is to call an action while pressing the Press Here button.
Step 10
Let us change the name of the label to labelPressHere. A good convention is to create label names as per the action it operates to.
Step 11
Now double click the Press Here button from the Designer.
A class will be created automatically in the Form1.cs file that would look similar to the one below.
Now, let us add the following code to create action while pressing the Press Here button.
labelPresshere.Text = “Welcome to C# Corner”
Let us test what the program can do now. You can run the program, by clicking the Start button.
Let us see, what happens when we click the Press Here button.
See, label1 changes to Welcome to C# Corner now.
Step 12 — ROCK PAPER SCISSOR
Let us get creative now with button2. Let’s create a small Rock Paper Scissor game.
Let us rename the button to Rock Paper Scissor and the label to labelRPS and create another label called labelDYW.
Double Clicking the Rock Paper Scissor button, new classes are created.
Add the following code for button2_Click action.
private void button2_Click(object sender, EventArgs e) {
string[] game = {
"Rock",
"Paper",
"Scissor"
};
Random rand = new Random();
int index = rand.Next(game.Length);
labelRockPaperScissor.Text = game[index];
labelDYW.Text = "Did you win?";
}
An array of strings named game is created. The random function is called and with randomness for the possible outcome for Rock, Paper, and Scissor – this is now a legit game you can play when you are bored.
Step 13
When we run the program, we can see, how every time we press the Rock Paper Scissor button, the new Round comes out with a different answer. So, Did You Win?
Step 14
Let us go, and change the label text to white spaces. This will make the User Interface of the App, cleaner as follows.
Step 15
Think of something creative of your own and making something out of the button3 from the lessons you learned above.
Conclusion
Thus, in this article, we learned about creating the Windows Form Application in C# using Visual Studio 2019. All the tools and resources in this article are freemium versions. So, you can try it without any payment requirement. Here, we went through a step-by-step procedure to create windows form app, design a simple app, call actions when clicking a button and with a pinch of creativity, literally made a game. I wanted to showcase; how powerful programming is. With this bit of learning, you have now entered a huge possibility of creation. You can now make an app, you might in the future make a fun game. Find out problems that can be solved, and with the stepping stone of today, their possibilities of creation are endless for you in days to come.