Top Banner
Visual C++ Programming Penn Wu, PhD 280 Lecture #10 Hand-Coding Windows Form Applications Introduction Although Microsoft Visual Studio makes it much easier for developers to create Windows Forms applications, it is still a very good idea to create Microsoft Windows-based applications by hand-coding. There is a strong demand of developers with capability to hand code applications in the industry. Anatomy of Windows Forms application All of the Windows Forms application share the same anatomy which is a generic form” that inherits members defined in the System::Windows::Forms namespace. A Windows formis a visual surface on which you display information to the user. The following is the code that creates a generic Windows form which you have seen in previous lectures. #using <System.dll> #using <System.Windows.Forms.dll> #using <System.Drawing.dll> using namespace System; using namespace System::Drawing; using namespace System::Windows::Forms; public ref class Form1: public Form { public: Form1() { } }; [STAThread] int main() { Application::Run(gcnew Form1); } Windows forms with form controls must include the following dynamic-link library (or DLL) files. They are Microsofts implementation of the shared library and often contain class(es) or function declarations to be referenced by other C++ source files by the use of “usingdirective. #using <System.dll> #using <System.Windows.Forms.dll> The instructor also “using” the following namespace to reference them from a Windows form application. using namespace System; using namespace System::Windows::Forms; The System namespace contains fundamental classes and base classes that define commonly- used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. The System::Windows::Forms namespace contains classes for creating Windows-based applications that take full advantage of the rich user interface features available in the Microsoft Windows operating system. Depending on controls you choose to use, you might have to use other namespaces and their corresponding header files. For example, you need to use the System::Drawing namespace if you have to specify the Location property. There are two ways to use this namespace: (1) referencing to the namespace whenever you need it or, (2) declaring the use of namespace at the beginning of the code.
38

The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Aug 05, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 280

Lecture #10 Hand-Coding Windows Form Applications

Introduction Although Microsoft Visual Studio makes it much easier for developers to create Windows

Forms applications, it is still a very good idea to create Microsoft Windows-based applications

by hand-coding. There is a strong demand of developers with capability to hand code

applications in the industry.

Anatomy of

Windows

Forms

application

All of the Windows Forms application share the same anatomy which is a generic “form” that

inherits members defined in the System::Windows::Forms namespace. A Windows “form” is

a visual surface on which you display information to the user. The following is the code that

creates a generic Windows form which you have seen in previous lectures.

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

public: Form1() { }

};

[STAThread]

int main() {

Application::Run(gcnew Form1);

}

Windows forms with form controls must include the following dynamic-link library (or DLL)

files. They are Microsoft’s implementation of the shared library and often contain class(es) or

function declarations to be referenced by other C++ source files by the use of “using” directive.

#using <System.dll>

#using <System.Windows.Forms.dll>

The instructor also “using” the following namespace to reference them from a Windows form

application.

using namespace System;

using namespace System::Windows::Forms;

The System namespace contains fundamental classes and base classes that define commonly-

used value and reference data types, events and event handlers, interfaces, attributes, and

processing exceptions. The System::Windows::Forms namespace contains classes for creating

Windows-based applications that take full advantage of the rich user interface features available

in the Microsoft Windows operating system.

Depending on controls you choose to use, you might have to use other namespaces and their

corresponding header files. For example, you need to use the System::Drawing namespace if

you have to specify the Location property. There are two ways to use this namespace: (1)

referencing to the namespace whenever you need it or, (2) declaring the use of namespace at the

beginning of the code.

Page 2: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 281

#using <System.Drawing.dll>

......

......

textBox1->Location = System::Drawing::Point(48, 488);

or

#using <System.Drawing.dll>

......

......

Using namespace System::Drawing;

......

......

textBox1->Location = Point(48, 488);

To programmatically create the form, you need to declare a public class with a unique ID (e.g.

Form1) to be reference by its components, so all the components in this Form1 class will know

they belong to a “Windows form”.

public ref class Form1: public Form

{

public: Form1() // Create a new instance of the form {

this->Text = "My Form";

this->Size = Drawing::Size(250, 150);

}

};

Inside the public class (e.g. Form1), you create a new instance of the form, which is a function

(in the above case, the function name is Form1()). Inside the Form1() function, there are two

properties, Text and Size. These two properties describe the appearance of this form. The

keyword “this” refers to the form being created.

Since each C++ program must have a starting point, usually the main() function, under the

[STAThread] section.

[STAThread]

int main(){

Application::Run(gcnew Form1);

}

The STAThread attribute marks the STA (single-thread apartment), which means to treat the

main() function a STA, so the main() function will be running in thread that starts on

initialization. When there is an attempt to access other part of the code, the STAThread attribute

will force Windows to give the sole priority to main function, and thus the rest attempt will not

be possible. Consequently, the main() function is always the starting point of the code.

Property,

method, and

event

To programmatically (1) modify the appearance and function of a form or (2) create controls or

components and add them to a particular form, you need learn three basic programming

techniques: assigning properties, implementing methods, and associating events with objects.

• Property: Properties are something that define the appearance of an object. Width, height,

size, and location are properties of an object.

• Method: Methods are something that an object can behave. Hide(), Sort(), Remove(), and

Add() are functions an object can perform.

• Event: Events are something the user perform; they are user activities. Clicking, double

clicking, pressing key, and moving mouse cursors are event a user can trigger.

Page 3: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 282

Properties configure the appearance of an object, while methods give dynamic to the object.

The event handlers detect if a particular event is fired by the user and responds with counter

actions. In Visual C++, the format of syntax of using property is:

objectID->PropertyName = Value;

The syntax of using methods is:

objectID->MethodName();

Events are user actions. The event model in the .NET Framework is based on having an event

delegate that connects an event with its handler. To raise an event, two elements are needed: a

delegate and an optional class that holds the event data. The .NET Framework provides a list of

events specific to every kind of controls. For example, the TextChanged event occurs when the

Text property value changes. However, the event must be registered to the Windows form

before they can take effect. The syntax to register an event is:

objectName.eventName += gcnew EventHandler(objectName,

&className::functionName);

If the object is the form, the object name can be replaced with the “this” keyword which refers

to the form. The EventHandler delegate represents a method that will handle an event which

has no event data. A delegate is a class that can hold a reference to a method that match its

signature; therefore, the programmers must rigorously abide by the format: gcnew

EventHandler(objectNme, &className::functionName), where functionName is the

identifier of the function that will be called when the event occurs. This function is known as

“event handler”. Notice that & is the reference operator which holds the address of an object but

behaves syntactically like an object. The following demonstrates how to register a Click event

to the form.

this->Click += gcnew EventHandler(this, &Form1::Form1_Click);

The .NET Framework has a rigid syntax for event handler. The object that raises the event is

called the event sender. The object that captures the event and responds to it is called the event

receiver. Since the event sender class does not know which object or method will receive

(handle) the events it raises, the event handler in the .NET Framework have two parameters: the

source that raised the event and the event argument data for the event. Because the object can

be of any possible type, it is optimal to declare it as System::Object type (a universal data

type). The event arguments must be implemented by the EventArgs class or a class of similar

kind. Microsoft also recommends programmers to name the object “sender” and the EventArg

“e”.

private void functionName(Object^ sender, EventArgs^ e) { }

For example,

private: Void Form1_Click(Object^ sender, EventArgs^ e)

{

}

You then manually add the code to respond to the event, as shown below. It actually changes

the size of the form to 50×50 pixels.

private: Void Form1_Click(Object^ sender, EventArgs^ e)

{

this->Size = Drawing::Size(150, 150);

}

Page 4: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 283

