This extension is a very simple Windows Forms Project with a graphical user interace (GUI) written in C++. The form contains a button and textboxes for input and output, but you can easily extend it by adding more controls and functions.
The main purpose of this project is to show how the application logic can be separated from the user interface logic:
- 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. You can use most of C++11, C++14 and C++17.
- 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, menu item etc.
This strong separation is implemented in header1.h:
// header1.h
#pragma once
// In contrast to header2.h, here we have no interaction with
// the user interface. This header contains only business
// logic in standard C++ (including most of C++11, C++14 and C++17)
int plus_1(int x) // a very simple example for application logic
{
return x + 1;
}
This function is called after clicking the corresponding button:
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));
}
However, distributing a function definition and its call to two separate files results in the inconvenience of having to change the call in another file after changing the parameter list. This jumping back and forth between the header file and the forms file can be avoided with a less strict separation.
// header2.h
#pragma once
// In contrast to header1.h, here is no strong separation
// of the business logic and the user interface. Because of
// these two using directives
using namespace System;
using namespace System::Windows::Forms;
// Windows Forms types can be used in this header file.
int plus_2(int x) // another very simple example for application logic
{
return x + 2;
}
// The Windows Forms type TextBox is used as function
// parameter type. So you can place the GUI call close
// to the application logic (here plus_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));
}
In my book „C++ mit Visual Studio 2019 und Windows Forms-Anwendungen“ (in German) such a project is used for the solutions of the exercises (see chapter 2.11). It allows the students to learn standard C++ with Windows Application excercises.
This Visual Studio Extension is based on my other Extension C++ Windows Forms for VS 2022 .NET Framework. More details and background about my extensions you find here in English and in German.