task 1 – your first visual basic program · task 1 – your first visual basic program page 3...

24
Task 1 – Your First Visual Basic Program Page 1 Task 1 – Your First Visual Basic Program Visual Basic 2010 Express Edition is a free program and it can be downloaded from http://www.microsoft.com/express/Downloads/ Step 1: Create a New Project in Visual Basic For every Visual Basic program, we have to create a new project. 1. Click File New Project. By default, Windows Forms Application is selected. 2. Fill in a relevant Project Name (e.g. Task 1). 3. Press OK to continue. Step 2: Create a User Interface We have to add controls (e.g. button, textbox) from the Toolbox to create the user interface. 1. Click the Toolbox panel. 2. Drag and drop Label, Textbox, Button, and WebBrowser on the Form.

Upload: others

Post on 08-Feb-2020

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 1 – Your First Visual Basic Program

Page 1

Task 1 – Your First Visual Basic Program

Visual Basic 2010 Express Edition is a free program and it can be downloaded from

http://www.microsoft.com/express/Downloads/

Step 1: Create a New Project in Visual Basic

For every Visual Basic program, we have to create a new project.

1. Click File � New Project.

By default, Windows Forms

Application is selected.

2. Fill in a relevant Project Name

(e.g. Task 1).

3. Press OK to continue.

Step 2: Create a User Interface

We have to add controls (e.g. button, textbox) from the Toolbox to create the user interface.

1. Click the Toolbox panel.

2. Drag and drop Label, Textbox,

Button, and WebBrowser on

the Form.

Page 2: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 1 – Your First Visual Basic Program

Page 2

Step 3: Add Program Code

1. Double-click the Button.

A new window called the Code

Editor opens. We can add

program code in it.

2. Type the following:

WebBrowser1.Navigate(Textbox1.Text)

Step 4: Run and Test Your Program

1. Click Debug � Start Debugging or press F5.

This command runs your program.

2. In the text box, type a URL (e.g. http://hk.yahoo.com/) and click the button.

Step 5: Save and Publish the Project

To save the project:

1. Click File � Save All.

To enable other people to use this program, we can publish the project:

2. Click Project � Publish [project_name].

A file called Setup.exe and other necessary files will then be created for

other people to install your program.

Self-Reflection

� What are the pros & cons of the program?

� How can you improve it?

Page 3: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 1 – Your First Visual Basic Program

Page 3

Step 6: Enhance the interface by customizing looks and behavior

By using the Properties window, we can change the properties of various controls to customize

their appearance.

1. Drag and drop a Panel

on the Form.

2. Move the existing

Label, Textbox &

Button to be on the

panel.

3. Select the Panel control.

4. In the Properties window, select

the Dock property and choose

the top box (i.e. Top).

Then, the Panel will expand to fill the

top of the form.

5. Select the WebBrowser.

6. In the Properties window, select

Dock property and click the

middle (i.e. Fill).

Then the WebBrowser will fill the

remaining form.

Page 4: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 1 – Your First Visual Basic Program

Page 4

7. Select the Button control.

8. In the Properties window, select

the Text property. Delete

“Button1” and replace it with

“Go!”.

9. Similarly, replace the Text

property of Label1 to be

“Address”

10. We may also change the font and

color of the text shown by

modifying the Font and

ForeColor property.

11. Resize or relocate any of the controls, and resize the form to suit your taste.

Self-Reflection

� What are the pros & cons of the program?

� How can you improve it?

Page 5: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 1 – Your First Visual Basic Program

Page 5

Bonus Part

You may add the following extra functions in the web browser.

1) Go Back and Go Forward

Hints: Browse the available functions in Webbrowser1

2) Bookmark

Hints: add buttons for going to specified hyperlinks

3) Click “Enter” to navigate website of the typed URL

Hints: Type the program in the appropriate event

4) For every change of window size, re-position “Go!” button in right hand side