Simply use any text editor, such as Notepad, to manually and programmatically create a

Windows form. The form has two properties: Text and Size. It also has one method: Close().

The only event registered to it is “Click” which is also associated with an event handler:

Form1_Click. And it surprisingly is fully compatible to the one created by Visual C++ IDE.

// FileName: test.cpp

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

public: Form1()

{

// properties

this->Text = "My Form";

this->Size = Drawing::Size(250, 150);

// event

this->Click += gcnew EventHandler(this, &Form1::Form1_Click);

}

// event handler

private: Void Form1_Click(Object^ sender, EventArgs^ e)

{

// method

this->Close();

}

};

[STAThread]

int main() {

Application::Run(gcnew Form1);

}

Compile this code using cl /clr test.cpp /link /subsystem:windows

/ENTRY:main, the output looks:

As shown above, a Form is a representation of any window displayed in your application. The

Form class provided by the .NET Framework can create standard, tool, borderless, and floating

windows. To create a form programmatically, programmers must initialize a new instance of

the Form class. For example, to create a form with an ID form2, use:

Form^ form2 = gcnew Form;

You will also need to add the STAThread attribute to the Main method in order for the form to

run. When the starting form is closed, the application is also closed.

Using the properties available in the Form class, you can determine the appearance, size, color,

and window management features of the window or dialog box you are creating. For example,

Page 5: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 284

• The Text property allows you to specify the caption of the window in the title bar.

• The Size and DesktopLocation properties allow you to define the size and position of the

window when it is displayed. Also, the default size of a form is 300 pixels in height and

300 pixels in width.

• You can use the ForeColor color property to change the default foreground color of all

controls placed on the form.

• The FormBorderStyle, MinimizeBox, and MaximizeBox properties allow you to control

whether the form can be minimized, maximized, or resized at run time.

For example,

form2->Text = "Welcome to CIS!";

form2->FormBorderStyle = ::FormBorderStyle::Fixed3D;

Unlike Form1 which was created by the Form1() constructor and defaulted to be visible, form2

is not set to be visible by default. You need to programmatically set its Visible property to true.

form2->Visible = true;

You can use the SetDesktopLocation() method to position the form on the desktop.

form2->SetDesktopLocation(100,200);

Use the Activate method to keep the form2 form active. The Activate() method activates the

form and gives it focus. Activating a form brings it to the front if this is the active application,

or it flashes the window caption if this is not the active application. The form must be visible

for this method to have any effect.

form2->Activate();

The events of the Form class allow you to respond to actions performed on the form. To

programmatically create an event handler, declare a new EventHandler with two parameters in

it: the former refers to the main form (e.g. this in the following example); the later refer to the

class (e.g. the Form1 class) where the form2_Click subroutine resides. It is necessary to note

that the instructor prefers the naming conversion to name the event handler with the following

format; yet, it is optional. In this example, “form2” is the object being tied with the “Click”

event.

ObjectName_EventName

Consider the following example, which ties a Click event to form2.

form2->Click += gcnew EventHandler(this, &Form1::form2_Click);

The above statement also specifies that form2_Click is a function that will serves as the event

handler (which contains the code as response to the event when the event is raised). The

following illustrates how a simple event handler function is created. This function will activate

form1 (“this” is the keyword that represents form1) when form2 is clicked. By clicking form2,

the user raises the “Click” event. The above statement ties form2 with a “Click” event;

therefore, the following form2_Click() function will execute as the response to the event.

private: Void Form1::form2_Click(Object^ sender, EventArgs^ e)

{

this->Activate();

}

The following is a complete code that uses Form1() constructor to create two forms: form1 and

form2.

Page 6: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 285

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

Form^ form2; // global object

public: Form1()

{

// create form1

this->Text = "Form 1";

this->Name = "form1";

this->Size = Drawing::Size(250, 150);

this->SetDesktopLocation(10, 10);

this->Click += gcnew EventHandler(this, &Form1::form1_Click);

this->Activate();

// create form2

form2 = gcnew Form;

form2->Text = "Form 2";

form2->SetDesktopLocation(300, 10);

form2->Visible = true;

form2->Click += gcnew EventHandler(this, &Form1::form2_Click);

}

private: Void Form1::form1_Click(Object^ sender, EventArgs^ e)

{

form2->Activate();

}

private: Void Form1::form2_Click(Object^ sender, EventArgs^ e)

{

this->Activate();

}

};

[STAThread]

int main() {

Application::Run(gcnew Form1);

}

The form2_Click function is part of the Form1 class, the C++ language core requires you to

specify the reference using the (::) operator.

Form1::form2_Click()

The following is another example of event-based programming, which ties the Activated event

to form1 and associates the event to a handler named Form1_Activated().

this->Activated += gcnew EventHandler(this,

&Form1::Form1_Activated);

................. private: Void Form1_Activated(Object^ sender, EventArgs^ e) {

this->Size = Drawing::Size(150,150);

Page 7: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 286

}

Notice that form2 is fully controlled by Form1. If you close Form1, you will also close form2.

Visit http://msdn.microsoft.com/en-us/library/system.windows.forms.form_events.aspx for

a list of methods and properties of the Form class.

Different events might require different delegates. For example, the Closing event requires the

use of the System::ComponentModel::CancelEventHandler delegate while Activated and

Click events use the EventHandler delegate to represents the method that will handle an event

that has no event data. Different delegates also require different event argument classes. The

following demonstrates how the Closing event use different delegates and event argument

statements.

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

public: Form1()

{

this->Closing += gcnew

System::ComponentModel::CancelEventHandler(this,

&Form1::openIt);

}

private: Void openIt(Object^ sender,

System::ComponentModel::CancelEventArgs^ e)

{

MessageBox::Show("Do you want to close this form?");

}

};

[STAThread]

int main() {

Application::Run(gcnew Form1);

}

Concept of

Controls

You ordinarily build Windows Forms applications by adding controls to forms and developing

responses to user actions, such as mouse clicks or key presses. A control is a discrete user

interface (UI) element that displays data or accepts data input. The following is a sample list of

commonly used controls. There controls are components on a Windows form for displaying

information or accepting user inputs.

Control Sample UI Descriptions

Checkbox

Allows multiple option

Radio button

Allow only one option

Button

Clickable button

Textbox

A single line text entry

area

Page 8: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 287

ComboBox

A drop down menu

ListBox

An area of list of options

Controls are objects that are contained within form objects. Each type of control has its own set

of properties, methods, and events that make it suitable for a particular purpose. Programmers

can manipulate controls by writing code to add controls dynamically at run time.

Most controls in .NET derive from the System.Windows.Forms.Control class which defines

the basic functionality of the controls including properties, methods, and events of the controls.

Interestingly, most controls have individual classes under the System.Windows.Forms

namespace. The syntax to declare a Control is:

controlType objectID;

The following is the syntax to initialize the declared control, where gcnew operator creates an

instance of a managed type (reference or value type) on the garbage collected heap.

objectID = gcnew controlType;

It is a common practice to declare and initialize a control in one single statement. For example,

the following creates a Label control with an ID label1:

Label^ label1 = gcnew Label;

Windows Forms Label controls are used to display text or images that cannot be edited by the

user. They are used to identify objects on a form to provide a description of what a certain

control will do if clicked, for example, or to display information in response to a run-time event

or process in your application. Commonly used properties of Label controls are:

• Text: Gets or sets the caption (text) of the control.

• AutoSize: Gets or sets a value indicating whether the control is automatically resized to

display its entire contents.

• BackColor: Gets or sets the background color for the control.

• BorderStyle: Gets or sets the border style for the control.

• Size: Gets or sets the height and width of the control.

