Home

Introduction to Windows Programming

 

Microsoft Visual C++ Fundamentals

 

Introduction

In Lesson 1, we saw that most programming in Microsoft Windows was based on the Win32 library. We also saw that, to support modern requirements of computer applications, Microsoft created the .NET Framework that provides most of the functionality you will need for your application. Like any regular graphical library, the .NET Framework provides classes that can be used to create graphical objects.

A Windows application primarily appears as a rectangular object that occupies a portion of the screen. This type of object is under the management of the operating system: Microsoft Windows. Based on this, for an application to become useful, it must be opened. An application must have an entry point. On a C++/CLI application, this entry point is a function called main.

On a Win32 application, the entry point of a program is a function called WinMain and it is defined in the windows.h library. This function is declared as:

int WinMain(HINSTANCE hInstance,
            HINSTANCE hPrevInstance,
            LPSTR lpCmdLine,
            int nCmdShow);

In some versions of Microsoft Visual C++, this function is sometimes defined as _tWinMain.

Practical LearningPractical Learning: Windows Programming

  1. To start a new program, launch Microsoft Visual C++ 2005
  2. To create a new project, on the main menu, click File -> New -> Project...
  3. In the Project Types list, click Visual C++ if necessary. In the Templates list, click CLR Empty Project
  4. In the Name text box, type Exercise2:
     
    New Project
  5. Click OK

Windows Forms

Windows Forms is a technique of creating computer applications based on the common language runtime (CLR). It offers a series of objects called Windows Controls or simply, controls. These controls are already created in the .NET Framework through various classes. Application programming consists of taking advantage of these controls and customizing them for a particular application. There are various types of applications you can create with these controls, including graphical applications (Windows Forms Application), XML-based applications, or console applications (Console Application), etc.

There are two broad categories of objects used in a Windows Forms application: the forms and the controls. The objects used in a Windows Forms application are stored in libraries also called assemblies. As normal libraries, these assemblies have the extension .dll (which stands for dynamic link library). In order to use one of these objects, you must know the name of the assembly in which it is stored. Then you must add a reference to that assembly in your application.

To add a reference to an assembly:

  • On the main menu, you can click Project -> Add Reference...
  • You can right-click the automatically created References node in the Solution Explorer and click Add Reference...

Any of these actions would display the Add Reference dialog box from where you can click the reference, click Select and click OK. If you don't see the reference you are looking for, you can locate it on another drive or directory using the Browse button.

A form is the most fundamental object used in an application. It is a rectangular object that uses part of the computer screen to represent an application. A form is based on the Form class that is defined in the System::Windows::Forms namespace created in the System.Windows.Forms.dll assembly. Every GUI application you will create starts with a form.

You can include the System.Windows.Forms.dll library to your application manually or visually. To include it manually, type the following:

#using <System.Windows.Forms.dll>

To include this library visually, you would use the Add Reference dialog box to select System.Windows.Forms from the .NET property page.

There are various techniques you can use to get a form in your application: you can programmatically and manually create a form, you can inherit a form from the Form class, you can create a form based on another form that either you or someone else created already, etc.

The primary means of getting a form into an application consists of deriving one from the Form class. Before doing this manually, you should first include the System::Windows::Forms namespace in your application:

using namespace System::Windows::Forms;

If you create a Windows Forms Application, the System.dll assembly and the System namespace would automatically be added to your project.

Practical LearningPractical Learning: Deriving a Form From the Form Class

  1. To add a reference to the assembly in which the Form class is defined, on the main menu, click Project -> References...
  2. In the dialog box, click Add New Reference...
  3. In the Add Reference dialog box, click the .NET tab if necessary and scroll down in the list
  4. Click System
     
  5. Click OK
  6. Click Add New Reference again
  7. In the list, double-click System.Windows.Forms
     
  8. Click OK
  9. To create a new class, on the main menu, click Project -> Add Class...
  10. In the Templates list, click C++ Class and click Add
  11. In the Class Name text box, type CExercise
  12. In the Base Class text box, type Form
  13. Click Finish.
    You will receive a message box. Read it and click Yes
     
  14. Complete the header file as follows:
     
    #pragma once
    
    using namespace System;
    using namespace System::Windows::Forms;
    
    public ref class CExercise : public Form
    {
    public:
    	CExercise(void);
    };
  15. Save the file