5) For every change of window size, URL textbox will be resized to fit the window’s width

6) Textbox will show the updated URL

7) Any other suitable functions

Page 6: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 2 – Vending Machine

Page 6

Task 2 – Vending Machine

You are going to create a virtual vending machine selling your favourite products.

A. User Interface Design

A sample interface of a vending machine is shown as below:

Which VB controls does the above interface use?

� ____________________

� ____________________

To insert a picture on the button, simply modify the

BackgroundImage property of that button.

You can also handle the image placement and control sizing by

modifying BackgroundImageLayout.

You may download appropriate pictures from

� http://office.microsoft.com/en-us/images

Page 7: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 2 – Vending Machine

Page 7

B. Program Coding

� Arithmetic Operation

Common operators used in Visual Basic are:

Addition +

Subtraction -

Multiplication *

Division / Pay special attention

� Calculation

The value calculated in right-hand side will be put into left-hand side.

a = 1 + 3 after execution: a becomes ___________

b = 9 – 3 * 2 after execution: b becomes ___________

� Variable

Variable is a space for computer to store data (e.g. number, text).

We have to tell computer we are going to use variable before using them.

We use the following to tell computer:

Dim total As Integer = 0

The above statement tells computer that we allocate a space

called:

type of storage:

initial value:

Time to think

� What variables are needed for the vending machine program?

Page 8: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 2 – Vending Machine

Page 8

� Input Statement

We can get users’ input from the Textbox. The code is as follow:

Dim paid As Integer = 0

paid = Textbox1.Text

� Output Statement

You may display information to users by changing the Text property of Label. The code

examples are as follows

Label1.Text = "Hello!" ' to display text information

Dim amount As Integer = 30

Label1.Text = amount ' to display number information

Label1.Text = "You have to pay $" & amount

' to display both text & number

Task: Try to implement the vending machine program by using the skills learnt

above.

Self-Reflection

� What are the pros & cons of the program?

� How can you improve it?

Page 9: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 2 – Vending Machine

Page 9

Bonus Part

You may add the following extra functions in the vending machine.

1) Add a list to indicate no. of item sold for each product

2) Allow user to enter how much they will pay and calculate the change

3) Allow user to clear all the content and start it again

4) Any other suitable functions

Page 10: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 3 – Number Guessing Game

Page 10

Task 3 – Number Guessing Game

You are going to create a number guess game.

A. Game Rule

� Guess the secret number from a range of number (from ________ to ________).

� Hints will be displayed on the screen indicating the range.

� Decide whether the lower/upper limit IS / IS NOT included in the range.

B. User Interface Design

A sample interface is shown as below:

Which VB controls does the above interface use?

� ____________________

� ____________________

� ____________________

C. Program Coding

Time to think

� What variables do you need to use for the above program?

� What do you need to do to make the game work?

Page 11: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 3 – Number Guessing Game

Page 11

� Random number generator

The following code will generate a random number from 1 to 9 and put it into variable secret.

(note that 10 will NOT be generated).

Dim RandomClass As New Random()

secret = RandomClass.Next(1, 10)

� Relational Operator

To test whether certain situations happen, we use the following operators.

Try to circle the correct answer for each example.

Operator Meaning Example Result

> Greater 12 > 6 True / False

1 >= 9 True / False >= Greater or Equal

3 >= 3 True / False

< Less 10 < 33 True / False

7 <= 3 True / False <= Less or Equal

8 <= 8 True / False

= Equal 6 = 4 True / False

<> Not Equal 8 <> 2 True / False

� Conditional Statement

We can ask computer to run some statements ONLY WHEN certain situation is true.

The following code only checks for one situation. If the situation is TRUE, then the statement(s)

inside If … Then and End If will be executed.

If a > 4 Then

execute statement(s)

End If

a > 4

statement(s)

YES

NO

Page 12: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 3 – Number Guessing Game

Page 12

Time to think

