Building Graphical User Interface: C++/Common Language Infrastructure (C++/CLI)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 63

Computer Programming

9 Building Graphical User Interface

9. Building Graphical User Interface


M. Heege, Expert C++/CLI: .NET for Visual C++ Programmers. Berkeley, CA:
Apress, 2007. [Electronic resource]
I. Horton, Ivor Horton's Beginning Visual C++ 2010. Indianapolis, Ind.: Wiley,
2010. (Ch. 1, and C++/CLI sections from Ch. 2 to Ch. 10)
[Electronic resource]
1

Computer Programming
9 Building Graphical User Interface

C++/CommonLanguageInfrastructure(C++/CLI)
y So far the C++ programs we have learnt essentially
follow the ANSI standard (Native C++)
y It means that those programs should be able to be compiled

and run in any computer platform, including Windows, UNIX,


Linux, Mac OS, etc.

y Microsoft has developed in its Visual C++ 2010 a


new set of extension keywords (known as the
C++/CLI) to generate code that targets the .NET
framework. The code is referred to as managed
code
y Hence the codes that are not controlled by the .NET

framework are known as unmanaged code.

Native C++ Unmanaged code


C++/CLI Managed code

Computer Programming
9 Building Graphical User Interface

Computer Programming

9 Building Graphical User Interface

This specification underlies all of the languages that implement the .NET
Framework and defines standards for a common type system, and
functionality, that all languages must implement. This is how third-party
languages can integrate with the Framework.

C++ Type
bool
char
unsigned char
wchar_t, __wchar_t
unsigned short int
short int
unsigned long int
long int
unsigned int
int
long long, __int64
unsigned long long
float
double
(wchar_t*)

CTS
Boolean
SByte
Byte
Char
UInt16
Int16
UInt32
Int32
UInt32
Int32
Int64
UInt64
Single
Double
Decimal
String^

Values
true or false
ASCII character, -128 to 127
(8-bit)
0 to 255
(8-bit)
Unicode character, 0 to 65535,
(16-bit)
0 to 65535
(16-bit)
-32768 to 32767
(16-bit)
0 to 4294967295
(32-bit)
-2147483648 to 2147483647
(32-bit)
0 to 4294967295
(32-bit)
-2147483648 to 2147483647
(32-bit)
-9223372036854775808 to 9223372036854775807 (64)
0 to 18446744073709551615
(64-bit)
(+/-)1.2e38 to (+/-)3.4e38
(32-bit)
(+/-)2.2e308 to (+/-)1.8e308
(64-bit)
(+/-)1e-28 to (+/-)7.9228e28
(128-bit)
4
Unicode character string

Computer Programming
9 Building Graphical User Interface

When developing applications using Visual C++ 2010,


it can be either managed or unmanaged applications

An unmanaged application runs directly under Windows

No extra software is needed to run the application

A managed application, however, runs in CLR (Common


Language Runtime ) - Microsoft's implementation of CLI

Your computer needs to install the Microsoft .NET


Framework in order to run a managed application.
Unmanaged
application

Managed C++
.NET framework classes
Common Language Runtime

Computer Programming
9 Building Graphical User Interface

CommonLanguageRuntime
Source
code
Managed
code

VB.NET

VC#.NET

VC++.NET

Compiler

Compiler

Compiler

Assembly
IL Code

Assembly
IL Code

Assembly
IL Code

Unmanaged
Component

Common Language Runtime


JIT Compiler
Native Code

Operating System Services

Computer Programming
9 Building Graphical User Interface

So why do we want to develop managed


application?
Most new Windows systems have included the .NET

Framework It is installed when installing Windows


or its Updates

More importantly, Microsoft provides a set of

powerful .NET class libraries that can be used only


by managed applications
Aims: Productivity and Security

One of the important tasks that greatly benefits


from .NET class libraries is the development of
graphical user interface (GUI).
7

Computer Programming
9 Building Graphical User Interface

GraphicalUserInterface
User-friendliness is one of the important criteria
to evaluate the merit of a computer system
Particularly for home users, a user friendly

operating system is very important

Console
Command-line interface has been replaced by
application

Graphical User Interface (GUI) for personal


computers
Mouse vs Keyboard

Graphical User Interface


y Using a graphical approach, through icons,

menus, windows, etc. to interact with users.

Computer Programming
9 Building Graphical User Interface

AA typical
typical desktop
desktop of
of aa
personal
personal computer
computer full
full of
of
icons,
icons, menus,
menus, windows,
windows, etc.
etc.
to
to communicate
communicate with
with users
users

Computer Programming
9 Building Graphical User Interface

Targets

10

Computer Programming
9 Building Graphical User Interface

using namespace std; // unmanaged


int main()
{
cout << "Please input your name: ";
char name[50];
// char* name; name = new char [50];
cin.getline(name, 50);
int m = 8, n = 9;
cout << "Hello, " << name << " 8 x 9 = " << m*n << endl;
return 0;
}
using namespace System; // .NET, managed
int main()
{
Console::Write ("Please input your name: ");
String^ name = Console::ReadLine();
Int32 m = 8, n = 9;
Console::WriteLine("Hello, {0} 8 x 9 = {1}", name, m*n);
return 0;
}

11

Computer Programming
9 Building Graphical User Interface
using namespace std;
// cout, endl
using namespace System;
// Console::WriteLine
int main()
// array and pointer examples
{
float* f = new float(1.2); delete f;
Single^ mf = gcnew Single(1.2);
int ud[ ] = {1,2,3,4,5,6};
// 1-dim array
array<int>^ md = {1,2,3,4,5,6};
// gcnew array <Int32> {1,2,3,4,5,6}
cout << ud[0] + md[5] << endl; Console::WriteLine(ud[0]+md[5]);

CLI Array

// dynamic array
int* up; up = new int [100];
up[99] = 1; delete [] up;
array<int>^ mp; mp = gcnew array<int>(100);
mp[99] = 1;

double u2d[2][3] = { {1,2,3}, {4,5,6} };


// 2-dim array
array<double, 2>^ m2d = { {1,2,3}, {4,5,6} };
// array <Double, 2>
cout << u2d[0][0]+u2d[1][2] << endl;
Console::WriteLine(m2d[0,0]+m2d[1,2]);
// array of pointer
double* u2p[2];
u2p[0] = new double [3]; u2p[1] = new double [3];
u2p[0][0] = 1; u2p[1][2] = 6; delete [] u2p[0]; delete [] u2p[1];
array<double, 2>^ m2p = gcnew array<double, 2>(2, 3);
m2p[0,0] = 1; m2p[1,2] = 6;

return 0;
}

12

Computer Programming
System::Windows::Forms
9 Building Graphical User Interface

MFC: Microsoft Foundation Library


ATL: Active Template Library
window layout and controls
For Windows, GUI controls are contained in a form. Hence
developing Windows Forms means developing GUIs

CreatingWindowsForms

For unmanaged applications, developing Forms needs knowing the

MFC or ATL libraries - difficult and NOT supported by C++/CLI.

Visual C++ 2008 offers Rapid Application Development (RAD)

support for building managed Windows Forms applications

Managed applications allow GUI to be incorporated in a program

following a simple click-and-pick procedure


y

Something similar to using Visual Basic

Partially vs fully known

Managed Windows Forms applications can also use native C++

libraries

y Allow GUI to be introduced into our previously developed

unmanaged applications.

13

Computer Programming
9 Building Graphical User Interface