The Application Class

The form is the object that gives presence to an application. Once you have created the (primary) form of your application, you can get it ready to display on the screen. This is taken care of by the Application class equipped to start an application, process its messages or other related issues, and stop the application.

The Application class provides the overloaded Run() method that can be used to start a program. One of the versions of this method takes a form as argument. This form must be the first, main or primary form of your application; it will be the first to display when the application comes up.

Practical LearningPractical Learning: Starting an Application

  1. To create a source file, on the main menu, click Project -> Add New Item...
  2. In the Templates list, click C++ File (.cpp)
  3. In the New box, type Central and click Add
  4. To prepare the application for starting, change the file as follows:
     
    #include <windows.h>
    #include "Exercise.h"
    
    int APIENTRY WinMain(HINSTANCE hInstance,
    		     HINSTANCE hPrevInstance,
    		     LPSTR lpCmdLine,
    		     int nCmdShow)
    {
        Application::Run(gcnew CExercise());
    
        return 0;
    }
  5. To execute the application, on the main menu, click Debug -> Start Without Debugging
  6. Click Yes to save the file
     
    A Simple Form
  7. After viewing it, close the form by clicking its system Close button and return to your programming environment

Automatic Forms

Microsoft Visual Studio makes it easy to get a form to an application. This easiest technique consists of creating a Windows application. To do this, you first display the New Project dialog box, then select Windows Forms Application in the Templates list.

If you had already started an application, whether it was created as a Windows Forms Application or not, to add a new form to it, on the main menu, you can click File -> Add New Item... or Project -> Add New Item.... Then, in the Templates section of the Add New Item dialog box, you can select Windows Form, give it a name and click Open. A new form with its complete and necessary skeleton code would be added to your application, allowing you to simply customize it.

The Toolbox

 

Introduction

A Windows control is a graphical object that allows the user to interact with the computer. The controls are as varied as the needs and goals are. Because there are so many controls for various purposes, their insertion to an application and their configuration are left to the application programmer. The Toolbox is the accessory that provides most of the controls used in an application.

Design and Run Times

Application programming primarily consists of populating a form with objects called Windows controls. These controls are what the users of your application use to interact with the computer. As the application developer, one of your jobs will consists of selecting the necessary objects, adding them to your application, and then configuring their behavior. As mentioned with the form, there are various ways you can get a control into your application. One of the techniques consists of programmatically adding a control by writing code. Another technique consists of visually selecting a control and adding it to a form.

To create your applications, there are two settings you will be using. If a control is displaying on the screen and you are designing it, this is referred to as Design Time. This means that you have the ability to manipulate the control. You can visually set the controlís appearance, its location, its size, and other necessary or available characteristics. The design view is usually the most used and the easiest because you can glance at a control, have a realistic display of the control and configure its properties. The visual design is the technique that allows you to visually add a control and manipulate its display. This is the most common, the most regularly used, and the easiest technique.

The other technique you will be using to control a window is with code, writing the program. This is done by typing commands or instructions using the keyboard. This is considered, or referred to, as Run Time. This is the only way you can control an objectís behavior while the user is interacting with the computer and your program.

The Sections of the Toolbox

When you start a Windows Forms Application, it provides various controls on the Toolbox so you can choose which ones are appropriate for your particular application. Controls are organized in categories based on their function or role. A container is a control whose main purpose is to host other controls. To design it, you pick up objects from the Toolbox and drop them where desired. The Toolbox organizes its items in categories and each category is represented by a + button and a string:

Toolbox

If the available list of categories is not enough, you can add a new section of your choice. By default, Visual Studio hides some categories because they are judged hardly used. To display these additional sections, you can right-click anywhere in the Toolbox and click Show All Tabs:

Toolbox

If you still want an additional tab not included in the list, you can add one (or more). To do that, right-click anywhere in the Toolbox and click Add Tab. You would be prompted to provide a name. After typing the new name, press Enter.

The Layout of a Category

To use an object of a particular category, you can first click its + button. After selecting a category, it displays its items. In each category, a particular button called Pointer is selected by default. This simply indicates that no item in the group is currently selected.

By default, the items in each category are organized as horizontal wide buttons:

Toolbox

Alternatively, you can list the items of a category as buttons of a list view. To do that, you can right-click anywhere in the category and click List View to remove its check box:

 

Arrangement of Items in the Toolbox