• Location: Gets or sets the coordinates of the upper-left corner of the control relative to the

upper-left corner of its container.

• Dock: Gets or sets which control borders are docked to its parent control and determines

how a control is resized with its parent.

• Visible: Gets or sets a value indicating whether the control and all its parent controls are

displayed. The default is true.

• UseMnemonic: Gets or sets a value indicating whether the control interprets an ampersand

character (&) in the control’s Text property to be an access key prefix character.

The syntax for using the above properties is:

labelID->PropertyName = value;

where the member access operator (->) is used to refer to members of structures, unions, and

classes of managed type. For example,

label1->AutoSize = true;

Page 9: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 288

Hide() and Show() are two frequently used methods of the Label control. The syntax to use

them is:

label1->Hide();

The following code demonstrates how to hand-create a Label control, named “label1”, for a

Windows Form application. The instructor purposely tied a “Load” event to the form and used

it to call the Form1_Load event handler when the form is launched (by which the user raises

the “Load” event). The Form1_Load event handler creates the Label control and register a

“Click” to the label. The “Click” event is also associated with the label1_Click event handler

which calls the Remove() method to delete the Label control from the form.

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

Label^ label1; // declare as global

public: Form1()

{

this->Load += gcnew EventHandler(this, &Form1::Form1_Load);

}

private: Void Form1_Load(Object^ sender, EventArgs^ e)

{

label1 = gcnew Label;

label1->BorderStyle = BorderStyle::Fixed3D;

label1->UseMnemonic = true;

label1->AutoSize = true;

label1->Text = "First &Name:";

label1->Location = Point(10, 10);

//event registration

label1->Click += gcnew EventHandler(this,

&Form1::label1_Click);

Controls->Add(label1);

}

// event handler

private: Void label1_Click(Object^ sender, EventArgs^ e)

{

this->Controls->Remove(label1);

}

};

[STAThread]

int main() {

Application::Run(gcnew Form1);

}

It is necessary to note that the above code declare the Label control as a global object (member

of the Form1 class), and later initialize the Label control in the Form_Load() event handler.

Page 10: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 289

This arrangement is to ensure that other class members, such as the label1_Click() event

handler, can have access to the Label control. If the Label control is declared inside

Form_Load(), only the code inside Form_Load() can access it.

Label^ label1; // declaration

...............

private: Void Form1_Load(Object^ sender, EventArgs^ e)

{

label1 = gcnew Label; // initialization

...............

}

...............

// event handler

private: Void label1_Click(Object^ sender, EventArgs^ e)

{

this->Controls->Remove(label1); // access from a class member

}

As a matter of fact, one benefit of hand-coding is that programmers can create a much compact,

concise, and efficient code. The above code, for example, can be simplified to the following

without the use of “Load” event of the form. By using the default constructor, Form1(), to

create the from components, the following code can produce the same result.

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

Label^ label1;

public: Form1()

{

label1 = gcnew Label;

label1->BorderStyle = BorderStyle::Fixed3D;

label1->UseMnemonic = true;

label1->AutoSize = true;

label1->Text = "First &Name:";

label1->Size = Drawing::Size( label1->PreferredWidth, label1-

>PreferredHeight );

label1->Location = Point(10, 10);

this->Controls->Add(label1);

//event registration

label1->Click += gcnew EventHandler(this,

&Form1::label1_Click);

Controls->Add(label1);

}

// event handler

private: Void label1_Click(Object^ sender, EventArgs^ e)

{

this->Controls->Remove(label1);

}

};

Page 11: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 290

[STAThread]

int main() {

Application::Run(gcnew Form1);

}

In the above codes, the author register a “Click” event for Label control (“label1”). The “Click”

event is associated with the label1_Click event handler which define the response of the event

when it is raised by the user.

label1->Click += gcnew EventHandler(this, &Form1::label1_Click);

What to respond to the “Click” is then defined inside the label1_Click() event handler.

private: Void label1_Click(Object^ sender, EventArgs^ e)

{

this->Controls->Remove(label1);

}

Notice that Load is a form’s default event (as Click to a button). To tie an event handler (e.g.

Load) to a control or an object, use the += operator. The keyword this refers to the form,

particularly Form1.

Control Default event handler

Button Click

TextBox TextChanged

Label Click

CheckBox CheckedChanged

GroupBox Enter

RadioButton CheckedChanged

PictureBox Click

DateTimePicker ValueChanged

DatGrid Navigate

Another way to create controls of a form is to create them in the default constructor of the form.

In Visual C++, the default constructor is the constructor that has exactly the same identifier as

the class. In the following example, the name of the class is “Form1” which inherits the Form

class of the .NET Framework. Inside the Form1 class, there exists a Form1()constructor and a

void function myForm(). Since the identifier are Form1() constructor is “Form1” which is the

identifier of the class, it is the default constructor. The following code uses the default

constructor to create a Label control.

public ref class Form1: public Form

{

public: Form1() // default constructor

{

Label^ label1 = gcnew Label;

............

}

private: Void myForm() // user-defined function

{

}

};

You can also use the Void function to create form controls.

Page 12: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 291

public ref class Form1: public Form

{

public: Form1() // default constructor

{

myForm();

}

private: Void myForm() // user-defined function

{

Label^ label1 = gcnew Label;

............

}

};

Form controls, such as Label and Button, can be declared and created as arrays. The following

illustrates how you can create an array of Labels. When there is a need to access the control

array outside the Form1() constructor, declare the array as the class member.

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

array <Label^>^ cell; // declare array as class member

public: Form1()

{

cell = gcnew array<Label^>(5); // create array

for (int i=0; i<5; i++)

{

cell[i] = gcnew Label; // create 5 elements of array

cell[i]->Text = i + "";

cell[i]->Width=20;

cell[i]->Location = Point(10+i*30, 10);

Controls->Add(cell[i]);

}

}

};

[STAThread]

int main() {

Application::Run(gcnew Form1);

}

You can use the PreferredWidth property, along with the PreferredHeight property, to ensure

that the text in the Label control is displayed properly. You can use the AutoSize property to

automatically adjust the height and the width of the Label control based on the text and font

size.

With an ampersand character (&) in the control’s Text property, you can define a short-cut

keystroke as shown below. When executing this code, press the Alt key followed by the letter

“n” as keystroke.

label1->Text = "First &Name:";

Page 13: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 292

The label1 text value changes from

First Name to First Name

You can have image(s) displayed on the Label control. Consider the following code, which uses

the Image class to create an image1 object.

Label^ label1 = gcnew Label;

Image^ image1 = Image::FromFile("tree.gif");

// Set the size of the label to accommodate the bitmap size.

label1->Size = System::Drawing::Size( image1->Width,

image1->Height );

// Initialize the label control's Image property.

label1->Image = image1;

label1->Location = Point(10, 10);

Controls->Add(label1);

Notice that image1->Width and image->Height refers to the width and height of the image.

The FromFile() method specifies the source of the image file. A sample output looks:

When there are more than one images. You need to use the ImageList property, which stores

the collection of Image objects to display in the Label control. For example,

Label^ label1 = gcnew Label;

label1->ImageList = imageList1;

label1->ImageIndex = 1;

label1->ImageAlign = ContentAlignment::TopLeft;

The Button

class

The Windows Forms Button control allows the user to click it to perform an action. The Button

control can display both text and images. When the button is clicked, it looks as if it is being

pushed in and released. A Button can be clicked by using the mouse, ENTER key, or

SPACEBAR if the button has focus. To create with a button with an ID button1, use:

Button^ button1 = gcnew Button;

To specify properties of the button, use the following syntax:

buttonID->PropertyName = Value;

For example,

button1->Text = "OK";

button1->Location = Point(10,10);

The syntax to use methods of the Button class is:

buttonID->MethodName();

Consider the following example, which conceal the button control from the user.

Page 14: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 293

button1->Hide();

In order to add button1 to the form2 as a component, you need to use the Add() method of the

Controls property with the ID of the form (e.g. form2). For example,

form2->Controls->Add(button1);

You can change the button’s appearance by assigning values to properties. Commonly used

properties are:

• Text: Gets or sets the caption (text) of the control.

• AutoSize: Gets or sets a value indicating whether the control is automatically resized to

display its entire contents.

• BackColor: Gets or sets the background color for the control.

• BorderStyle: Gets or sets the border style for the control.

• Size: Gets or sets the height and width of the control.

• Location: Gets or sets the coordinates of the upper-left corner of the control relative to the

upper-left corner of its container.

• TextAlign: Gets or sets the alignment of the text on the button control.

In the following example, all the properties

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

Button^ button1;

public: Form1()

{

button1 = gcnew Button;

button1->Text = "Click Me";

button1->AutoSize = true;

button1->BackColor = Drawing::Color::Aqua;

button1->Location = Point(10, 10);

button1->TextAlign = ContentAlignment::MiddleRight;

// register an event

button1->Click += gcnew EventHandler(this,

&Form1::button1_Click);

this->Controls->Add(button1);

}

private: Void button1_Click(Object^ sender, EventArgs^ e)

{

button1->Hide();

}

};

[STAThread]

int main() {

Application::Run(gcnew Form1);

}

Page 15: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 294

Information about other properties are available at http://msdn.microsoft.com/en-

us/library/system.windows.forms.button_properties.aspx. For example, to make it appear flat

for a Web look, set the FlatStyle property to

button1->FlatStyle = FlatStyle::Flat;

The FlatStyle property can also be set to FlatStyle::Popup, which appears flat until the mouse

pointer passes over the button; then the button takes on the standard Windows button

appearance.

Set the AcceptButton or CancelButton property of a Form to allow users to click a button by

pressing the ENTER or ESC keys even if the button does not have focus. This gives the form

the behavior of a dialog box.

this->AcceptButton = button1;

this->CancelButton = button1;

When you display a form using the ShowDialog() method, you can use the DialogResult

property of a button to specify the return value of ShowDialog. For example,

Form^ form2 = gcnew Form;

Button^ button1 = gcnew Button;

button1->Text = "Click Me";

button1->DialogResult = Windows::Forms::DialogResult::OK;

form2->Controls->Add(button1);

form2->Visible = true;

Buttons also work with images, so you can assign an image to the button by using the Image

property. For example,

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

public: Form1()

{

Button^ button1 = gcnew Button;

button1->Image = Image::FromFile( "tree.gif" );

// Align the image on the button.

button1->ImageAlign = ContentAlignment::MiddleCenter;

button1->AutoSize = true;

Controls->Add(button1);

}

};

[STAThread]

int main() {

Application::Run(gcnew Form1);

}

Page 16: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 295

The TextBox

class

Windows Forms text boxes are used to get input from the user or to display text. The TextBox

control is generally used for editable text, although it can also be made read-only. Text boxes

can display multiple lines, wrap text to the size of the control, and add basic formatting. The

TextBox control allows a single format for text displayed or entered in the control. With the

TextBox control, the user can enter text in an application. To create with a TextBox object with

an ID textBox1, use:

TextBox^ textBox1 = gcnew TextBox;

Typically, a TextBox control is used to display, or accept as input, a single line of text. But, you

can use the Multiline and ScrollBars properties to enable multiple lines of text to be displayed

or entered. For example,

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

public: Form1()

{

createIt();

}

private: Void createIt()

{

TextBox^ textBox1 = gcnew TextBox;

textBox1->Multiline = true;

textBox1->ScrollBars = ScrollBars::Vertical;

textBox1->Location = Point(10, 10);

textBox1->Width = 260;

textBox1->Height = 245;

textBox1->AcceptsTab = true;

textBox1->AcceptsReturn = true;

textBox1->MaxLength = 350;

Controls->Add(textBox1);

}

};

[STAThread]

int main() {

Application::Run(gcnew Form1);

}

Also, you can set the AcceptsTab and AcceptsReturn properties to true to enable greater text

manipulation in a multiline TextBox control. You can limit the amount of text entered into a

TextBox control by setting the MaxLength property to a specific number of characters.

TextBox controls can also be used to accept passwords and other sensitive information. You

can use the PasswordChar property to mask characters entered in a single-line version of the

control. Use the CharacterCasing property to enable the user to type only uppercase, only

lowercase, or a combination of uppercase and lowercase characters into the TextBox control.

For example,

TextBox^ textBox1 = gcnew TextBox;

Page 17: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 296

Label^ label1 = gcnew Label;

label1->Text = "Password:";

label1->Size = Drawing::Size(60, 13);

label1->Location = Point(10, 10);

textBox1->Location = Point(75, 10);

textBox1->PasswordChar = '*';

textBox1->CharacterCasing = CharacterCasing::Lower;

Controls->Add(label1);

Controls->Add(textBox1);

The output looks:

The ScrollToCaret() method allows users to scroll the contents of the TextBox until the cursor

(caret) is within the visible region of the control. The Select() method allows users to select a

range of text in the text box.

textBox1->ScrollToCaret();

textBox1->Select():

Useful reference about methods and properties are available at http://msdn.microsoft.com/en-

us/library/system.windows.forms.textbox_members.aspx.

CheckBox and

RadioButton

CheckBox and RadioButton controls have a similar function: they allow the user to choose

from a list of options. Use a CheckBox to give the user an option, such as true/false or yes/no.

The CheckBox control can display an image or text or both. In contrast, RadioButton controls

allow a user to choose from mutually exclusive options.

The following code example creates two CheckBox controls and adds them to a Form. It uses

the Checked property to get the Boolean value indicating whether the CheckBox is in the

checked state. It also uses the CheckState property to get the value of a three-state CheckBox

control. The three statuses of CheckState property are: (1) Checked: the CheckBox displays a

check mark, (2) Unchecked: the CheckBox is empty, and (3) Indeterminate: the CheckBox

displays a check mark and is shaded. It is necessary to note that these two CheckBox controls

have been registered with a checkedChanged event, yet they share one event handler,

checkBox_CheckedChanged(), in the following code. In the event handler, the sender variable

represents the CheckBox control being checked. This variable is declared as System::Object

type; therefore, it is necessary to apply type casting in the format of: ((CheckBox^)

sender)->Checked.

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

public: Form1()

{

this->Size = Drawing::Size(300, 120);

Page 18: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 297

CheckBox^ checkBox1 = gcnew CheckBox;

checkBox1->Text = "Los Angeles";

checkBox1->Location = Point(10, 10);

checkBox1->CheckedChanged += gcnew EventHandler(this,

&Form1::checkBox_CheckedChanged);

Controls->Add(checkBox1);

CheckBox^ checkBox2 = gcnew CheckBox;

checkBox2->Text = "San Diego";

checkBox2->Location = Point(10, 30);

checkBox2->CheckedChanged += gcnew EventHandler(this,

&Form1::checkBox_CheckedChanged);

Controls->Add(checkBox2);

}

void checkBox_CheckedChanged(Object^ sender, EventArgs^ e)

{

this->Text = Convert::ToString(((CheckBox^) sender)-

>CheckState);

if(((CheckBox^) sender)->Checked)

{

MessageBox::Show(((CheckBox^) sender)->Text);

}

}

};