DevelopingasimpleGUI
Step 1:
Start Visual
Studio 2010.
Click New
Project...

14

Computer Programming
9 Building Graphical User Interface

Step 2

Select
Select Windows
Windows
Forms
Forms
Application
Application

15

Computer Programming
9 Building Graphical User Interface

AA plain
plain form
form
will
will be
be created
created
for
for you
you to
to fill
fill in
in
the
the details
details

16

Computer Programming
9 Building Graphical User Interface

UsingtheToolboxtoBuildtheUserInterface
Step 3
The
The toolbox
toolbox is
is aa
tabbed
tabbed window
window that
that
contains
contains all
all GUI
GUI
control
control elements
elements
If
If you
you cannot
cannot see
see it,
it,
click
click view
view

ToolBox
ToolBox
Try
Try to
to click
click the
the pin
pin
icon,
icon, see
see what
what
happen
happen
17

Computer Programming
9 Building Graphical User Interface

Step 3
From
From the
the
toolbox,
toolbox, drag
drag
aa Label,
Label, aa
TextBox
TextBoxand
and
aa Button
Buttonto
to
the
the form
form

18

Computer Programming
9 Building Graphical User Interface

Step 4
You
You can
can find
find the
the
property
property of
of each
each
component
component in
in the
the
Properties
window
Properties window

(If
(If cannot
cannot find
find it,
it, select:
select:
View->
View-> Other
Other Windows
Windows
->
-> Properties
Properties Window)
Window)

Try
Try to
to modify
modify the
the
label
label to
to "Please
"Please
enter
your
enter your name"
name"
and
the
label
and the label of
of the
the
button
button to
to "OK"
"OK" by
by
modifying
modifying the
the Text
Text
item
item in
in their
their
Properties
Properties
19

Computer Programming
9 Building Graphical User Interface

You
You can
can find
find in
in
the
the Properties
Properties
window
window the
the
name
name of
of each
each
control.
control.
e.g.
e.g. the
the name
name
for
for this
this text
text box
box
is
is textBox1
textBox1
It
It is
is important
important
for
for developing
developing
program
program codes
codes
for
for them
them
20

Computer Programming
9 Building Graphical User Interface

Try
Try to
to resize
resize the
the form.
form. You
You
will
will find
find that
that the
the size
size of
of the
the
textbox
textbox will
will not
not change
change
accordingly.
accordingly.
By
By default,
default, all
all components
components
are
are anchored
anchored with
with respect
respect
to
the
top
and
left
to the top and left
boundaries
boundaries of
of the
the form.
form.
Hence,
Hence, not
not only
only the
the size,
size,
but
the
position
of
all
but the position of all
components
components will
will not
not
change
change when
when resizing
resizing the
the
form
form

21

Computer Programming
9 Building Graphical User Interface

Step 5

Click
Click the
the textbox
textbox
On
On the
the Properties
Properties
window,
window, change
change the
the
Anchor
Anchorproperty
property to
to
"Top
Left
Right"
"Top Left Right"
Try
Try to
to enlarge
enlarge your
your
form.
form. You
You will
will see
see the
the
size
of
the
textbox
size of the textbox
changes
changes with
with the
the
form
size
form size

22

Computer Programming
9 Building Graphical User Interface

WritingEventHandler
A major task that a GUI designer needs to do is to determine

what will happen when a GUI is invoked

Every GUI component may generate different kinds of "events"

when a user makes access to it using his mouse or keyboard

E.g. if a user moves his mouse on top of a button, an event


of that button will be generated to the Windows system

E.g. if the user further clicks, then another event of that


button will be generated (actually it is the click event)

For any event generated, the system will first check if there is

an event handler, which defines the action for that event

For a GUI designer, he needs to develop the event handler to

determine the action that he wants Windows to take for that


event.
Writing C++ programs

23

Computer Programming
9 Building Graphical User Interface

Any event?
No

Yes

Is there
an event handler
for that
event?

Yes

No
Run event
handler

The part that a GUI designer needs to develop


24

Computer Programming
9 Building Graphical User Interface

Step 6 Add Event Handler


Double-click the OK button such that the default
event handler button1_Click will be introduced in
Form1.h
Add the following codes to the function button1_Click()

System::Void button1_Click(System::Object^ sender,


System::EventArgs^ e)
{ String^ message = "Hello "; // ^ specifies a tracking handle
String^ title = "Welcome"; // String is a managed class
MessageBox::Show(message,title,
MessageBoxButtons::OK);
} // A tracking handle has similarities to a native C++ pointer

When
When the
the OK
OKbutton
button is
is clicked,
clicked, aa message
message
box
box will
will be
be invoked
invoked to
to show
show aa message.
message.
25

Computer Programming
9 Building Graphical User Interface

String^ message = "Hello ";


y The symbol "^" identifies a tracking handle of class

String
y A tracking handle is similar to a native C++ pointer

which stores an address, but the address it contains


is automatically updated if the object it references is
moved
y No address arithmetic or casting is allowed for
tracking handles
y Tracking handle is for referencing objects created in
CLR heap, including objects that are of reference
class type (e.g. the String class)
26

Computer Programming
9 Building Graphical User Interface

MessageBox::Show(message,title,
MessageBoxButtons::OK);
Show() is a static member function of the
MessageBox class. We can call any member
function of a class without instantiating an object of
that class
message is the message to be displayed in the message

box. It is of the managed class String^


title is the title of the message box. It is of the
managed class String^
OK is a static member enumeration of the class
MessageBoxButtons. If OK is used, only the OK button will
be shown. There can be other buttons, such as, YesNo,
OKCancel, AbortRetryIgnore, etc.
Use Help of Visual C++ 2010 to learn MessageBox and MessageBoxButtons
27

Computer Programming
9 Building Graphical User Interface

Step 7 Build and run the program

28

Computer Programming
9 Building Graphical User Interface

Manageddatatypes CommonTypeSystem(CTS)
All GUI inputs are of managed type, data
received from these GUIs may be different from
the unmanaged version
For example, the string received from the textbox is

of managed type

It needs conversion if we want to use it with unmanaged


codes

char abc[] = textBox1->Text;


unmanaged type

Text is the input made by user in


textBox1. It is of managed type
29

Computer Programming
9 Building Graphical User Interface

y Conversion between managed type and unmanaged


type: String^ char *
#include <cstring>

// Due to strcat; ADD at the beginning

using namespace System::Runtime::InteropServices; //Must add


private: System::Void button1_Click(System::Object^ sender,
System::EventArgs^ e)
{ char message[100] = "Hello "; //Unmanaged type
String ^ tbstr = textBox1->Text;
char *name =
(char*)Marshal::StringToHGlobalAnsi(tbstr).ToPointer();
strcat(message,name); //Combine "Hello " with name
String^ Mmge=Marshal::PtrToStringAnsi((IntPtr)message);
String^ title = "Welcome";
MessageBox::Show(Mmge,title,MessageBoxButtons::OK);
Marshal::FreeHGlobal((IntPtr)name); // just like delete
}
30

Computer Programming
9 Building Graphical User Interface

using namespace
System::Runtime::InteropServices;
The class name such as Marshal is defined under
the System::Runtime::InteropServices
namespace
i.e. the full name of the class is
System::Runtime::InteropServices::Marshal
The above statement needs to be added at the beginning

of Form1.h with the other namespace definitions.

String ^ tbstr = textBox1->Text;


For C++/CLI, any string should be defined as a
handle to an object of the System::String class
Here, textBox1->Text is a managed string. Thats why it

