Professional Documents
Culture Documents
Building Graphical User Interface: C++/Common Language Infrastructure (C++/CLI)
Building Graphical User Interface: C++/Common Language Infrastructure (C++/CLI)
Building Graphical User Interface: C++/Common Language Infrastructure (C++/CLI)
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
Computer Programming
9 Building Graphical User Interface
Computer Programming
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
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
Computer Programming
9 Building Graphical User Interface
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
Console
Command-line interface has been replaced by
application
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
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;
return 0;
}
12
Computer Programming
System::Windows::Forms
9 Building Graphical User Interface
CreatingWindowsForms
libraries
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
For any event generated, the system will first check if there is
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
Computer Programming
9 Building Graphical User Interface
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
y A tracking handle is similar to a native C++ pointer
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
Computer Programming
9 Building Graphical User Interface
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
Computer Programming
9 Building Graphical User Interface
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
31
Computer Programming
will
will return
return an
an object
object of
of type
type IntPtr
IntPtr
9 Building Graphical User Interface
heap
Computer Programming
9 Building Graphical User Interface
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
Another method:
String^ Mmge = gcnew String(message);
34
Computer Programming
9 Building Graphical User Interface
Computer Programming
9 Building Graphical User Interface
Computer Programming
9 Building Graphical User Interface
Computer Programming
9 Building Graphical User Interface
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
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
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
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
A key is pressed
KeyEventArgs
OnKeyPress
KeyPressEventArgs
OnKeyUp
A key is released
KeyEventArgs
OnMouseDown
MouseEventArgs
OnMouseEnter
EventArgs
OnMouseOver
EventArgs
OnMouseLeave
EventArgs
OnMouseMove
MouseEventArgs
OnMouseUp
MouseEventArgs
OnMouseWheel
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
OnDeactivate
A form is deactivated
OnGotFocus
OnLoad
A form is created
OnLocationChanged
A form is moved
OnLostFocus
OnPaintBackground
OnSizeChanged
A form is resized
45
Computer Programming
9 Building Graphical User Interface
Class
Dialog Type
ColorDialog
FontDialog
OpenFileDialog
PageSetupDialog
PrintDialog
SaveFileDialog
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
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
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
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
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
53
Computer Programming
9 Building Graphical User Interface
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
Application as usual
E:\VS_Proj
Set the project name, e.g. LibArith
However, on choosing the options in the
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
Computer Programming
9 Building Graphical User Interface
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
member functions
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
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
65
Computer Programming
9 Building Graphical User Interface
66
Computer Programming
9 Building Graphical User Interface
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
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
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
four cards
76
Computer Programming
9 Building Graphical User Interface
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
Computer Programming
9 Building Graphical User Interface
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
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
form
Computer Programming
9 Building Graphical User Interface
In Form2.h
Computer Programming
9 Building Graphical User Interface
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
Computer Programming
9 Building Graphical User Interface
else
// It is face-down
{ ShowCard();
face = 0; // currently face-up
}
}
}
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
Computer Programming
9 Building Graphical User Interface
Computer Programming
9 Building Graphical User Interface
94
Computer Programming
9 Building Graphical User Interface
GraphicsClass
Graphics^ g = CreateGraphics();
g->DrawLines(Pens::Green, pts);
g->TranslateTransform(50, 20);
delete g;
95
Computer Programming
9 Building Graphical User Interface
PaintEvent
Void Form1_Paint(Object^
sender, PaintEventArgs^
e)
{
Graphics^ g = e->Graphics;
g->DrawLines(Pens::Green, pts);
g->TranslateTransform(50, 20);
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
BackgroundImage = bm;
bm->Save("test.jpg", Imaging::ImageFormat::Jpeg);
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
99
Computer Programming
9 Building Graphical User Interface
Project name:
Chap9gdi
100
Computer Programming
9 Building Graphical User Interface
101
Computer Programming
9 Building Graphical User Interface
timer1 is enabled
Event is generated at
every 10 ms
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
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
105
Computer Programming
9 Building Graphical User Interface
106
Computer Programming
9 Building Graphical User Interface
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().)
Computer Programming
9 Building Graphical User Interface
Computer Programming
9 Building Graphical User Interface
double-click
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
DrawLine()
DrawRectangle()
DrawImage()
:
111
Computer Programming
9 Building Graphical User Interface
x co-ordinate
the Form1
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
corner
113
Computer Programming
9 Building Graphical User Interface
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 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
Computer Programming
9 Building Graphical User Interface
116
Computer Programming
9 Building Graphical User Interface
Comparisonwithusingstandardformcontrol
The above can also be achieved using standard
form controls, however, with much difficulty
Computer Programming
pixel or block of pixels
Doublebuffering
Memory
CPU
Screen
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
Undisplayed Buffer
memory
memory
screen
The original
graphic
Screen
119
Computer Programming
9 Building Graphical User Interface
120
Computer Programming
9 Building Graphical User Interface
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
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