[STAThread]

int main() {

Application::Run(gcnew Form1);

}

A sample output looks:

The following code example creates two RadioButton controls. The example uses the

CheckedChanged event to track which RadioButton is selected and reports the text of the

selected RadioButton when the user clicks a Button. Notice that the instructor purposely

declared the two RadioButton controls as “private” member of the class.

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

private:

RadioButton^ radioButton1;

RadioButton^ radioButton2;

public: Form1()

Page 19: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 298

{

radioButton1 = gcnew RadioButton;

radioButton1->Location = Point(10, 10);

radioButton1->Text = "Biology";

radioButton1->CheckedChanged += gcnew EventHandler(this,

&Form1::radioButton_CheckedChanged);

Controls->Add(radioButton1);

radioButton2 = gcnew RadioButton;

radioButton2->Location = Point(10, 30);

radioButton2->Text = "Chemistry";

radioButton2->CheckedChanged += gcnew EventHandler(this,

&Form1::radioButton_CheckedChanged);

Controls->Add(radioButton2);

}

void radioButton_CheckedChanged(Object^ sender, EventArgs^ e)

{

this->Text = "You picked " + ((RadioButton^) sender)->Text;

}

};

[STAThread]

int main() {

Application::Run(gcnew Form1);

}

A sample output looks:

and

The GroupBox class can display a frame around a group of controls with or without a caption.

Use a GroupBox to logically group a collection of controls on a form. The group box is a

container control that can be used to define groups of controls. The typical use for a group box

is to contain a logical group of RadioButton controls. If you have two group boxes, each of

which contain several option buttons (also known as radio buttons), each group of buttons is

mutually exclusive, setting one option value per group. The following code example instantiates

and creates a GroupBox and two RadioButton controls. The radio buttons are added to the

group box and the group box is then added to the Form.

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

private:

RadioButton^ radioButton1;

RadioButton^ radioButton2;

Page 20: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 299

GroupBox^ groupBox1;

public: Form1()

{

groupBox1 = gcnew GroupBox;

groupBox1->Text = "What is your major?";

groupBox1->FlatStyle = FlatStyle::Flat;

groupBox1->Location = Point(10, 10);

Controls->Add(groupBox1);

radioButton1 = gcnew RadioButton;

radioButton1->Location = Point(10, 10);

radioButton1->Text = "Biology";

radioButton1->CheckedChanged += gcnew EventHandler(this,

&Form1::radioButton_CheckedChanged);

groupBox1->Controls->Add(radioButton1);

radioButton2 = gcnew RadioButton;

radioButton2->Location = Point(10, 30);

radioButton2->Text = "Chemistry";

radioButton2->CheckedChanged += gcnew EventHandler(this,

&Form1::radioButton_CheckedChanged);

groupBox1->Controls->Add(radioButton2);

}

void radioButton_CheckedChanged(Object^ sender, EventArgs^ e)

{

this->Text = "You picked " + ((RadioButton^) sender)->Text;

}

};

[STAThread]

int main() {

Application::Run(gcnew Form1);

}

A sample output looks:

Trackbar The Windows Forms TrackBar control (also sometimes called a “slider” control) is used for

navigating through a large amount of information or for visually adjusting a numeric setting.

The TrackBar control has two parts: the thumb, also known as a slider, and the tick marks. The

thumb is the part that can be adjusted. Its position corresponds to the Value property. The tick

marks are visual indicators that are spaced at regular intervals. The track bar moves in

increments that you specify and can be aligned horizontally or vertically. An example use of a

track bar would be for setting cursor blink rate or mouse speed.

You can configure TrackBar ranges through which the value of the Value property of a track

bar scrolls by setting the Minimum property to specify the lower end of the range and the

Maximum property to specify the upper end of the range. The LargeChange property defines

Page 21: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 300

the increment to add or subtract from the Value property when clicks occur on either side of the

scroll box. The track bar can be displayed horizontally or vertically. You can use this control to

input numeric data obtained through the Value property. You can display this numeric data in a

control or use it in code.

The following code example displays a form containing a TrackBar control and a TextBox

control. The example demonstrates setting the Maximum, TickFrequency, LargeChange, and

SmallChange properties and handling the Scroll event. The TextBox contents are updated to

the Value property value when the Scroll event occurs.

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

TrackBar^ trackBar1;

TextBox^ textBox1;

public: Form1()

{

trackBar1 = gcnew TrackBar;

trackBar1->Location = Point( 8, 8 );

trackBar1->Size = Drawing::Size( 224, 45 );

trackBar1->Maximum = 100;

trackBar1->TickFrequency = 5;

trackBar1->LargeChange = 3;

trackBar1->SmallChange = 2;

trackBar1->Scroll += gcnew EventHandler(this,

&Form1::trackBar1_Scroll);

Controls->Add(trackBar1);

textBox1 = gcnew TextBox;

textBox1->Location = Point(240, 16);

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

textBox1->Text = trackBar1->Value + "";

Controls->Add(textBox1);

ClientSize = Drawing::Size(296, 62);

}

private: void trackBar1_Scroll(Object^ sender, EventArgs^ e)

{

textBox1->Text = trackBar1->Value + "";

}

};

[STAThread]

int main()

{

Application::Run(gcnew Form1);

}

The output looks:

Page 22: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 301

By the way, the Form::ClientSize property sets the height and width of the client area of the

form.

The ListBox

class

The ListBox control enables you to display a list of items to the user that the user can select by

clicking. To create with a button with an ID listBox1, use:

ListBox^ listBox1 = gcnew ListBox;

A ListBox control can provide single or multiple selections using the SelectionMode property.

The ListBox also provides the MultiColumn property to enable the display of items in columns

instead of a straight vertical list of items. With this, the control can display more visible items

and the user no longer needs to scroll to an item. For example,

ListBox^ listBox1 = gcnew ListBox;

listBox1->Size = Drawing::Size(200, 100);

listBox1->Location = Point(10, 10);

this->Controls->Add(listBox1);

listBox1->MultiColumn = true;

listBox1->SelectionMode = SelectionMode::MultiExtended;

The items property references to the list of items that are currently stored in the ListBox. With

this reference, you can add items, remove items, and obtain a count of the items in the

collection. The following example adds 10 items to the ListBox using the Add() method, and

then selects three items from the list using the SetSelected() method.

listBox1->BeginUpdate();

// Loop through and add 10 items to the ListBox.

for (int x = 1; x <= 10; x++) {

listBox1->Items->Add(Convert::ToString(x));

}

listBox1->EndUpdate();

// Select three items from the ListBox.

listBox1->SetSelected(0, true);

listBox1->SetSelected(2, true);

listBox1->SetSelected(4, true);

The SetSelected method has a syntax of:

SetSelected(index, true/false)

where index is an integer starting at 0; namely the first item is given an index value 0, the

second 1, the third 2, and so on. Additionally, true/false means true to select the specified item.

The BeginUpdate() method maintains performance while items are added to the ListBox one at

a time by preventing the control from drawing until the EndUpdate() method is called.

Use the Remove(Str) method to remove a particular item with a value “8”. For example,

Page 23: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 302

listBox1->Items->Remove("8");

Or you can remove an item with index 7 using the RemoveAt() method. For example,

listBox1->Items->RemoveAt(7);

To remove all items, use Clear(). For example, listBox1->Items->Clear();

Arrays can be used in Windows form controls. For example,

ListBox^ listBox1 = gcnew ListBox;

array<String ^> ^ campus = gcnew array<String ^>{

"Pomona", "Long Beach", "Sherman Oaks", "Irvin",

"San Diego", "Las Vegas"};

