C++ Tutorial: UI Application using visual studio – 2020

C++ Tutorial – UI Application using visual studio 2020

cplusplus_icon.png

bogotobogo.com site search:

Application using visual studio

In this section, we will build UI application using Windows Form provided by Visual Studio 2013.

In Project Setup stage for deploy, VS 2012 will be used. Express versions will work except the project setup for deployment.

The app is a very simple random number generator with two buttons (Generator/Reset), 7 Labels for the display of the random numbers with a PictureBox.

For WPF (Windows Presentation Foundation), please visit WPF & XAML.

1494.strip.gif

Source: Dilbert

The simplest UI program

  1. Select Visual C++ CLR and CLR Empty Project
    and type in RandomNumberGenerator for the project name. The, OK.
  2. Project->Add New Item… .
    Select UI under Visual C++.
    Leave the Form name as given by default MyForm.h.
    Then, click Add.

    MyForm.png

  3. We need to edit the MyForm.cpp file:
    #include "MyForm.h"
    
    using namespace System;
    using namespace System::Windows::Forms;
    
    
    [STAThread]
    void Main(array<String^>^ args)
    {
    	Application::EnableVisualStyles();
    	Application::SetCompatibleTextRenderingDefault(false);
    
    	RandomNumberGenerator::MyForm form;
    	Application::Run(%form);
    }
      

    The System namespace provides functions to work with UI controls.

  4. At the right-mouse click on RandomNumberGenerator, we get the Properties window.
    Configuration Properties->Linker->System
    Select Windows (/SUBSYSTEM:WINDOWS) for SubSystem.
    Advanced->Entry Point, type in Main.
    The, hit OK.
  5. Hit F5, then we will have to run result, the Form.

UI Setup

  1. Locate the ToolBox, and then expand the list of Common Controls.
    Double-click its Label items to add it to our Form.
    Do this seven times.
    We need to add two Buttons and a PixtureBox.
    Double-click those as well from the list.
  2. Resize and rearrange the items. Rename the buttons and tile of the Form, then it should look like this:

    MyFormWithLabelsAndButtons.png

  3. We can put the picture onto the PictureBox.
    At a right mouse click, we get Choosing Picture….
    Then, select the image file we want to use.
  4. Let’s try if it works.
    Run it (Hit F5).

    FormWithPictureRun.png

Event handling code for UI components

  1. Let’s look at the file MyForm.h.
    #pragma once
    
    namespace RandomNumberGenerator {
    
    	using namespace System;
    	using namespace System::ComponentModel;
    	using namespace System::Collections;
    	using namespace System::Windows::Forms;
    	using namespace System::Data;
    	using namespace System::Drawing;
    
    	/// 
    	/// Summary for MyForm
    	/// 
    	public ref class MyForm : public System::Windows::Forms::Form
    	{
    	public:
    		MyForm(void)
    		{
    			InitializeComponent();
    			//
    			//TODO: Add the constructor code here
    			//
    		}
            ...
    
      

    It begins with a pragma once directive.
    To VS compiler, it means only open this file once during the compilation.
    Also, as explained it before, the System namespace gives us functions to deal with UI controls.
    The line public ref class MyForm : public System::Windows::Forms::Form defines a derived class named MyForm. The members of the class are the interface components.

  2. To get a skeleton code for events, select the Generate button (button1), then type in button1_Click into for the Click under Action of the Properties window.
    Then, VS will add additional code to MyForm.h for us:

    void InitializeComponent(void)
    {
       this->button1->Click += gcnew System::EventHandler(this, &MyForm;::button1_Click);
       ...
    
    #pragma endregion
       private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) { } 			 
      

    Do the same for the Reset button (button2).

  3. Inside the bracket of Reset (button2), insert the following code to set the values to 0 when we click the button:
     // Reset button
     private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {
            // clear label fields
    	this->label1->Text = "0";
    	this->label2->Text = "0";
    	this->label3->Text = "0";
    	this->label4->Text = "0";
    	this->label5->Text = "0";
    	this->label6->Text = "0";
    	this->label7->Text = "0";
     
            // set button state
    	this->button1->Enabled = true;
    	this->button2->Enabled = false;
    }
       

    Also, the fields should be set to 0 when we load the form. So, click the Label1, then set the Text to 0 under Properties window. Repeat the same to the reset of the labels. Note that we disabled the Reset button, and enabled the Generate button at the click.

Generate Random numbers

  1. When the Generate is clicked, random numbers should be generated and displayed. We will put the code into the event handling function,
    private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e).

    // Generate button
    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
    
    	int num[7] = { 0 };
    
    	// seed
    	srand((int) time(0));
    
    	// Randomize the array values.
    	for (int i = 0; i < 7; i++) 
    		num[i] = (rand() % 99) + 1;
    
    	// set the label text with random number
    	this->label1->Text = Convert::ToString(num[0]);
    	this->label2->Text = Convert::ToString(num[1]);
    	this->label3->Text = Convert::ToString(num[2]);
    	this->label4->Text = Convert::ToString(num[3]);
    	this->label5->Text = Convert::ToString(num[4]);
    	this->label6->Text = Convert::ToString(num[5]);
    	this->label7->Text = Convert::ToString(num[6]);
    
    	// change the button states.
    	this->button1->Enabled = false;
    	this->button2->Enabled = true;
    }
    

    For more info on the random number, please visit Random Numbers in C++.

  2. Press F5 to run it again.

    Random_InitA.png

    Random_InitB.png

Deploy

  1. Launch the Configuration Manager…, and select Release from Active solution configuration.

    ConfigurationManager.png

  2. We’ve done the following steps for the Debug version. Now, let’s do it for Release version.
    At the right-mouse click on RandomNumberGenerator, we get the Properties window.
    Configuration Properties->Linker->System
    Select Windows (/SUBSYSTEM:WINDOWS) for SubSystem.
    Advanced->Entry Point, type in Main.
    The, hit OK.
  3. To deploy the application, a Setup Project should be added to the solution to create the required files for installation.
  4. File->New. Launch a New Project dialog.
  5. From the New Project dialog, choose Other Project Types->Setup and Deployment.
    We need to enter a name for the Setup Project.

    DeployNewProject.png

    Click OK to add the project files to the Solution. Then we see the SetupProject in the Solution Explorer.

    SolutionExplorerAfterSetupProject.png

  6. From the Project Assistant window, we setup the properties of installation.

    ProjectAssistant_Add_Folders.png

    For example, the picture shows adding a Release folder to the install.

  7. After setup the install, we build the Setup Project. In this case, we do right click on the SetupRandomApp in the Solution Explorer
  8. Then, locate the setup.exe file and run. In this case, it’s in
    C:\Users\KHyuck\Documents\Visual Studio 2012\
    Projects\Random\SetupRandomApp\SetupRandomApp\Express\SingleImage\DiskImages\DISK1

    InstallShieldWizard.png

  9. Go to the install directory, run the RandomNumberGenerator.exe. In this example,
    It’s installed in C:\Program Files (x86)\Bogotobogo\My Product Name\Release directory.

Source Files

Source files used in the example is Random.zip.

Please enable JavaScript to view the comments powered by Disqus.