� How many situations do you need to check for the number guessing program?

� For each situation, what do you need to do?

� How do you tell users that they have won the game?

Self-Reflection

� What are the pros & cons of the program?

� How can you improve it?

Page 13: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 3 – Number Guessing Game

Page 13

Bonus Part

1) When an out-of-range number is entered, the lower/upper limit may be reset to a

lower/upper number (refers to the example below). Try to solve this problem.

2) Allow users to guess for a number of times (e.g. 10 times) and display “YOU LOSE”.

3) Allow users to define the range of number (e.g. from 1 to 200)

4) Any other functions to make the game more interesting

You may need to use the following Boolean operators or Conditional Statements.

� Boolean Operators

For the operator AND, only both conditions which are true will give a true value.

Example Operation Meaning Result

3 > 1 AND 4 > 2 True AND True True

3 > 1 AND 2 > 4 True AND False False

1 > 3 AND 4 > 2 False AND True False

1 > 3 AND 1 > 4 False AND False False

For the operator OR, any one of the conditions which is true will give a true value.

Example Operation Meaning Result

3 > 1 OR 4 > 2 True OR True True

3 > 1 OR 2 > 4 True OR False True

1 > 3 OR 4 > 2 False OR True True

1 > 3 OR 1 > 4 False OR False False

For operator NOT, it will give an opposite value.

Example Operation Meaning Result

NOT 1 > 3 NOT False True

NOT 3 > 1 NOT True False

Page 14: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 3 – Number Guessing Game

Page 14

� Conditional Statement (continue)

The following code will check for one situation. If the situation is TRUE, statement 1 will be

executed. Otherwise, statement 2 will be executed.

If a > 4 Then

execute statement 1

Else

execute statement 2

End If

The following code checks for two situations. If the first situation is TRUE, statement 1 will be

executed. Otherwise, it will continue to check for the second situation. If the second situation

is TRUE, then statement 2 will be executed. Otherwise, statement 3 will be executed.

If a > 4 Then

execute statement 1

ElseIf b > 5 Then

execute statement 2

Else

execute statement 3

End If

Note that you may add more than one Else If … Then statement.

Also, Else Statement is optional and can be omitted.

a > 4

statement 1

YES

NO

statement 2

a > 4

statement 1

YES

NO

b > 5

statement 2

YES

NO

statement 3

Page 15: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 4 – Curve Stitching

Page 15

Task 4 – Curve Stitching

You are going to create a program for drawing lines & curves.

A. Introduction

By using computer, we can ask computer to draw lines accurately and repetitively. Example

works are:

B. User Interface Design

A suggested interface is shown below. Please change the background to white to facilitate

drawing and clearing.

Page 16: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 4 – Curve Stitching

Page 16

C. Program Coding

� Coordinate System in Visual Basic

Please fill in the coordinates (x, y) of the following points.

� Line Drawing

To draw a line, we firstly define a pen with a specific colour & pen width. The code below tells computer to define a pen with

Dim myPen As Pen = New Pen(Color.Red, 3)

color: width:

By providing the coordinates of two endpoints, we can ask computer to draw a straight line to

connect them. For example:

Me.CreateGraphics.DrawLine(myPen, 100, 200, 300, 100)

Try to draw the line of the above statement:

� Clear

We can clear the whole screen by filling the whole background with color white.

Me.CreateGraphics.Clear(Color.White)

x

y

100

100

0 200 300

200

x

y

( , ) ( , ) ( , )

( , ) ( , ) ( , )

100

100

0 200 300

200

1st point 2nd point

Page 17: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 4 – Curve Stitching

Page 17

Level 1

� Rectangle Drawing

To draw a rectangle, _____ lines have to be drawn.

Try to fill the following programming code which draws the

rectangle in the left:

Dim myPen As Pen = New Pen(Color.Red, 3)

Me.CreateGraphics.DrawLine(myPen, ___, ___, ___, ___)