When Microsoft Visual Studio is installed, it adds the buttons in a somewhat random order. In the beginning, this can make it difficult to find a particular control when you need it. If you find it more convenient, you can arrange the list of controls in any order of your choice. You have two main options. To change the position of an item in the list, right-click it and click either Move Up or Move Down. Alternatively, you can arrange the items in alphabetic order. To do that, right-click anywhere in the Windows Forms section and click Sort Items Alphabetically:

Toolbox

Once you have rearranged items alphabetically, the Toolbox forgets the previous arrangement and you cannot restore it. Alternatively, you can right-click the button of a control and click either Move Up or Move Down.

Visual Control Addition

To add a control to your application, you can select it from the Toolbox and click the desired area on the form. Once added, the control is positioned where your mouse landed. In the same way, you can add other controls as you judge them necessary for your application. Here is an example of a few controls added to a form:

A form equipped with various controls

Alternatively, to add a control, you can also double-click it from the Toolbox and it would be added to the top-left section of the form.

If you want to add a certain control many times, before selecting it on the Toolbox, press and hold Ctrl. Then click it in the Toolbox. This permanently selects the control. Every time you click the form, the control would be added. Once you have added the desired number of this control, on the Toolbox, click the Pointer button to dismiss the control.

Practical LearningPractical Learning: Using the Toolbox

  1. To create a new application, on the main menu, click File -> New Project...
  2. In the Templates list, click Windows Forms Application
  3. Set the Name to Windows1 and click OK
  4. On the main menu, click View -> Toolbox.
    Position the mouse on the Toolbox word and wait for the Toolbox to expand
  5. Click the Label button Label and position the mouse on the form
     
  6. Click
  7. To add another control, position the mouse again on the Toolbox word until the Toolbox has expanded
  8. Find and double-click the TextBox button TextBox
  9. To use a hidden area of the form, position the mouse on the Toolbox word. When the Toolbox has expanded, click the Auto Hide button
  10. On the Toolbox, click the TreeView button TreeView and click the left section of the form
  11. After using the Toolbox, to hide it, click the Auto Hide button
  12. To execute the application, on the main menu, click Debug -> Start Without Debugging
  13. After using it, close the form and return to your programming environment

The Toolbox and Additional Controls

When Microsoft Visual Studio is set up, it installs in the Toolbox the most regularly used controls. If you are working in an environment that creates only a particular group of applications and there are controls you hardly use, if you want, you can remove them from the list. To remove a control, right-click it and click Delete.

Besides the objects in the Windows Forms section, other controls are left out but are still available. Some of the left out controls were created with the .NET Framework but are not installed by default because they are judged hardly used. To add one or more of these left out controls, right-click anywhere in the Toolbox and click Choose Items... In the Choose Toolbox Items dialog box, click the .NET Framework Components tab, then click the check box of the desired control and click OK:

In addition to custom .NET controls, some other objects called ActiveX controls were used in previous versions of Visual Basic or Visual Studio and are available. To take care of compatibility issues, most previous ActiveX controls were reconfigured and adapted to be used in a .NET application. To add some of these left out controls, right-click anywhere in the Toolbox and click Choose Items... In the Choose Toolbox Items dialog box, click the COM Components tab, select the desired control and click OK

 

Dynamic Control Creation

 

Introduction

The objects used in a Windows application are defined in various assemblies. To add one of these controls to your application, you must first know the name of its class. With this information, you can declare a variable of its class. For example, a command button is an object of type Button that is based on the Button class. The Button class is defined in the System::Windows::Forms namespace of the System.Windows.Forms.dll assembly. Based on this, to create a button, you can create a handle to Button. Here is an example:

#pragma once

using namespace System;
using namespace System::Windows::Forms;

public ref class CFundamentals : public Form
{
	Button ^ btnSubmit;

public:
	CFundamentals(void);
};

After declaring the variable, you can use the gcnew operator to allocate memory for it:

CFundamentals::CFundamentals(void)
{
	btnSubmit = gcnew Button;
}

This is also referred to as dynamically creating a control. After declaring the variable and allocating memory for it, the control is available but doesn't have a host, which makes it invisible. Remember that the controls are positioned on a host like a form. The Form class itself contains a member variable named Controls. This member holds a list of the objects that are placed on a form. To specify that a control you have instantiated must be positioned on a for, the Controls member has a method named Add. Therefore, to make an object part of the form, pass its variable to the Add() method. Here is an example:

