Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Microsoft Visual C++ .NET Professional Projects - Premier Press

.pdf
Скачиваний:
168
Добавлен:
24.05.2014
Размер:
25.78 Mб
Скачать

310 Project 2 CREATING AN APPLICATION USING MANAGED C++

//…

}

In the next section, you will learn about data type conversion methods referred to as boxing and unboxing.

Boxing

As mentioned in Chapter 1, .NET types areYof two varieties:

Value types. Include data types likeLInt32, enumerated types, and structs.

Reference types. Include Class,FInterface, String, and Array. Some salient features of the valueMtypes are as follows:

The type need not inherit from any other type.

The type will not have any other types derived from it.

A variable representing an object of value type contains the object itself and not a reference to the location of the data.TEA

A variable representing an object of Reference type contains the reference or address of the actual data.

Converting a value type to a Reference type is called boxing. Retrieving the value from a Reference type is called unboxing. In boxing, all values are converted to the type Object, whereas in unboxing, you need to specify the type into which you want to convert the unboxed value. A sample code snippet illustrating boxing and unboxing follows:

Int32 n = 6; // Create an unboxed value type variable

Object o = n;

// boxing

n = (Int32)o; //unboxing

I will round off this discussion of Managed Extensions for C++ with a small application. I will call it the ImageConverter. It is a simple application that allows you to view images of different formats and convert them to the supported formats.

Creating a GUI Application

Although the Managed C++ wizard creates a console-based application, you still have the flexibility to convert it into a GUI application. To do so, you first need

Team-Fly®

INTRODUCTION TO MANAGED EXTENSIONS Chapter 10 311

to declare the namespace System::Windows::Forms that contains classes for commonly used GUI elements such as forms, buttons, menus, and list boxes. However, the biggest drawback to creating GUI applications using Managed Extensions for C++ is the lack (currently) of a drag-and-drop designer. You need to create the basic form and add all the controls through code. Here you go!

ImageConverter – Managed C++ Application

I will now step you through a very simple application that displays graphic files and allows you to convert between several of the popular graphic formats:

1.Create a new Visual C++ application and use the template Managed C++ Application. Name the application ImageConverter.

2.From the Solution Explorer, open the file ImageConverter.cpp. All the code for implementing the application will be added here.

You will design this application as a form-based application with a File menu that will have the options Open, SaveAs, and Exit.

The application will make use of classes declared in the following namespaces:

System::Windows::Forms, System::Windows::Drawing

System::Windows::Drawing::Imaging namespaces

Therefore, add the following declarations to the CPP file:

#using <System.dll>

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

using namespace System;

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

using namespace System::Drawing::Imaging;

A form needs to be added to the application. To do this, you will create a form class, which derives from the Form class, as shown here:

__gc class MyForm : public Form

{

public:

MyForm();

312 Project 2 CREATING AN APPLICATION USING MANAGED C++

};

Next, you need to add a menu to this form. You will add the menu in the constructor of the form class. Define the constructor as indicated in the following snippet:

MyForm::MyForm()

{

MainMenu *mnu=new MainMenu();

MenuItem *item = mnu->MenuItems->Add(“File”); item->MenuItems->Add(“Open”,new EventHandler(this,&MyForm::OnMnuOpen)); item->MenuItems->Add(“SaveAs”,new EventHandler(this,&MyForm::OnMnuSave)); item->MenuItems->Add(“Exit”,new EventHandler(this,&MyForm::OnMnuExit)); this->Menu=mnu;

}

The preceding code snippet accomplishes the following:

Creates an object of the type MainMenu. This class is declared under the

System::Windows::Forms namespace.

Creates a MenuItem object in the Forms namespace, and adds it to the

MainMenu object.

Creates the options that appear under the File menu option as MenuItems, and adds them to the File MenuItem object.

This creates the entire menu. But the menu becomes visible only when its reference is passed to the Menu property of the form, which is done by the following line of code:

this->Menu=mnu;

To each of the menu items that appear under the File option, an event handler has been assigned. For example:

item->MenuItems->Add(“Open”,new EventHandler(this,&MyForm::OnMnuOpen));

All event handler methods have the following signature:

void MethodName (Object* sender, EventArgs *e);

INTRODUCTION TO MANAGED EXTENSIONS Chapter 10 313

In the preceding method, the first parameter, sender, is the control that generated the event. The second parameter, EventArgs, is a structure that contains the target control and the method name that will handle the event.

Each of these menu items generates an event when it is clicked on. Therefore, as you do in MFC, you need to associate the event for each menu item to its event handler method:

item->MenuItems->Add(“Open”,new EventHandler(this,&MyForm::OnMnuOpen));

In the preceding code, the menu item Open is associated with the event handler

method OnMnuOpen.

Next, you need to add the declarations of the event handlers to the form class. Also, to display the graphic file opened, add a declaration of an object of the

Bitmap class (which belongs to System::Drawing::Imaging).

The complete declaration of the MyForm class is as follows:

__gc class MyForm : public Form

{

public:

MyForm();

protected:

void OnPaint(PaintEventArgs *e); private:

Bitmap *m_Bitmap;

void OnMnuOpen (Object* sender, EventArgs *e); void OnMnuSave(Object* sender, EventArgs *e); void OnMnuExit (Object* sender, EventArgs *e);

};