listBox1->Items->Clear();

listBox1->Items->AddRange(campus);

listBox1->AutoSize = true;

listBox1->Width = 110;

listBox1->Location = Point(10, 10);

// this control to the form

this->Controls->Add(listBox1);

// set the form size

this->Size = Drawing::Size(150, 150);

A sample output looks:

Review

Questions

1. Which is not one of the header files that must be included in a Visual C++ CLR Windows

Form Application?

A. <System.dll>

B. <System.CLR.dll>

C. <System.Windows.Forms.dll>

D. <System.Drawing.dll>

2. Which specifies the Location property of "label2" object to (100, 200)?

A. label2->Location.Point = (100, 100);

B. label2->Location = Location(100, 100);

C. label2->Location = Point(100, 100);

D. label2->Location = (100, 100);

3. Given the following code segment, which statement is correct?

public ref class Form1: public System::Windows::Forms::Form

{

public: Form1() { // Create a new instance of the form

this->Text = "My Form";

this->Size = Drawing::Size(250, 150);

}

};

Page 24: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 303

A. It names the Windows form "Form".

B. The keyword “this” refers to the operating system.

C. It names the Windows form "Form1".

D. It specifies only two properties of the Windows form.

4. Given the following code segment, which statement is incorrect?

[STAThread]

int main(){

Application::Run(gcnew Form1);

}

A. STA stands for single-thread apartment.

B. STA forces Windows to give the sole priority to main function.

C. STA ensures that the main() function is always the starting point of the code.

D. STATread is an optional declaration and is typically ignored by Windows OS.

5. Which option of the "cl" compiler must be used to compile a CLR Windows form

application?

A. /clr

B. /clr:oldstyle

C. /GR

D. /RTC

6. Which is the default event handler of a CheckBox?

A. Click

B. CheckedChanged

C. Enter

D. ValueChanged

7. Which creates a button with an ID "button1"?

A. Button button1 = gcnew Button;

B. Button^ button1 = gcnew Button;

C. Button button1 = new Button;

D. Button^ button1 = new Button;

8. Which sets the size of the "label2" object to accommodate the size of image1?

A. label2->Size = (image1->Width, image1->Height );

B. label2->Size = label2->image1->Size;

C. label2->Size = Drawing::Size( image1->Width, image1->Height );

D. label2->Size = (int) label2->Size;

9. The __ method of the ListBox class maintains performance while items are added to the

ListBox one at a time by preventing the control from drawing until the EndUpdate() method is

called.

A. BeginUpdate()

B. AfterUpdate()

C. NoUpdate()

D. StopUpdate()

10. The following statement __.

listBox1->Items->Clear();

A. deletes the listBox1.

B. removes all items from the listBox1.

Page 25: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 304

C. removes a particular item from the listBox1.

D. clears the background color of the listBox1.

Page 26: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 305

Lab #10 Hand-Coding Windows Form Programming

Learning Activity #1: A Simple DNS Lookup tool

1. Create the C:\cis223 directory if it does not exist.

2. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223

directory.

3. Use Notepad to create a new text file C:\cis223\lab10_1.cpp with the following contents:

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

using namespace System::Net;

public ref class Form1: public Form {

private:

TextBox^ textBox1;

Label^ label1;

public:

Form1()

{

this->Text = "My First Form"; //title

textBox1 = gcnew TextBox;

textBox1->Width = 265;

textBox1->Location = Point(10, 10);

this->Controls->Add(textBox1);

Button^ button1 = gcnew Button;

button1->Text = "DNS Lookup";

button1->AutoSize = true;

button1->Location = Point(10, 40);

// register event

button1->Click += gcnew EventHandler(this, &Form1::button1_Click);

this->Controls->Add(button1);

label1 = gcnew Label;

label1->Size = Drawing::Size(265, 205);

label1->Location = Point(10, 70);

this->Controls->Add(label1);

}

// event handler

private: Void button1_Click(Object^ sender, EventArgs^ e)

{

String^ str;

if (textBox1->Text == "")

{

MessageBox::Show("Enter a host name (e.g. www.cnn.com)");

Page 27: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 306

}

else

{

IPHostEntry^ hostInfo = Dns::GetHostEntry(textBox1->Text);

for (int i = 0; i < hostInfo->AddressList->Length; i++)

{

str += hostInfo->AddressList[i] + "\n";

}

label1->Text = str;

}

}

};

[STAThread]

int main()

{

Application::Run(gcnew Form1);

}

4. Open the Developer Command Prompt.

5. Type cd c:\cis223 and press [Enter] to change to C:\cis223 directory.

C:\Program Files\Microsoft Visual Studio\2017\Community>cd c:\cis223

C:\cis223>

6. Type cl /clr lab10_1.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile

the code using:

C:\cis223>cl /clr lab10_1.cpp /link /subsystem:windows /ENTRY:main

7. Type lab10_1 and press [Enter] to test the program.

C:\cis223>lab10_1

8. The output looks. Type in a domain name (such as www.cnn.com or www.yahoo.com) to resolve the IP

address(es). Click the button.

9. Download the “assignment template” and rename it to lab10.doc if necessary. Capture a screen shot similar to

the above figure and paste it to the Word document named lab10.doc (or .docx).

Learning Activity #2:

1. Download the “tree.gif” file and save it to C:\cis223 directory.

2. Use Notepad to create a new text file C:\cis223\lab10_2.cpp with the following contents:

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

Page 28: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 307

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

Label^ label1;

TrackBar^ trackBar1;

TextBox^ textBox1;

Image^ image1;

public: Form1()

{

trackBar1 = gcnew TrackBar;

trackBar1->Location = Point(10, 10);

trackBar1->Size = Drawing::Size(224, 45);

trackBar1->Maximum = 100;

trackBar1->Minimum = 10;

trackBar1->Value = 10;

trackBar1->TickFrequency = 5;

trackBar1->LargeChange = 3;

trackBar1->SmallChange = 2;

trackBar1->Scroll += gcnew EventHandler(this, &Form1::trackBar1_Scroll);

Controls->Add(trackBar1);

textBox1 = gcnew TextBox;

textBox1->Location = Point(240, 16);

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

textBox1->Text = trackBar1->Value + "";

Controls->Add(textBox1);

image1 = Image::FromFile("tree.gif");

//drawIt(10, 10);

label1 = gcnew Label;

label1->Location = Point(10, 50);

label1->Image = drawIt(trackBar1->Value * 10, trackBar1->Value * 10);

label1->Size = Drawing::Size(trackBar1->Value * 10, trackBar1->Value * 10);

Controls->Add(label1);

ClientSize = Drawing::Size(296, 300);

}

private: Bitmap^ drawIt(int w, int h)

{

Bitmap^ bmp = gcnew Bitmap(image1, w, h);

return bmp;

}

private: void trackBar1_Scroll(Object^ sender, EventArgs^ e)

{

textBox1->Text = trackBar1->Value + "";

label1->Image = drawIt(trackBar1->Value * 10, trackBar1->Value * 10);

label1->Size = Drawing::Size(trackBar1->Value * 10, trackBar1->Value * 10);

}

};

[STAThread]

int main()

{

Page 29: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 308

Application::Run(gcnew Form1);

}

3. Open the Developer Command Prompt. Compile the code using:

cl /clr lab10_2.cpp /link /subsystem:windows /ENTRY:main

4. Test the program. Move the track bar. The output looks:

5. Capture a screen shot similar to the above figure and paste it to the Word document named lab10.doc (or .docx).

Learning Activity #3: Calculator

1. Use Notepad to create a new text file C:\cis223\lab10_3.cpp with the following contents:

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