should be assigned to the handle tbstr as above.

31

Computer Programming
will
will return
return an
an object
object of
of type
type IntPtr
IntPtr
9 Building Graphical User Interface

char *name = (char*)Marshal::


StringToHGlobalAnsi(tbstr).ToPointer();
:
Marshal::FreeHGlobal((IntPtr)name);
To convert a managed string to an unmanaged

string, we use the function StringToHGlobalAnsi(),


which is a static member function of the class
HGlobal Marshal
= Global

heap

The function will return an object of class IntPtr


We need to call the member function ToPointer() of
IntPtr to convert the object to a pointer, but we havent
specified what kind of pointer it is
Finally, casting the pointer to a character pointer
As some memory is used in the unmanaged heap
(pointed by name), we free it using the function
32
FreeHGlobal().

Computer Programming
9 Building Graphical User Interface

String^ mes = "Hello char *nam;


1 char *nam = (char*)Marshal::StringToHGlobalAnsi(mes).ToPointer();
Marshal::FreeHGlobal((IntPtr)nam);
2 pin_ptr<unsigned char> nam=&(Encoding::ASCII->GetBytes(mes)[0]);
3 pin_ptr<const wchar_t> wnam = PtrToStringChars(mes);
4 int L = mes->Length;
char *nam = new char [L+1];
for (int i=0; i<L; i++) nam[i] = mes[i];
nam[L] = 0;
delete [ ] nam;

33

Computer Programming
9 Building Graphical User Interface

strcat(message,name);
String^ Mmge=Marshal::PtrToStringAnsi((IntPtr)message);
y strcat() combines the string "Hello " in message

with the string the user entered into the textbox,


and stores it in message
y Marshal::PtrToStringAnsi((IntPtr)message)
allocates a managed String and copies the
unmanaged ANSI string message into it.

Another method:
String^ Mmge = gcnew String(message);

34

Computer Programming
9 Building Graphical User Interface

y Conversion between managed type and unmanaged


type: String^ char *
y Notice that both native C++ and managed C++ codes can

be present in the same C++/CLI program


y However, the heap for the native C++ variables is the
unmanaged heap, which needs to be freed after use. In
the above, the memory pointed by name has to be freed.
y

The heap for the managed C++ variables is the CLR


heap, which is also termed garbage-collected heap.
y

We do NOT need to worry about the management and clean-up


of this heap.
To allocate memory in the CLR heap, use the operator gcnew

y The above example is for illustrating how to convert

between managed and unmanaged types


y A simpler managed C++ program can do the same job.
35

Computer Programming
9 Building Graphical User Interface

Step 8 Receive TextBox Input


y Modify the function button1_Click() as follows:
System::Void button1_Click(System::Object *
sender, System::EventArgs * e)
{ String ^ message = "Hello ";
String ^ title = "Welcome";
Char a='!'; //A managed character
MessageBox::Show(message + textBox1->Text + a,
title, MessageBoxButtons::OK);
}
// A text or string can easily be joined to
another string by direct "adding", if they are of
managed type, e.g. String^, Char, etc.
Char in fact is the System::Char base class for CLR; it is equivalent to
__wchar_t in C++/CLI
36

Computer Programming
9 Building Graphical User Interface

Step 9 Build and run the program

Enter a name into textBox1


37

Computer Programming
9 Building Graphical User Interface

y Conversion between managed types:


int String^
System::Void button1_Click(System::Object * sender,
System::EventArgs * e)
{ String^ title = "Welcome";
String^ message = "The number is ";
int a=12;
String^ no =""+a;//int converted to string automatically
MessageBox::Show(message+no,title,MessageBoxButtons::OK);
}

y We can replace the above by:


String^ no; //default is ""
no=no+a; //no = a.ToString();

What about String^ int?

int a = Convert::ToInt32(no)

38

Computer Programming
9 Building Graphical User Interface

WindowsForms
Windows API (Application Programming Interface)
HWND hwndMain = CreateWindowEx(
0, "MainWinClass", "Main Window",
WS_OVERLAPPEDWINDOW | WS_HSCROLL | WS_VSCROLL,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
(HWND)NULL, (HMENU)NULL, hInstance, NULL);
ShowWindow(hwndMain, SW_SHOWDEFAULT);
UpdateWindow(hwndMain);

.NET Framework
Form^ fm = gcnew Form();
fm->Text = "Main Window";
fm->Show();

39

Computer Programming
9 Building Graphical User Interface

using namespace System


using namespace System::Windows::Forms;
int main()
{
Form^ fm = gcnew Form();
fm->Text = "Hello From WinFormDemo";
fm->ShowDialog();
// File: winformdemo.cs
}
using System;
using System.Windows.Forms;
namespace WinFormDemo
{
public class SimpleForm : Form
{
public SimpleForm() {
Text = Hello From WinFormDemo;
}
public static void Main() {
Application.Run(new SimpleForm());
}
}
}

40

Computer Programming
9 Building Graphical User Interface
using namespace System;
using namespace System::Windows::Forms;
using namespace System::Drawing;
void b_Click(Object^ sender, EventArgs^ e)
{
Button^ b = (Button^) sender;
b->Text = "Click!";
MessageBox::Show("test");
}
int main()
{
Form^ fm = gcnew Form();
fm->BackColor = Color::LightGreen;
fm->Text="Hello From WinFormDemo";
Button^ bt = gcnew Button;
bt->Location = Point(30,30);
bt->Size = Size(100,50);
bt->BackColor = Color::FromArgb(100,0,0,255);
bt->Click += gcnew EventHandler(&b_Click);
fm->Controls->Add(bt);
fm->ShowDialog(); //Application::Run(fm);
}

41

Computer Programming
9 Building Graphical User Interface
ref class userForm: Form
{
public:
userForm()
{
Text = "userForm";
bt = gcnew Button;
bt->Location = Point(30,60);
bt->Size.Width = 100;
bt->Height = 30;
Controls->Add(bt);
bt->Click += gcnew EventHandler(this, &userForm::b_Click);
tb = gcnew TextBox;
tb->Location = Point(30,30);
tb->Size.Width = 100;
tb->Height = 50;
Controls->Add(tb);
}
private:
Button^ bt;
TextBox^ tb;
void b_Click(Object^ sender, EventArgs^ e)
{
Button^ b = (Button^)sender;
b->Text = tb->Text;
}
};

int main()
{
userForm^ u = gcnew userForm;
u->ShowDialog();
}
42

Computer Programming
9 Building Graphical User Interface

System.Windows.Forms Control Classes


Class

Description

Button

Push buttons

CheckBox

GroupBox

Group boxes

NumericUpDown

HScrollBar

Horizontal
scroll bars

Spinner
buttons
(up-down
controls)

PictureBox

Label

Label
controls that
display
static text

Controls
that
display
images

Check boxes

List boxes whose


items include
check boxes

CheckedListBox
ComboBox

Combo boxes

DataGrid

Controls that
display tabular
data

DataGridTextBox

Edit controls
hosted by
DataGrid controls

DateTimePicker

Controls for
selecting dates
and times

PrintPreviewCont
rol

Controls
that
display
print
previews

ProgressBar

Progress
bars

PropertyGrid

Controls
that list
the
properties
of other
objects

LinkLabel

Label
controls that
display
hyperlinks

ListBox

List boxes

ListView

List views
(display flat
lists of
items in a
variety of
styles)

RadioButton

Monthcalendar
controls

Radio
buttons

RichTextBox

