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

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

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

340 Project 2 CREATING AN APPLICATION USING MANAGED C++

Users can use the Delegate keyword implemented by languages. The compiler for these languages is derived from the MulticastDelegate class. A delegate is an instance of the delegate type and is used to reference the following:

Target object and instance of that object

Static method

Delegates can be used to reference methods. However, the signature of the

entry point of the method, and the second isYthe object, called the target, which is an instance of the class on which the method is invoked. The target may even be a null reference.

method should match the signature of the delegate type. The delegate references an instance of the method and stores twoLkinds of information. The first is the

 

A

Delegates may be multicast or singlecastF. A multicast delegate can be used to

 

E

invoke more than one method, whereas a singlecast delegate can be used to invoke

exactly one method.

 

M

T

 

Some of the members of this class are listed and described in Table 11-9.

Table 11-9 Members of the Delegate Class

 

 

Member Name

Description

 

 

Method

This is a property for the Delegate class and is used for retriev-

 

ing the static method of the delegate.

Target

This property is used to retrieve the instance of the class, which

 

invokes the instance method for the delegate.

Clone

This method is used to create a shallow copy for the delegate.

Combine

This method is used to concatenate the invocation lists in a mul-

 

ticast delegate.

CreateDelegate

This method is used to create a delegate.

Equals

This method is used to determine whether an object and a single-

 

cast delegate have the same invocation list, method instance, and

 

target object.

GetHashCode

This method is used to return a hash code for hashing algorithms.

GetInvocationList

This method is used to return the invocation list for the delegate.

 

 

 

Team-Fly®

INTRODUCTION TO GDI+, EVENTS, AND DELEGATES

Chapter 11

 

341

 

 

 

 

 

 

Another important class associated with delegates is the MulticastDelegate class. This class is discussed in the next section.

The MulticastDelegate Class

This class also belongs to the System namespace. Only compilers and other tools are permitted to derive from this class. This class has a list of delegates called an invocation list. An invocation list consists of many elements. However, it may at times consist of just one element. When you invoke a multicast delegate, the members in the invocation list are called.

Some of the members of this class are listed in Table 11-10.

Table 11-10 Members of the Multicast Delegate Class

Member Name

Description

Method

This is a property for this class and is used for retrieving the

 

static method of the delegate. This property is inherited from

 

the Delegate class.

Target

This property is used to retrieve the instance of the class,

 

which invokes the instance method for the delegate. This

 

property is inherited from the Delegate class.

Clone

This method is used to create a shallow copy for the delegate.

 

This property is inherited from the Delegate class.

DynamicInvoke

This public method is used to invoke the method of the cur-

 

rent delegate dynamically.

Equals

This method is used to determine whether an object and the

 

multicast delegate have the same invocation list, method

 

instance, and target object.

GetHashCode

This method is used to return a hash code for hashing algo-

 

rithms. This method is overridden.

GetInvocationList

This method is used to return the invocation list for the multi-

 

cast delegate. This method is overridden.

 

 

You have learned about the basics of event handling and the function of delegates in this section. In the next section, I discuss event handling in managed code.

342 Project 2 CREATING AN APPLICATION USING MANAGED C++

Event Handling in Managed Code

In managed event handling, you need to set up an event source and an event receiver by using the event_source and the event_receiver attributes. You specify type=managed to inform that events are to be handled in a managed context.

To declare a method as an event, you need to use the _event keyword in an event source class. You need to declare the method but do not define it. The compiler automatically defines the method implicitly when the method is made as an event. Therefore, the compiler would result in a compile error if the method is defined. Another point to keep in mind while declaring events is that the return type of the event handler must match the return type of the delegate, and the return type of the delegate must comply with the Common Language Specification.

To work with event handlers, you need to define them. You define an event handler in an event receiver class. Event handlers are nothing but methods that are used to handle events.

Once you have defined event handlers, the next step is to attach these event handlers to events. In an event receiver class, you can use the _hook keyword to attach event handlers to events. To detach the event handler from events, you can use the _unhook keyword. There is no limit to the number of event handlers that you can attach to an event or the number of events that can be attached to an event handler.

To trigger an event, you need to call the data member or the method, which is declared as an event, in the data source class. The equivalent event handler that is attached to the events will be called.

NOTE

You can raise an event only from the class in which it is declared. Therefore, to raise an event, you need a member function that is accessible from outside the class.

The important keywords for event handling in managed code are described in the following sections.

layout_dependent

INTRODUCTION TO GDI+, EVENTS, AND DELEGATES

Chapter 11

 

343

 

 

 

 

 

 

_event

The _event keyword is used to declare an event. You can apply this keyword to a method, interface, or data member. Once you have created an event by using the _event keyword, all event handlers that are hooked to the event, by using the _hook keyword, will be executed when the event occurs. As stated in the previous section, the _event keyword cannot have a definition.

event_source

The event_source keyword is used to specify a class or a structure as an event source. The syntax for this keyword is as follows:

[event_source (type)]

The type parameter is an enumeration and can take any of the following values:

native. Used for unmanaged C/C++ code. This is the default value for the type parameter.

com. Used for COM code.

managed. Used for Managed Extensions for C++ code.

event_receiver

The event_receiver keyword is used to specify the class or the structure that will be used as an event receiver. The syntax for this keyword is as follows:

[event_receiver (type [, layout_dependent = false ])]

The parameter is a Boolean value and needs to be specified only if the type parameter is assigned the value com. The possible values for the layout_dependent parameter are as follows:

true. This value specifies that the signature of the delegates in the event receiver class must match the event source. Also, the names in the event receiver must match the names in the event source.

false. This value specifies that the signature of the delegates do not need to match the event handlers. Also, the names of the handlers do not need to match those of the event source. This value is the default value for the layout_dependent parameter.

344 Project 2 CREATING AN APPLICATION USING MANAGED C++

The default value for the Type parameter is native. However, if the class is managed, the default is changed from native to managed.

_hook

The _hook keyword is used to associate or attach an event handler with an event. The _hook keyword can be used in two forms. The syntax for the _hook keyword is as follows:

long_hook (&SourceClass::EventMethod, source, &ReceiverClass::Handlermethod [,

receiver = this]);

long_hook (interface, source);

The parameters in the preceding syntax are described here:

&SourceClass::EventMethod. This is a pointer to the event method, which is being attached to the event handler method.

interface. This is the interface name that is being attached to the receiver. This parameter is applicable only for COM event receivers in which the value for the layout_dependent is true.

source. This points to an instance of the event source.

&ReceiverClass::HandlerMethod. This is a pointer to the event handler method that is hooked to an event.

receiver. This points to an instance of the event receiver class.

The first form of the _hook keyword can be used for COM event handlers where

the layout_dependent parameter for event_receiver is false. The second form

can be used for a COM event receiver where the layout_dependent parameter is

true.

_unhook

The _unhook keyword is used to detach an event handler from an event. There are three forms for the _unhook keyword. The syntax for the _unhook keyword is as follows:

long_unhook (&SourceClass::EventMethod, source, &ReceiverClass::HandlerMethod [,

receiver = this]);

long_unhook (interface, source)

long_unhook (source)

INTRODUCTION TO GDI+, EVENTS, AND DELEGATES

Chapter 11

 

345

 

 

 

 

 

 

The first form of the _unhook keyword can be used in most of the situations. However, the second form can be used only for a COM event receiver, and the third form can be used to unhook all delegates.

In this section, I have discussed the important keywords used for event handling in managed code. In the next section, I discuss the Unified Event Model.

The Unified Event Model

Many times, it may be required by components to pass back information related to events to their clients. Many programming languages take care of this through function callbacks. Although C supports function callbacks, C++ lacks callbacks for object methods. One of the solutions to this problem is an event model provided by COM. However, this event model is difficult to maintain and implement.

The Unified Event Model proves to be a better solution in this regard. It allows events to be used in an effective manner such that the component is no longer dependent on its client, and also ensures the component’s reusability.

This model supports both single-threaded and multithreaded usage. However, it does not support simultaneous multithread access to the data.

You can derive classes from event source and receiver classes in this model. The model also supports extended sourcing and receiving in the derived class.

Summary

In this chapter, you learned about GDI+, its various classes, and the System.Drawing namespace. You also learned about events and delegates and handling events in managed code. You will learn to use these events, delegates, and classes in the forthcoming project.

This page intentionally left blank

Chapter 12

Creating a

Managed

Extensions

Application

Chapter 11 introduced you to the basic concepts of GDI+, events, and delegates. It is time now to implement those concepts.

Project Case Study

Red Sky IT Systems is a reputed training institute in New York that trains students and IT professionals in the latest information technologies. It is a 10-year-old institute and has many centers across New York. It has an experienced faculty. The institute has a number of divisions, such as the Front Office, the Sales and Marketing division, the Software Development division, and the Services division. Each division has a Division Head to monitor the proceedings of the division.

Red Sky IT Systems offers various programs and courses. Students can select from a range of courses and admission is based on an entrance test. The biggest unique selling point of Red Sky IT Systems is that students also get to develop real-life applications. The students are taught not just from books but also get a lot of exposure through real-life projects at the end of the course. The responsibility of developing these projects for the various courses lies with the Software Development division of the institute.

As part of the VC++.NET course, the institute requires a project to be built using Managed C++ code. The responsibility for developing the application is with the following team of the Software Development division:

Susan Ward, project manager

David Wong, developer

Mary Peterson, developer

The team has decided to create a dummy paint application by using Managed Extensions code and has named the application Easy Tool. Using the application, users can type, change font, and paint. The team also decided to add the functionality of a Calculator, which can be used to illustrate the concepts of delegates.

The team also decided on the following development life cycle (DLC) for the project:

CREATING A MANAGED EXTENSIONS APPLICATION Chapter 12 349

1.Requirements analysis phase

2.Design phase

3.Coding phase

4.Testing phase

5.Execution phase

The following sections discuss each of the stages of the DLC in detail.

The Requirements Analysis Phase

In this phase, the team decides on the requirements for the project. It is also one of the most crucial phases in a project development, as all the rest of the phases depend upon this phase. The requirements of the application as decided by the team are as follows:

The application should include text functionality, such as enabling users to change the font name and font size, apply bold or italics, and so on.

The application should allow for paint functionality using pens and brushes.

The application should allow for basic calculations, such as addition, subtraction, and multiplication.

The application should provide menus from which users may choose all the preceding options.

The Design Phase

This phase of the DLC is used for designing the screens for the application. The screens for the application are decided based on the requirements of the project in the requirements analysis phase.

Figure 12-1 shows a sketch of the screen for the Easy Tool application based on the requirements of the project.

The screen will contain a number of menu options, such as File, Edit, Pen, View, Draw, Window, and Help. Clicking on a menu item will display the corresponding drop-down list to the user.

The drop-down list for the File menu option is displayed in Figure 12-2.