String^ n1; // operand2

String^ n2; // operand2

String^ ops; // operator

Button^ button1; // 1

Button^ button2; // 2

Button^ button3; // 3

Button^ button4; // +

Button^ button5; // 4

Button^ button6; // 5

Button^ button7; // 6

Button^ button8; // -

Button^ button9; // 7

Button^ button10; // 8

Button^ button11; // 9

Button^ button12; // *

Button^ button13; // .

Button^ button14; // 0

Button^ button15; // =

Button^ button16; // /

Button^ button17; // Cls

Button^ button18; // x^y

Button^ button19; // Sqrt

Button^ button20; // Mod

Page 30: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 309

TextBox^ textBox1; // display

public: Form1()

{

int w = 30; // button width

int h = 30; // button height

textBox1 = gcnew TextBox;

textBox1->Location = Point(10, 10);

textBox1->TextAlign = HorizontalAlignment::Right;

Controls->Add(textBox1);

// 1st row

button1 = gcnew Button;

button1->Location = Point(10, textBox1->Top + textBox1->Height + 5);

button1->Text = "1";

button1->Size = Drawing::Size(w, h);

button1->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button1);

textBox1->Width = (w * 4) + 15; // 5 pixel apart between every two buttons

int bY = textBox1->Top + textBox1->Height; // y-coordinate of 1st row buttons

button2 = gcnew Button;

button2->Location = Point(button1->Left + w + 5, bY + 5); // 5 pixels apart

button2->Text = "2";

button2->Size = Drawing::Size(w, h);

button2->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button2);

button3 = gcnew Button;

button3->Location = Point(button2->Left + w + 5, bY + 5);

button3->Text = "3";

button3->Size = Drawing::Size(w, h);

button3->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button3);

button4 = gcnew Button;

button4->Location = Point(button3->Left + w + 5, bY + 5);

button4->Text = "+";

button4->Size = Drawing::Size(w, h);

button4->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button4);

// 2nd row

button5 = gcnew Button;

button5->Location = Point(10, button1->Top + h + 5);

button5->Text = "4";

button5->Size = Drawing::Size(w, h);

button5->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button5);

button6 = gcnew Button;

button6->Location = Point(button1->Left + w + 5, button1->Top + h + 5);

button6->Text = "5";

button6->Size = Drawing::Size(w, h);

button6->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button6);

button7 = gcnew Button;

button7->Location = Point(button2->Left + w + 5, button1->Top + h + 5);

button7->Text = "6";

Page 31: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 310

button7->Size = Drawing::Size(w, h);

button7->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button7);

button8 = gcnew Button;

button8->Location = Point(button3->Left + w + 5, button1->Top + h + 5);

button8->Text = "-";

button8->Size = Drawing::Size(w, h);

button8->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button8);

// 3rd row

button9 = gcnew Button;

button9->Location = Point(10, button5->Top + h + 5);

button9->Text = "7";

button9->Size = Drawing::Size(w, h);

button9->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button9);

button10 = gcnew Button;

button10->Location = Point(button1->Left + w + 5, button5->Top + h + 5);

button10->Text = "8";

button10->Size = Drawing::Size(w, h);

button10->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button10);

button11 = gcnew Button;

button11->Location = Point(button2->Left + w + 5, button5->Top + h + 5);

button11->Text = "9";

button11->Size = Drawing::Size(w, h);

button11->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button11);

button12 = gcnew Button;

button12->Location = Point(button3->Left + w + 5, button5->Top + h + 5);

button12->Text = "*";

button12->Size = Drawing::Size(w, h);

button12->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button12);

// 4th row

button13 = gcnew Button;

button13->Location = Point(10, button9->Top + h + 5);

button13->Text = ".";

button13->Size = Drawing::Size(w, h);

button13->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button13);

button14 = gcnew Button;

button14->Location = Point(button1->Left + w + 5, button9->Top + h + 5);

button14->Text = "0";

button14->Size = Drawing::Size(w, h);

button14->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button14);

button15 = gcnew Button;

button15->Location = Point(button2->Left + w + 5, button9->Top + h + 5);

button15->Text = "=";

button15->Size = Drawing::Size(w, h);

button15->Click += gcnew EventHandler(this, &Form1::equalIt);

Controls->Add(button15);

button16 = gcnew Button;

Page 32: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 311

button16->Location = Point(button3->Left + w + 5, button9->Top + h + 5);

button16->Text = "/";

button16->Size = Drawing::Size(w, h);

button16->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button16);

// 5th row

button17 = gcnew Button;

button17->Location = Point(10, button13->Top + h + 5);

button17->Text = "Cls";

button17->Size = Drawing::Size(w, h);

button17->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button17);

button18 = gcnew Button;

button18->Location = Point(button1->Left + w + 5, button13->Top + h + 5);

button18->Text = "x^y";

button18->Size = Drawing::Size(w, h);

button18->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button18);

button19 = gcnew Button;

button19->Location = Point(button2->Left + w + 5, button13->Top + h + 5);

button19->Text = "Sqrt";

button19->Size = Drawing::Size(w, h);

button19->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button19);

button20 = gcnew Button;

button20->Location = Point(button3->Left + w + 5, button13->Top + h + 5);

button20->Text = "Mod";

button20->Size = Drawing::Size(w, h);

button20->Click += gcnew EventHandler(this, &Form1::button_Click);

Controls->Add(button20);

this->Width = textBox1->Width + 35;

this->Height = button1->Height * 5 + textBox1->Height + 85;

}

void button_Click(Object^ sender, EventArgs^ e)

{

if (((Button^) sender)->Text == "Cls")

{

textBox1->Text = ""; // clear the display

ops = "";

n1 = "";

n2 = "";

}

else if (((Button^) sender)->Text == "Sqrt")

{

if (textBox1->Text != "")

{

textBox1->Text = Math::Sqrt(Convert::ToDouble(textBox1->Text)) + "";

}

}

else if (((Button^) sender)->Text == "x^y" || ((Button^) sender)->Text == "Mod"

|| ((Button^) sender)->Text == "+" || ((Button^) sender)->Text == "-" || ((Button^)

sender)->Text =="*" || ((Button^) sender)->Text == "/")

{

ops = ((Button^) sender)->Text;

Page 33: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 312

n1 = textBox1->Text;

textBox1->Text = ""; // clear the display

}

else

{

textBox1->Text += ((Button^) sender)->Text;

}

}

void equalIt(Object^ sender, EventArgs^ e)

{

n2 = textBox1->Text;

if (ops == "+")

{

textBox1->Text = (Convert::ToDouble(n1) + Convert::ToDouble(n2)) + "";

}

if (ops == "-")

{

textBox1->Text = (Convert::ToDouble(n1) - Convert::ToDouble(n2)) + "";

}

if (ops == "*")

{

textBox1->Text = (Convert::ToDouble(n1) * Convert::ToDouble(n2)) + "";

}

if (ops == "/")

{

textBox1->Text = (Convert::ToDouble(n1) / Convert::ToDouble(n2)) + "";

}

if (ops == "Mod") // modulus

{

textBox1->Text = (Convert::ToInt32(n1) % Convert::ToInt32(n2)) + "";

}

if (ops == "x^y") // exponent

{ //Math::Pow(x, y)

textBox1->Text = (Math::Pow(Convert::ToInt32(n1), Convert::ToInt32(n2))) + "";

}

}

};

[STAThread]

int main() {

Application::Run(gcnew Form1);

}

2. Open the Developer Command Prompt. Compile the code using:

cl /clr lab10_3.cpp /link /subsystem:windows /ENTRY:main

3. Test the program.

Page 34: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 313