Me.CreateGraphics.DrawLine(myPen, ___, ___, ___, ___)

Me.CreateGraphics.DrawLine(myPen, ___, ___, ___, ___)

Me.CreateGraphics.DrawLine(myPen, ___, ___, ___, ___)

� Triangle Drawing

Try to draw a triangle in your program.

Level 2

� Rectangle Drawing (with different size)

To draw the rectangle based on the inputted size in the Textbox, we have to read the length,

declare a variable and get the input from the Textbox:

Dim len As Integer

len = Textbox1.Text

By studying the figure in the right, we can assume the

coordinate of one point remains unchanged. Then, other

coordinates will increase based on the input size.

Try to rewrite the programming code above and draw the

rectangle based on the input size.

Hints: the first line of code is

Me.CreateGraphics.DrawLine(myPen, 50, 50, 50, 50+len)

x

y

100

100

0 200

200

150 50

50

150

x

y

100

100

0 200

200

Page 18: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 4 – Curve Stitching

Page 18

Level 3

� Parallel Lines Drawing

To draw 10 lines (as shown in the right), we can use the DrawLine statement for

10 times. For each line, we have to specify their coordinates separately:

Me.CreateGraphics.DrawLine(mypen, 100, 100, 100, 200)

Me.CreateGraphics.DrawLine(mypen, 110, 100, 110, 200)

Me.CreateGraphics.DrawLine(mypen, 120, 100, 120, 200)

Me.CreateGraphics.DrawLine(mypen, 130, 100, 130, 200)

Me.CreateGraphics.DrawLine(mypen, 140, 100, 140, 200)

Me.CreateGraphics.DrawLine(mypen, 150, 100, 150, 200)

Me.CreateGraphics.DrawLine(mypen, 160, 100, 160, 200)

Me.CreateGraphics.DrawLine(mypen, 170, 100, 170, 200)

Me.CreateGraphics.DrawLine(mypen, 180, 100, 180, 200)

Me.CreateGraphics.DrawLine(mypen, 190, 100, 190, 200)

Alternatively, we can also use the following statements:

Dim mypen As Pen = New Pen(Color.Chocolate, 3)

Dim i As Integer

For i = 100 To 190 Step 10

Me.CreateGraphics.DrawLine(mypen, i, 100, i, 200)

Next

Value of i

1st i:

2nd i:

10th i:

� Grid Drawing

Try to modify the above code and draw the shape in the right.

Level 4

� Curve Stitching

By studying the figure in the right, write the x and y coordinate of the

endpoints of first 5 lines and fill the following blanks:

Me.CreateGraphics.DrawLine(myPen, ____, ____, ____, ____)

Me.CreateGraphics.DrawLine(myPen, ____, ____, ____, ____)

Me.CreateGraphics.DrawLine(myPen, ____, ____, ____, ____)

Me.CreateGraphics.DrawLine(myPen, ____, ____, ____, ____)

Me.CreateGraphics.DrawLine(myPen, ____, ____, ____, ____)

Based on the program code in level 3, modify it according to draw the above curve.

Page 19: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 4 – Curve Stitching

Page 19

Bonus Part

Try to write programs drawing the following shapes or your own shapes:

Page 20: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Project 1 – Cat Catching

Page 20

Project 1 – Cat Catching

This is a simple game which allows

users to catch the cat by pressing

the button.

The bigger no. of hits that the user

presses, the better reaction

he/she has.

When the “New” button is

pressed, button with the image

cat will move to different positions

at an interval of time.

After the preset time limit, game

will end automatically.

We can reset the game by

pressing button “Reset”.

Checkpoint 1: Cat can jump

When the button is clicked, cat should move to a new position.

1. Use random number generator to generate random numbers (refer to task 3 of the notes) for

the new position.

2. Move Button1 to a new position (e.g. to point 30, 50). You may use the following code:

Button1.Location = New Point(30, 50)