In the preceding code snippet, the method OnPaint is an event handler that is invoked whenever the form has to be repainted (this is the same as MFC’s OnPaint method).

The next step is to implement the menu event handler methods:

void MyForm::OnMnuOpen(Object* sender, EventArgs *e)

{

//Using Windows Open dialog box

314

 

Project 2

 

CREATING AN APPLICATION USING MANAGED C++

 

 

 

 

 

 

 

 

 

 

OpenFileDialog *ODlg = new OpenFileDialog ();

 

 

 

ODlg->Filter = ODlg->Filter->Concat((String *)”Image Files (JPEG, GIF, BMP,

 

 

 

etc.)|*.jpg;*.jpeg;*.gif;*.bmp;*.tif;*.tiff;*.png”);

 

 

 

ODlg->Filter =ODlg->Filter->Concat(ODlg->Filter,”|JPEG files

 

 

 

(*.jpg;*.jpeg)|*.jpg;*.jpeg”);

 

 

 

ODlg->Filter =ODlg->Filter->Concat(ODlg->Filter,”|GIF Files (*.gif)|*.gif”);

 

 

 

ODlg->Filter =ODlg->Filter->Concat(ODlg->Filter,”|BMP Files (*.bmp)|*.bmp”);

ODlg->Filter =ODlg->Filter->Concat(ODlg->Filter,”|TIFF Files (*.tif;*.tiff)|*.tif;*.tiff”);

ODlg->Filter =ODlg->Filter->Concat(ODlg->Filter,”|PNG Files (*.png)|*.png”); ODlg->Filter =ODlg->Filter->Concat(ODlg->Filter,”|All files (*.*)|*.*”); ODlg->FilterIndex=3;

//Handling the OK click

if ((ODlg->ShowDialog ()) == DialogResult::OK)

{

String *fileName = ODlg->FileName; if (fileName->Length != 0)

{

try

{

m_Bitmap = new Bitmap (fileName); AutoScroll = true; AutoScrollMinSize =m_Bitmap->Size; Invalidate ();

}

catch(Exception *e)

{

MessageBox::Show (“Invalid image format”, “Error”);

}

}

}

}

In the preceding code snippet, the OpenFileDialog class implements the standard Windows Open dialog box. The Filter property of the class accepts a string, which specifies the types of files to be displayed in the dialog box. For handling strings, the System::String class is used. This class provides a wide variety of

INTRODUCTION TO MANAGED EXTENSIONS Chapter 10 315

methods for string manipulation, such as Copy, Clone, IndexOf, LastIndexOf, and so on.

When the user clicks on the OK button, the bitmap is displayed and the scrolling property of the form is set.

Similarly, the OnMnuSave method displays the Windows standard Save As dialog box. If the user clicks on the OK button, save the bitmap in the format specified using the Bitmap::Save() method. This method accepts two parameters:

The first parameter is a string representing the name and path of the file.

The second parameter is an enumerated type, which specifies the bitmap format in which the file should be saved.

The code for the OnMnuSave event handler follows:

void MyForm::OnMnuSave(Object* sender, EventArgs *e)

{

SaveFileDialog *SDlg=new SaveFileDialog();

SDlg->Filter=”JPEG files (*.jpg;*.jpeg)|*.jpg;*.jpeg|GIF Files (*.gif)|*.gif|BMP Files (*.bmp)|*.bmp|TIFF Files (*.tif;*.tiff)|*.tif;*.tiff”; if(SDlg->ShowDialog()==DialogResult::OK)

{

String *str1;

//FilterIndex refers to the index of the file types in the Filter string that is //currently selected by the user.

int tr1=SDlg->FilterIndex;

//The file name entered by the user str1=SDlg->FileName;

switch(tr1)

{

case 1:

m_Bitmap->Save(str1, ImageFormat::Jpeg); break;

case 2:

m_Bitmap->Save(str1, ImageFormat::Gif); break;

case 3:

316 Project 2 CREATING AN APPLICATION USING MANAGED C++

m_Bitmap->Save(str1, ImageFormat::Bmp);

break;

case 4:

m_Bitmap->Save(str1, ImageFormat::Tiff);

break;

}

}

}

The Save method of the Bitmap class accepts two parameters:

A string containing the path and file name of the file to be stored.

An enumerated image type value, which can have values like ImageFor-

mat::Gif and ImageFormat::Jpeg.

The OnMnuExit method is the simplest of all. See it for yourself!

void MyForm::OnMnuExit(Object* sender, EventArgs *e)

{

this->Close();

}

The MyForm class is now ready with all of its methods. You just need to create an instance of it whenever the application executes:

int _tmain(void)

{

Application::Run(new MyForm()); // instantiating the MyForm class

return 0;

}

Build and execute the application. Figure 10-1 shows a running instance of the application.

INTRODUCTION TO MANAGED EXTENSIONS Chapter 10 317

FIGURE 10-1 The ImageConverter application

Summary

This chapter introduced you to Managed Extensions for C++, which enables you to create managed applications in Visual C++. You learned the basic components involved in Managed C++ programming. Finally, you created a Managed C++ application, which involved creating a form using the Form class.

In chapters following this, you will further explore Managed C++ programming.

This page intentionally left blank

Chapter 11

Introduction to GDI+, Events, and Delegates