4. Capture a screen shot similar to the above figure and paste it to the Word document named lab10.doc (or .docx).

Learning Activity #4:

1. Use Notepad to create a new text file C:\cis223\lab10_4.cpp with the following contents:

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

GroupBox^ groupBox1;

GroupBox^ groupBox2;

RadioButton^ radioButton1;

RadioButton^ radioButton2;

CheckBox^ checkBox1;

CheckBox^ checkBox2;

Label^ label1;

String^ ans1;

String^ ans2;

public: Form1()

{

this->Width = 500;

// CheckBox

groupBox1 = gcnew GroupBox;

groupBox1->Text = "1. Which city is in California?";

groupBox1->FlatStyle = FlatStyle::Flat;

groupBox1->Location = Point(10, 10);

Controls->Add(groupBox1);

checkBox1 = gcnew CheckBox;

checkBox1->Text = "Los Angeles";

checkBox1->Location = Point(10, 20);

checkBox1->CheckedChanged += gcnew EventHandler(this,

&Form1::checkBox_CheckedChanged);

groupBox1->Controls->Add(checkBox1);

checkBox2 = gcnew CheckBox;

checkBox2->Text = "San Diego";

checkBox2->Location = Point(10, 40);

checkBox2->CheckedChanged += gcnew EventHandler(this,

&Form1::checkBox_CheckedChanged);

groupBox1->Controls->Add(checkBox2);

Page 35: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 314

// RadioButton

groupBox2 = gcnew GroupBox;

groupBox2->Text = "2. What is your major?";

groupBox2->FlatStyle = FlatStyle::Standard;

groupBox2->Location = Point(10, groupBox1->Height + 20);

Controls->Add(groupBox2);

radioButton1 = gcnew RadioButton;

radioButton1->Location = Point(10, 20);

radioButton1->Text = "Biology";

radioButton1->CheckedChanged += gcnew EventHandler(this,

&Form1::radioButton_CheckedChanged);

groupBox2->Controls->Add(radioButton1);

radioButton2 = gcnew RadioButton;

radioButton2->Location = Point(10, 40);

radioButton2->Text = "Chemistry";

radioButton2->CheckedChanged += gcnew EventHandler(this,

&Form1::radioButton_CheckedChanged);

groupBox2->Controls->Add(radioButton2);

label1 = gcnew Label;

label1->Location = Point(groupBox1->Width + 20, 10);

label1->AutoSize = true;

this->Controls->Add(label1);

}

void checkBox_CheckedChanged(Object^ sender, EventArgs^ e)

{

ans1 = "";

if(((CheckBox^) sender)->Checked)

{

((CheckBox^) sender)->Name = ((CheckBox^) sender)->Text;

}

else

{

((CheckBox^) sender)->Name = "";

}

ans1 = "1. You picked : " + checkBox1->Name + ", " + checkBox2->Name;

label1->Text = ans1 + "\n" + ans2;

}

void radioButton_CheckedChanged(Object^ sender, EventArgs^ e)

{

ans2 = "2. You picked " + ((RadioButton^) sender)->Text;

label1->Text = ans1 + "\n" + ans2;

}

};

[STAThread]

int main() {

Application::Run(gcnew Form1);

Page 36: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 315

}

2. Open the Developer Command Prompt. Compile the code using “cl /clr lab10_4.cpp /link

/subsystem:windows /ENTRY:main”.

3. Test the program. Click the image (label) to shrink its size, and then click the “Resize Image” label to change it

back. Capture a screen similar to the following and paste it to the Word document named lab10.doc (or .docx).

Learning Activity #5: Programmatically create a ListBox

1. Use Notepad to create a new text file C:\cis223\lab10_5.cpp with the following contents:

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public System::Windows::Forms::Form

{

public:

Form1() {

this->Size = Drawing::Size(240, 150);

ListBox^ listBox1 = gcnew ListBox;

listBox1->Size = Drawing::Size(200, 100);

listBox1->Location = Point(10, 10);

this->Controls->Add(listBox1);

listBox1->MultiColumn = true;

listBox1->SelectionMode = SelectionMode::MultiExtended;

listBox1->BeginUpdate();

// Loop through and add 10 items to the ListBox.

for (int x = 1; x <= 10; x++) {

listBox1->Items->Add(Convert::ToString(x));

}

listBox1->EndUpdate();

// Select three items from the ListBox.

listBox1->SetSelected(0, true);

listBox1->SetSelected(2, true);

listBox1->SetSelected(4, true);

}

Page 37: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 316

};

[STAThread]

int main()

{

Application::Run( gcnew Form1 );

}

2. Open the Developer Command Prompt. Compile the code using “cl /clr lab10_5.cpp /link

/subsystem:windows /ENTRY:main”.

3. Test the program.

4. Capture a screen shot similar to the above figure and paste it to the Word document named lab10.doc

(or .docx).

Submittal

1. Complete all the 5 learning activities and the programming exercise in this lab.

2. Create a .zip file named lab10.zip containing ONLY the following self-executable files.

• Lab10_1.exe

• Lab10_2.exe

• Lab10_3.exe

• Lab10_4.exe

• Lab10_5.exe

• Lab10.doc (or lab10.docx or .pdf) [You may be given zero point if this Word document is missing]

3. Upload the zipped file to Question 11 of Assignment as response.

Programming Exercise 10:

1. Launch the Developer Command Prompt.

2. Use Notepad to create a new text file named ex10.cpp.

3. Add the following heading lines (Be sure to use replace [YourFullNameHere] with the correct one).

//File Name: ex10.cpp

//Programmer: [YourFullNameHere]

4. Hand code a Windows form application that has one ListBox control with the following specifications:

• AutoSize: false

• Width: 110

• Height: 50

• Location: (10, 10)

5. Create a string array named “course” using the following code. Be sure to add six elements to this array:

"CIS211", "CIS212", "CIS213", "CIS214", "CIS215", "CIS216", "CIS217", and "CIS218".

array<String ^> ^ course = gcnew array<String ^> { … }

6. Use the AddRange() method to add the six elements of the “course” array to the ListBox control.

7. Set the size of the form to (150, 200).

8. Compile the source code to produce executable code. The output must look similar to the following:

Page 38: The instructor also “using” the following namespace to reference …students.cypresscollege.edu/cis223/lc10.pdf · 2018-08-25 · Inside the public class (e.g. Form1), you create

Visual C++ Programming – Penn Wu, PhD 317

9. Your application must meet the above requirements to get credit. No partial credit is given.

10. Download the “programming exercise template” and rename it to ex10.doc if necessary. Copy your source

code to the file and then capture the screen shot(s) similar to the above one and paste it to the Word document

named “ex10.doc” (or .docx).

11. Compress the source file (ex10.cpp), executable code (ex10.exe), and Word document (ex10.doc) to a .zip file

named “ex10.zip”.

Grading criteria:

You will earn credit only when the following requirements are fulfilled. No partial credit is given.

• You successfully submit both source file and executable file.

• Your source code must be fully functional and may not contain syntax errors in order to earn credit.

• Your executable file (program) must be executable to earn credit.

Threaded Discussion

Note: Students are required to participate in the thread discussion on a weekly basis. Student must post at

least two messages as responses to the question every week. Each message must be posted on a

different date. Grading is based on quality of the message.

Question:

Class, as you know, Visual Studio IDE can automatically build a "Windows form" for programmers

to assemble applications? What is/are the advantage(s) and disadvantage(s) of hand-coding a

Windows form application? [There is never a right-or-wrong answer for this question. Please free

feel to express your opinion.]

Be sure to use proper college level of writing. Do not use texting language.