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

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

.pdf
Скачиваний:
180
Добавлен:
24.05.2014
Размер:
26 Мб
Скачать

370 Project 2 CREATING AN APPLICATION USING MANAGED C++

In the Easy Tool application, a number of menu options are available to the user. Based on the menu option the user selects, appropriate action needs to be taken. The menu handler function is defined in the application header file as follows:

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

As you can see from the signature of the function, it takes two parameters. The

first parameter is the object that raised the event, and the second parameter is the

 

 

Y

EventArg object that contains the event data. Consider the following code snip-

 

L

pet, which illustrates the usage of this event handler:

 

F

pNewMenuItem = new Windows::Forms::MenuItem(S”&New”,new EventHandler(this,

&CMainWindow::MenuItemHandler));

M

 

 

 

A

 

An important point to mention here is that the Windows environment also pro-

E

 

vides some default event handling for controls that it provides. These default event handlers can be overridden to provide the functionality that you require. Consider the followingTcode sample, which shows how to override the Windows default event handling:

pToolBar->ButtonClick += new

System::Windows::Forms::ToolBarButtonClickEventHandler(this,&CMainWindow::Toolbar-

Handler);

The following is the code for the ToolbarHandler function:

void CMainWindow::ToolbarHandler(Object* sender, ToolBarButtonClickEventArgs* e)

{

// Evaluate the Button property to determine which button was clicked. switch (this->pToolBar->Buttons->IndexOf(e->Button))

{

case 0: New(); break;

case 1: Open(); break;

case 2: Save(); break;

case 3:

Team-Fly®

CREATING A MANAGED EXTENSIONS APPLICATION Chapter 12 371

PrintPreview();

break;

case 4:

Print();

break;

case 5:

HelpTopics();

break;

default:

break;

}

}

The MenuItemHandler function handles events raised by all user interface elements. The code for the function is shown here:

void CMainWindow::MenuItemHandler(Object* sender, EventArgs* e)

{

if(sender->Equals(pNewMenuItem))

{

New();

}

else if(sender->Equals(pOpenMenuItem))

{

Open();

}

else if(sender->Equals(pSaveMenuItem))

{

Save();

}

else if(sender->Equals(pPrintPreviewMenuItem))

{

PrintPreview();

}

else if(sender->Equals(pPrintMenuItem))

{

Print();

}

else if(sender->Equals(pHelpAboutMenuItem))

372 Project 2 CREATING AN APPLICATION USING MANAGED C++

{

AboutHelp();

}

else if(sender->Equals(pExitMenuItem))

{

Exit();

}

else if(sender->Equals(pCloseMenuItem))

{

CloseView();

}

else if(sender->Equals(pTileMenuItem))

{

Tile();

}

else if(sender->Equals(pCascadeMenuItem))

{

Cascade();

}

else if(sender->Equals(pClearAllMenuItem))

{

ClearAll();

}

else if(sender->Equals(pSaveAsMenuItem))

{

Save();

}

else if(sender->Equals(pNewWindowMenuItem))

{

NewWindow();

}

else if(sender->Equals(pPenWidthMenuItem))

{

PenWidthsDlg();

}

else if(sender->Equals(pThickLineMenuItem))

{

ThickLine();

CREATING A MANAGED EXTENSIONS APPLICATION Chapter 12 373

}

else if(sender->Equals(pHelpTopicsMenuItem))

{

HelpTopics();

}

else if(sender->Equals(pToolbarMenuItem))

{

pToolBar->Visible = !pToolBar->Visible ; pToolbarMenuItem->Checked = pToolBar->Visible;

}

else if(sender->Equals(pStatusbarMenuItem))

{

pStatusBar->Visible = !pStatusBar->Visible; pStatusbarMenuItem->Checked = pStatusBar->Visible;

}

else if(sender->Equals(pDrawLine))

{

DrawLine();

}

else if(sender->Equals(pDrawEllipse))

{

DrawEllipse();

}

else if(sender->Equals(pDrawRect))

{

DrawRect();

}

else if(sender->Equals(pDrawText))

{

DrawText();

}

else if(sender->Equals(pDrawFilledEllipse))

{

DrawFilledEllipse();

}

else if(sender->Equals(pDrawFilledRect))

{

DrawFilledRect();

374 Project 2 CREATING AN APPLICATION USING MANAGED C++

}

else if(sender->Equals(pDelegateHandler))

{

HandleDelegate();

}

}