Rich-edit
controls

MonthCalendar

StatusBar

Status
bars

TabControl

Tab
controls

TextBox

Edit
controls

ToolBar

Toolbars

ToolTip

Tooltips

TrackBar

Track
bars
(slider
controls)

TreeView

Tree views
(display
hierarchica
l lists of
items)

VScrollBar

Vertical
scroll
bars

43

Computer Programming
9 Building Graphical User Interface

Mouse and Keyboard Events/Handlers


OnKeyDown

A key is pressed

KeyEventArgs

OnKeyPress

A character is typed on the


keyboard

KeyPressEventArgs

OnKeyUp

A key is released

KeyEventArgs

OnMouseDown

A mouse button is pressed

MouseEventArgs

OnMouseEnter

The mouse cursor enters a


form

EventArgs

OnMouseOver

The mouse cursor pauses

EventArgs

OnMouseLeave

The mouse cursor leaves a


form

EventArgs

OnMouseMove

The mouse cursor moves


over a form

MouseEventArgs

OnMouseUp

A mouse button is released

MouseEventArgs

OnMouseWheel

The mouse wheel is rolled

MouseEventArgs

over a form

44

Computer Programming
9 Building Graphical User Interface

Form-Level Events
OnActivated

A form is activated

OnClosed

A form is closed

OnClosing

A form is about to close

OnDeactivate

A form is deactivated

OnGotFocus

A form receives the input focus

OnLoad

A form is created

OnLocationChanged

A form is moved

OnLostFocus

A form loses the input focus

OnPaintBackground

A forms background needs


repainting

OnSizeChanged

A form is resized
45

Computer Programming
9 Building Graphical User Interface

Common Dialog Classes Defined in System.Windows.Forms

Class

Dialog Type

ColorDialog

Color dialog boxes for choosing


colors

FontDialog

Font dialog boxes for choosing


fonts

OpenFileDialog

Open File dialog boxes for choosing


files

PageSetupDialog

Page Setup dialog boxes for


entering page setup parameters

PrintDialog

Print dialog boxes for entering print


parameters

SaveFileDialog

Save File dialog boxes for entering


file names

46

Computer Programming
9 Building Graphical User Interface

Exercise 9.1
Modify the form as shown below. When a user
enters 2 numbers and click Add, a message box
will be shown to display the sum of the 2
numbers.
Don't forget to
change the title
of the form

47

Computer Programming
9 Building Graphical User Interface

Exercise 9.1 (cont.)


Hint 1 : To convert an unmanaged string to an
integer, you may include the library <stdlib.h>
and use
int atoi (char *abc)
// Return an integer converted, if
// possible, from the string abc
Hint 2: If unmanaged type is NOT used, you may
consider using the managed member function of
the Convert class:
int System::Convert::ToInt32(String)
48

Computer Programming
9 Building Graphical User Interface

WorkingwithUnmanagedCode
Thanks to the IJW (It Just Works) technology,
managed C++ application can directly work with
the legacy C++/C codes
It means all C++ programs developed previously can

be used directly with managed programs

It is a unique feature of Visual C++, not the case for

other components of Visual Studio, such as Visual


Basic or Visual C#

The simplest way for a managed C++ application


to call legacy C++/C functions is by means of
using static library.
49

Computer Programming
9 Building Graphical User Interface

GeneralApproach
DogClass.h

Main Program

CatClass.h
class CAT

MainProject.cpp

class CAT

#include "DogClass.h"
#include "CatClass.h"
void main()
{

DOG Bobby;
CAT Frisky;
Bobby.DrawShape();
Frisky.DrawShape();

:
Frisky.PlaySound();
}

public:
:
int DrawShape();
int PlaySound();
public:
int DrawShape();
int PlaySound();

Library for CAT

};

Library
DOG
10 for
20 2d
35};5f 43 23
43 23
10 20 2d 35 5f 43 23
43 23

:
:

22 6f
21 44 dd 23
22 6f
21 44 dd 23
50

Computer Programming
9 Building Graphical User Interface
DogClass.h
CatClass.h
class CAT
class CAT
{

public:
:
int DrawShape();
int PlaySound();
public:
int DrawShape();
int PlaySound();

Library for CAT

};

Library
DOG
10 for
20 2d
35};5f 43 23
43 23
10 20 2d 35 5f 43 23
43 23

22 6f
21 44 dd 23
22 6f
21 44 dd 23

Managed C++
Application

:
CAT c;
DOG d;
c.DrawShape();
d.DrawShape();

:
51

Computer Programming
9 Building Graphical User Interface

Example:Addingtwonumbers
Step 1: Create the class required
class Arithmetic
// declare the class
{
public: void SetNum (int in1, int in2);
int GetNum1();
int GetNum2();
int Add();
// return num1 + num2
private: int num1;
int num2;
};
Arithmetic.h
Arithmetic.h

52

Computer Programming
9 Building Graphical User Interface

Step 2: Implement the class


void Arithmetic::SetNum(int in1, int in2)
{
num1 = in1; num2 = in2;
}
int Arithmetic::GetNum1()
{
return num1;
}
int Arithmetic::GetNum2()
For
{
return num2;
For each
each member
member
}
function,
function, develop
develop
int Arithmetic::Add()
the
the required
required
{
return num1 + num2;
codes
}
codes

53

Computer Programming
9 Building Graphical User Interface

Step 3: Test the class


Create the header file and a main() for testing
the functionality of the class
This main() is only for testing purpose, not

supposed to be used in real application


class Arithmetic
// declare the class
{
public: void SetNum (int in1, int in2);
int GetNum1();
Arithmetic.h
Arithmetic.h
int GetNum2();
int Add();
// return num1 + num2
private: int num1;
int num2;
};
54

Computer Programming
9 Building Graphical User Interface

MainTest.cpp
MainTest.cpp Just a testing
#include <iostream>
using namespace std;
console application,
#include "Arithmetic.h"
not supposed to be
// Implement the functions and test them
used in real
void Arithmetic::SetNum(int in1, int in2)
application
{
num1 = in1; num2 = in2;
}
int Arithmetic::GetNum1()
int main()
{
return num1;
{ Arithmetic Op;
}
Op.SetNum(3,4);
int Arithmetic::GetNum2()
int Num1 = Op.GetNum1();
{
return num2;
int Num2 = Op.GetNum2();
}
cout << Num1 << " + " << Num2
int Arithmetic::Add()
<< " = " << Op.Add() << endl;
{
return num1 + num2;
return 0;
}
}
55

Computer Programming
9 Building Graphical User Interface

Step 4: Create the library with Visual C++


Assume your class is fully tested. You can create
your library using Visual C++
In Visual C++ 2010, start a new Win32 Console

Application as usual

Set the location to store your library project, e.g.

E:\VS_Proj
Set the project name, e.g. LibArith
However, on choosing the options in the

Application Settings window, check Static


library and uncheck the option Precompiled
header.
56

Computer Programming
9 Building Graphical User Interface

57

Computer Programming
9 Building Graphical User Interface

3. Choose Pure
MSIL Common
Language
Runtime Support
(/clr:pure)
4. Click Apply and
OK

1. In the Visual Studio environment, click Project


Properties
2. Go to Configuration Properties General
Project Defaults Common Language
Runtime support
58

Computer Programming
9 Building Graphical User Interface

In the Visual Studio environment, click Project


Add New Item... and choose Header File
(.h)
Set the Header File name to, e.g. Arithmetic
Click Odd and the header file Arithmetic.h will
be added to the project LibArith
Type the class declaration.