CFundamentals::CFundamentals(void)
{
	btnSubmit = gcnew Button;
	
	this->Controls->Add(btnSubmit);
} 

These two techniques of visual addition of objects and dynamic creation are the most used to add Windows controls to an application. The Windows controls are also called components.

Initializing the Components

Because there can be many controls used in a program, instead of using the constructor to initialize them, Visual Studio 2005 standards recommends that you create a method called InitializeComponent to initialize the various objects used in your application. Then simply call that method from the constructor of your form. This would be done as follows:

Header File: Fundamentals.h
#pragma once

#using <System.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Windows::Forms;

public ref class CFundamentals : public Form
{
    Button ^ btnSubmit;

public:
    CFundamentals(void);
    ~CFundamentals();

private:
    void InitializeComponent();
};
Source File: Fundamentals.cpp
#include "Fundamentals.h"

CFundamentals::CFundamentals(void)
{
    InitializeComponent();
}

void CFundamentals::InitializeComponent()
{
    btnSubmit = gcnew Button;

    this->Controls->Add(btnSubmit);
}

CFundamentals::~CFundamentals()
{
}
Source File: Exercise.cs
#include <windows.h>
#include "Inventory.h"

int  APIENTRY WinMain(HINSTANCE hInstance,
		     HINSTANCE hPrevInstance,
		     LPSTR lpCmdLine,
		     int nCmdShow)
{
    Application::Run(gcnew CFundamentals());
    return 0;
}

This would produce:

Notice that the control is created in the InitializeComponent() method.

Components Tracking on an Application

As you add and remove components on an application, you need a way to count them to keep track of what components and how many of them your application is using. To assist you with this, the .NET Framework provides a class called Container. This class is defined in the ComponentModel namespace that is itself part of the System namespace. To use a variable of this class in your application, declare a handle to Container. Because no other part of the application is interested in this variable, you should declare it private. This can be done as follows:

#pragma once

#using <System.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Windows::Forms;

public ref class CFundamentals : public Form
{
private:
	Button ^ btnSubmit;
	System::ComponentModel::Container ^ components;

public:
	CFundamentals(void);
	~CFundamentals();

private:
	void InitializeComponent();
};

After this declaration, the compiler can keep track of the components that are part of the form.

Control Derivation

If you are using a .NET Framework control, you must know the name of the class on which the control is based (and each control is based on a particular class). If you have examined the types of classes available but none implements the behavior you need, you can first locate one that is close to the behavior you are looking for, then use it as a base to derive a new class.

To derive a class from an existing control, you can use your knowledge of C++ inheritance to derive a new class. Here is an example:

public ref class Numeric : public System::Windows::Forms::TextBox
{
};

If you want to perform some early initialization to customize your new control, you can declare a constructor. Here is an example:

public ref class Numeric : public System::Windows::Forms::TextBox
{
public:
	Numeric() { }
};

Besides the constructor, in your class, you can add the member variable and methods you see fit. You can also use it to globally set a value for a member variable of the parent class. Once the control is ready, you can dynamically use it like any other control. Here is an example:

Header File: Fundamentals.h
#pragma once

#using <System.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Windows::Forms;

public ref class Numeric : public TextBox
{
public:
	Numeric() { }
};

public ref class CFundamentals : public Form
{
private:
	Numeric ^ txtBox;
	System::ComponentModel::Container ^components;

public:
	CFundamentals(void);
	~CFundamentals();

private:
	void InitializeComponent();
};
Source File: Fundamentals.cpp
#include "Fundamentals.h"

CFundamentals::CFundamentals(void)
{
    InitializeComponent();
}

void CFundamentals::InitializeComponent()
{
    txtBox = gcnew Numeric();
    this->Controls->Add(txtBox);
}

CFundamentals::~CFundamentals()
{
}
Source File: Exercise.cpp
#include <windows.h>
#include "Fundamentals.h"

int  APIENTRY WinMain(HINSTANCE hInstance,
		     HINSTANCE hPrevInstance,
		     LPSTR lpCmdLine,
		     int nCmdShow)
{
    Application::Run(gcnew CFundamentals());
    return 0;
}

This produce:

Fundamentals

 

Previous Copyright © 2007, yevol.com Next