Delegates

A delegate is a class with its own signature that is responsible for holding references to methods. It can hold only those methods that match its signature. Therefore, a delegate is similar to a callback or a type-safe function pointer.

The concept of delegates has been illustrated in the Easy Tool application using a simple calculator. The following code sample creates a delegate class named MyDelegate and implements event handling for the same:

public __delegate void MyDelegate(int, int); //Declare delegate

// Managed class with virtual event __gc class CMyClass

{

public:

virtual __event MyDelegate *E;

};

// Implement virtual events

__gc class EventSource : public CMyClass

{

public:

__event MyDelegate *E;

void Fire_E(int n1, int n2)

{

E(n1, n2);

}

};

// class to hold event handlers, the event receiver public __gc struct EventReceiver

CREATING A MANAGED EXTENSIONS APPLICATION Chapter 12 375

{

void Add(int num1, int num2)

{

String* pStr;

pStr = String::Format(“ {0} + {1} = {2}”, Convert::ToString(num1), Convert::ToString(num2), Convert::ToString(num1+num2));

MessageBox::Show(pStr, “Addition”);

}

void Subtract(int num1, int num2)

{

String* pStr;

pStr = String::Format(“ {0} - {1} = {2}”, Convert::ToString(num1), Convert::ToString(num2), Convert::ToString(num1-num2));

MessageBox::Show(pStr, “Subtraction”);

}

void Multiply(int num1, int num2)

{

String* pStr;

pStr = String::Format(“ {0} * {1} = {2}”, Convert::ToString(num1), Convert::ToString(num2), Convert::ToString(num1*num2));

MessageBox::Show(pStr, “Multiplication”);

}

void Divide(int num1, int num2)

{

if (num2 == 0)

{

MessageBox::Show(“Divide by Zero error”, “Division”); return;

}

String* pStr;

pStr = String::Format(“ {0} / {1} = {2} (Rounded)”, Convert::ToString(num1), Convert::ToString(num2), Convert::ToString(num1/num2));

MessageBox::Show(pStr, “Division”);

}

376 Project 2 CREATING AN APPLICATION USING MANAGED C++

};

void CMainWindow::HandleDelegate()