59

Computer Programming
9 Building Graphical User Interface

Type
Type your
your class
class declaration
declaration here
here
Remember
Remember to
to comment
comment your
your codes
codes

60

Computer Programming
9 Building Graphical User Interface

In Visual Studio, click ProjectAdd New Item...

and choose C++ File (.cpp)

Set the C++ source file name, e.g. ArithCodes


Click Add and the C++ source file ArithCodes.cpp

will be added to the project LibArith

You may verify it by checking the Solution Explorer

Type the codes for the implementation of the

member functions

Remember to include your header file and note its


location

Build the library by clicking Build Solution.


61

Computer Programming
9 Building Graphical User Interface

You
You need
need to
to enter
enter the
the correct
correct path
path of
of the
the header
header file
file
It
It shows
shows that
that the
the Arithmetic.h
Arithmetic.h is
is in
in the
the same
same
folder
folder as
as that
that of
of ArithCodes.cpp
ArithCodes.cpp

62

Computer Programming
9 Building Graphical User Interface

Step 5: Locate the library and header


files
Locate the files Arithmetic.h and
LibArith.lib
Arithmetic.h shows the class definition

From its contents, we know how to use the class

LibArith.lib contains the codes for the

implementation of the member functions

Note that it is in object code form. No one can see or


modify the source code.

63

Computer Programming
9 Building Graphical User Interface

E:\VS_Proj\LibArith
E:\VS_Proj\LibArith
\Debug
\Debug

E:\VS_Proj\LibArith
E:\VS_Proj\LibArith
\LibArith
\LibArith

64

Computer Programming
9 Building Graphical User Interface

Step 6: Integrating into the application


Open a project
of Windows
Forms
Application,
e.g. ArithForm
in the folder e.g.
E:\VS_Proj\
Design the form
as shown:

65

Computer Programming
9 Building Graphical User Interface

Copy Arithmetic.h and LibArith.lib to the


current folder
E:\VS_Proj\ArithForm\ArithForm
In the Visual Studio environment, click
ProjectAdd Existing Item... under
ArithForm. Select All Files (*.*) to show
all the files in the folder
Add Arithmetic.h and LibArith.lib to the
project.

66

Computer Programming
9 Building Graphical User Interface

y Double-click the Add button and add the


following codes to button1_Click()
#include "Arithmetic.h"
#include <stdlib.h> // For atoi()
// Must be added at the beginning of Form1.h
using namespace System::Runtime::InteropServices;
private: System::Void button1_Click(System::Object^ sender,
System::EventArgs^ e)
{ int num1, num2, res; // variables used by unmanaged code
String ^ tbstr1 = textBox1->Text;
String ^ tbstr2 = textBox2->Text;
char *strNum1 =
(char*)Marshal::StringToHGlobalAnsi(tbstr1).ToPointer();
char *strNum2 =
(char*)Marshal::StringToHGlobalAnsi(tbstr2).ToPointer();
67

Computer Programming
9 Building Graphical User Interface

num1 = atoi(strNum1);
num2 = atoi(strNum2);

Arithmetic Op;
// Class from the static libray
Op.SetNum(num1,num2);
// Using the unmanaged codes
res = Op.Add();
// Using the unmanaged codes
MessageBox::Show(""+res,"Result",MessageBoxButtons::OK);
Marshal::FreeHGlobal((IntPtr)strNum1);
Marshal::FreeHGlobal((IntPtr)strNum2);
}

68

Computer Programming
9 Building Graphical User Interface

After
After building
building the
the
application,
application, the
the
result
result is
is shown
shown See
See the
the added
added
Arithmetic.h
Arithmetic.h and
and
LibArith.lib
LibArith.lib here
here
69

Computer Programming
9 Building Graphical User Interface

You
You may
may double-click
double-click
LibArith.lib.
LibArith.lib. You
You
can
can only
only see
see some
some hex
hex
codes.
codes. No
No source
source
codes
codes can
can be
be found
found
70

Computer Programming
9 Building Graphical User Interface

To
To see
see how
how to
to use
use the
the
class
class Arithmetic,
Arithmetic,
double-click
double-click
Arithmetic.h
Arithmetic.h
71

Computer Programming
9 Building Graphical User Interface

Step 7: Execute the application

The
The addition
addition is
is
done
done by
by the
the
library
library function
function

72

Computer Programming
9 Building Graphical User Interface

Exercise 9.2
Modify your static library such that it will provide
the other 3 arithmetic functions: subtraction,
multiplication and division; all of them in integer
arithmetic.
For division, detect if the divisor is 0.
Your GUI should include 3 more buttons namely
"Subtract", "Multiply", and "Divide" such that
when any one is clicked, the corresponding
function of the static library will be called and
the result will be shown in a message box.
73

Computer Programming
9 Building Graphical User Interface

CreatingaMultipleFormInterface
It is common that an application may have
more than one form

In addition, one form may be invoked by another


form
Each form has its own GUI

To add one more form to a project, we need to


follow the steps below:
1. Add one more form class to your project
2. Design the form layout
3. Set the properties of the GUIs in the new form
4. Update the program code of the original form.
74

Computer Programming
9 Building Graphical User Interface

Example

Radio button

When
When the
the button
button Show
Show Card
Card is
is
clicked,
Form2
will
be
shown
clicked, Form2 will be shown
75

Computer Programming
9 Building Graphical User Interface

Step 1: Specification of the program


1. A user is asked to select one and only one of the

four cards

2. If the user does not check any of the radio button,

no card will be shown

3. If the user clicks the Show Card button, another

form (Form2) will be shown with the selected card

4. The user cannot access the original form (Form1)

until he clicks the OK button of Form2. Form2 is


known as the modal form.

5. If the user clicks on the picture, the card will

toggle between face-up and face-down.

76

Computer Programming
9 Building Graphical User Interface

Project name: Chap9p5

Step 2: Develop Form1


GroupBox
GroupBox
All
All controls
controls inside
inside
aa group
box
group box will
will
be
grouped
be grouped
together
together

RadioButton
RadioButton
For
For the
the radio
radio
buttons
buttons inside
inside aa
group
group box,
box, only
only
one
one of
of them
them can
can
be
selected
be selected

Make sure the TabStop property of


the radio buttons (under Behavior)
are False
TabStop enables the user to give the
focus to this control using the TAB key
77

Computer Programming
9 Building Graphical User Interface

Step 3: Develop Form2

In the Solution Explorer, right click your project


name and select Add New Item...

Select Windows Form. Give a name, say Form2, to


your new form (Form2 will also be the class name
of the form)

You will see another set of files added to your


project, e.g. Form2.cpp, Form2.h.

78

Computer Programming
9 Building Graphical User Interface

PictureBox
PictureBox
allows
allows you
you to
to
put
put aa picture
picture
into
into it.
it.
The
The picture
picture
can
can be
be
obtained
obtained from
from
aa file
file

We
We can
can add
add the
the control
control we
we
want
want to
to here
here
79

Computer Programming
9 Building Graphical User Interface

View Code

Base class

namespace chap9p5
// define the namespace of the class
{
Derived class
public ref class Form2 : public System::Windows::Forms::Form
{
// The class name is Form2.
public:
Form2(void) // The constructor. Define the things
{
:
// that will be done when the class
}
// is instantiated. TO BE WRITTEN LATER.
:
private: System::Windows::Forms::Button^ button1;
:
// The button is defined here
private: System::Windows::Forms::PictureBox^ pictureBox1;
:
// The picture box is defined here
private:
void InitializeComponent(void)
{
:
// Record the properties of the controls
}
Form2.h
Form2.h is
is used
used mainly
mainly for
for defining
defining
};
the
the class
class structure
structure of
of this
this form
form
}
80