Time to think

� For every position, how many random numbers are needed?

� What is the range of random numbers to be generated so that the button will not go out

of screen?

Page 21: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Project 1 – Cat Catching

Page 21

Checkpoint 2: Cat can jump at an interval of time

When the “New” button is pressed, button with the image cat will move to different positions at

an interval of time (e.g. 0.5 second).

1. We need to use a VB control Timer (under the category “Components”).

2. When the timer is enabled, it will ask computer to automatically run specific tasks at an

interval of time (i.e. run the program code in Timer1_Tick constantly)

Timer1.Enabled = True ' Timer1 will start counting

Timer1.Enabled = False ' Timer1 will stop counting

3. To adjust the interval of time, we can simply adjust

the property Interval of Timer.

The unit used at Interval is milliseconds.

For example:

500 = 0.5 second

1000 = 1 second

5000 = 5 seconds

4. We can insert the program code into Timer_Tick by double clicking the Timer.

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)

Handles Timer1.Tick

' Insert the program code to move the button to a new position

End Sub

Checkpoint 3: Limit the game by 10 seconds

After the preset time limit (e.g. 10 seconds), the game will end automatically.

1. Add another Timer to count the time left for the game.

2. Display the time left (default is 10 seconds). Reduce the time by 1 for every second.

3. Stop moving the “cat” button when there is no time left (i.e. value = 0).

Page 22: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Project 1 – Cat Catching

Page 22

Checkpoint 4: Update no. of hits

1. Update the no. of hits whenever users press the button.

2. After the game stop, we should not allow users to press the “cat” button anymore.

To control it, we can adjust the property Enabled by using the following code:

Button1.Enabled = True ' Button1 CAN be pressed

Button1.Enabled = False ' Button1 CANNOT be pressed

Checkpoint 5: Reset the game

We can reset the game by pressing button “Reset”.

1. Update the text label and reset the status of button.

2. Make sure 2 Timers have stopped.

Self-Reflection

� What are the pros & cons of the program?

� How can you improve it?

Bonus Part

You may allow users to adjust

8) default time limit of the game

9) the time interval that the “cat” button will move

10) the image of button

11) other appropriate parts

Page 23: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 2 – Simple Calculator

Page 23

Project 2 – Simple Calculator

You are going to create a simple calculator.

You may study various designs on the Internet for your

reference.

A sample interface is shown in the right for facilitating

discussion.

Checkpoint 1: Number keys

1. We should append the number on the display by pressing the number keys.

We may use the following code to do so:

TextBox1.Text = TextBox1.Text * 10 + 1

2. However, after we press the keys of

operators (+, -, *, /), we should reset

the display so as to display the new

number.

3. We may refer to the flow chart in the

right to know when we should reset the

display.

Time to think

� What variables are needed for the simple calculator?

YES

Press = Y

Display new no.

NO

Append the no.

Press = N

Page 24: Task 1 – Your First Visual Basic Program · Task 1 – Your First Visual Basic Program Page 3 Step 6: Enhance the interface by customizing looks and behavior By using the Properties

Task 2 – Simple Calculator

Page 24

Checkpoint 2: Keys for Operators (+, - , *, /)

When we press the keys of operators, we should record the last number and the operator pressed.

Time to think

� What variables are needed for the above steps?

Checkpoint 3: Equal and Reset key

When user presses the equal key, we have to calculate and display the results.

The results should be based on the stored data, including

� last number stored

� the operator

� the latest number shown on textbox

When user presses reset key, we have to erase all the content and reset the valuables.

Bonus Part

You may allow calculator to work on

1) Decimal calculation (e.g. 3.5 + 4.8)

2) More than one operation (e.g. 1 + 2 - 3 + 4)

3) Special functions (e.g. sin, cosine, square)

Hints: Use VB functions in Math class.

4) Memory function (e.g. M+, M-, MR, MC)

5) Other appropriate functions