{

int nOp = 0; int nNum1 = 0; int nNum2 = 0; String* pOp;

//Simple calculation form

Form* f = new Form();

//Get the document of active view

CGDIPlusView* pActiveView = dynamic_cast<CGDIPlusView*> (this- >ActiveMdiChild);

CGDIPlusDoc* pActiveDoc = pActiveView->GetDocument();

f->AutoScaleBaseSize = System::Drawing::Size(5, 13);

f->Text = “Simple Calculation”;

f->ClientSize = System::Drawing::Size(200, 125);

ComboBox* cmbBox1 = new ComboBox(); cmbBox1->Location = System::Drawing::Point(70, 40); cmbBox1->Size = System::Drawing::Size(30, 20); cmbBox1->TabIndex = 2;

cmbBox1->set_DropDownStyle(ComboBoxStyle::DropDownList);

//Add existing operations cmbBox1->Items->Add(Convert::ToString(“+”)); cmbBox1->Items->Add(Convert::ToString(“-”)); cmbBox1->Items->Add(Convert::ToString(“*”)); cmbBox1->Items->Add(Convert::ToString(“/”));

Label* label1 = new Label();

label1->Location = System::Drawing::Point(15, 20); label1->Text = “Num1:”;

CREATING A MANAGED EXTENSIONS APPLICATION Chapter 12 377

label1->Size = System::Drawing::Size(40, 16);

Label* label2 = new Label();

label2->Location = System::Drawing::Point(15, 48); label2->Text = “Operation:”;

label2->Size = System::Drawing::Size(56, 16);

Label* label3 = new Label();

label3->Location = System::Drawing::Point(15, 75); label3->Text = “Num2:”;

label3->Size = System::Drawing::Size(40, 16);

Button* button1 = new Button();

button1->Location = System::Drawing::Point(35, 100); button1->Size = System::Drawing::Size(60, 20); button1->TabIndex = 4;

button1->Text = “OK”;

button1->DialogResult = System::Windows::Forms::DialogResult::OK ; //Make this “OK” button

Button* button2 = new Button();

button2->Location = System::Drawing::Point(105, 100); button2->Size = System::Drawing::Size(60, 20); button2->TabIndex = 5;

button2->Text = “Cancel”;

TextBox* textBox1 = new TextBox();

textBox1->Location = System::Drawing::Point(70, 15); textBox1->TabIndex = 1;

textBox1->Size = System::Drawing::Size(64, 20);

TextBox* textBox2 = new TextBox();

textBox2->Location = System::Drawing::Point(70, 65); textBox2->TabIndex = 3;

textBox2->Size = System::Drawing::Size(64, 20);

f->FormBorderStyle = FormBorderStyle::FixedDialog; f->MaximizeBox = false;

378 Project 2 CREATING AN APPLICATION USING MANAGED C++

f->MinimizeBox = false; f->AcceptButton = button1; f->CancelButton = button2;

f->StartPosition = FormStartPosition::CenterScreen;

f->Controls->Add(button1); f->Controls->Add(button2); f->Controls->Add(cmbBox1); f->Controls->Add(textBox1); f->Controls->Add(textBox2); f->Controls->Add(label1); f->Controls->Add(label2); f->Controls->Add(label3);

System::Windows::Forms::DialogResult res = f->ShowDialog(); if(res == System::Windows::Forms::DialogResult::OK )

{

String *pStr1, *pStr2; pStr1 = textBox1->Text; pStr1 = pStr1->Trim(); pStr2 = textBox2->Text; pStr2 = pStr2->Trim(); //Check for Empty values

if (pStr1 == “” || pStr2 == “”)

{

MessageBox::Show(“Operands missing...”, “Message”); return;

}

//Convert Strings to Integers nNum1 = Convert::ToInt16(pStr1); nNum2 = Convert::ToInt16(pStr2);

//Get the operand from the Combo box pOp = cmbBox1->Text;

//Check which operator (+,-,*,/) user has chosen if (pOp->CompareTo(“+”) == 0)

CREATING A MANAGED EXTENSIONS APPLICATION Chapter 12 379

nOp=1;

else if (pOp->CompareTo(“-”) == 0) nOp=2;

else if (pOp->CompareTo(“*”) == 0) nOp=3;

else if (pOp->CompareTo(“/”) == 0) nOp=4;

f->Close();

}

EventSource* pE = new EventSource;

EventReceiver* pR = new EventReceiver;

// Add event handlers if (nOp == 1)

pE->E += new MyDelegate(pR, &EventReceiver::Add); else if (nOp == 2)

pE->E += new MyDelegate(pR, &EventReceiver::Subtract); else if (nOp == 3)

pE->E += new MyDelegate(pR, &EventReceiver::Multiply); else if (nOp == 4)

pE->E += new MyDelegate(pR, &EventReceiver::Divide);

// Raise events pE->Fire_E(nNum1, nNum2);

}

The Complete Code Listing for the Easy Tool Application

Before you start dissecting the code of the Easy Tool application, let me give you a quick overview of the application, in terms of the files it comprises and the flow of control. The Easy Tool application is based on the Document/View architecture and comprises the following files:

Application header and CPP files