Computer Programming
9 Building Graphical User Interface

Rather
Rather than
than writing
writing many
many lines
lines of
of code,
code,
we
can
simply
define
the
function
of
we can simply define the function of aa
button
button as
as OK
OK (i.e.
(i.e. the
the form
form will
will close
close ifif
itit is
clicked)
in
the
DialogResult
is clicked) in the DialogResult item
item
of
the
Properties
window
of the Properties window

Returned enumerated
values of a dialog box
81

Computer Programming
9 Building Graphical User Interface

double-click Show Card

Step 4: Implement the handler of Form1


#include "Form2.h"

// Add to the beginning of Form1.h

private: System::Void button1_Click(System::Object ^ sender,


System::EventArgs ^ e)
{
// Called when button1 of Form1 is clicked
int card = 0;
// 0 = no card, 1 = sA, 2 = hA
// 3 = cA, 4 = dA
if (radioButton1->Checked)
card = 1;
// spade ace selected
if (radioButton2->Checked)
card = 2;
// heart ace selected
if (radioButton3->Checked)
card = 3;
// club ace selected
if (radioButton4->Checked)
card = 4;
// diamond ace selected
Form2 ^ F2 = gcnew Form2(card); //Form2 defined in Form2.h
F2->ShowDialog(); // Show modal form, return DialogResult value
}
82
82

Computer Programming
9 Building Graphical User Interface

An
An object
object of
of Form2
Form2 is
is
created
in
the
gc
heap
created in the gc heap
pointed
pointed by
by F2
F2
Use
Use gcnew
gcnew because
because Form2
Form2is
is
aa reference
reference type
type under
under
Common
Type
System
Common Type System (CTS)
(CTS)

Since
Since we
we want
want to
to tell
tell Form2
Form2
which
card
a
user
has
which card a user has selected,
selected,
the
the constructor
constructor of
of Form2
Form2 has
has to
to
be
be modified
modified to
to accept
accept one
one input
input
parameter
parameter that
that indicates
indicates the
the
selected
card
selected card

Form2 ^ F2 = gcnew Form2(card);


To
F2->ShowDialog();
To show
show Form2,
Form2, we
we need
need to
to call
call the
the
member
member function
function ShowDialog()
ShowDialog() of
of
the
the class
class Form2
Form2

If ShowDialog() is called, Form2 is a modal form

we cannot access other forms unless we close Form2

If Show() is called instead, Form2 is a modeless

form

we can access other forms without closing Form2.


83

Computer Programming
9 Building Graphical User Interface

In Form2.h

Step 5: Implement the constructor and


other functions of Form2
Form2(int c)// The constructor is modified by adding
{
// an input parameter
InitializeComponent();
cd_no = c; // 0 = no card, 1 = sA, 2 = hA
// 3 = cA, 4 = dA
face = 0; // By default, the card is face up (0).
// When the card is clicked, the
// state will toggle from face-up to
// face-down or vice versa
ShowCard(); // Show card based on the info in "card"
}
// Two private variables are added
private:
int cd_no;// To keep the info of the card selected
int face; // See the comment above
84

Computer Programming
9 Building Graphical User Interface

Add a member function at the end

Visible
Visible is
is aa property
property of
of
pictureBox.
If
it
is
0,
the
pictureBox. If it is 0, the
pictureBox
pictureBox will
will not
not be
be
visible.
visible.

void ShowCard()
{ if (cd_no == 0)
pictureBox1->Visible = 0;
The
The file
file for
for Spade
Spade Ace
Ace
if (cd_no == 1)
{ pictureBox1->Visible = 1;
pictureBox1->Image = Image::
FromFile("e:\\temp\\cards\\s1.gif");
}
// codes for other cards follow
FromFile
FromFile is
is aa static
static member
member
function
of
the
Image
function of the Image class.
class. It
It
returns
a
file
handler
of
an
image
returns a file handler of an image
stored
stored at
at the
the specified
specified location
location

Image
Image is
is another
another property
property of
of
pictureBox.
It
defines
the
pictureBox. It defines the
location
location where
where the
the picture
picture
can
can be
be found
found
85

Computer Programming
9 Building Graphical User Interface

Image property

Visible
property
86

Computer Programming
9 Building Graphical User Interface

The
The file
file for
for Heart
Heart Ace
Ace
if (cd_no == 2)
{
pictureBox1->Visible = 1;
pictureBox1->Image =
Image::FromFile("e:\\temp\\cards\\h1.gif");
}
if (cd_no == 3)
The
The file
file for
for Club
Club Ace
Ace
{
pictureBox1->Visible = 1;
pictureBox1->Image =
Image::FromFile("e:\\temp\\cards\\c1.gif");
}
if (cd_no == 4)
The
The file
file for
for Diamond
Diamond Ace
Ace
{
pictureBox1->Visible = 1;
pictureBox1->Image =
Image::FromFile("e:\\temp\\cards\\d1.gif");
}
\\ is
is aa special
special character
character for
for escape
escape
sequence.
If
we
want
to
use
sequence. If we want to use itit as
as just
just
the
the \\ character,
character, we
we have
have to
to use
use \\
\\

87

Computer Programming
9 Building Graphical User Interface

Double-click pictureBox1

// Define the thing to be done when pictureBox1 is


clicked
private: System::Void pictureBox1_Click(System::Object
^ sender, System::EventArgs ^ e)
{
if (cd_no != 0) // A card is selected
{ if (face == 0) // face = 0 means face-up
{ pictureBox1->Image = Image::
FromFile("e:\\temp\\cards\\b1fv.gif");
// Show the card as facing down, actually a
// different file is shown
face = 1; // Currently face-down
} // codes for face==1 follow
If
If user
user clicks
clicks on
on the
the pictureBox,
pictureBox, itit will
will change
change from
from
face-up
face-up to
to face-down
face-down or
or vice
vice versa
versa
It
It is
is controlled
controlled by
by the
the member
member variable
variable "face"
"face"
88

Computer Programming
9 Building Graphical User Interface

else
// It is face-down
{ ShowCard();
face = 0; // currently face-up
}
}
}

Step 6: Build and run the project

89

Computer Programming
9 Building Graphical User Interface

Exercise 9.3
Follow the above steps to build the project.
Add one more button in Form1 such that if it is clicked, your
program will randomly display one of the four cards,
disregarding the selection of the user.
Hint: We can generate a random number by using the
function int rand(void), which returns a random integer
between 0 to 0x7FFF. Remember to include stdlib.h before
you use this function.
Remark: On using rand(), the random sequence is
repeatable on every execution of the program. If we don't
want it to be repeatable, what should we do? (Hint: learn
srand(unsigned int) )
90

Computer Programming
9 Building Graphical User Interface

Drawing in .NET
.NET Drawing Classes: in System.Drawing.
Graphics Device Interface (GDI) software to interface with the
graphics hardware.
GDI+ Graphics Primitives (System.Drawing.Drawing2D):
Bitmap, Font, HatchBrush, LinearGradientBrush, Pen,
SolidBrush, TextureBrush, DrawArc, DrawCurve,
DrawEllipse, DrawIcon, DrawImage, DrawLine, DrawPie,
DrawPolygon, DrawString, FillEllipse, FillPie, FillPolygon,
FillRectangle.
91

Computer Programming
9 Building Graphical User Interface

WhatisGDI+?

System::Drawing

Using the .NET framework class librarys


Windows Form controls is NOT the only way to
graphically present data

Windows Form controls sometimes are too


restrictive that make the displaying of graphic data
difficult, e.g.

Drawing a line on the screen

Putting an image on a button

Showing a sequence of images as an animation, etc.

Graphics can be put into a program only if a related


control is found, hence it restricts creativity.
92

Computer Programming
9 Building Graphical User Interface

To programmers, GDI+ is just a set of


namespaces that provides library functions for
the rendering of 2D graphics
An API
It provides support for colors, pens, fonts, image
transformations, etc.

However, it does not have advanced animation and


3D rendering features found in DirectX

GDI+ is originated from the Windows Graphical


Device Interface (GDI) with several improvements

GDI+ is device independent output of the graphics


can be shown on screens and printers.

Programmer makes calls to methods provided by GDI+ classes and those


methods in turn make the appropriate calls to specific device drivers.
93

Computer Programming
9 Building Graphical User Interface

When starting a Windows Form project in Visual


C++ 2010, GDI+ has been included by default

One can verify this by checking if the Form class


contains the following statement
y
y
y

using namespace System::Drawing;


and if the References part of the solution contain
Right-click project name and select
System.Drawing
References...

For detailed discussion of GDI+, one can refer to


y

Microsoft MSDN home page:


http://msdn.microsoft.com/en-us/library/ms533798

94

Computer Programming
9 Building Graphical User Interface

GraphicsClass
Graphics^ g = CreateGraphics();

//create a Graphics object with a form

array <Point>^ pts = gcnew array<Point>(100);


for (int x = 0; x<100; x++) pts[x] = Point(x, 80-80*Math::Sin(x/10.0));

g->DrawLines(Pens::Green, pts);

//draw a sine curve of one pixel width

g->TranslateTransform(50, 20);

//translate the origin to (50, 20)

g->DrawLines(gcnew Pen(Color::Red, 3), pts);

delete g;

//with width 3 pixels

//remove Graphics object from memory

95

Computer Programming
9 Building Graphical User Interface

PaintEvent
Void Form1_Paint(Object^

sender, PaintEventArgs^

e)

{
Graphics^ g = e->Graphics;

//Graphics object that needs repaint


//do not try to delete this object

array <Point>^ pts = gcnew array<Point>(100);


for (int x = 0; x<100; x++) pts[x] = Point(x,80-80*Math::Sin(x/10.0));

g->DrawLines(Pens::Green, pts);

//draw a sine curve

g->TranslateTransform(50, 20);

//translate the origin to (50, 20)

g->DrawLines(gcnew Pen(Color::Red,3), pts); //draw with 3 pixels width


}

96

Computer Programming
9 Building Graphical User Interface

CreatingGraphicsObjectfromBitmap
Bitmap^ bm = gcnew Bitmap(800, 600); //a Bitmap object of size 800x600
Graphics^ g = Graphics::FromImage(bm);//a Graphics object of the Bitmap

g->FillEllipse(Brushes::Green, 10, 10, 780,580); //draw on the Bitmap


delete g;

BackgroundImage = bm;

//display the Bitmap

bm->Save("test.jpg", Imaging::ImageFormat::Jpeg);

//save the Bitmap

Computer Programming
9 Building Graphical User Interface

Example:MovingGraphicandPicture

98

Computer Programming
9 Building Graphical User Interface

Requirements:
1. The card will fly from left to right and the circle

(graphic) will fly from right to left

2. A counter is put at the bottom to show the current

horizontal position of the card

3. When clicking on the counter, the motion of both

the circle and card will stop. When clicking on the


counter again, the motion restarts.

99

Computer Programming
9 Building Graphical User Interface

Step 1: Design the Form

Project name:
Chap9gdi

Add a label here

Drag a timer into the form. It


will result in the timer1 as
shown in the bottom of the
window

100

Computer Programming
9 Building Graphical User Interface

Timer is one of the .NET GUI controls

When enabled, it generates an event for every


clock tick, by default, of 100 ms

An event handler can be designed in response to


every clock tick; hence, it is useful to the tasks that
need to be done periodically in time,

e.g. to show an animation

By default, timers are disabled

All defaults can be changed in the Properties


window.

101

Computer Programming
9 Building Graphical User Interface

timer1 is enabled

Event is generated at
every 10 ms

Name of the timer

102

Computer Programming
9 Building Graphical User Interface

PaintEventstotheForm
All controls (e.g. a graphic) to a form generate
a paint event when they determine that the
form needs to be updated, e.g. at every clock
tick of the timer

More specifically, a paint event is triggered when

a control is created, resized, or restored; or

when another control that had overlaid it is moved

By default, the paint event of a control is handled


by one of its member functions called OnPaint()

Additional event handler can be added if one wants


to do additional thing whenever the control is
103
updated.

Computer Programming
9 Building Graphical User Interface

To add an additional
Paint event handler
for a form, click this
button
In the Paint item,
add the name of the
event handler
104

Computer Programming
9 Building Graphical User Interface

Step 2: Develop the Event Handlers


From Requirements 1 & 2, a picture and a
graphic will move across the form; and the
position of the picture is shown on the label

It can be implemented by changing the positions of


the picture and graphic at every clock tick. To
achieve this, we need to have
a handler for the clock tick event that

will show the position of the picture on the label;


generate a paint event for the whole form at every clock
tick

a handler for the paint event that will show the


picture and graphic on the form at the new positions.

105

Computer Programming
9 Building Graphical User Interface

From Requirement 3, the picture and the


graphic will stop moving when one clicks on the
label

To achieve this, we need to have a handler for the


label click event that

toggles the state of the timer between "Enabled"


and "Not Enabled" every time the label is clicked.

106

Computer Programming
9 Building Graphical User Interface

Step 2a: The Event Handler for Timer1


public: Form1(void)
// Form1 constructor
{ X = 0;
// Initialize the counter to 0
InitializeComponent();
} // X is the x-coordinate of the picture
private: int X;

// Serve as a counter of the


//
position of the picture
private: System::Void timer1_Tick(System::
Object ^ sender, System::EventArgs ^ e)
{ if (X%10 == 0)
// If X is a multiple of 10,
label1->Text =""+X; // show its value on label1
this->Invalidate();
}

// Generate a Paint message to


//
Form1
107

Computer Programming
9 Building Graphical User Interface

this->Invalidate()
this->Invalidate()
Equivalent to Invalidate()
Just to indicate we are not
talking about other
Invalidate(), but the
Invalidate() of Form1
Cannot use
Form1->Invalidate()
since Form1 is the name of a
class, not an object

Invalidate() method is
the manual way of
triggering a paint event
Since we are calling the
Invalidate() of Form1,
hence the paint event
handler of Form1 will be
called (which is
Form1_Paint().)

Invalidate(): Invalidates the entire surface of the


control and causes the control to be redrawn.
108

Computer Programming
9 Building Graphical User Interface

Step 2b: The Event Handler


Label1_Click
private: System::Void
label1_Click(System::Object ^ sender,
System::EventArgs ^ e)
{
timer1->Enabled = !(timer1->Enabled);
// Whenever the label is clicked, the
// state of timer1 toggles between enable
// and disable
}
109

Computer Programming
9 Building Graphical User Interface

double-click

Step 2c: The Event Handler Form1_Paint


private: System::Void Form1_Paint(System::Object ^
sender, System::Windows::Forms::PaintEventArgs ^ e)
{ It is a member property of PaintEventArgs, and is a handle to the class Graphics
Graphics ^g = e->Graphics;
Update
if(X < this->Size.Width)
{ X += 1;}
position
else
{ X = 0;}
Bitmap ^bp = gcnew Bitmap("e:\\temp\\cards\\h1.gif");
g->DrawImage(bp, X, 25); //same as e->Graphics->DrawImage
Draw image
Drawing::Rectangle Head =
Drawing::Rectangle(this->Size.Width-X, 25, 70, 70);
g->FillEllipse(Brushes::Yellow, Head);
Pen ^b4pen = gcnew Pen(Color::Black, 4);
Draw circle
g->DrawEllipse(b4pen, Head);
}
110

Computer Programming
9 Building Graphical User Interface

Graphics ^g = e->Graphics;
The Graphics class is the heart of all rendering
activities of GDI+
Its a device-independent representation of the

drawing surface that you plan to render graphics on


The above statement indicates that a tracking handle
g of a Graphics object is created to the drawing
surface on Form1 (i.e. g stores the Graphics object of Form1's
address returned by e->Graphics)

Graphics has many member functions

DrawLine()
DrawRectangle()
DrawImage()
:
111

Computer Programming
9 Building Graphical User Interface

x co-ordinate

if(X < this->Size.Width)


{ X += 1;}
else { X = 0;}

For each paint event, the value of X will be


incremented by 1
It will get back to 0 when it is equal to the Width of

the Form1

Since Form1 can be resized during run-time, we


need to check the actual width of Form1 in the
program
It is returned by this->Size.Width.

112

Computer Programming
9 Building Graphical User Interface

Bitmap ^bp =
gcnew Bitmap("e:\\temp\\cards\\h1.gif");
g->DrawImage(bp, X, 25); y co-ordinate
The class Bitmap is for the temporary storage of

image data

The constructor of Bitmap requires a string that


indicates the path of the image file
The location of the Bitmap created (in the CLR heap) is
indicated by a tracking handle bp

We can render the data in the Bitmap on the

drawing surface using the DrawImage function of the


Graphics object of handle g

The 2nd and 3rd parameters of DrawImage refer to the x


Top-left and y co-ordinates at which the image is drawn.

corner

113

Computer Programming
9 Building Graphical User Interface

Upper-left corner co-ordinates

Drawing::Rectangle Head =
Drawing::Rectangle(this->Size.Width-X, 25,
70, 70);
g->FillEllipse(Brushes::Yellow, Head);
The class Rectangle is a subclass of Drawing

The constructor Drawing::Rectangle() allows one to


create a rectangular region Head with specified size and
position. It requires 4 parameters

1st and 2nd the x and y co-ordinates of the rectangle


3rd and 4th the width and height of the rectangle

It will return the rectangular region created


g->FillEllipse(Brushes::Yellow, Head) allows one
to create a filled ellipse

The ellipse is filled using the Yellow brush and has size the
same as that defined by the rectangular region Head.
114

Computer Programming
9 Building Graphical User Interface

Pen ^b4pen = gcnew Pen(Color::Black, 4);


g->DrawEllipse(b4pen, Head);
Besides brush, GDI+ provides the Pen class for one

to draw a graphic structure


The class Pen let us define the pen we can use for
drawing
The constructor of Pen requires two parameters

1st parameter the color of the Pen


2nd parameter the size of the Pen

g->DrawEllipse(b4pen, Head); enable one to draw

a circle on the drawing surface with size as specified


in Head using the pen b4pen.
115

Computer Programming
9 Building Graphical User Interface

Step 3: Build and Run the Project

116

Computer Programming
9 Building Graphical User Interface

Comparisonwithusingstandardformcontrol
The above can also be achieved using standard
form controls, however, with much difficulty

E.g. if we want to show an animation of images, we


can create many PictureBox on the way of the
motion; and display the PictureBox one by one
y

Very time consuming when developing

We can show a moving circle by converting it to an


image and use PictureBox the way before
y

Even more time consuming

GDI+ has simplified the job of graphic and image


manipulation and provided much flexibility.
117

Computer Programming
pixel or block of pixels

9 Building Graphical User Interface

Doublebuffering

Memory

CPU

Screen

Very serious flickering effect in the image and


graphic may be seen

Rendering graphic information and transfer them


onto the screen can be a relatively slow process

It is preferable to do it in a block rather than pixel


by pixel

Traditional way

screen

Graphic is rendered
pixel-by-pixel directly
onto the screen
It so happens only
half of the picture is
drawn when it needs
to be displayed.
118

Computer Programming
9 Building Graphical User Interface

When using double


buffering, graphic is
first rendered into a
buffer (memory) first

When the rendering


process finishes, the
whole buffer data are
transferred to the
screen in a block

Undisplayed Buffer

memory

memory

screen

Result in much faster


and smoother graphic
and image drawing.

The original
graphic

Screen
119

Computer Programming
9 Building Graphical User Interface

The easiest way to enable double buffering is to


use default double buffer for forms and the
controls, which is provided by the .NET Framework,
i.e.

Enable default double buffering for our Windows


Forms and authored Windows controls by using the
SetStyle and UpdateStyles
methods
public:Form1(void)
// Modified
constructor
{
// with double buffering
X = 0;
InitializeComponent();
this->SetStyle(static_cast<ControlStyles>(
ControlStyles::AllPaintingInWmPaint |
Specify which 3 bits
ControlStyles::DoubleBuffer |
ControlStyles::UserPaint), true);
this->UpdateStyles();
}

120

Computer Programming
9 Building Graphical User Interface

The SetStyle() method allows one to modify the


ControlStyles of the control

The UpdateStyles() method allows the modified


ControlStyles to be effective

When the control style DoubleBuffer is set to


true,

Drawing is performed in a buffer, and after it


completes, the result is output to the screen

Double-buffering prevents flickering

If DoubleBuffer is set to true, one should also set


UserPaint and AllPaintingInWmPaint to true.
Learn these enumerations using Help
121

Computer Programming
9 Building Graphical User Interface

Exercise 9.4
Follow the above steps to build the project.
See the difference with and without Double-buffering

Add two buttons ('+' and '') in Form1 such that


you can change the motion speed of the picture
and the circle
Hint: We can change the speed by either changing
the Interval of the timer or changing the step size
of X when increasing.
122

Computer Programming
9 Building Graphical User Interface

MediaPlayerActiveX(COMInterop)

123

Computer Programming
9 Building Graphical User Interface

124

Computer Programming
9 Building Graphical User Interface

MediaPlayerActiveX
axWindowsMediaPlayer1->URL=music.mp3;
axWindowsMediaPlayer1->URL = openFileDialog1->FileName;
axWindowsMediaPlayer1->uiMode="full"; //"mini, "none, "invisible"
axWindowsMediaPlayer1->Visible=false;
axWindowsMediaPlayer1->Ctlcontrols->play();
axWindowsMediaPlayer1->Ctlcontrols->stop();
axWindowsMediaPlayer1->Ctlcontrols->pause();
Text=Convert::ToString(axWindowsMediaPlayer1->playState)
125

Computer Programming
9 Building Graphical User Interface

Other
ActiveX

axShockwaveFlash1->Movie = "c:\\newyear.swf";
axShockwaveFlash1->Play();

126

You might also like