Before You Start

This book teaches you to write programs for DVX with DVX BASIC, from the very first line to a finished program that other people install and use. You do not need to have written a program before. Each chapter builds on the ones before it, and every program in the book is one you type in and run yourself.

Who This Book Is For

  • Beginners. If you have never programmed, start at Part I and read the chapters in order. Each new idea is explained the first time it appears, and each chapter ends with something that works.

  • Programmers new to DVX. If you have written BASIC before, especially Visual Basic, skim Part I for what is different in DVX BASIC, then read Part II and Part III.

  • Anyone looking something up. This book’s companion, the DVX BASIC Language Reference, describes every statement, function, control, and window of DVX BASIC.

What You Need

  • DVX, installed and running. The DVX User’s Guide explains how to install it and how to use its desktop.

  • The DVX BASIC part. Setup installs it unless you leave it out on its What to install page. If Program Manager’s Installed Programs group has a DVX BASIC icon, you have it. If not, run Setup again, choose Upgrade or repair DVX, and check DVX BASIC.

  • The Developer Tools part, for the last part of the book. It holds Icon Editor, Help Editor, Resource Editor, and Package Builder, which you use to finish a program and share it.

  • For Chapter 30, a network connection and an account on the package server.

How to Read This Book

The book has three parts:

  • Part I teaches programming itself: values, decisions, loops, procedures, text, and lists, and how to find and fix mistakes.

  • Part II covers the windows your programs show and the controls in them, menus, files, drawing, sound, databases, and more.

  • Part III takes one program, a to-do list, all the way from an idea to a package on the package server, with an icon, a help file, and version information.

This book’s companion, the DVX BASIC Language Reference, describes the whole language, every control, and the DVX BASIC program in detail, and the chapters here point into it for more.

Type the examples in yourself rather than reading them only. Typing a program makes you look at every word, and the mistakes you make along the way teach as much as the program does. When something does not work, compare what you typed with the book, character by character.

Conventions

  • Keys are shown like F5 and Ctrl+S. Ctrl+S means: hold down Ctrl, press S, then let go of both.

  • Menu commands are shown like File › New Project…​: open the File menu, then choose New Project…​.

  • Buttons are shown like OK.

  • Text you type, and the code of programs, is shown in a typewriter font: MsgBox "Hello". Longer programs are shown in boxes:

    Sub Command1_Click ()
        MsgBox "Hello, world!"
    End Sub
  • Words in bold are the names of things on the screen: windows, boxes, and settings.

DVX BASIC does not care whether you type its words, or the names you make up, in capital or small letters: msgbox, MsgBox, and MSGBOX are the same. This book writes them with a capital at the start of each word, as most BASIC programs do, because that is easiest to read.

Part I: Learning to Program

Chapter 1. What Is a Program?

A program is a list of instructions for the computer to carry out. Notepad, the Clock, and Program Manager are programs; so is every game you play. Each of them is, underneath, a long list of small, exact steps: show this window, wait for a key, put the letter on the screen, and so on.

A program is a lot like a recipe. A recipe says "beat two eggs, add a cup of flour, stir": small steps, in order, that anyone can follow. The difference is that the computer follows its steps exactly. It never guesses what you meant. If a recipe says "add salt" and forgets to say how much, a cook uses common sense; a computer stops and tells you something is wrong. Most of programming is learning to say exactly what you mean.

1.1. Programming Languages and BASIC

You write a program in a programming language: a small set of words and rules that both you and the computer can read. There are many languages. This book uses BASIC, one of the oldest and friendliest. BASIC was made in 1964 for students who were not engineers, and its name says so: Beginner’s All-purpose Symbolic Instruction Code. A line of BASIC reads almost like English:

If score > 100 Then MsgBox "You win!"

You can probably guess what that line does: when the score is more than 100, it shows a message saying "You win!".

DVX BASIC is the BASIC that comes with DVX. It works the way Visual Basic does on Windows: you draw the windows of your program with the mouse, and then write the instructions for what happens when someone uses them. If you have used Visual Basic, you will feel at home; if not, you will learn it here from the start.

1.2. Programs That Wait for You

Older programs ran from top to bottom: ask a question, wait for the answer, print a result, and stop. Programs on a desktop like DVX’s work differently. They put up a window and then wait. When you click a button, type in a box, or choose a menu command, something happens, and then the program waits again.

Each of those things you do is called an event. A DVX BASIC program is mostly a collection of small pieces of code, each one answering one event: "when this button is clicked, do this". You will write your first one in Chapter 3.

1.3. What a DVX BASIC Program Is Made Of

A DVX BASIC program is kept as a project: a few files in a folder of their own.

  • The project file (its name ends in .dbp) lists the other files and holds settings such as the program’s name and version.

  • Each form (.frm) is one window of the program: the window itself, the controls on it (buttons, boxes to type in, lists, and so on), and the code that answers their events.

  • Modules (.bas) hold code that is not tied to one window, which several forms can share.

  • When the program is finished, DVX BASIC turns the project into one file ending in .app: the program itself, which starts like any other DVX program.

The program DVX BASIC you write all of this in is called an IDE, an Integrated Development Environment: one place with everything you need to write, run, and fix a program. The next chapter shows you around it.

1.4. What You Will Build

Along the way you will write a series of small programs, each showing something new: a greeting, a temperature converter, a guessing game, a times table, a word counter, a list of high scores, and more. In Part III you will build one program the way real programs are built, a to-do list, and give it an icon, a help file, and a version number, and then package it and put it on the package server, so anyone with DVX can install it.

Chapter 2. A Tour of DVX BASIC

This chapter shows you around DVX BASIC, the program you write programs in. You do not need to remember all of it now; come back to it when you wonder what a window is for.

2.1. Starting DVX BASIC

Start DVX BASIC in any of these ways:

  • In Program Manager’s Installed Programs group, double-click the DVX BASIC icon.

  • In the Welcome window, click Write a program.

  • In File Manager, double-click a DVX BASIC project (a file whose name ends in .dbp). DVX BASIC starts with that project open.

When DVX BASIC starts without a project, you see only a few windows:

The DVX BASIC main window across the top of the screen
Figure 1. DVX BASIC as it starts
  • The main window, across the top of the screen. It has the menus, a toolbar of buttons for the commands you use most, and a status line that says what DVX BASIC is doing, such as “Ready.”.

  • The Output window, at the bottom left. Your program can print text here while it runs, and DVX BASIC shows its error messages here.

  • The Immediate window, at the bottom right. Type a line of BASIC here and press Enter, and DVX BASIC carries it out at once.

2.2. The Windows of a Project

Once you open a project, or start a new one as you will in Chapter 3, more windows appear around the form you are working on:

DVX BASIC with the Toolbox at the left
Figure 2. DVX BASIC with a project open
The form designer

In the middle. It shows the form (the window of your program) as it will look, and you place controls on it with the mouse. Its title is the form’s caption followed by [Design].

The Toolbox

At the left. Each button is a kind of control you can put on a form: buttons, labels, boxes to type in, lists, pictures, timers, and more. They are in alphabetical order. Hold the mouse pointer over one for a moment to see its name.

The Project window

At the top right. It lists the files of the project: its forms, its modules, its class modules, and its controls. Double-click a file to open it.

The Properties window

At the right, below the Project window. Its top part lists the form and the controls on it; click one to choose it. Its bottom part lists that control’s properties: settings such as its caption, its size, and its color, with Name first and the rest in alphabetical order. You will use it a lot.

The Code window

Opens when you write code (you will see it in the next chapter). It covers the middle of the screen. At its top are two lists, Object and Function, that pick which piece of code it shows.

If a window gets covered or closed, the Window menu brings it back: Window › Toolbox, Window › Properties, Window › Project Explorer, and so on.

2.3. Design and Code

You switch between two views of a form many times while you work:

  • Design view shows the form in the designer, with the Toolbox and the Properties window: View › Designer, or Shift+F7.

  • Code view shows the form’s code in the Code window: View › Code, or F7.

The two buttons at the right end of the toolbar do the same.

2.4. The Toolbar

From left to right, the toolbar’s buttons are:

Button What it does

Open

Opens a project (File › Open Project…​).

Save

Saves the file you are working on (File › Save File, Ctrl+S).

Run

Runs your program (Run › Run, F5).

Stop

Stops your program (Run › Stop, Esc).

Debug

Runs your program so that it can stop at the lines you mark (see Chapter 10).

Step Into, Step Over, Step Out, Run to Cursor

Run your program a little at a time (see Chapter 10).

Code, Design

Switch between Code view and Design view.

Hold the mouse pointer over a button to see its name and its key.

2.5. Trying the Immediate Window

The Immediate window is a good place to try things. Click in it, type this line, and press Enter:

PRINT 2 + 3

DVX BASIC answers 5 on the next line. PRINT shows a value; 2 + 3 is the value to show. Try a few more:

PRINT 10 * 4
PRINT "Hello" & " there"
2 + 2

The * means "times". The & joins two pieces of text together. The last line has no PRINT at all: when what you type is not a statement, the Immediate window shows its value anyway, as if you had typed PRINT in front of it.

2.6. Getting Help

Press F1, or choose Help › DVX BASIC Help, to open DVX BASIC’s own help: the language reference, a guide to DVX BASIC, and a page for each control. It holds the same text as this book’s companion, the DVX BASIC Language Reference. Press F1 while a control is chosen in the designer to go straight to that control’s page.

Chapter 3. Your First Program

In this chapter you write a small program from start to finish: a window with a button that says hello when you click it. Along the way you meet the four ideas every DVX BASIC program is built from: forms, controls, properties, and events.

3.1. Starting a Project

Every program starts as a project. Start DVX BASIC (see Section 2.1), then:

  1. Choose File › New Project…​. (With the keyboard: Alt+F, then P.)

    The DVX BASIC File menu open
  2. DVX BASIC asks for the project’s name. Type Hello and click OK (or press Enter).

    The New Project box with Hello typed in the Project name box
  3. DVX BASIC then asks where to save the project, and suggests a folder of its own for it: HELLO, in the PROJECTS folder of your user folder (usually C:\DVX\USER\PROJECTS\HELLO), with the project file hello.dbp in it. Click Save to take the suggestion.

    The Save New Project box

A new project starts with one form, Form1, which opens in the form designer. The Toolbox appears at the left and the Properties window at the right:

DVX BASIC with the new project: the Toolbox
Figure 3. A new project, with Form1 in the designer

The form is the window your program will show. Right now it is empty.

3.2. Changing a Property

Everything you can see about a form or a control is a property of it: its size, its color, the text it shows. The text in a form’s title bar is its Caption property, and it starts as Form1. Change it:

  1. In the Properties window, click Caption in the list (it is the third line).

  2. Double-click it, or press Enter. The Edit Property box opens with the caption in it, already selected.

  3. Type My First Program. What you type replaces the old caption. Click OK.

    The Edit Property box for Caption

The designer’s title changes to My First Program [Design]: when the program runs, its window will have that caption.

3.3. Adding a Button

Controls are the things on a form that the user works with. The most common one is the button, which DVX BASIC calls a CommandButton.

  1. In the Toolbox, find the button tool: the third one in the top row. Hold the mouse pointer over it, and its tooltip says CommandButton.

    The Toolbox with the pointer over the button tool and its tooltip
  2. Click the tool, then click anywhere on the form. A button named Command1 appears.

    The form designer with a button

The button goes to the top of the form and stretches across it. That is how DVX BASIC lays out a form: the controls stand in a column, top to bottom, in the order you place them, each as wide as the form. Section 11.4 shows how to arrange them in other ways.

Now give the button a caption, the text on it. The Properties window now shows the button’s properties (the button is selected: it has small black squares at its edges). Its Caption is the third line again: double-click it, type Say Hello, and click OK.

3.4. Writing the Code

A button does nothing until you write the code for it. Double-click the button on the form. The Code window opens:

The Code window showing Sub Command1_Click with MsgBox "Hello

DVX BASIC has written two lines for you:

Sub Command1_Click ()

End Sub

This is an event procedure. Its name says when it runs: Command1 is the button, and Click is the event, so Command1_Click runs every time someone clicks the button. Whatever you write between Sub and End Sub is what happens then. The Object and Function lists at the top of the Code window show the same two names.

The blinking cursor is already on the empty line in the middle. Press Tab to indent the line, then type:

Sub Command1_Click ()
   MsgBox "Hello, world!"
End Sub

MsgBox shows a message in a box with an OK button. The text to show goes in double quotes: "Hello, world!". A piece of text in quotes is called a string.

Indenting the line, so that it starts a little to the right of Sub, is not required: DVX BASIC runs the code the same either way. It makes it easy to see where a procedure starts and ends, and every program in this book is indented that way.

3.5. Running the Program

Press F5, or click the Run button on the toolbar. DVX BASIC checks your code, turns it into a program, and starts it. The program’s window appears, with the caption you gave it and the button:

The program running: a window titled My First Program with a Say Hello button

Click Say Hello. The message appears in a box titled with the project’s name:

The program’s window with a message box titled Hello that says Hello

Click OK to close the message. Click the button again, and it appears again: the event procedure runs every time.

To end the program, close its window: click its close box, or press Alt+F4 while it is the active window. You can also press Esc in DVX BASIC, or click the Stop button on the toolbar.

Tip
Each time you run a program, DVX BASIC first saves every file you changed. That is the Run › Save on Run setting, which is on at first. You can also save at any time: Ctrl+S saves the file you are working on, and File › Save All saves them all. A file that has changes not saved yet has a * after its name in titles and in the Project window.

3.6. Changing a Property from the Code

A message box is one way to show something. Another is a Label: a control that shows a line of text on the form. Put one on the form, and have the button put "Hello, world!" in it.

  1. Go back to the form: press Shift+F7 (View › Designer).

  2. In the Toolbox, click the Label tool (the first one in the fourth row; its tooltip says Label), then click the form. Label1 goes below the button.

  3. A label shows its Caption. Clear it, so the label starts empty: in the Properties window, double-click Caption, press Delete, and click OK.

    The form designer with the button and an empty Label1 below it
  4. Double-click the button to go back to its code, and change the line inside Command1_Click to:

    Sub Command1_Click ()
       Label1.Caption = "Hello, world!"
    End Sub

The new line sets a property from the code. Label1.Caption means "the Caption property of Label1"; the dot joins a control’s name to the name of one of its properties. The = puts the string on its right into that property. Run the program again (F5) and click the button:

The program running

This time the words appear on the form itself. A program can read and change almost any property of a control while it runs: make a button disabled, change a color, move a control, or show a new value.

3.7. What You Made

Your project is in its folder, C:\DVX\USER\PROJECTS\HELLO:

  • hello.dbp, the project file;

  • Form1.frm, the form. Open it in Notepad and you see the form’s properties, the button and the label with theirs, and below them your code.

To work on the project another day, start DVX BASIC and choose File › Open Project…​, or double-click hello.dbp in File Manager.

To make the project into a program that starts from Program Manager like any other, you compile it into an .app file; Chapter 27 shows how.

3.8. Try It Yourself

  • Change the button’s caption to Click Me, and run the program again.

  • Add a second button, Command2, with the caption Goodbye, whose Click event procedure shows MsgBox "Goodbye!".

  • Make the first button put a different message in the label, such as your name.

Chapter 4. Values and Variables

Every program works with values: numbers such as 42 and 3.5, and pieces of text such as "Hello". In this chapter you learn to calculate with values, to keep them in variables so that the program can remember them, and to turn the text a user types into a number. At the end you build a temperature converter.

4.1. A Practice Project

The programs in the next few chapters are small: a few lines that calculate something and show the result. They do not need a window of their own, so you write them in a module, a file of code without a form. When a program has no form, DVX BASIC runs the code of its module from the top line to the bottom line and then stops. Whatever it shows with Print appears in the Output window.

Make a project to practice in. You will use it for the rest of Part I.

  1. Choose File › New Project…​, type Practice, and click OK; then click Save to take the folder DVX BASIC suggests.

  2. You do not need the form this time. In the Project window, click Form1.frm, then choose File › Remove File. DVX BASIC asks whether to remove it from the project: click Yes. It then asks whether to save it first: click No.

  3. Choose File › New Module. DVX BASIC adds a module, Module1, to the project and opens it in the Code window. It already has one line in it, Option Explicit; you will see what that line does later in this chapter.

  4. Click below Option Explicit, leave an empty line, and type these two lines:

    Print "Hello from Module1"
    Print 2 + 3
  5. Press F5. The Output window shows:

    Hello from Module1
     5 
The Code window with Module1’s two Print lines

The first Print showed its text. The second calculated 2 + 3 and showed the answer. The status line says “Done.”: the program has run to its end.

Each time you run the program, the Output window starts empty. To try the next example, select the lines below Option Explicit and type the new ones over them. Always keep Option Explicit as the first line. The examples in this book show only the lines below it.

4.2. Numbers and Arithmetic

BASIC calculates with the usual signs, called operators, although two of them look different from the ones you write on paper: multiplication is * and division is /.

Print 7 + 2
Print 7 - 2
Print 7 * 2
Print 7 / 2
Print 7 \ 2
Print 7 Mod 2
Print 7 ^ 2

The Output window shows:

 9 
 5 
 14 
 3.5 
 3 
 1 
 49 
Operator Meaning Example

+

Add

7 + 2 is 9

-

Subtract

7 - 2 is 5

*

Multiply

7 * 2 is 14

/

Divide

7 / 2 is 3.5

\

Divide, and drop what is left over (whole-number division)

7 \ 2 is 3

Mod

What is left over after whole-number division (the remainder)

7 Mod 2 is 1

^

Raise to a power: 7 ^ 2 is 7 times 7

7 ^ 2 is 49

\ and Mod belong together. Share 7 cookies between 2 people: each gets 7 \ 2, which is 3, and 7 Mod 2, which is 1, is left over. Mod is handy for more than cookies: a number is even when number Mod 2 is 0.

Look closely at the output. Print puts a space before each number, where a minus sign would go if the number were negative, and one after it. Text is shown exactly as it is written.

4.2.1. Which Comes First

When a line has more than one operator, BASIC follows the order you learned in school: first ^, then * and /, then \, then Mod, and last + and -. Operators of the same kind go from left to right. To make something happen first, put it in parentheses:

Print 2 + 3 * 4
Print (2 + 3) * 4
Print 10 - 4 - 3
Print 10 - (4 - 3)
 14 
 20 
 3 
 9 

2 + 3 * 4 multiplies first, so it is 2 + 12. With parentheses, (2 + 3) * 4 adds first, so it is 5 times 4. When you are not sure which comes first, add parentheses: they never hurt, and they make the line easier to read.

4.3. Text

A piece of text, a string, is written between double quotes. & joins two values into one string, numbers too:

Print "Hello, " & "world"
Print "The answer is " & 42
Print "Two and two make"; 2 + 2
Print "Ann", 12
Print "Benjamin", 9
Hello, world
The answer is 42
Two and two make 4 
Ann            12 
Benjamin       9 

A Print line can show several values. Between them, a semicolon (;) shows the next value right after the last one, and a comma (,) moves on to the next column first; the columns are 14 characters apart. A number joined with & becomes text, so it has no spaces around it: compare "The answer is " & 42 with "Two and two make"; 2 + 2.

To put a double quote inside a string, write two: Print "She said ""hi""" shows She said "hi".

4.4. Variables

A variable is a named place to keep a value, like a labeled box. You make one with Dim, which gives it a name and says what kind of value it holds, and you put a value in it with =:

Dim apples As Integer
Dim price As Double
Dim cost As Double

apples = 6
price = 0.25
cost = apples * price
Print "Apples:"; apples
Print "Cost:"; cost
Apples: 6 
Cost: 1.5 

Dim apples As Integer makes a variable called apples that holds whole numbers. Dim price As Double makes one that holds numbers with decimals. (Dim is short for dimension, an old word for setting space aside.)

apples = 6 puts 6 in apples. A line like this is an assignment. The = does not say that the two sides are equal; it means "store what is on the right in the variable on the left". The right side can be any calculation: cost = apples * price multiplies the two values and stores the result in cost.

Once a variable holds a value, you use its name wherever you would write the value.

4.4.1. Changing a Variable

A variable holds one value at a time. Storing a new value replaces the old one, and the new value can be calculated from the old:

Dim score As Integer

score = 10
Print score
score = score + 5
Print score
score = score * 2
Print score
 10 
 15 
 30 

score = score + 5 reads as "take what is in score, add 5, and put the result back in `score`". Lines like this one are everywhere in programs: they count, keep totals, and keep score.

A variable starts out empty: 0 for a number, "" (an empty string) for text.

4.5. Kinds of Values

The word after As is the variable’s type: what kind of value it holds. These are the ones you will use most:

Type Holds Example

Integer

A whole number from -32,768 to 32,767

Dim count As Integer

Long

A whole number from about -2 billion to 2 billion

Dim people As Long

Double

A number that can have decimals, with about 15 digits of precision

Dim height As Double

Currency

An amount of money: exact to four decimal places, so totals never drift

Dim price As Currency

String

Text of any length

Dim pet As String

Boolean

True or False

Dim hungry As Boolean

Dim count As Integer
Dim people As Long
Dim height As Double
Dim pet As String
Dim hungry As Boolean

count = 3.7
people = 250000
height = 1.82
pet = "Rex"
hungry = True
Print count; people; height
Print pet; " is hungry: "; hungry
 4  250000  1.82 
Rex is hungry: True

Notice the first number. count is an Integer, so it cannot hold 3.7: the value is rounded to the nearest whole number, 4, as it is stored.

A value too big for its type stops the program. Try count = 40000: the program stops, and the Output window says Runtime error 6: Overflow, with the line it happened on. A Long has room for it.

Which type to choose? Use Integer for counting small things, Long when the count can get big, Double for measurements and anything with decimals, Currency for money, String for text, and Boolean for yes-or-no facts. “Data Types” in the DVX BASIC Language Reference lists every type, including Byte, Single, Date, and Variant.

4.6. Naming Variables

You choose the names of your variables. A name:

  • starts with a letter;

  • is made of letters, digits, and the underscore (_), with no spaces;

  • is not one of BASIC’s own words, such as Print, Dim, or If.

total, score2, and first_name are names; 2nd, first name, and print are not. Capital and small letters do not matter: Total and TOTAL are the same variable as total.

Choose names that say what the variable holds. cost = apples * price explains itself; c = a * p does the same work, but in a month you will not remember what c was. When a name has several words, start each word after the first with a capital letter (firstName, totalCost): it is easy to read and easy to type.

4.7. Option Explicit: Catching Typing Mistakes

Now you can see what the Option Explicit at the top of Module1 is for. It tells DVX BASIC that every variable must be made with Dim before it is used. Try a program with a typing mistake in it:

Dim total As Integer

total = 5
Print totl

DVX BASIC does not run it. The Output window says:

COMPILE ERROR:
Module1.bas line 6:
Variable not declared: totl (OPTION EXPLICIT is on)

and the blinking cursor goes to the mistake. (The line number counts every line of the module, Option Explicit and the empty line too.)

Without Option Explicit, DVX BASIC would decide that totl is a new variable, which starts out as 0, and the program would print 0 without a word of complaint. A mistake like that can take a long time to find. With Option Explicit it takes a second, so keep it at the top of every module you write.

A form’s code can have its own Option Explicit line too, at the very top of the code. To have it in every file of a project without writing it, check Require variable declaration (OPTION EXPLICIT) in File › Project Properties…​. Do that for every project you start from now on in one step: choose Tools › Preferences…​, check OPTION EXPLICIT default for new projects, and click OK. The projects in the rest of this book assume you have.

4.8. Constants

Some values never change while the program runs: a tax rate, the number of days in a week, the name of the program. Give such a value a name with Const:

Const TaxRate = 0.08

Dim price As Double

price = 20
Print "Tax:"; price * TaxRate
Print "Total:"; price + price * TaxRate
Tax: 1.6 
Total: 21.6 

A constant is used like a variable, but nothing can store a new value in it. Naming a value says what it is (TaxRate explains itself; 0.08 does not), and if the rate changes, you change one line instead of hunting for every 0.08 in the program.

4.9. Comments

A comment is a note for people reading the program; BASIC skips it. A comment starts with an apostrophe (') and runs to the end of the line. It can have a line of its own, or follow the code on a line:

' Work out what the apples cost
cost = apples * price     ' price is for one apple

Older programs write Rem (short for remark) at the start of a comment line instead of '. It means the same.

Use comments to say why the code does something, not to repeat what it does: “price is for one apple” helps; “multiply apples by price” does not.

4.10. Turning Text into Numbers and Back

What a user types is text, even when it is a number. To calculate with it, turn it into a number with Val. To turn a number back into text, use CStr, or Format$ when you want to say how many decimals to show:

Dim typed As String
Dim number As Double

typed = "12.5"
number = Val(typed)
Print number * 2
Print "Twice that is " & CStr(number * 2)
Print Val("3 apples"); Val("apples")
Print Format$(2 / 3, "0.00")
Print Int(7.8); Round(7.8); Round(3.14159, 2)
 25 
Twice that is 25
 3  0 
0.67
 7  8  3.14 
Function What it gives

Val(text)

The number at the start of the text: Val("12.5") is 12.5, Val("3 apples") is 3, and text that does not start with a number gives 0.

CStr(number)

The number as text, without the spaces Print adds: CStr(25) is "25".

Format$(number, "0.00")

The number as text, with as many decimals as the format has zeros after the point: Format$(2 / 3, "0.00") is "0.67".

Int(number)

The whole number at or below it: Int(7.8) is 7.

Round(number)

The nearest whole number: Round(7.8) is 8. Round(number, places) keeps that many decimals.

Val, CStr, Format$, Int, and Round are functions: each takes the values in its parentheses and gives back a new value, which you can print, store, or calculate with. A function whose name ends in $ gives back a string. BASIC has many functions; “String Functions” in the DVX BASIC Language Reference, “Math Functions” in the DVX BASIC Language Reference, and “Conversion Functions” in the DVX BASIC Language Reference list them.

4.11. A Temperature Converter

Now put this chapter to work in a program with a window: the user types a temperature in degrees Fahrenheit, clicks a button, and sees it in degrees Celsius. It uses a new control, the TextBox, a box the user types in. What is typed is in its Text property.

  1. Choose File › New Project…​, name the project TempConv, and click Save to take the suggested folder. (DVX BASIC closes the Practice project; you can open it again with File › Open Project…​.)

  2. Set the form’s Caption to Temperature Converter.

  3. Place four controls on the form, in this order, and set their properties in the Properties window:

    Control Name it gets Set this property

    Label

    Label1

    Caption: Degrees Fahrenheit:

    TextBox

    Text1

    Text: nothing (delete the Text1 that is there)

    CommandButton

    Command1

    Caption: Convert

    Label

    Label2

    Caption: nothing

    The TextBox tool is the third one in the eighth row of the Toolbox; hold the pointer over it, and its tooltip says TextBox:

    The Toolbox with the pointer over the TextBox tool and its tooltip

    A TextBox has no Caption; the text in it is its Text property. To find a property in a long list, click the list and type its first letter: T goes to Text. When you then click another control, the property you had selected stays selected if that control has it too, which is handy for setting the Caption of one control after another.

    The form designer with the label
  4. Double-click the Convert button and type the code of its Click event procedure. Press Tab once at the start of the first line: when you press Enter, the next line starts at the same indent.

    Sub Command1_Click ()
       Dim fahrenheit As Double
       Dim celsius As Double
    
       fahrenheit = Val(Text1.Text)
       celsius = (fahrenheit - 32) * 5 / 9
       Label2.Caption = Format$(celsius, "0.0") & " degrees Celsius"
    End Sub
  5. Press F5. Type 98.6 in the box and click Convert:

    The Temperature Converter window: 98.6 typed in the box

Read the procedure line by line:

  • The two Dim lines make two variables for the procedure to work with. Variables made inside a procedure exist only while it runs; each click starts with fresh ones.

  • fahrenheit = Val(Text1.Text) reads what the user typed, turns it into a number, and stores it.

  • celsius = (fahrenheit - 32) * 5 / 9 is the conversion formula. The parentheses make the subtraction come first.

  • The last line builds the answer, such as 37.0 degrees Celsius, and puts it in the label’s Caption, where the user sees it.

Try typing something that is not a number, such as hot. Val gives 0 for it, so the program converts 0 degrees Fahrenheit (-17.8 degrees Celsius). In Chapter 5 you will make the program say that it needs a number instead.

4.12. Try It Yourself

  • In the Practice project, work out how many seconds there are in a day, and in a year, with Print.

  • Make variables for the width and the height of a room in meters, and print its area (width times height) and the length of its walls all the way around (two widths and two heights).

  • Add a second button to the temperature converter that converts the other way: degrees Celsius times 9, divided by 5, plus 32. Change the first label’s caption so that it does not say Fahrenheit.

  • A pizza has 8 slices. Write a program with a variable for the number of people, and print how many whole slices each person gets and how many are left over (use \ and Mod).

Chapter 5. Making Decisions

So far every line of a program has run, one after another. Real programs choose: they do one thing when the user typed a number and another when they did not, one thing when the guess is too high and another when it is too low. In this chapter you learn to make a program decide, and you build a guessing game.

Type the examples in the Practice project’s Module1, as in Chapter 4.

5.1. If ... Then

If runs a statement only when something is true:

Dim age As Integer

age = 15
If age >= 13 Then Print "You are a teenager or older."
If age < 13 Then Print "You are a child."
Print "Done."
You are a teenager or older.
Done.

The part between If and Then is the condition: a question whose answer is either true or false. age >= 13 asks "is age 13 or more?". Here it is true, so the first Print runs. age < 13 is false, so the second does not. The last line has no If, so it always runs.

5.2. Comparing Values

These are the comparisons you can make:

Operator Asks Example that is true

=

Equal to?

2 + 2 = 4

<>

Not equal to?

5 <> 3

<

Less than?

3 < 5

>

Greater than?

5 > 3

<=

Less than or equal to?

5 <= 5

>=

Greater than or equal to?

7 >= 5

Notice that = has two jobs. In age = 15 on a line of its own, it stores a value. After If, in a condition, it compares. BASIC can tell which you mean from where it is.

A comparison is itself a value: True or False. Print shows it:

Print 5 > 3
Print 5 = 3
Print 5 <> 3
Print "apple" < "banana"
Print "Apple" = "apple"
True
False
True
True
False

Strings compare in dictionary order, so "apple" < "banana" is true. Capital and small letters are different characters, though, so "Apple" = "apple" is false. To compare text without minding the case, compare LCase$(a) = LCase$(b): LCase$ gives the text in small letters (Chapter 8 has more of these functions).

5.3. Several Lines, and Else

When more than one statement depends on the condition, write the If as a block: If ... Then on a line of its own, the statements below it, and End If at the end. Else adds the statements to run when the condition is false:

Dim temperature As Integer

temperature = 30
If temperature > 25 Then
   Print "It is hot."
   Print "Drink some water."
Else
   Print "It is not hot."
End If
It is hot.
Drink some water.

Change temperature = 30 to temperature = 10 and run it again: this time the line after Else runs instead. Exactly one of the two parts runs, never both.

The statements inside the block are indented, so you can see at a glance which lines the If controls. DVX BASIC does not need the indent, but you do.

5.4. ElseIf: More Than Two Choices

ElseIf asks another question when the ones before it were false. DVX BASIC checks the conditions from the top and runs the part of the first one that is true; Else catches everything else:

Dim score As Integer

score = 72
If score >= 90 Then
   Print "Grade A"
ElseIf score >= 80 Then
   Print "Grade B"
ElseIf score >= 70 Then
   Print "Grade C"
Else
   Print "Keep practicing"
End If
Grade C

A score of 72 is not 90 or more, and not 80 or more, but it is 70 or more, so the program says Grade C. The order matters: if the line for 70 came first, a score of 95 would get a C too.

5.5. And, Or, and Not

Join conditions with And (both must be true) and Or (at least one must be true). Not turns true into false and false into true:

Dim age As Integer
Dim hasTicket As Boolean

age = 15
hasTicket = True

If age >= 12 And hasTicket Then Print "You may go in."
If age < 12 Or Not hasTicket Then Print "Sorry, not today."
If age >= 13 And age <= 19 Then Print "Teenager"
You may go in.
Teenager

hasTicket is a Boolean variable: it holds True or False itself, so it can stand alone as a condition. age >= 13 And age <= 19 is the way to ask whether a number is in a range: each side of And is a complete comparison. (Writing age >= 13 And <= 19 does not work.)

When a condition mixes And and Or, put parentheses around the part that goes together: (a Or b) And c.

5.6. Select Case

When one value decides among many choices, Select Case is easier to read than a long chain of `ElseIf`s:

Dim day As Integer

day = 6
Select Case day
   Case 1
      Print "Sunday"
   Case 2 To 6
      Print "A weekday"
   Case 7
      Print "Saturday"
   Case Else
      Print "There is no day"; day
End Select
A weekday

Select Case day names the value to look at. Each Case lists the values its statements are for:

  • a single value: Case 1;

  • several values: Case 1, 7;

  • a range: Case 2 To 6;

  • a comparison: Case Is > 100 (Is stands for the value being tested);

  • Case Else for every value no other Case matched.

The first Case that matches runs, and the program goes on after End Select. Select Case works with strings too: Case "red", "green".

5.7. Random Numbers

Games need surprises. Rnd gives a random number from 0 up to (but not including) 1, such as 0.7055475. To turn it into a whole number from 1 to 100, multiply and cut off the fraction:

secret = Int(Rnd * 100) + 1

Rnd * 100 is from 0 up to 99.99…​, Int makes it 0 to 99, and adding 1 makes it 1 to 100. For a dice roll, use Int(Rnd * 6) + 1.

Without anything else, Rnd gives the same "random" numbers every time the program runs, which is handy when you are testing but no fun in a game. Randomize starts the numbers at a different place each time (it uses the clock), so call it once before the first Rnd.

5.8. A Guessing Game

The program picks a number from 1 to 100, and the player guesses until they find it. After each guess the program says "too low" or "too high", and at the end how many guesses it took.

The Guess the Number window: the prompt
Figure 4. Guess the Number, after a few guesses
  1. Start a new project called Guess. Set the form’s Caption to Guess the Number.

  2. Place a Label, a TextBox, a CommandButton, and another Label, as in the temperature converter, and set:

    Control Name Set this property

    Label

    Label1

    Caption: I am thinking of a number from 1 to 100.

    TextBox

    Text1

    Text: nothing

    CommandButton

    Command1

    Caption: Guess

    Label

    Label2

    Caption: nothing

The program has to remember two things between clicks: the secret number, and how many guesses the player has made. A variable made with Dim inside an event procedure is new each time the procedure runs, so it cannot remember anything from one click to the next. A variable made with Dim outside every procedure, at the top of the form’s code, lives as long as the form does, and every procedure of the form can use it. This is a form-level variable.

  1. Press F7 to open the form’s code. The form has no procedures yet, so the Code window shows its (General) part, the code that is not in any procedure: the Object list says (General). (When you want this part later, choose (General) in the Object list.) Type:

    Dim secret As Integer
    Dim guesses As Integer
    The Code window with the Object list at (General) and the two Dim lines
  2. The secret number has to be picked when the program starts. A form has a Load event that runs just before the form first appears. Go back to the designer (Shift+F7) and double-click an empty part of the form, below the controls: DVX BASIC opens the form’s Load event procedure, Form1_Load. Type:

    Sub Form1_Load ()
       Randomize
       secret = Int(Rnd * 100) + 1
    End Sub
  3. Go back to the designer, double-click the Guess button, and type its Click event procedure:

    Sub Command1_Click ()
       Dim typed As String
       Dim guess As Integer
    
       typed = Text1.Text
       Text1.Text = ""
       Text1.SetFocus
    
       If Not IsNumeric(typed) Then
          Label2.Caption = "Type a number first."
          Exit Sub
       End If
    
       guess = Val(typed)
       guesses = guesses + 1
    
       If guess < secret Then
          Label2.Caption = guess & " is too low."
       ElseIf guess > secret Then
          Label2.Caption = guess & " is too high."
       Else
          Label2.Caption = "Yes! You took " & guesses & " guesses."
       End If
    End Sub
  4. Press F5 and play.

Here is what the Click procedure does:

  • It copies what the player typed into the variable typed, then empties the box and puts the blinking cursor back in it, ready for the next guess. SetFocus is a method: something a control can do, where a property is something it has. Methods are written after the control’s name and a dot, like properties.

  • IsNumeric(typed) is true when the text is a number. If the player typed something else, or nothing, the program says so, and Exit Sub leaves the procedure at once: none of the lines below it run.

  • guesses = guesses + 1 counts the guess. Because guesses is a shared form-level variable, it still holds the count from the last click.

  • The If ... ElseIf ... Else block compares the guess with the secret number and puts the answer in Label2.

The temperature converter from Chapter 4 has the problem that the game avoids: when the user types something that is not a number, Val quietly gives 0. Add the same If Not IsNumeric(...) check at the top of its Click procedure, with a message in Label2, and it will tell the user instead.

5.9. Try It Yourself

  • Add a New Game button to the guessing game. Its Click procedure picks a new secret number, sets guesses back to 0, and clears Label2.

  • Make the game say "Very close!" when the guess is within 3 of the secret number. (Hint: Abs(guess - secret) <= 3. Abs gives a number without its minus sign.)

  • In the Practice project, make a variable hour from 0 to 23 and print "Good morning", "Good afternoon", or "Good evening" with Select Case and ranges.

  • Make a dice program: a button that shows two random numbers from 1 to 6 and says "Doubles!" when they are the same.

Chapter 6. Doing Things Again: Loops

Computers are good at doing the same thing many times without getting bored or making mistakes. A loop runs a group of statements again and again: a fixed number of times, or until something becomes true. In this chapter you meet BASIC’s loops and build a program that shows times tables.

Type the examples in the Practice project’s Module1, as before.

6.1. For ... Next: Counting

For repeats the statements between it and Next while a variable counts from one number to another:

Dim i As Integer

For i = 1 To 5
   Print "Hello number"; i
Next i
Print "After the loop, i is"; i
Hello number 1 
Hello number 2 
Hello number 3 
Hello number 4 
Hello number 5 
After the loop, i is 6 

For i = 1 To 5 sets i to 1 and runs the statements down to Next i. Then it adds 1 to i and runs them again, as long as i is not past 5. The variable is the loop’s counter; i is the traditional name for one, but any name will do. Writing the counter’s name after Next is optional, but it makes it clear which loop the Next ends.

Notice the last line: after the loop, i is 6. The loop stops when the counter goes past the end.

6.1.1. Counting by Other Steps

Step says how much to add each time. A negative step counts down:

Dim i As Integer

For i = 0 To 20 Step 5
   Print i;
Next i
Print
For i = 5 To 1 Step -1
   Print i;
Next i
Print "Liftoff!"
 0  5  10  15  20 
 5  4  3  2  1 Liftoff!

The Print i; inside the loops ends with a semicolon, so the numbers go on the same line. The Print with nothing after it then ends that line.

6.1.2. Adding Things Up

A loop and a variable together can keep a running total. Each time through, the next number is added to total:

Dim i As Integer
Dim total As Long

total = 0
For i = 1 To 100
   total = total + i
Next i
Print "1 + 2 + ... + 100 ="; total
1 + 2 + ... + 100 = 5050 

total is a Long, because the answer, 5050, is fine for an Integer but the total of 1 to 1000 (500,500) is not.

6.2. Do ... Loop: Repeating Until Something Happens

Often you do not know in advance how many times to repeat: keep going while something is true, or until it becomes true. That is the Do ... Loop. How many years does it take to double your money at 10% interest a year?

Dim money As Double
Dim years As Integer

money = 100
Do While money < 200
   money = money * 1.1
   years = years + 1
Loop
Print "Doubled after"; years; "years: "; Format$(money, "0.00")
Doubled after 8 years: 214.36

Do While money < 200 checks the condition first: if it is true, the statements down to Loop run, and then it checks again. When it is false, the program goes on after Loop. If it is false the very first time, the statements never run at all.

The condition can also go at the bottom, after Loop. Then the statements always run at least once, and the check comes after them. Until is the opposite of While: it keeps going until the condition becomes true.

Dim n As Integer

n = 1
Do
   n = n * 2
Loop Until n > 1000
Print n
 1024 

Older programs also write While condition ... Wend, which works like Do While condition ... Loop.

6.3. Leaving a Loop Early

Exit For leaves a For loop at once, and Exit Do a Do loop. Use them when the loop has found what it was looking for:

Dim i As Integer

For i = 50 To 100
   If i Mod 7 = 0 Then Exit For
Next i
Print "The first number from 50 on that 7 divides:"; i
The first number from 50 on that 7 divides: 56 

6.4. When a Loop Never Ends

A Do loop whose condition never changes runs forever:

Do While 1 < 2
   Print "Help!"
Loop

This is a common mistake, and an easy one to make: forget the line that changes the variable the condition looks at, and the loop goes round and round. DVX itself keeps running, so you can stop the program: press Esc in DVX BASIC, or click the Stop button on the toolbar (Run › Stop). Then look for the line that should have made the condition change.

6.5. Loops Inside Loops

A loop can contain another loop. The inner loop then runs completely each time the outer loop goes round once:

Dim row As Integer
Dim col As Integer

For row = 1 To 4
   For col = 1 To 4
      Print row * col,
   Next col
   Print
Next row
 1             2             3             4            
 2             4             6             8            
 3             6             9             12           
 4             8             12            16           

For each row, the inner loop counts col from 1 to 4 and prints row * col, each followed by a comma to move to the next column. The Print after Next col ends the line before the next row begins. Each loop has its own counter: never use the same variable for a loop inside a loop.

6.6. Times Tables

The next program shows the times table of any number. It puts the twelve lines of the table in a ListBox: a box that shows a list of lines, with a scroll bar when they do not all fit. A program adds a line to it with the AddItem method and empties it with Clear.

The Times Tables window: 7 typed in the box
Figure 5. The times table of 7
  1. Start a new project called Tables and set the form’s Caption to Times Tables.

  2. The table needs more room than the form has. Make the form taller: set its Height to 400 (the form is 400 pixels tall then). To find Height in the Properties list quickly, click the list and press H.

  3. Place a Label, a TextBox, a CommandButton, and a ListBox, and set:

    Control Name Set this property

    Label

    Label1

    Caption: The times table for:

    TextBox

    Text1

    Text: nothing

    CommandButton

    Command1

    Caption: Show

    ListBox

    List1

    MinHeight: 200

    The ListBox tool is the third one in the fourth row of the Toolbox. A control stands as tall as its MinHeight says (30 when it is placed), so a MinHeight of 200 makes room in the list for all twelve lines. Press M three times in the Properties list to get to MinHeight.

  4. Double-click the Show button and type its Click event procedure:

    Sub Command1_Click ()
       Dim number As Integer
       Dim i As Integer
    
       List1.Clear
    
       If Not IsNumeric(Text1.Text) Then
          List1.AddItem "Type a number first."
          Exit Sub
       End If
    
       number = Val(Text1.Text)
       For i = 1 To 12
          List1.AddItem number & " x " & i & " = " & number * i
       Next i
    End Sub
  5. Press F5, type a number, and click Show.

List1.Clear empties the list first, so that clicking Show twice does not give two tables. The For loop then adds one line for each number from 1 to 12. Each line is joined together from five pieces with &: the number, " x ", the counter, " = ", and the product.

When a list has more lines than fit, it shows a scroll bar, so the user can scroll through them.

6.7. Try It Yourself

  • In the Practice project, print the numbers from 1 to 20 that are even. (Two ways: Step 2, or an If with Mod inside a loop that counts by 1.)

  • Print the total of the numbers from 1 to 1000. Then change the program to stop adding as soon as the total passes 10,000, and print how many numbers it added.

  • Change the times tables program to show the table up to a number the user types in a second TextBox, instead of always 12.

  • Make a program that shows the squares of the numbers from 1 to 20 in a ListBox: 1 squared is 1, 2 squared is 4, and so on.

Chapter 7. Subs and Functions

As programs grow, the same few lines turn up again and again, and one long list of statements gets hard to follow. A procedure gives a group of statements a name; the program then uses the name wherever it needs them. You have been writing procedures since Chapter 3: every event procedure, such as Command1_Click, is one. In this chapter you write your own.

7.1. Your Own Sub

A Sub is a procedure that does something. Type this in the Practice project’s Module1:

Greet
Print "And once more:"
Greet

Sub Greet ()
   Print "Hello!"
   Print "Welcome to DVX BASIC."
End Sub
Hello!
Welcome to DVX BASIC.
And once more:
Hello!
Welcome to DVX BASIC.

Type the first three lines as usual. Then type Sub Greet and press Enter. DVX BASIC turns the line into a procedure of its own: it adds () and End Sub, shows the new procedure in the Code window, and puts the blinking cursor inside it, ready for its statements:

The Code window showing only the new procedure: Sub Greet ()

Type the two Print lines there. To get back to the first three lines, choose (Global) in the Code window’s Function list; to see Greet again, choose Greet. The Code window shows one procedure at a time, and the Function list names them all.

Running the program, DVX BASIC carries out the lines outside the procedure from the top, as always. The line Greet calls the procedure: the program jumps to Sub Greet, runs its statements, and comes back to the line after the call when it reaches End Sub. A procedure runs only when it is called, as many times as it is called.

Name a procedure for what it does, like a variable, and keep it to one job. The names follow the same rules as variable names (Section 4.6).

7.2. Giving a Procedure Values

A procedure becomes far more useful when the caller can hand it values to work with. The names in the parentheses after the procedure’s name are its parameters: variables that the call fills in.

Greet "Ann"
Greet "Ben"
ShowSum 3, 4

Sub Greet (who As String)
   Print "Hello, "; who; "!"
End Sub

Sub ShowSum (a As Integer, b As Integer)
   Print a; "+"; b; "="; a + b
End Sub
Hello, Ann!
Hello, Ben!
 3 + 4 = 7 

Sub Greet (who As String) says that Greet takes one string and calls it who. The call Greet "Ann" passes "Ann", so inside the procedure who is "Ann"; the next call passes "Ben". The values in a call are its arguments. A procedure with several parameters takes its arguments in the same order, separated by commas: in ShowSum 3, 4, a is 3 and b is 4.

A call can also start with the word Call; then the arguments go in parentheses:

ShowSum 1, 2
Call ShowSum(3, 4)

Sub ShowSum (a As Integer, b As Integer)
   Print a + b
End Sub
 3 
 7 

Both calls do the same. Without Call, the usual style, and this book’s, is to leave the parentheses out, as in the first call (DVX BASIC accepts ShowSum (1, 2) too).

7.3. Functions: Procedures That Give a Value Back

A Function is a procedure that works out a value and gives it back to the caller, as Val and Format$ do. You use your own functions the same way:

Print Square(4)
Print Square(2.5)
Print "A 3 by 5 rectangle's area is"; Area(3, 5)

Function Square (n As Double) As Double
   Square = n * n
End Function

Function Area (w As Double, h As Double) As Double
   Area = w * h
End Function
 16 
 6.25 
A 3 by 5 rectangle's area is 15 

Function Square (n As Double) As Double says that Square takes a number and gives back a Double: the As after the parentheses is the type of the value it returns. Inside the function, storing a value in the function’s own name (Square = n * n) sets what it gives back. A function is called in the middle of an expression, with its arguments in parentheses: Print Square(4), x = Area(3, 5) + 1.

Use a Sub when the procedure does something (shows a message, fills a list), and a Function when it works out something (a price, a temperature, whether a guess is right).

7.4. Changing the Caller’s Variable

When the argument of a call is a variable, the parameter is that variable, under another name, for as long as the procedure runs: storing a value in the parameter changes the caller’s variable. To give the procedure only a copy of the value, so that it cannot change the variable, put ByVal before the parameter.

Dim score As Integer

score = 10
AddBonus score
Print score
TryBonus score
Print score

Sub AddBonus (points As Integer)
   points = points + 5
End Sub

Sub TryBonus (ByVal points As Integer)
   points = points + 5
End Sub
 15 
 15 

AddBonus adds 5 to points, which is score, so score becomes 15. TryBonus adds 5 to its own copy, and score stays 15. Most procedures only read their parameters, and then it makes no difference; when a procedure changes a parameter only for its own work, write ByVal so that the caller’s variable is safe.

7.5. Where Variables Live

A variable made with Dim inside a procedure is local to it: it exists only while the procedure runs, starts from 0 (or "") each time it is called, and no other procedure can see it. Two procedures can each have a local variable called count, and they never get in each other’s way. Most variables should be local.

A variable that several procedures share is made with Dim outside every procedure, at the top of the module. Every procedure of the module can use it:

Dim total As Integer

AddUp 5
AddUp 7
Print "The total is"; total

Sub AddUp (n As Integer)
   Dim before As Integer

   before = total
   total = total + n
   Print before; "plus"; n; "is"; total
End Sub
 0 plus 5 is 5 
 5 plus 7 is 12 
The total is 12 

total belongs to the module and keeps its value from one call to the next; before is `AddUp’s own and is made afresh at each call. (A procedure that declares a local variable with the name of a module variable gets its own variable, and the module’s is out of its reach. Give them different names.)

The same holds in a form’s code: as in the guessing game of Section 5.8, a variable the form’s event procedures share is made with Dim at the top of its code.

Between the two is Static: a local variable that keeps its value from one call to the next, so a procedure can remember something without sharing it with anyone:

Counter
Counter
Counter

Sub Counter ()
   Static calls As Integer
   Dim fresh As Integer

   calls = calls + 1
   fresh = fresh + 1
   Print "calls:"; calls; " fresh:"; fresh
End Sub
calls: 1  fresh: 1 
calls: 2  fresh: 1 
calls: 3  fresh: 1 

7.6. Leaving Early

Exit Sub leaves a Sub at once, and Exit Function a Function, as you saw in the guessing game. In a function, set its value before you leave: a function that leaves without one gives back 0 (or "" for a string).

7.7. A Converter That Goes Both Ways

The temperature converter of Chapter 4 converts one way. This one has a button for each way, and procedures share the work, so the two Click procedures are one line each.

  1. Start a new project called Converter, and set the form’s Caption to Temperature Converter.

  2. Place a Label, a TextBox, two CommandButtons, and another Label, and set:

    Control Name Set this property

    Label

    Label1

    Caption: Temperature:

    TextBox

    Text1

    Text: nothing

    CommandButton

    Command1

    Caption: To Celsius

    CommandButton

    Command2

    Caption: To Fahrenheit

    Label

    Label2

    Caption: nothing

  3. Press F7 for the form’s code. In (General), type the first line of each function and press Enter, then type its body. (After the first function, type the next one’s first line below its End Function.)

    Function ToCelsius (degrees As Double) As Double
       ToCelsius = (degrees - 32) * 5 / 9
    End Function
    
    Function ToFahrenheit (degrees As Double) As Double
       ToFahrenheit = degrees * 9 / 5 + 32
    End Function
  4. Below the second function’s End Function, type the Sub that does the work:

    Sub Convert (unit As String)
       Dim degrees As Double
    
       If Not IsNumeric(Text1.Text) Then
          Label2.Caption = "Type a number first."
          Exit Sub
       End If
    
       degrees = Val(Text1.Text)
    
       If unit = "Celsius" Then
          degrees = ToCelsius(degrees)
       Else
          degrees = ToFahrenheit(degrees)
       End If
    
       Label2.Caption = Format$(degrees, "0.0") & " degrees " & unit
    End Sub
  5. Double-click each button in the designer and give it its one line:

    Sub Command1_Click ()
       Convert "Celsius"
    End Sub
    
    Sub Command2_Click ()
       Convert "Fahrenheit"
    End Sub
  6. Press F5, type a temperature, and try both buttons.

The Temperature Converter: 100 in the box
Figure 6. The converter, 100 degrees Celsius in Fahrenheit

Convert does everything both buttons need: it checks the text, reads the number, converts it with the right function, and shows the answer. The only difference between the buttons is the scale, so that is what each one passes. If you later want to show three decimals, there is one line to change, not two.

7.8. Try It Yourself

  • Write a Function Larger(a As Double, b As Double) As Double that gives back the larger of its two numbers, and print Larger(3, 7) and Larger(-1, -5).

  • Write a Sub Stars(count As Integer) that prints a line of that many * characters (build the line in a String variable in a loop). Call it in a loop to print a triangle.

  • Add a To Kelvin button to the converter. Kelvin is degrees Celsius plus 273.15. Which procedures do you need to change?

  • Write a Function IsEven(n As Long) As Boolean, and use it to print the even numbers from 1 to 20.

Chapter 8. Working with Text

Much of what programs handle is text: names, messages, files, what the user types. BASIC has a function for almost everything you might want to do with a string: measure it, cut pieces out of it, search it, and change it. In this chapter you meet the ones you will use most, and build a word counter.

Type the examples in the Practice project’s Module1, as before.

8.1. Length and Pieces

The characters of a string are numbered from 1. Len gives how many there are, and three functions cut pieces out:

Dim word As String

word = "Programming"
Print Len(word)
Print Left$(word, 7)
Print Right$(word, 4)
Print Mid$(word, 4, 4)
Print Mid$(word, 8)
 11 
Program
ming
gram
ming
Function Gives

Len(s)

The number of characters in s.

Left$(s, n)

The first n characters.

Right$(s, n)

The last n characters.

Mid$(s, start, n)

n characters starting at character number start; without n, all the rest from start on.

Mid$(s, i, 1) is the single character number i: with a For loop from 1 to Len(s), a program can look at every character of a string in turn.

8.2. Searching

InStr looks for one string inside another and gives the number of the character where it starts, or 0 when it is not there:

Dim sentence As String

sentence = "The cat sat on the mat."
Print InStr(sentence, "cat")
Print InStr(sentence, "dog")
Print InStr(sentence, "the")
Print InStr(5, sentence, "at")
 5 
 0 
 16 
 6 

The search minds capitals: "the" is not found at the start, where the sentence has "The", but at character 16. With a number first, InStr starts looking from that character, which is how a program finds the second, third, and later places where something appears.

If InStr(s, "@") > 0 Then is the usual way to ask whether s contains something at all.

8.3. Capitals and Spaces

UCase$ and LCase$ give the string in capitals or in small letters. Trim$ takes the spaces off both ends, LTrim$ off the left, and RTrim$ off the right. The square brackets in the example show where the strings begin and end:

Dim typed As String

typed = "   Hello There   "
Print "["; UCase$(typed); "]"
Print "["; LCase$(typed); "]"
Print "["; Trim$(typed); "]"
Print "["; LTrim$(typed); "]"
Print "["; RTrim$(typed); "]"
[   HELLO THERE   ]
[   hello there   ]
[Hello There]
[Hello There   ]
[   Hello There]

These are just what you need to understand what a user typed. Someone answering a question may type Yes, YES, or ` yes ` with a stray space; LCase$(Trim$(answer)) = "yes" is true for all of them:

Dim answer As String

answer = " YES "
If LCase$(Trim$(answer)) = "yes" Then Print "You said yes."
If Left$(LCase$(Trim$(answer)), 1) = "y" Then
   Print "It starts with a y."
End If
You said yes.
It starts with a y.

8.4. Changing and Building Text

Replace gives the string with every copy of one piece replaced by another (minding capitals, so Cats stays). String$ makes a string of one character repeated, and Space$ one of spaces:

Print Replace("I like cats. Cats like me.", "cats", "dogs")
Print Replace("a-b-c", "-", "")
Print String$(10, "*")
Print "[" & Space$(5) & "]"
I like dogs. Cats like me.
abc
**********
[     ]

A string never changes in place: each of these functions gives back a new string, and the old one stays as it was until you store the new one over it (s = Replace(s, "a", "b")).

A loop can build a string a piece at a time with &. This one reads a word from its last character to its first:

Dim word As String
Dim backwards As String
Dim i As Integer

word = "stressed"
For i = Len(word) To 1 Step -1
   backwards = backwards & Mid$(word, i, 1)
Next i
Print word; " backwards is "; backwards
stressed backwards is desserts

8.5. Characters and Their Numbers

Inside the computer every character is a number: its character code. Asc gives the code of a string’s first character, and Chr$ the character of a code:

Print Asc("A"); Asc("a"); Asc("0")
Print Chr$(72); Chr$(105); Chr$(33)
Print "Line one" & Chr$(10) & "Line two"
 65  97  48 
Hi!
Line one
Line two

The capital letters are codes 65 to 90, the small letters 97 to 122, and the digits 48 to 57. Codes below 32 are not characters you can see: Chr$(10) starts a new line, Chr$(9) is a tab. Code 32 is the space. “String Functions” in the DVX BASIC Language Reference lists every text function.

8.6. A Word Counter

This program counts the words and characters of whatever is typed in it, as you type. It uses a TextArea: a TextBox for many lines of text, with scroll bars. Its Change event happens every time its text changes, so the count is always up to date.

The Word Counter window with three lines of text typed in
Figure 7. The word counter
  1. Start a new project called WordCount and set the form’s Caption to Word Counter.

  2. Place a TextArea (the second tool in the eighth row of the Toolbox) and a Label below it, and set:

    Control Name Set this property

    TextArea

    TextArea1

    Text: nothing

    Label

    Label1

    Caption: 0 words, 0 characters

    The TextArea grows to fill the room the label leaves.

  3. Press F7, and in (General) type the function that counts:

    Function CountWords (s As String) As Long
       Dim i As Long
       Dim words As Long
       Dim inWord As Boolean
    
       For i = 1 To Len(s)
          If Asc(Mid$(s, i, 1)) <= 32 Then
             inWord = False
          ElseIf Not inWord Then
             inWord = True
             words = words + 1
          End If
       Next i
    
       CountWords = words
    End Function
  4. Double-click the TextArea in the designer: its default event is Change, so DVX BASIC opens TextArea1_Change. Type:

    Sub TextArea1_Change ()
       Dim s As String
       Dim words As Long
    
       s = TextArea1.Text
       words = CountWords(s)
       Label1.Caption = words & " words, " & Len(s) & " characters"
    End Sub
  5. Press F5 and type.

A word is a run of characters that are not spaces. CountWords walks along the text one character at a time and remembers, in inWord, whether it is inside a word. Each character with a code of 32 or less (a space, a tab, a line break) ends any word it was in. Any other character either continues the current word or, when inWord is false, starts a new one, and that is when it counts.

8.7. Try It Yourself

  • Add a count of lines to the word counter: count the Chr$(10) characters in the text and add 1 (or 0 when the text is empty).

  • Write a Function CountOf(s As String, ch As String) As Long that counts how many times the character ch appears in s, and print how many `"e"`s are in a sentence.

  • Write a Function that reports whether a word is a palindrome, the same backwards as forwards (level is one; stressed is not). Ignore capitals with LCase$.

  • Make a form where the user types their full name in a TextBox, and a button shows their initials: the first letter of each word, in capitals.

Chapter 9. Lists of Things: Arrays and Collections

A variable holds one value. Programs often need many values of the same kind: the scores of a game, the names in an address book, the words of a sentence. An array is a numbered row of variables under one name, and a loop can go through all of them. In this chapter you learn arrays and their friendlier cousin, the Collection, and build a high score list.

Type the examples in the Practice project’s Module1, as before.

9.1. Arrays

An array is made with Dim, like a variable, with the range of its numbers in parentheses:

Dim days(1 To 7) As String
Dim i As Integer

days(1) = "Sunday"
days(2) = "Monday"
days(3) = "Tuesday"
days(4) = "Wednesday"
days(5) = "Thursday"
days(6) = "Friday"
days(7) = "Saturday"

Print "Day 3 is "; days(3)
For i = 2 To 6
   Print days(i); " is a weekday."
Next i
Day 3 is Tuesday
Monday is a weekday.
Tuesday is a weekday.
Wednesday is a weekday.
Thursday is a weekday.
Friday is a weekday.

Dim days(1 To 7) As String makes seven String variables, days(1) to days(7). Each one is an element of the array, and the number in the parentheses is its index. The index can be any expression, a variable most often, which is what makes arrays useful: days(i) in a loop reaches every element in turn.

Using an index outside the array’s range, such as days(8), stops the program with Runtime error 9: Subscript out of range.

9.2. Arrays and Loops

Loops and arrays go together. This program keeps five scores and works out their total, their average, and the best of them:

Dim scores(1 To 5) As Integer
Dim i As Integer
Dim total As Integer
Dim best As Integer

scores(1) = 72
scores(2) = 95
scores(3) = 81
scores(4) = 64
scores(5) = 88

For i = 1 To 5
   total = total + scores(i)
   If scores(i) > best Then best = scores(i)
Next i
Print "Total:"; total
Print "Average:"; total / 5
Print "Best:"; best
Total: 400 
Average: 80 
Best: 95 

Finding the best is a pattern worth remembering: start with a value no element can be below, look at each element in turn, and keep it when it beats the best so far.

9.3. Counting from 0

An array can also be made with only its last index: Dim a(4). Then it starts at 0, so it has five elements, a(0) to a(4). LBound and UBound give an array’s first and last index:

Dim a(4) As Integer
Dim b(1 To 10) As Integer

Print LBound(a); UBound(a)
Print LBound(b); UBound(b)
Print "a has"; UBound(a) - LBound(a) + 1; "elements"
 0  4 
 1  10 
a has 5 elements

A loop For i = LBound(a) To UBound(a) goes through any array without your having to remember its size. In this book’s programs, arrays start at 1 unless there is a reason not to: element 1 is the first.

9.4. Arrays That Grow

When you do not know in advance how many elements you need, make the array without a size, Dim names() As String, and give it one later with ReDim. ReDim Preserve changes the size and keeps the values already in it; plain ReDim empties the array.

Dim names() As String
Dim i As Integer

ReDim names(1 To 2)
names(1) = "Ann"
names(2) = "Ben"

ReDim Preserve names(1 To 3)
names(3) = "Cal"

For i = 1 To UBound(names)
   Print i; names(i)
Next i
 1 Ann
 2 Ben
 3 Cal

9.5. Text into Arrays and Back

Split cuts a string into an array of pieces, at every place a separator appears. Join does the opposite: it glues the elements of an array into one string, with a separator between them. The array Split makes starts at 0.

Dim words() As String
Dim i As Integer

words = Split("red,green,blue", ",")
Print "There are"; UBound(words) + 1; "words."
For i = 0 To UBound(words)
   Print i; words(i)
Next i
Print Join(words, " and ")
There are 3 words.
 0 red
 1 green
 2 blue
red and green and blue

Split(sentence, " ") gives the words of a sentence, and Split(text, Chr$(10)) its lines.

9.6. Putting Things in Order

Many programs need their lists in order: names from A to Z, scores from best to worst. Here is one simple way to sort an array, smallest first. For each position from the first on, the inner loop looks at every element after it, and whenever one is smaller, Swap exchanges the two:

Dim n(1 To 5) As Integer
Dim i As Integer
Dim j As Integer

n(1) = 42
n(2) = 7
n(3) = 19
n(4) = 3
n(5) = 25

For i = 1 To 4
   For j = i + 1 To 5
      If n(j) < n(i) Then Swap n(i), n(j)
   Next j
Next i

For i = 1 To 5
   Print n(i);
Next i
Print
 3  7  19  25  42 

After the first round of the outer loop, the smallest number is in n(1); after the second, the next smallest is in n(2), and so on. Change < to > and the array comes out largest first. For a few hundred elements this is plenty fast.

9.7. Collections

A Collection is a list that looks after its own size: you add things to it and remove them, and it keeps count. Make one with Dim name As New Collection:

Dim pets As New Collection
Dim pet As Variant

pets.Add "cat"
pets.Add "dog"
pets.Add "fish"
Print pets.Count; "pets; the first is a "; pets(1)

pets.Remove 2
For Each pet In pets
   Print pet
Next pet
 3 pets; the first is a cat
cat
fish
Use To

pets.Add value

Add a value at the end.

pets.Count

Get how many values it holds.

pets(i)

Get value number i; a Collection counts from 1.

pets.Remove i

Remove value number i; the ones after it move up.

For Each pet In pets

Go through every value in turn.

For Each ... Next gives the loop variable each value of the collection in turn, without an index. The loop variable is a Variant: a variable that can hold a value of any type, which is what For Each needs.

Use an array when you know (or can work out) how many elements there are and want them by number, and a Collection when things come and go. “Collection Object” in the DVX BASIC Language Reference describes everything a Collection can do, including finding values by a name instead of a number.

9.8. A High Score List

This program keeps a list of players and their scores, best first. It stores them in two arrays that grow with each new entry, kept side by side: players(3) scored points(3).

The High Scores window: the Name and Score boxes
Figure 8. The high score list
  1. Start a new project called HighScores. Set the form’s Caption to High Scores and its Height to 400.

  2. Place the controls and set:

    Control Name Set this property

    Label

    Label1

    Caption: Name:

    TextBox

    Text1

    Text: nothing

    Label

    Label2

    Caption: Score:

    TextBox

    Text2

    Text: nothing

    CommandButton

    Command1

    Caption: Add

    ListBox

    List1

    MinHeight: 150

  3. Press F7 and type the shared variables in (General):

    Dim players() As String
    Dim points() As Integer
    Dim entries As Integer
  4. Below them, type the two Subs that sort and show the list (type each one’s first line and press Enter, then its body):

    Sub SortScores ()
       Dim i As Integer
       Dim j As Integer
    
       For i = 1 To entries - 1
          For j = i + 1 To entries
             If points(j) > points(i) Then
                Swap points(i), points(j)
                Swap players(i), players(j)
             End If
          Next j
       Next i
    End Sub
    
    Sub ShowScores ()
       Dim i As Integer
    
       List1.Clear
       For i = 1 To entries
          List1.AddItem i & ". " & players(i) & "  " & points(i)
       Next i
    End Sub
  5. Double-click the Add button and type its Click procedure:

    Sub Command1_Click ()
       If Trim$(Text1.Text) = "" Or Not IsNumeric(Text2.Text) Then
          MsgBox "Type a name and a score."
          Exit Sub
       End If
    
       entries = entries + 1
       ReDim Preserve players(1 To entries)
       ReDim Preserve points(1 To entries)
       players(entries) = Trim$(Text1.Text)
       points(entries) = Val(Text2.Text)
    
       SortScores
       ShowScores
    
       Text1.Text = ""
       Text2.Text = ""
       Text1.SetFocus
    End Sub
  6. Press F5. Type a name and a score, click Add, and add a few more.

Each click makes room for one more entry with ReDim Preserve, stores the new name and score at the end, sorts both arrays, and shows them. The sort compares the scores, but it swaps the names along with them, so each name stays with its score.

9.9. Try It Yourself

  • Keep only the ten best scores in the high score list: after sorting, when there are more than 10 entries, set entries back to 10.

  • Write a Function Average(values() As Integer) As Double that gives the average of any array of scores. (A parameter written values() takes a whole array.)

  • Make a program that splits a sentence the user types into words and shows each word on its own line in a ListBox, then the longest word.

  • Use a Collection to make a shopping list: a TextBox, an Add button, a Remove button that removes the item selected in a ListBox, and the ListBox showing the list. (List1.ListIndex is the number of the selected line, from 0.)

Chapter 10. Finding and Fixing Mistakes

Every programmer makes mistakes, all the time; the good ones are simply good at finding them. A mistake in a program is called a bug, and finding and fixing bugs is debugging. This chapter shows the three kinds of mistakes and the tools DVX BASIC gives you for each, from the messages it shows to stopping a running program and looking inside it.

10.1. Three Kinds of Mistakes

  • A compile error is a line DVX BASIC cannot understand: a misspelled word, a missing End If, a variable that was never made. DVX BASIC checks the whole program before it runs it, so the program does not start at all.

  • A runtime error is something the program cannot do while it runs: divide by zero, use an array element that does not exist, store 40000 in an Integer. The program stops at that line.

  • A logic error is a program that runs without complaint but does the wrong thing: the total is too small, the list is in the wrong order. DVX BASIC cannot know what you meant, so these are the hardest to find, and the debugger is for them.

10.2. When the Program Does Not Start

When DVX BASIC finds a compile error, the Output window says COMPILE ERROR:, where it is, and what is wrong, and the blinking cursor goes to the mistake in the Code window. You met one in Section 4.7:

COMPILE ERROR:
Module1.bas line 6:
Variable not declared: totl (OPTION EXPLICIT is on)

In a form’s code, the place is the procedure and the line in it, such as Command1.Click line 3:. Read the message, then look at the line it names; when the line looks right, look at the line before it, too, because a mistake there (a missing closing quote or parenthesis) often shows up only on the next line.

Common messages and what they usually mean:

Message Usually

Variable not declared: name

A misspelled variable, or one you forgot to make with Dim (see Section 7.5).

Expected THEN, got newline

A word or a sign is missing where the message says: here the Then of an If. A missing ) is reported the same way.

Expected END IF, Expected NEXT

A block that is not closed: an If without its End If, a For without its Next.

Unexpected token: NEXT

A word where it makes no sense, such as a Next without a For.

10.3. When the Program Stops

When a runtime error stops your program, the Output window says RUNTIME ERROR:, the line, and the error’s number and message, and the Code window shows the line:

RUNTIME ERROR:
Module1.bas line 5:
Runtime error 6: Overflow

Some of the errors you will meet most:

Error Means

5: Illegal function call

A function was given a value it cannot use, such as Left$(s, -1).

6: Overflow

A number too big for its variable’s type (40000 in an Integer).

9: Subscript out of range

An array index outside the array’s range.

11: Division by zero

A division by 0.

13: Type mismatch

Text that is not a number where a number is needed (n = "twelve" for an Integer).

A runtime error is often the sign of a logic error earlier in the program: the index is out of range because a loop counted one too far, the division is by zero because a count was never increased. The line where the program stopped is where to start looking, not always where the mistake is.

10.4. When the Answer Is Wrong

Here is a program with a logic error. It should print the average of five scores, 80:

Dim scores(1 To 5) As Integer
Dim i As Integer
Dim total As Integer

scores(1) = 70
scores(2) = 80
scores(3) = 90
scores(4) = 60
scores(5) = 100

For i = 1 To 4
   total = total + scores(i)
Next i
Print "Average:"; total / 5

It prints:

Average: 60 

Perhaps you can already see the mistake. In a bigger program you would not, so here are two ways to find it: watching the values as the program runs, and stopping it to look.

10.4.1. Printing What Happens

The simplest tool is to make the program tell you what it is doing. Debug.Print works like Print, but it always writes to the Output window, also from a program with forms, so add one inside the loop:

Dim scores(1 To 5) As Integer
Dim i As Integer
Dim total As Integer

scores(1) = 70
scores(2) = 80
scores(3) = 90
scores(4) = 60
scores(5) = 100

For i = 1 To 4
   total = total + scores(i)
   Debug.Print "i ="; i; " total ="; total
Next i
Print "Average:"; total / 5
i = 1  total = 70 
i = 2  total = 150 
i = 3  total = 240 
i = 4  total = 300 
Average: 60 

The loop runs only four times: score number 5 is never added. The For line should say For i = 1 To 5. Once the program works, take the Debug.Print lines out again (in a program made into an .app file they do nothing).

10.4.2. Stopping to Look: Breakpoints and Stepping

The debugger can stop a program at a line you choose and let you look at every variable, then go on one line at a time. Put the average program (without the Debug.Print) in the Practice project’s Module1 and try it:

  1. Click the line total = total + scores(i) and press F9, or click the line’s number at the left. A red dot marks a breakpoint there.

  2. Start the program with Run › Debug (Shift+F5) instead of F5. A program started with F5 runs straight through; one started with Debug stops at its breakpoints.

  3. The program stops before the line with the breakpoint, and DVX BASIC shows it with a yellow background. The Locals window opens and lists the program’s variables with their values: i is 1 and total is 0.

    DVX BASIC paused at the breakpoint: the line highlighted in yellow in the Code window
  4. Press F8 (Run › Step Into) to run that one line. The yellow line moves to Next i, and in the Locals window total is now 70. Press F8 again and again, and watch i and total change.

  5. While the program is stopped, the Immediate window can show any value: click in it, type ? total / 4 and press Enter. (? is short for Print.) You can even change a variable there: total = 0.

  6. When i is 4 and you step on, the loop ends instead of going round once more, and you have found the bug. Press Esc to stop the program (or Shift+F5 to let it run on to the next breakpoint), fix the line, and press F9 on the breakpoint line again to take the breakpoint away.

When the line is a call of one of your own procedures, F8 steps into the procedure, line by line. Shift+F8 (Step Over) runs the whole call as one step, Ctrl+Shift+F8 (Step Out) runs to the end of the procedure you are in, and Ctrl+F8 (Run to Cursor) runs until the program reaches the line the blinking cursor is on. The toolbar has a button for each.

The Call Stack window, which opens with the Locals window, lists the procedures the program is in, the innermost first. The Watch window (Window › Watch) shows the values of expressions you choose, such as total / i, all the time the program is stopped. “Debugger” in the DVX BASIC Language Reference describes them all.

10.5. Handling Errors in Your Program

Some errors cannot be avoided by writing the program carefully, because they come from outside it: the user types something odd, a file is missing, a disk is full. Instead of letting the program stop, it can handle the error. On Error GoTo label tells DVX BASIC where to go in the procedure when an error happens:

ShowShare 100, 4
ShowShare 100, 0
Print "The program goes on."

Sub ShowShare (amount As Double, people As Integer)
   Dim share As Double

   On Error GoTo Problem
   share = amount / people
   Print "Each gets"; share
   Exit Sub

Problem:
   Print "Cannot share among"; people; "people: "; Err.Description
End Sub
Each gets 25 
Cannot share among 0 people: Division by zero
The program goes on.

Problem: is a label: a name followed by a colon, marking a line that GoTo can jump to. When the division fails, the procedure jumps there, and Err.Description holds the error’s message (Err.Number holds its number). The Exit Sub before the label makes sure the normal path does not run into the error handling. Either way, the program goes on.

On Error Resume Next is the other way: after an error, the program simply goes on with the next line, and you check Err.Number yourself:

Dim n As Integer

On Error Resume Next
n = "twelve"
If Err.Number <> 0 Then
   Print "Error"; Err.Number; "- "; Err.Description
   Err.Clear
End If
Print "n is still"; n
Error 13 - Type mismatch
n is still 0 

Err.Clear sets Err.Number back to 0, ready for the next check. Use On Error Resume Next for a line or two that may fail, and check right after them; left on for a whole procedure, it hides mistakes.

Better than handling an error is avoiding it: check that the user typed a number with IsNumeric before using it, that an index is in range with UBound, that a count is not 0 before dividing by it. Keep error handling for what you cannot check in advance, such as files (Chapter 13).

10.6. Good Habits

  • Keep Option Explicit on, so misspellings are compile errors instead of logic errors.

  • Run the program often, after every few lines you add. A mistake in the last five lines is easy to find; one somewhere in the last hundred is not.

  • When a result is wrong, find the first place where a value is not what you expected, with Debug.Print or a breakpoint, rather than guessing at a fix.

  • Read the error message all the way through. It usually says exactly what is wrong.

  • Try your program with odd input: nothing at all, a word where a number goes, a very big number, a negative one.

10.7. Try It Yourself

  • Put the bug back into the average program, and find it with a breakpoint and F8, watching the Locals window.

  • Make the temperature converter of Chapter 4 crash with a runtime error: store the result in an Integer and type a huge number. Then make it handle the error with On Error GoTo and show a message instead.

  • Write a program with a For loop that counts the vowels in a sentence, and use the debugger to step through it one character at a time.

Part II: Building Programs with Forms

Chapter 11. Forms, Controls, and Events

In Part I you built small programs with a form, a few controls, and an event procedure or two. This part of the book is about programs like the ones you use every day: windows full of controls, menus, files, pictures, and sound. This chapter looks closer at the three things every such program is made of, forms, controls, and events, and shows how DVX BASIC arranges the controls on a form for you.

11.1. How a Form Program Runs

A program made of lines outside any procedure, like the ones in Module1, runs from its first line to its last and is done. A program with a form works differently:

  1. When it starts, DVX BASIC loads the project’s startup form (Form1, unless File › Project Properties…​ names another) and runs its Form1_Load procedure, if it has one, before the window appears.

  2. Then the program waits. It does nothing at all until the user does something.

  3. Each thing the user does is an event: a click, a key, a change of the text in a box. When an event happens to a control that has an event procedure for it, DVX BASIC runs that procedure, and then the program waits again.

  4. The program ends when its last form closes: when the user clicks its close box, or when the program’s code says Unload Me.

Programs that work like this are called event-driven. Your code is a set of answers, one for each event you care about; DVX BASIC decides when to run them. Events you write no procedure for are simply ignored.

Because the program waits between events, an event procedure should do its work and finish. While one runs, the program cannot answer the user: clicks and keys wait until it is done, so a procedure that runs for a minute leaves the user waiting for a minute. Section 12.9 shows what to do when a program has a long job.

11.2. Properties in Code

Every control, and the form itself, has properties: its caption, its size, its color, whether it can be used. You set them in the Properties window while you design the form, and your code can read them and change them while the program runs. In code, a property is written as the control’s name, a dot, and the property’s name:

Label1.Caption = "Ready"            ' change a property
total = Val(Text1.Text)             ' read one
Command1.Enabled = False            ' gray out a button
Label1.ForeColor = RGB(255, 0, 0)   ' red text

In a form’s code, Me means the form itself: Me.Caption = "Done" changes its title, and Unload Me closes it. (The form’s own name works too, but Me keeps working if you rename the form.)

Some properties every control has:

Property What it is

Name

The name your code uses for the control. Set it in the Properties window only.

Caption, Text

What a label, button, or check box shows (Caption), or what is typed in a box (Text).

Enabled

False grays the control out: the user cannot click it or type in it. On a Frame or a box, it grays out everything inside too.

Visible

False hides the control; the others close up the gap.

ForeColor, BackColor

The colors of its text and its background, made with RGB(red, green, blue), each from 0 to 255, or a name such as vbBlue.

FontName, FontSize, FontBold

The font of its text. The Font row of the Properties window sets them all at once.

ToolTipText

A hint shown when the mouse rests on the control.

MinWidth, MinHeight, MaxWidth, Weight

How it is sized on the form (see Section 11.4).

Tag

Any text you want to keep with the control. DVX BASIC does nothing with it.

The form has Enabled too: Me.Enabled = False makes the whole window ignore the user, as a disabled form does in Visual Basic. Its controls gray out, and its title bar, borders, and close box do nothing, though it still shows, its timers still run, and your code can still change it. When Enabled is True again, the control that had the focus gets it back.

Each kind of control has more of its own. The Properties window lists them for the control selected, and “Control Reference” in the DVX BASIC Language Reference describes every one. A few properties exist only while the program runs, such as the position of the cursor in a text box (SelStart), so the Properties window does not show them.

11.3. Events

An event procedure’s name is the control’s name, an underscore, and the event’s name: Command1_Click, Text1_Change, Form1_Load. That name is all that connects the procedure to the control, so if you rename a control in the Properties window, DVX BASIC renames its event procedures too.

The events you will use most:

Event Happens when

Click

The control is clicked: the mouse button goes down and comes up over it. For a list, an item is picked.

DblClick

The control is double-clicked.

Change

The text or value of the control changes, by the user or by your code.

KeyPress

A key that types a character is pressed in the control.

KeyDown, KeyUp

Any key goes down or comes up, the arrow keys too.

GotFocus, LostFocus

The control gets the keyboard, or loses it.

MouseDown, MouseMove, MouseUp

A mouse button goes down, the mouse moves, a button comes up. A click is MouseDown, MouseUp, and then Click (on a list, Click comes with the pick, before MouseUp); a double-click goes on with DblClick and another MouseUp.

Load

(The form) It is loaded, before it appears.

Resize

(The form) The window changes size.

QueryUnload, Unload

(The form) It is about to close. Its code can still say no.

The form gets Click, DblClick, and the mouse events too, for the mouse on its background, where there is no control: Form1_Click, Form1_MouseDown, and so on.

Double-clicking a control in the designer opens its most used event, its default event: Click for a button, Change for a text box, Load for the form. For any other event, use the two lists at the top of the Code window: choose the control in the Object list, then the event in the Function list. Events in square brackets, such as [KeyPress], have no procedure yet; choosing one makes it, with the cursor inside, ready for you to type.

The Code window with Text2 in the Object list and the Function list open
Figure 9. Choosing Text2’s KeyPress event in the Function list

Some events come with values in parentheses, as parameters (Section 7.2). KeyPress gets KeyAscii, the character code of the key (Section 8.5); the mouse events get the button, the Shift, Ctrl, and Alt keys held, and the position (Section 16.5). A few parameters work backwards, too: change KeyAscii to another code and the box gets that character instead, or set it to 0 and the box never sees the key. That is how a box can refuse letters, as the program in this chapter does.

11.4. Laying Out a Form

In many programming systems you drag each control to an exact place on the form. DVX BASIC arranges the controls for you, the way a word processor arranges words on a page: you say what goes where, in rows and columns, and DVX BASIC works out the sizes and positions, and works them out again when the window changes size or the user picks a larger font.

11.4.1. Columns and Rows

A form stands its controls in a column, top to bottom, in the order you place them, each as wide as the form. You saw that in Part I. To put controls side by side, put them in a row: an HBox control, which has no look of its own and lines up everything in it from left to right. Its partner, the VBox, makes a column inside a row. Rows and columns can hold each other as deep as you like, so any layout is made of them.

Controls that hold other controls are called containers. Besides HBox and VBox there is the Frame, a column with a border and a title, for grouping controls that belong together. To put a control in a container, click inside the container when you place it. The tree at the top of the Properties window shows what is inside what, and you can drag a control there, or in the designer, to move it to another place.

11.4.2. Who Gets the Room

Each control asks for the room its contents need, and at least its MinWidth and MinHeight (which the designer sets to 100 by 30 for a new control). A size is in pixels, unless you type it as a percentage of the container, 50%, or as a number of characters, 20ch, which grows with a larger font. A percentage only takes room the container has to spare. When the form has more room than that, the Weight property decides who gets it:

  • A control with Weight 0 keeps its size. Labels, buttons, and check boxes start with 0.

  • Controls with a Weight above 0 share the spare room in proportion: one with 2 gets twice as much as one with 1. Text boxes, text areas, combo boxes, list views, and tree views start with 100. (A one-line text box only grows across, never taller.)

  • MaxWidth and MaxHeight put a limit on the growth (0 means no limit), in the same units.

Across a column every control stretches to the column’s width; along a row, only the ones with a weight do. So in a row with a label and a text box, the label stays the width you give it and the text box takes the rest.

11.4.3. Space and Alignment

A form, an HBox, a VBox, and a Frame each have:

  • Padding: the space between their edge and the controls inside (4 pixels unless you change it).

  • Spacing: the space between one control and the next (4 pixels; none in a Frame). Padding and Spacing take 50% and 20ch sizes too.

  • Alignment: where the controls go when they do not fill the container: Left, Center, or Right (for a column, Left is the top and Right the bottom). A row of buttons with Alignment set to Right sits at the right of the form, as the buttons of a dialog box do.

A Spacer control is empty room that takes the spare room (its Weight is 100): put one between two buttons in a row, and it pushes them to the two ends.

The form itself has AutoSize, which makes the window just big enough for its controls, and Resizable, which says whether the user may drag its edges (True unless you set it to False). With the layout doing the arithmetic, a resizable window looks right at any size.

BackColor colors the whole form behind its controls. Labels, CheckBoxes, and OptionButtons have no color of their own, so they sit on it too. Set it in the Properties window, or in code with RGB: Me.BackColor = RGB(255, 255, 192) makes the form a pale yellow.

11.5. A Sign-Up Form

This program asks for a name and a phone number, the way a club’s sign-up sheet does. It uses rows to line up each label with its box, a row of buttons at the right, and four kinds of events.

The Join the Club window: Name and Phone labels each beside a text box
Figure 10. The sign-up form, with a name and a phone number typed in

11.5.1. Designing It

  1. Start a new project called SignUp. Set the form’s Caption to Join the Club and its Height to 200.

  2. Make the first row: in the Toolbox, click the HBox tool (the fourth in the second row), then click the form. The HBox appears at the top of the form, empty.

  3. Click the Label tool, then click inside the HBox: the label goes into it. Set its Caption to &Name:. (The & makes Alt+N an access key that moves the cursor to the box beside the label; the N is shown underlined.)

  4. Click the TextBox tool, then click inside the HBox again, to the right of the label. Set the text box’s Text to nothing. The label keeps its width and the text box fills the rest of the row.

  5. Make the second row the same way: an HBox placed below the first row, a Label in it with the Caption &Phone:, and a TextBox with no Text.

  6. Make the third row: an HBox below the second, and in it two CommandButtons. Set their captions to OK and Cancel.

  7. Select the OK button, click Default in the Properties window, and press Enter: a True or False property switches to the other value, here True. A button with Default True is pressed by Enter, wherever the cursor is on the form. Select the Cancel button and set its Cancel to True the same way: Esc presses it.

  8. Click the empty part of the third row, to the right of the buttons, to select the HBox. Click its Alignment property and press Enter twice: a property with a list of values goes to the next value each time, from Left to Center to Right. The buttons move to the right.

The Join the Club form in the designer with its three rows
Figure 11. The finished design. The tree at the top of the Properties window shows the buttons inside HBox3.

The controls and their settings, for checking:

Control Name Set this property

HBox

HBox1

  Label

Label1

Caption: &Name:

  TextBox

Text1

Text: nothing

HBox

HBox2

  Label

Label2

Caption: &Phone:

  TextBox

Text2

Text: nothing

HBox

HBox3

Alignment: Right

  CommandButton

Command1

Caption: OK, Default: True

  CommandButton

Command2

Caption: Cancel, Cancel: True

11.5.2. The Code

  1. Double-click an empty part of the form, below the buttons. The form’s default event is Load, which runs before the window appears. Gray out the OK button, since there is no name yet:

    Sub Form1_Load ()
       Command1.Enabled = False
    End Sub
  2. Press Shift+F7 to go back to the designer, and double-click the name box. Its Change event runs every time its text changes, so the OK button is ready exactly when there is a name:

    Sub Text1_Change ()
       ' OK only once there is a name
       Command1.Enabled = Trim$(Text1.Text) <> ""
    End Sub

    Trim$(Text1.Text) <> "" is True or False, and a property that takes True or False can be set to it directly: no If is needed.

  3. The phone box should take only digits, spaces, and dashes. In the Code window, choose Text2 in the Object list, and then [KeyPress] in the Function list. (Choosing Text2 first makes an empty Text2_Change; DVX BASIC throws away empty event procedures you leave, so it does no harm.) Type:

    Sub Text2_KeyPress (KeyAscii As Integer)
       ' Digits, spaces, dashes, and Backspace only
       If KeyAscii = vbKeyBack Then
          Exit Sub
       End If
       If InStr("0123456789 -", Chr$(KeyAscii)) = 0 Then
          KeyAscii = 0
       End If
    End Sub

    Backspace must still work, so when the key is Backspace (whose code has the name vbKeyBack), the procedure leaves at once and the box gets the key. For any other key, InStr looks for its character in the string of the allowed ones (Section 8.2), and when it is not there, KeyAscii = 0 throws the key away.

  4. Back in the designer, double-click the OK button:

    Sub Command1_Click ()
       Dim msg As String
    
       msg = "Welcome to the club, " & Trim$(Text1.Text) & "!"
       If Trim$(Text2.Text) <> "" Then
          msg = msg & " We will call " & Trim$(Text2.Text) & "."
       End If
       MsgBox msg
       Unload Me
    End Sub
  5. And the Cancel button:

    Sub Command2_Click ()
       Unload Me
    End Sub
  6. Press F5. Type a name, press Tab, and type a phone number with a letter or two in it: the letters do not appear. Press Enter, and the OK button answers.

A message box over the form: Welcome to the club
Figure 12. Enter presses the default button

Unload Me closes the form, and since it is the program’s only form, the program ends. Esc or the Cancel button closes it without a word.

11.6. The Keyboard on a Form

One control at a time has the focus: it gets what is typed, and shows a blinking cursor or a dotted outline. Tab moves the focus to the next control that can take it, in the order of the controls on the form, top to bottom and left to right; Shift+Tab moves it back. Labels never take the focus.

A program that works well from the keyboard is a pleasure to use, and DVX BASIC gives you most of it for nothing:

  • An & in a caption makes an access key: Alt with the underlined letter presses a button, ticks a check box, or, for a label, moves the focus to the control after it.

  • A Default button is pressed by Enter, and a Cancel button by Esc.

  • In code, Text1.SetFocus moves the focus to a control, for example to the box where the user should type next, as the high score list of Section 9.8 does.

11.7. Try It Yourself

  • Add a third row for an e-mail address. Make the OK button ready only when there is both a name and an e-mail address with an @ in it. (Both boxes' Change procedures can call one Sub that decides.)

  • Give the phone box a Mask of () -## instead of the KeyPress procedure, and see what it does. (“TextBox” in the DVX BASIC Language Reference describes it.)

  • Set the form’s Height to 300, run it, and make the window larger and smaller (it is resizable, since its Resizable is True). Then put a TextArea for comments between the second and third rows, and see who gets the room now.

  • Give the form a Form1_Resize procedure that shows the window’s size in its caption: Me.Caption = Me.Width & " x " & Me.Height.

Chapter 12. The Controls You Will Use Most

The Toolbox holds more than thirty kinds of controls. This chapter shows the ones almost every program uses: check boxes and option buttons for choices, lists for many items, number boxes and progress bars, and the timer, which does things at a time you choose. You build two programs with them, a pizza order and an egg timer, and learn how a program does a long job without leaving the user stuck.

12.1. Good Names for Controls

Command1, Label3, and Text2 are fine names in a program with three controls. In a program with twenty, code such as Label3.Caption = Text2.Text says nothing about what it does. Give each control your code uses a name that says what it is for, with a short prefix that says what kind of control it is:

Control Prefix Example

CommandButton

cmd

cmdAdd

Label

lbl

lblTotal

TextBox

txt

txtName

CheckBox

chk

chkCheese

OptionButton

opt

optLarge

ListBox

lst

lstOrder

ComboBox, DropDown

cbo

cboCrust

SpinButton

spn

spnMinutes

ProgressBar

prg

prgDone

Timer

tmr

tmrTick

Then lblTotal.Caption = txtPrice.Text reads almost like a sentence. To name a control, select it and change its Name, the first property in the Properties window. Names follow the rules for variable names (Section 4.6). DVX BASIC renames the control everywhere in the form’s code too, so you can rename one at any time, but naming each control as you place it saves going back. Labels that the code never uses can keep their own names, as can the HBoxes that only arrange things.

12.2. Choices: Check Boxes and Option Buttons

A CheckBox is a yes-or-no choice: each one is ticked or not, on its own. Its Value is True when it is ticked, so If chkCheese.Value Then asks whether the user wants cheese. Clicking it, or pressing Space while it has the focus, ticks or clears it and runs its Click procedure.

An OptionButton is one choice out of several: small, medium, or large. Option buttons in the same container form a group, and choosing one clears the others, so exactly one of them is chosen. Its Value is True for the chosen one. To have two groups on one form, put each in a container of its own; a Frame, with its border and title, also shows the user which buttons belong together.

Setting Value in code works too: optMedium.Value = True chooses medium, as if the user had clicked it, and runs its Click procedure.

12.3. Lists of Items

A ListBox shows a list of lines and lets the user pick one. Your code fills it and reads it:

Use To

lstOrder.AddItem "text"

Add a line at the end.

lstOrder.ListCount

Get how many lines it has.

lstOrder.ListIndex

Get the number of the line picked, counting from 0; -1 when none is.

lstOrder.Text

Get the text of the line picked.

lstOrder.List(i)

Get the text of line i.

lstOrder.RemoveItem i

Remove line i.

lstOrder.Clear

Remove all the lines.

Set its Sorted property to True, and the list keeps its lines in alphabetical order as you add them. Picking a line runs the list’s Click procedure, and double-clicking one runs DblClick.

Each line can carry a number of your own that the user never sees, its ItemData. lstOrder.NewIndex is the number of the line just added, so lstOrder.ItemData(lstOrder.NewIndex) = 42 gives the new line the number 42, and lstOrder.ItemData(lstOrder.ListIndex) reads the number of the line picked. The pizza order uses it to remember each pizza’s price.

Set its Style to Checkbox, and each line gets a check box of its own, so the user can tick several lines at once: a shopping list, or the toppings of a pizza. lstOrder.Selected(i) is True when line i is ticked, and setting it ticks or clears the line. Each tick or untick runs the list’s ItemCheck procedure, with the number of the line:

Sub lstOrder_ItemCheck (Item As Integer)
   If lstOrder.Selected(Item) Then
      lblTotal.Caption = lstOrder.List(Item) & " added"
   End If
End Sub

Two controls fold a list into one line, with an arrow that opens it, to save room on the form. A DropDown lets the user only pick one of its items. A ComboBox is a text box and a list together: the user can pick an item or type something else. Both have AddItem, ListIndex, List, RemoveItem, and Clear, as a ListBox does, and Text is the item shown.

12.4. Control Arrays

A pizza can come in three sizes, and the program has to look at all three option buttons. With the names optSmall, optMedium, and optLarge, that takes three If lines, and each button needs its own Click procedure doing the same thing. A control array works like an array of variables (Section 9.1): several controls of the same kind share one name and are told apart by a number, their Index: optSize(0), optSize(1), and optSize(2). Code can then go through them with a loop, and they share one Click procedure, which is told which one was clicked:

Sub optSize_Click (Index As Integer)
   ShowPrice
End Sub

Sub chkTop_Click (Index As Integer)
   ShowPrice
End Sub

Sub cboCrust_Click ()
   ShowPrice
End Sub

The Index As Integer parameter is the number of the control the event happened to.

The array’s name alone stands for the whole array. optSize.Count is how many controls it has, and optSize.LBound and optSize.UBound are its lowest and highest numbers, so a loop For i = 0 To optSize.UBound reaches every one, however many there are. For Each goes through them too:

Dim opt As Control

For Each opt In optSize
   opt.Enabled = False
Next opt

To make a control array in the designer, give the first control its name and set its Index to 0. Then give the next control of the same kind the same name: DVX BASIC makes it element 1, the one after element 2, and so on.

12.5. A Pizza Order

This program takes pizza orders. The customer chooses a size, the toppings, and the crust, the price changes as they choose, and Add to Order adds the pizza to the order. Double-clicking a pizza in the order takes it off again.

The Pizza Order window: Size and Toppings frames side by side
Figure 13. The pizza order with two pizzas ordered

12.5.1. Designing It

  1. Start a new project called PizzaOrder. Set the form’s Caption to Pizza Order and its Height to 400.

  2. Place an HBox, then a Frame in it (the third tool in the second row). Set the frame’s Caption to Size.

  3. Click the OptionButton tool (the first in the fifth row) and click inside the frame. Set the button’s Caption to Small, its Name to optSize, and its Index to 0.

  4. Place two more option buttons in the same frame (clicking anywhere inside the frame puts the new one below the others). Caption them Medium and Large, and name both optSize: they become optSize(1) and optSize(2).

  5. Place a second Frame in the HBox, to the right of the first, with the Caption Toppings. Put three CheckBoxes in it, captioned Cheese, Mushrooms, and Olives, as the control array chkTop: name the first chkTop with the Index 0, then the others chkTop.

  6. Below the frames, place another HBox with a Label (Caption Crust:) and a DropDown (the second tool in the second row) named cboCrust.

  7. Below that, a third HBox with a Label named lblPrice (no Caption) and a CommandButton named cmdAdd with the Caption &Add to Order.

  8. Below the rows, place a ListBox named lstOrder, and below it a Label named lblTotal with the Caption Total: $0.00.

  9. The order list should take the room the other controls leave. Select it and set its Weight to 1 (Section 11.4.2).

The Pizza Order form in the designer with the order list selected
Figure 14. The design. The Properties window shows the list’s Weight.

12.5.2. The Code

  1. Press F7. In (General), type the variable that holds the order’s total, which every procedure needs to see:

    Dim total As Currency
  2. Below it, type a Function that works out the price of the pizza being chosen. (Type its first line and press Enter, as in Section 7.1.)

    Function PizzaPrice () As Currency
       Dim price As Currency
       Dim i As Integer
    
       ' Small $8, Medium $10, Large $12
       For i = 0 To optSize.UBound
          If optSize(i).Value Then
             price = 8 + 2 * i
          End If
       Next i
    
       ' $1 for each topping
       For i = 0 To chkTop.UBound
          If chkTop(i).Value Then
             price = price + 1
          End If
       Next i
    
       ' A stuffed crust is $2 more
       If cboCrust.Text = "Stuffed" Then
          price = price + 2
       End If
    
       PizzaPrice = price
    End Function

    The loops go through the control arrays. A size costs 8 dollars, plus 2 for each size up: 8 + 2 * i is 8, 10, or 12.

  3. Below the Function, type one that describes the pizza in words, such as Large, Thin, Cheese:

    Function Describe () As String
       Dim i As Integer
       Dim what As String
    
       For i = 0 To optSize.UBound
          If optSize(i).Value Then
             what = optSize(i).Caption
          End If
       Next i
       what = what & ", " & cboCrust.Text
       For i = 0 To chkTop.UBound
          If chkTop(i).Value Then
             what = what & ", " & chkTop(i).Caption
          End If
       Next i
       Describe = what
    End Function
  4. And two Subs that show the price and the total, each in its label:

    Sub ShowPrice ()
       lblPrice.Caption = "Price: " & Format$(PizzaPrice(), "$0.00")
    End Sub
    
    Sub ShowTotal ()
       lblTotal.Caption = "Total: " & Format$(total, "$0.00")
    End Sub

    Format$ with "$0.00" writes an amount the way prices are written: $12.00.

  5. Choose Form1 in the Code window’s Object list. Its Load procedure opens. Fill the crust list and start with a medium pizza:

    Sub Form1_Load ()
       cboCrust.AddItem "Thin"
       cboCrust.AddItem "Thick"
       cboCrust.AddItem "Stuffed"
       cboCrust.ListIndex = 0
       optSize(1).Value = True
       ShowPrice
    End Sub
  6. Back in the designer (Shift+F7), double-click one of the option buttons, one of the check boxes, and the crust list, and give each Click procedure the line ShowPrice, as shown in Section 12.4. Every choice now shows the new price at once.

  7. Double-click the Add to Order button:

    Sub cmdAdd_Click ()
       Dim price As Currency
    
       price = PizzaPrice()
       lstOrder.AddItem Describe() & ": " & Format$(price, "$0.00")
       ' Keep the price with the line, in cents
       lstOrder.ItemData(lstOrder.NewIndex) = price * 100
       total = total + price
       ShowTotal
    End Sub

    The pizza’s price goes with its line as its ItemData. ItemData holds whole numbers only, so the price goes in cents: price * 100.

  8. Choose lstOrder in the Object list and [DblClick] in the Function list:

    Sub lstOrder_DblClick ()
       Dim i As Integer
    
       i = lstOrder.ListIndex
       If i >= 0 Then
          total = total - lstOrder.ItemData(i) / 100
          lstOrder.RemoveItem i
          ShowTotal
       End If
    End Sub
  9. Press F5 and order a few pizzas.

12.6. Numbers: Spin Buttons, Scroll Bars, and Progress Bars

A SpinButton is a box for a whole number, with small arrows that make it bigger or smaller (so do the arrow keys); the user can also type a number. Its Value is the number. Its range starts as 0 to 100; set another with SetRange, before you set its Value: spnMinutes.SetRange 1, 60. Every change runs its Change procedure.

An HScrollBar is a slider: the user drags it, or clicks or uses the arrow keys, to choose a number between its Min and Max. Its Value is the number, and every move runs its Change procedure. It is the control for a volume, a speed, or anything where the exact number matters less than more or less.

A ProgressBar shows how far a job has come: its Value goes from 0 (empty) to 100 (full). Only your code changes it.

12.7. Timers

A Timer runs a procedure on its own, again and again, at a time you choose. It is the only control the user never sees: while the program runs it is invisible. In the designer it shows in the form’s tray, a small window just below the form, as its picture with its name under it. Click it there to select it, and double-click it to write its procedure. Its properties:

  • Interval: how long it waits between one run and the next, in thousandths of a second (milliseconds): 1000 is one second, 250 a quarter of a second.

  • Enabled: True while it runs. Set it to False in the Properties window and the timer waits until your code sets it to True.

Each time the interval passes, DVX BASIC runs the timer’s Timer procedure, tmrTick_Timer for a timer called tmrTick. To write it, choose the timer in the Code window’s Object list. A timer is how a program shows a clock, moves a picture in a game, saves the user’s work every few minutes, or counts down, as the egg timer does.

12.8. An Egg Timer

The egg timer counts down the minutes you set, shows the time left and a bar that fills up, and beeps and says so when the time is up.

The Egg Timer window: Minutes 1 in the spin box
Figure 15. The egg timer at work
  1. Start a new project called EggTimer, with the Caption Egg Timer and the Height 200.

  2. Place an HBox, and in it a Label with the Caption &Minutes: and a SpinButton (the fourth tool in the sixth row) named spnMinutes.

  3. Below the row, place a Label named lblLeft with the Caption 3:00, a ProgressBar (the third tool in the fifth row) named prgTime, and a CommandButton named cmdStart with the Caption &Start.

  4. Click the Timer tool (the last one in the eighth row) and click the form. Nothing appears on the form, but the tray below it shows Timer1, and so does the Properties window. Name it tmrTick, set its Interval to 1000, and set its Enabled to False (select it and press Enter).

    The Egg Timer form in the designer
  5. In the form’s code, (General) gets the two numbers the procedures share, and a Sub that shows the time left:

    Dim secondsLeft As Long
    Dim secondsTotal As Long
    
    Sub ShowLeft ()
       Dim minutes As Long
       Dim seconds As Long
    
       minutes = secondsLeft \ 60
       seconds = secondsLeft Mod 60
       lblLeft.Caption = minutes & ":" & Format$(seconds, "00")
       prgTime.Value = 100 - secondsLeft * 100 \ secondsTotal
    End Sub

    secondsLeft \ 60 is the whole minutes left and secondsLeft Mod 60 the seconds after them (Section 4.2); Format$ with "00" writes the seconds with two digits, 3:05 and not 3:5. The bar is full when no seconds are left.

  6. The form’s Load procedure sets the spin button’s range and its starting value:

    Sub Form1_Load ()
       spnMinutes.SetRange 1, 60
       spnMinutes.Value = 3
    End Sub
  7. The Start button starts the timer, or stops it when it is running, and changes its own caption to match:

    Sub cmdStart_Click ()
       If tmrTick.Enabled Then
          ' Stop
          tmrTick.Enabled = False
          cmdStart.Caption = "&Start"
       Else
          secondsTotal = spnMinutes.Value * 60
          secondsLeft = secondsTotal
          ShowLeft
          tmrTick.Enabled = True
          cmdStart.Caption = "&Stop"
       End If
    End Sub
  8. Choose tmrTick in the Code window’s Object list. Its Timer procedure opens; it runs once a second while the timer is enabled:

    Sub tmrTick_Timer ()
       secondsLeft = secondsLeft - 1
       ShowLeft
       If secondsLeft = 0 Then
          tmrTick.Enabled = False
          cmdStart.Caption = "&Start"
          Beep
          MsgBox "Your eggs are ready!"
       End If
    End Sub

    Beep makes the computer beep. The timer stops itself before the message, so it does not go on counting below zero while the message waits for OK.

  9. Press F5, set 1 minute, and click Start.

The message Your eggs are ready! over the Egg Timer window
Figure 16. Time is up

12.9. Long Jobs

Some jobs take a while: counting the words of a long file, working out a big table, copying many files. While one event procedure runs, the program’s other events wait (Section 11.1): the window still shows what the code puts in it, but a click on a Stop button does nothing until the job is over, which is too late.

DoEvents is the answer. It lets the events that are waiting run now, and then the code goes on after it. A long loop that calls DoEvents every so often lets the user stop it. This program counts to ten million, showing how far it has come, with a Stop button that works:

The Counting window: the count so far
Figure 17. Counting, with Start grayed out until the job is done

The form has a Label lblCount, a ProgressBar prgDone, and an HBox with two buttons, cmdStart (Caption &Start) and cmdStop (Caption S&top). The code:

Dim stopNow As Boolean

Sub cmdStart_Click ()
   Dim i As Long

   stopNow = False
   cmdStart.Enabled = False
   For i = 1 To 10000000
      If i Mod 100000 = 0 Then
         lblCount.Caption = i
         prgDone.Value = i \ 100000
         ' Let the Stop button's click in
         DoEvents
         If stopNow Then
            Exit For
         End If
      End If
   Next i
   cmdStart.Enabled = True
End Sub

Sub cmdStop_Click ()
   stopNow = True
End Sub

Every 100,000 counts, the loop shows the count, moves the bar, and calls DoEvents. If the user has clicked Stop meanwhile, cmdStop_Click runs right there and sets stopNow, and the loop sees it and leaves. Start is grayed out while the job runs, so that it cannot be started a second time in the middle.

Call DoEvents often enough for the program to answer quickly, but not on every turn of a fast loop: it takes time of its own. A timer is the other way to do a long job: do one piece of it each time the timer fires, and the rest of the time the program is free.

12.10. Try It Yourself

  • Add an Extra large size to the pizza order: a fourth option button, optSize(3), for 14 dollars. Which lines of the code must change? (The loops say To optSize.UBound, so they take the new button in by themselves.)

  • Put a Clear Order button on the pizza order that empties the list and sets the total back to 0.

  • Make the egg timer play a little tune instead of beeping: Play "CDEFG" plays five notes (Chapter 19 has more).

  • Add an HScrollBar to the egg timer that shows how far the timer has run, instead of the progress bar. What should happen when the user drags it?

  • Make a clock: a form with a Label and a Timer whose Timer procedure shows Time$, the time of day, every second.

Chapter 13. Files and Settings

Everything a program keeps in its variables is gone when it ends. The high score list of Section 9.8 starts empty every time, and a shopping list that forgets its items is no use at all. To keep something until next time, a program writes it to a file on the disk, and reads it back when it starts. This chapter shows how, and how a program remembers the user’s settings, such as a choice they made last time.

The examples in the first sections are for the Practice project’s Module1 (Section 4.1).

13.1. Where Files Go

A file has a name, such as scores.txt, and lives in a folder; the whole path names both, with a backslash between each folder and the next: C:\DVX\USER\NOTES.TXT. Where should your program keep its files? DVX gives every program a folder of its own for them, inside the user folder, and the App object knows where:

Folder What it is for

App.User

Everything the program writes: its settings, its lists, saved games, documents. DVX makes the folder the first time the program uses App.User. It is kept apart from the program, so installing a new version of the program never touches it.

App.Path

The folder the program itself is in. Read from it if you like, but do not write there: on a CD-ROM, or a shared computer, the program’s folder cannot be written.

App.Data

The DATA folder in the program’s folder: files that come with the program, such as pictures or game levels, for reading.

Put the folder and the file’s name together with & and a backslash: App.User & "\scores.txt". (DVX also accepts / between folders, as many other systems write them; it shows paths with \.)

13.2. Writing and Reading a Text File

The simplest kind of file is a text file: lines of text, which any text editor, such as Notepad, can show. Writing one takes three steps: Open the file, Print # lines into it, and Close it. Reading one is the same with Line Input #:

Dim f As Integer
Dim fileName As String
Dim lineText As String

fileName = App.User & "\greeting.txt"

' Write two lines
f = FreeFile
Open fileName For Output As #f
Print #f, "Hello"
Print #f, "from a file"
Close #f

' Read them back
f = FreeFile
Open fileName For Input As #f
Do While Not EOF(f)
   Line Input #f, lineText
   Print lineText
Loop
Close #f
Hello
from a file
  • Open fileName For Output As #f makes the file, or empties it if it is there already, ready for writing. f is the file’s number: every statement that works on the file says which one with #f.

  • FreeFile gives a number no open file is using. A program can have up to 16 files open at once.

  • Print #f, ... writes a line to the file, exactly as Print would show it.

  • Close #f finishes the file. Until it is closed, some of what was written may not be on the disk yet, so always close a file when you are done with it.

  • Open ... For Input opens a file for reading. Line Input #f, lineText reads its next line into lineText, and EOF(f) (for end of file) is True once every line has been read, which is what the Do While Not EOF(f) loop waits for.

13.3. Adding to a File

For Output starts the file again from nothing. To add lines at the end of what is there, open it For Append; a file that is not there yet is made, as with For Output. This program adds a line each time round its loop, as if it were run three times:

Dim f As Integer
Dim n As Integer
Dim fileName As String
Dim lineText As String

fileName = App.User & "\visits.txt"

For n = 1 To 3
   f = FreeFile
   Open fileName For Append As #f
   Print #f, "Visit number " & n
   Close #f
Next n

f = FreeFile
Open fileName For Input As #f
Do While Not EOF(f)
   Line Input #f, lineText
   Print lineText
Loop
Close #f
Visit number 1
Visit number 2
Visit number 3

A program’s log, a diary, or a list of high scores that only grows are all files opened For Append.

13.4. Numbers and Text Together

A line of a text file is just text. To keep values apart, such as a name and a score, write them with Write # and read them back with Input #. Write # puts commas between the values and quotes around text, so a name with a comma in it comes back whole:

Dim f As Integer
Dim fileName As String
Dim lineText As String
Dim who As String
Dim points As Integer

fileName = App.User & "\scores.txt"

f = FreeFile
Open fileName For Output As #f
Write #f, "Ann", 95
Write #f, "Ben", 72
Write #f, "Cal, the Great", 88
Close #f

Print "The file holds:"
f = FreeFile
Open fileName For Input As #f
Do While Not EOF(f)
   Line Input #f, lineText
   Print lineText
Loop
Close #f

Print "Read back:"
f = FreeFile
Open fileName For Input As #f
Do While Not EOF(f)
   Input #f, who, points
   Print who; " scored"; points
Loop
Close #f
The file holds:
"Ann",95
"Ben",72
"Cal, the Great",88
Read back:
Ann scored 95 
Ben scored 72 
Cal, the Great scored 88 

Input #f, who, points reads one value into each variable, text into the String and a number into the Integer. Read the values in the order they were written.

13.5. Is the File There?

The first time a program runs, its files are not there yet. Dir$(path) gives the file’s name when it is there and "" when it is not, so a program can check before it reads:

Dim f As Integer
Dim fileName As String

fileName = App.User & "\notes.txt"
If Dir$(fileName) = "" Then
   Print "No notes yet."
End If

f = FreeFile
Open fileName For Output As #f
Print #f, "Buy milk"
Close #f

If Dir$(fileName) <> "" Then
   Print "notes.txt is"; FileLen(fileName); "bytes long."
End If

Kill fileName
If Dir$(fileName) = "" Then
   Print "And now it is gone."
End If
No notes yet.
notes.txt is 10 bytes long.
And now it is gone.

A program that opens a missing file For Input stops with Runtime error 53: File not found. Files go missing, disks fill up, and floppies are taken out, so a program that works with files should be ready for errors, with On Error (Section 10.5):

Dim f As Integer

On Error GoTo NoFile
f = FreeFile
Open App.User & "\missing.txt" For Input As #f
Print "It opened."
Close #f
End

NoFile:
Print "Could not open it: "; Err.Description
Could not open it: File not found

End ends the program at once; here it keeps the normal path out of the error handling below it.

DVX BASIC has a statement for most things you do with files in a file manager:

Statement Does

Kill path

Delete a file.

Name oldPath As newPath

Rename a file, or move it to another folder on the same disk.

FileCopy source, destination

Copy a file.

MkDir path, RmDir path

Make a folder, or remove an empty one.

FileLen(path)

The size of a file, in bytes.

Dir$(pattern), then Dir$

The first file whose name fits a pattern such as App.User & "\*.txt", then the next one each time, then "".

13.6. Remembering Settings

Programs remember the user’s choices: the size of the text, the last file opened, whether the list is sorted. DVX keeps its own settings in INI files, text files made of sections in square brackets and lines of the form name = value, and your program can do the same with two functions:

Dim settings As String
Dim f As Integer
Dim lineText As String

settings = App.User & "\settings.ini"
Print "Name: "; IniRead(settings, "Player", "Name", "(none yet)")

IniWrite settings, "Player", "Name", "Ann"
IniWrite settings, "Player", "Level", "3"
Print "Name: "; IniRead(settings, "Player", "Name", "(none yet)")
Print "Next level:"; Val(IniRead(settings, "Player", "Level", "1")) + 1

Print "The file holds:"
f = FreeFile
Open settings For Input As #f
Do While Not EOF(f)
   Line Input #f, lineText
   Print lineText
Loop
Close #f
Name: (none yet)
Name: Ann
Next level: 4 
The file holds:
[Player]
Name = Ann
Level = 3

IniRead(file, section, name, default) gives the setting’s value, or default when the file, the section, or the setting is not there yet, as the first time a program runs. IniWrite file, section, name, value sets it, making the file and the section when they are missing and keeping everything else in the file as it was. Settings are text: turn a number into text to store it (CStr(level)) and back into a number when you read it (Val).

13.7. A Shopping List That Remembers

This program keeps a shopping list. It saves the list to a file every time it changes, and reads it back when it starts, so the list is still there tomorrow. A check box sorts the list, and the program remembers that choice in a settings file.

The Shopping List window with an empty box
Figure 18. The shopping list on its second run: the items, and the Sorted choice, were saved the first time
  1. Start a new project called Shopping, with the Caption Shopping List.

  2. Place an HBox, and in it a TextBox named txtItem (no Text) and a CommandButton named cmdAdd with the Caption &Add and Default True, so Enter adds what was typed.

  3. Below the row, place a CheckBox named chkSorted with the Caption &Sorted, and a ListBox named lstItems with Weight 1.

  4. In the form’s code, (General) gets the names of the two files, and two Subs that read and write the list:

    Dim listFile As String
    Dim iniFile As String
    
    Sub LoadList ()
       Dim f As Integer
       Dim item As String
    
       If Dir$(listFile) = "" Then
          Exit Sub
       End If
       f = FreeFile
       Open listFile For Input As #f
       Do While Not EOF(f)
          Line Input #f, item
          lstItems.AddItem item
       Loop
       Close #f
    End Sub
    
    Sub SaveList ()
       Dim f As Integer
       Dim i As Integer
    
       f = FreeFile
       Open listFile For Output As #f
       For i = 0 To lstItems.ListCount - 1
          Print #f, lstItems.List(i)
       Next i
       Close #f
    End Sub

    SaveList writes every line of the list, from List(0) to List(ListCount - 1), into the file For Output, which replaces what the file held before: the file always holds the list as it is now.

  5. The form’s Load procedure (choose Form1 in the Object list) works out where the files are, puts the check box back as the user left it, and reads the list:

    Sub Form1_Load ()
       Dim saved As String
    
       listFile = App.User & "\shopping.txt"
       iniFile = App.User & "\shopping.ini"
       saved = IniRead(iniFile, "List", "Sorted", "False")
       chkSorted.Value = (saved = "True")
       LoadList
    End Sub

    saved = "True" is True or False, just what a check box’s Value takes. The setting is checked before the list is read, so the list is sorted as its lines come in.

  6. Double-click the check box. Its Click procedure sorts the list (or stops sorting the items added from now on) and saves the choice:

    Sub chkSorted_Click ()
       lstItems.Sorted = chkSorted.Value
       IniWrite iniFile, "List", "Sorted", CStr(chkSorted.Value)
    End Sub
  7. Double-click the Add button:

    Sub cmdAdd_Click ()
       If Trim$(txtItem.Text) <> "" Then
          lstItems.AddItem Trim$(txtItem.Text)
          SaveList
       End If
       txtItem.Text = ""
       txtItem.SetFocus
    End Sub
  8. A double-click on an item takes it off the list (choose lstItems, then [DblClick]):

    Sub lstItems_DblClick ()
       If lstItems.ListIndex >= 0 Then
          lstItems.RemoveItem lstItems.ListIndex
          SaveList
       End If
    End Sub
  9. Press F5, add a few things, tick Sorted, and close the window. Press F5 again: the list is back, sorted.

The Shopping List window with Milk
Figure 19. The first run, before Sorted is ticked

One thing to know about For Output: it empties the old file the moment it opens it. If the disk fills up while the new list is written, the old list is gone too. For a short list that is a small risk, but a program that saves the user’s documents should do better: [forms-menus-save] shows how a text editor saves a document safely.

13.8. Try It Yourself

  • Make the high score list of Section 9.8 remember its scores: save the players and their points with Write # after each new score, and read them back with Input # in Form1_Load.

  • Give the shopping list a Clear button that empties the list, after asking with MsgBox "Clear the whole list?", vbYesNo (the answer is vbYes or vbNo).

  • Write a program that counts how many times it has been started: read a number from a settings file, add 1, show it, and write it back.

  • Use Dir$ in a loop to list every .txt file in App.User in a ListBox.

Chapter 14. Menus and Dialog Boxes

A program with more than a few commands puts them in menus: File › Open…​, Edit › Copy, Help › About. And it talks to the user in small windows of their own, dialog boxes: a message with buttons, a question, a box for picking a file. This chapter shows how to give a form a menu bar, how to use the dialog boxes DVX has ready for you, and builds a small text editor, TinyPad, that opens and saves files.

14.1. Menus

A form’s menu bar runs across the top of its window. Each name on it, such as File, is a menu, and each line in a menu is a menu item. A line across a menu, a separator, groups the items. Menus are made with the Menu Editor: with the form in the designer, choose View › Menu Editor…​ (Ctrl+E).

The Menu Editor: Caption
Figure 20. The Menu Editor with TinyPad’s menus

The list in the middle shows the menus, in order, and the items of each menu indented under it with →. The boxes above the list are for the line selected:

Box What it is

Caption

The text the menu shows. An & makes the letter after it the access key: Alt+F opens &File, and N chooses &New when the menu is open. A caption of just - makes a separator.

Name

The name the code uses. DVX BASIC makes one from the caption, mnu and its letters (mnuSaveAs for Save &As...), so you seldom type one.

Shortcut

A key that chooses the item at once, without opening the menu, such as Ctrl+S or F5. The menu shows it beside the item.

Text

Key text the menu shows without making it a shortcut, for keys a control handles itself (see below).

Checked

A check mark in front of the item, for an item that is on or off.

Enabled

Cleared, the item is grayed and cannot be chosen.

To build the menus, type the caption of the first menu, &File, and click Next (Alt+N): a new line appears below, ready for the next caption. Type the first item, &New, and click → to indent it, which makes it an item of the File menu. Lines added with Next after that are indented the same, until you click ← for the next menu of the menu bar. Up and Dn move the selected line, Insert adds a line before it, and Delete removes it. Click OK when you are done, and the menu bar appears on the form in the designer.

Choosing a menu item runs its Click procedure, mnuNew_Click for mnuNew. To write one, choose the item’s name in the Code window’s Object list.

A shortcut works wherever the focus is on the form, before the control with the focus sees the key. That is right for Ctrl+S, which no control uses, but not for Ctrl+C: a text box copies with it itself. For such items, put the key in the Text box instead: the menu shows it, and the key is left to the control.

While the program runs, an item’s Enabled, Checked, Visible, and Caption properties can change: mnuSave.Enabled = False grays out Save, and mnuWrap.Checked = Not mnuWrap.Checked turns a check mark on or off.

14.2. Message Boxes

You have used MsgBox since your first program to show a message. It can also ask a question, with buttons, and tell the program which one the user clicked. Used that way it is a function, with its arguments in parentheses:

answer = MsgBox("Save your changes?", vbYesNoCancel + vbQuestion)
If answer = vbYes Then
   ' save, then go on
ElseIf answer = vbNo Then
   ' go on without saving
Else
   ' vbCancel: do nothing
End If

The second argument says which buttons and which picture the box has; add a set of buttons and a picture together with a plus sign. The third, if you give one, is the box’s title (without one, it is the program’s name):

Buttons Picture Answers

vbOKOnly (the default)

vbInformation (i)

vbOK

vbOKCancel

vbQuestion (?)

vbCancel

vbYesNo

vbExclamation (!)

vbYes

vbYesNoCancel

vbCritical (a stop sign)

vbNo

vbRetryCancel

vbRetry

Esc, or the box’s close button, answers vbCancel when the box has a Cancel button. To put a message on more than one line, put vbCrLf between the lines: MsgBox "Saved." & vbCrLf & "Bye!".

14.3. Asking for Text

InputBox$ asks the user to type something and gives back what was typed, or "" when they clicked Cancel:

what = InputBox$("Find what?", "Find", lastFind)

The first argument is the question, the second the box’s title, and the third the text the box starts with, already selected, so typing replaces it and Enter takes it as it is.

14.4. Libraries: More Dialog Boxes

DVX has more dialog boxes than MsgBox and InputBox$: for choosing a file to open or a name to save under, a folder, a color, or a font. They, and many other things DVX can do, come in libraries: files of BASIC declarations that give your program more functions. To use one, add it to the project with File › Add Library…​ and pick it from the list:

Library Gives your program

commdlg.bas

The common dialog boxes: Open, Save As, a folder, a color, a font, and message boxes with buttons of your own.

fileops.bas

Files and folders: listing them, copying and deleting whole folders, free disk space, and saving a document safely.

sql.bas

Databases (Chapter 18).

sound.bas, music.bas

Sound effects and music (Chapter 19).

print.bas

Printing (Chapter 20).

DVX BASIC copies the library into the project’s folder and lists it under Modules in the Project window, and the file you were working on stays in front. You never need to change a library’s text. Chapter 21 tells more about libraries, and “Include Libraries” in the DVX BASIC Language Reference lists them all, with everything each one gives.

With commdlg.bas in the project, these functions show the file dialog boxes:

Function Shows

DlgFileOpen$(title, filter)

An Open box, starting in the current folder.

DlgFileOpenIn$(title, filter, folder)

An Open box starting in folder.

DlgFileSaveAs$(title, filter, folder, name)

A Save box starting in folder, with name suggested ("" for none).

Each gives back the path of the file the user chose, or "" when they clicked Cancel. The filter lists the kinds of file the box offers, with | between them: "Text Files (.txt)|All Files (.*)" offers text files first and every file second. An Open box only takes a file that is there; a Save box asks before it gives back one that is there already.

14.5. TinyPad, a Text Editor

TinyPad edits text files, like DVX’s own Notepad. It has a File menu to start, open, and save files, an Edit menu with a search, and it asks before it throws away changes that were not saved.

TinyPad with text typed and its File menu open
Figure 21. TinyPad’s File menu

14.5.1. The Form and Its Menus

  1. Start a new project called TinyPad, with the Caption TinyPad.

  2. Place a TextArea (the second tool in the eighth row), name it txtDoc, and set its Text to nothing. It fills the form.

  3. Choose View › Menu Editor…​ and make these menus. Indent each item under its menu with →, and type its key in the Shortcut or the Text box as the table shows:

    Caption Shortcut Text

    &File

        &New

    Ctrl+N

        &Open...

    Ctrl+O

        &Save

    Ctrl+S

        Save &As...

        -

        E&xit

    &Edit

        Cu&t

    Ctrl+X

        &Copy

    Ctrl+C

        &Paste

    Ctrl+V

        -

        Select &All

    Ctrl+A

        &Find...

    Ctrl+F

    &Help

        &About TinyPad...

    Click OK. (An item’s ... says that it opens a dialog box before it does anything, a custom every program follows.)

  4. Choose File › Add Library…​, pick commdlg.bas, and click OK. Do the same for fileops.bas.

14.5.2. The Code

Press F7 for the form’s code. In (General), the filter for the file boxes and three shared variables: the path of the file being edited ("" until it has one), whether the text has changed since it was saved, and the last text searched for:

Const TEXT_FILES = "Text Files (*.txt)|All Files (*.*)"

Dim docPath As String
Dim changed As Boolean
Dim lastFind As String

Below them, a Sub that shows the file’s name and a * for unsaved changes in the title bar, as DVX’s programs do. InStrRev is InStr from the right end of the text: the position of the last backslash, after which the file’s name starts.

Sub ShowTitle ()
   Dim title As String

   If docPath = "" Then
      title = "Untitled"
   Else
      ' The file's name, without its folder
      title = Mid$(docPath, InStrRev(docPath, "\") + 1)
   End If
   If changed Then
      title = title & " *"
   End If
   Me.Caption = title & " - TinyPad"
End Sub

Saving takes two Functions, which call each other. SaveDoc saves under the file’s name, or asks for one with SaveAs when it has none yet; SaveAs asks for a name and saves with SaveDoc. Each gives back True when the text was saved:

Function SaveDoc () As Boolean
   Dim failure As Long

   If docPath = "" Then
      SaveDoc = SaveAs()
      Exit Function
   End If
   failure = FileOpsSaveText(docPath, txtDoc.Text & vbLf)
   If failure <> 0 Then
      MsgBox Error$(failure), vbExclamation, "Could Not Save"
      SaveDoc = False
   Else
      changed = False
      ShowTitle
      SaveDoc = True
   End If
End Function

Function SaveAs () As Boolean
   Dim path As String

   path = DlgFileSaveAs$("Save As", TEXT_FILES, App.User, "")
   If path = "" Then
      SaveAs = False
   Else
      docPath = path
      SaveAs = SaveDoc()
   End If
End Function

FileOpsSaveText, from fileops.bas, saves the text safely: it writes the new file beside the old one and swaps them only when the new one is complete, so a full disk or a write-protected floppy leaves the old file as it was. It gives back 0 when the file is saved, or the number of the error that stopped it, and Error$(number) is that error’s message. A TextArea’s lines end in a line feed, vbLf, and FileOpsSaveText writes each line end as a DOS text file has it; the & vbLf ends the last line too.

OkToLose decides whether the text may be thrown away: when it has changed, it asks.

Function OkToLose () As Boolean
   Dim style As Integer
   Dim answer As Integer

   OkToLose = True
   If changed Then
      style = vbYesNoCancel + vbQuestion
      answer = MsgBox("Save your changes?", style)
      If answer = vbYes Then
         OkToLose = SaveDoc()
      ElseIf answer = vbCancel Then
         OkToLose = False
      End If
   End If
End Function

Opening reads the file a line at a time, as in Section 13.2, and puts the lines together with vbLf between them:

Sub LoadDoc (path As String)
   Dim f As Integer
   Dim lineText As String
   Dim text As String

   On Error GoTo Failed
   f = FreeFile
   Open path For Input As #f
   Do While Not EOF(f)
      Line Input #f, lineText
      text = text & lineText & vbLf
   Loop
   Close #f
   ' Without the line end after the last line
   If text <> "" Then
      text = Left$(text, Len(text) - 1)
   End If
   txtDoc.Text = text
   docPath = path
   changed = False
   ShowTitle
   Exit Sub

   Failed:
   MsgBox "Could not open: " & Err.Description, vbExclamation
End Sub

Now the event procedures. Choose each name in the Code window’s Object list (Form1, txtDoc, then the menu items) and type its procedure:

Sub Form1_Load ()
   ShowTitle
End Sub

Sub txtDoc_Change ()
   If Not changed Then
      changed = True
      ShowTitle
   End If
End Sub

Sub mnuNew_Click ()
   If OkToLose() Then
      txtDoc.Text = ""
      docPath = ""
      changed = False
      ShowTitle
   End If
End Sub

Sub mnuOpen_Click ()
   Dim path As String

   If OkToLose() Then
      path = DlgFileOpenIn$("Open", TEXT_FILES, App.User)
      If path <> "" Then
         LoadDoc path
      End If
   End If
End Sub

Sub mnuSave_Click ()
   SaveDoc
End Sub

Sub mnuSaveAs_Click ()
   SaveAs
End Sub

Sub mnuExit_Click ()
   Unload Me
End Sub

SaveDoc and SaveAs are Functions, but a Function can be called on its own line like a Sub when the program does not need its value.

A form’s QueryUnload event comes just before it closes, whether the user clicked its close button, pressed Alt+F4, or the code said Unload Me. Setting Cancel to 1 keeps it open. Choose Form1 in the Object list and [QueryUnload] in the Function list:

Sub Form1_QueryUnload (Cancel As Integer, UnloadMode As Integer)
   If Not OkToLose() Then
      Cancel = 1
   End If
End Sub

The Edit menu’s items let the TextArea do the work, with its own methods:

Sub mnuCut_Click ()
   txtDoc.Cut
End Sub

Sub mnuCopy_Click ()
   txtDoc.Copy
End Sub

Sub mnuPaste_Click ()
   txtDoc.Paste
End Sub

Sub mnuSelectAll_Click ()
   txtDoc.SelectAll
End Sub

Find asks for the text with InputBox$, and a TextArea’s FindNext looks for it after the cursor and selects it. Its two other arguments say whether capitals must match (False: they need not) and whether to search forward (True). When nothing is found after the cursor, the search starts again from the top:

Sub mnuFind_Click ()
   Dim what As String

   what = InputBox$("Find what?", "Find", lastFind)
   If what = "" Then
      Exit Sub
   End If
   lastFind = what
   If Not txtDoc.FindNext(what, False, True) Then
      ' Not after the cursor: from the top
      txtDoc.SelStart = 0
      If Not txtDoc.FindNext(what, False, True) Then
         MsgBox "Cannot find " & what & ".", vbInformation
      End If
   End If
End Sub
TinyPad showing note.txt with the word from selected
Figure 22. Find has found the word

A click with the right mouse button opens the Edit menu where the mouse is, as a popup menu. Choose txtDoc and [MouseUp]:

Sub txtDoc_MouseUp (Button As Integer, Shift As Integer, X As Single, Y As Single)
   If Button = vbRightButton Then
      PopupMenu mnuEdit
   End If
End Sub

And Help’s only item:

Sub mnuAboutTinyPad_Click ()
   Dim msg As String

   msg = "TinyPad" & vbCrLf & "A small text editor."
   MsgBox msg, vbInformation, "About TinyPad"
End Sub

Press F5. Type some text, save it with Ctrl+S, start a new one with Ctrl+N, and open the first one again. Change it and close the window: TinyPad asks.

TinyPad with the message Save your changes? and the buttons Yes
Figure 23. Closing with changes not saved

14.6. Try It Yourself

  • Gray out File › Save while there is nothing to save: set mnuSave.Enabled = changed in ShowTitle.

  • Add a Edit › Find Next item with the shortcut F3 that searches for lastFind again without asking.

  • Add a Format menu with a Format › Font…​ item that lets the user choose the TextArea’s font with DlgFont from commdlg.bas. Give DlgFont the flag DLG_FONT_FIXED, so it offers only the fonts a TextArea can show (“Include Libraries” in the DVX BASIC Language Reference describes DlgFont).

  • Make TinyPad remember the last file it opened, with IniWrite (Section 13.6), and open it again when it starts.

Chapter 15. Programs with More Than One Form

Most programs have more than one window: a main window, and dialog boxes for questions that need more than a message box can ask, options, an About box. Each is a form of its own in the project. This chapter shows how to add forms, show and hide them, pass values between them, and share code among them, and builds an address book with a dialog box of its own.

15.1. Adding a Form

Choose File › New Form. DVX BASIC adds Form2 to the project and opens it in the designer, empty, ready for its controls. The Project window lists every form of the project under Forms: to work on another one, double-click its name there. (If the Project window is behind another window, Window › Project Explorer brings it to the front.)

When the program starts, DVX BASIC shows only its startup form, Form1 unless you choose another in File › Project Properties…​. The program shows its other forms itself, when it needs them.

15.2. Showing, Hiding, and Unloading

A form is shown with its Show method, and there are two ways to show it:

Statement Does

Form2.Show

Shows the form, and the code goes on at once. The user can work in either window: a modeless form, like a Find box that stays open beside the text.

Form2.Show vbModal

Shows the form as a modal dialog box: the user must finish with it before going back to the other windows, and the code after Show waits until the form is hidden or closed. A dialog box that asks something works this way.

Form2.Hide

Hides the form. It is still loaded: its controls keep what is in them, ready to read.

Unload Form2

Closes the form and frees its controls.

The first use of a form loads it, which runs its Load procedure; showing it again after Hide does not load it again. Each time a form comes to the front with the keyboard, its Activate procedure runs: the place to put the cursor where the user should start typing.

A program ends when its last loaded form is unloaded. A hidden form is still loaded, so a program whose main window is closed while a dialog box is hidden keeps running, unseen. Unload a dialog box when you are done with it.

15.3. Using One Form from Another

The code of one form can use another form’s controls and properties: put the form’s name in front, Form2.txtName.Text = "Ann", Form2.Caption = "New Contact". That is how a program fills in a dialog box before it shows it, and reads what the user typed afterwards.

A variable a form’s code declares Public, instead of Dim, can be used from the other forms too, as if it were a property of the form: with Public accepted As Boolean in Form2’s code, `Form1 can set and read Form2.accepted. A form’s Subs and Functions can be called the same way, Form2.Refill, unless they are declared Private.

15.4. Code Every Form Shares: Modules

Code that several forms need belongs in a module of its own: File › New Module adds one. A module’s Subs and Functions can be called from every form by their names alone. A module’s variables made with Dim are its own; to share a variable with the forms, declare it Public at the top of the module:

' Module1
Public userName As String          ' every form sees it

Public Function Greeting () As String
   Greeting = "Hello, " & userName & "!"
End Function

With that, any form can say userName = Text1.Text or Label1.Caption = Greeting(). Keep Public for what really is shared: a variable only one form uses is easier to follow in that form’s code.

15.5. An Address Book

The address book keeps a list of names and phone numbers. Its Add…​ and Edit…​ buttons show a second form, a dialog box with a box for the name and one for the number; Delete asks first, with a message box.

The New Contact dialog box
Figure 24. Adding a contact: the address book’s own dialog box

15.5.1. The Main Form

  1. Start a new project called Contacts, with the Caption Contacts.

  2. Place an HBox and in it three CommandButtons: cmdAdd (Caption &Add...), cmdEdit (&Edit...), and cmdDelete (&Delete).

  3. Below the row, place a ListBox named lstContacts and set its Weight to 1.

15.5.2. The Dialog Box

  1. Choose File › New Form. Set Form2’s Caption to `Contact and its Height to 200.

  2. Give it the rows of the sign-up form of Section 11.5: a row with a Label &Name: and a TextBox txtName, a row with a Label &Phone: and a TextBox txtPhone (both with no Text), and a row at the right with cmdOK (Caption OK, Default True) and cmdCancel (Caption Cancel, Cancel True).

    The Contact form in the designer: the Name and Phone rows and the OK and Cancel buttons at the right
  3. Press F7. In (General), the variable that tells the main form which button was clicked:

    Public accepted As Boolean
  4. The buttons set it and hide the form, which lets the main form’s code go on after its Show vbModal:

    Sub cmdOK_Click ()
       accepted = True
       Hide
    End Sub
    
    Sub cmdCancel_Click ()
       accepted = False
       Hide
    End Sub

    In a form’s own code, its properties and methods need no form name: Hide hides Form2.

  5. Choose Form2 in the Object list and [Activate] in the Function list. Each time the dialog box appears, the cursor goes to the name, with the name selected so that typing replaces it:

    Sub Form2_Activate ()
       ' Start in the name, selected, so typing replaces it
       txtName.SetFocus
       txtName.SelStart = 0
       txtName.SelLength = Len(txtName.Text)
    End Sub

    SelStart is where the selection starts (0: before the first character), and SelLength how many characters it holds.

15.5.3. The Main Form’s Code

Back in the Project window, double-click Form1.frm, and press F7. The contacts are kept in two arrays that grow (Section 9.4), side by side, and a count:

Dim names() As String
Dim phones() As String
Dim count As Integer

The Function that shows the dialog box does all the talking to Form2. It fills in the boxes, shows the form modally, and when the user clicked OK it gives back True and the new name and number in its parameters, which change the caller’s variables (Section 7.4):

Function AskContact (who As String, phone As String) As Boolean
   If who = "" Then
      Form2.Caption = "New Contact"
   Else
      Form2.Caption = "Edit Contact"
   End If
   Form2.txtName.Text = who
   Form2.txtPhone.Text = phone
   Form2.accepted = False
   Form2.Show vbModal
   ' Here once Form2 is hidden or closed
   If Form2.accepted Then
      who = Form2.txtName.Text
      phone = Form2.txtPhone.Text
      AskContact = True
   End If
   Unload Form2
End Function

Form2.accepted = False comes first in case the user closes the dialog box with its close button, which unloads it without either button’s code running. And Unload Form2 at the end, so a hidden dialog box never keeps the program running.

A Sub fills the list from the arrays:

Sub ShowList ()
   Dim i As Integer

   lstContacts.Clear
   For i = 1 To count
      lstContacts.AddItem names(i) & "   " & phones(i)
   Next i
End Sub

The three buttons:

Sub cmdAdd_Click ()
   Dim who As String
   Dim phone As String

   If AskContact(who, phone) Then
      count = count + 1
      ReDim Preserve names(1 To count)
      ReDim Preserve phones(1 To count)
      names(count) = who
      phones(count) = phone
      ShowList
   End If
End Sub

Sub cmdEdit_Click ()
   Dim i As Integer

   i = lstContacts.ListIndex + 1
   If i > 0 Then
      If AskContact(names(i), phones(i)) Then
         ShowList
      End If
   End If
End Sub

Sub cmdDelete_Click ()
   Dim i As Integer
   Dim j As Integer

   i = lstContacts.ListIndex + 1
   If i = 0 Then
      Exit Sub
   End If
   If MsgBox("Delete " & names(i) & "?", vbYesNo) = vbYes Then
      For j = i To count - 1
         names(j) = names(j + 1)
         phones(j) = phones(j + 1)
      Next j
      count = count - 1
      ShowList
   End If
End Sub

Edit…​ hands AskContact the very array elements of the contact: when the user clicks OK, they are changed right where they are. Delete moves every contact after the deleted one up by one place, and counts one fewer.

And a double-click on a contact edits it, by running Edit…​'s own procedure (choose lstContacts, then [DblClick]):

Sub lstContacts_DblClick ()
   cmdEdit_Click
End Sub

Press F5, add a few people, and change one with a double-click.

The Contacts window with the Add
Figure 25. The address book after a contact was renamed

15.6. Try It Yourself

  • Make OK in the dialog box refuse an empty name: show a message and leave the dialog box open (Exit Sub before Hide).

  • Save the contacts to a file when the program ends (the main form’s Unload event) and read them back in Form1_Load, with Write # and Input # (Section 13.4).

  • Add an About box: a third form with a Label and an OK button, shown with Show vbModal from a ? button on the main form.

  • Show the dialog box modeless (Form2.Show without vbModal) and see what goes wrong: the code after Show goes on at once, before the user has typed anything.

Chapter 16. Drawing and Pictures

Programs draw: charts, games, diagrams, a signature. DVX BASIC draws with a handful of statements that put points, lines, boxes, circles, and text where you say, in the colors you choose. This chapter shows them, draws a picture with them, builds a sketch pad you draw on with the mouse, and shows how to show pictures from files.

16.1. Where to Draw

Drawings go on a PictureBox, a control that is a blank drawing surface (the second tool in the fifth row of the Toolbox). Its drawing is a grid of dots, pixels. Each pixel has two numbers, its coordinates: how far across it is (x) and how far down (y), counting from 0 at the top-left corner. So (0, 0) is the top-left pixel, (10, 0) is ten pixels to its right, and (0, 10) ten pixels below it. Unlike in a math book, y grows downwards.

A new PictureBox’s drawing is 64 pixels square. picScene.Resize 300, 200 makes it 300 pixels wide and 200 high (and clears it to white); ScaleWidth and ScaleHeight tell how big it is. The control grows with its drawing.

A form can be drawn on too, with the same statements without the control’s name. A form’s drawing covers the whole form, behind its controls, which are drawn over it, and it grows with the window. A PictureBox keeps a drawing in a place of its own among the form’s controls.

16.2. Colors

Every color on the screen is a mix of red, green, and blue light. RGB(red, green, blue) makes a color from the three, each from 0 (none) to 255 (all it can give): RGB(255, 0, 0) is red, RGB(255, 255, 0) yellow (red and green light together), RGB(0, 0, 0) black, RGB(255, 255, 255) white, and RGB(160, 200, 255) the light blue of a sky. The most common colors have names:

vbBlack vbRed vbGreen vbBlue

vbYellow

vbMagenta

vbCyan

vbWhite

A color is a number (a Long), so a variable can hold one: Dim penColor As Long.

16.3. Points, Lines, Boxes, and Circles

The drawing statements are methods of the PictureBox, written after its name:

Statement Draws

picScene.PSet (x, y), color

One point.

picScene.Line (x1, y1)-(x2, y2), color

A line from one point to another.

picScene.Line -(x2, y2), color

A line on from where the last drawing ended.

picScene.Line (x1, y1)-(x2, y2), color, B

A box with those two corners.

picScene.Line (x1, y1)-(x2, y2), color, BF

A box filled with the color.

picScene.Circle (x, y), radius, color

A circle around a center point.

picScene.Cls

Nothing: it clears the drawing to its background color.

Without a color, they draw in the PictureBox’s ForeColor. A few properties change how they draw:

  • DrawWidth is the width of the pen, in pixels (1 to start with).

  • FillStyle set to vbFSSolid (0) fills circles and boxes with FillColor; vbFSTransparent (1, the start) leaves them empty.

  • BackColor is the color Cls clears to.

picScene.Print "Hello" writes text in the drawing, with its top-left corner at CurrentX, CurrentY. Every drawing statement leaves these at the last point it drew, so set them first to put text where you want it.

16.4. When to Draw: the Paint Event

A PictureBox’s drawing stays until you clear it or change its size. The best place for a drawing that is always the same is the PictureBox’s Paint event, which happens when the form appears, when the PictureBox changes size, and when your code calls its Refresh method: whatever happens, the drawing is there.

This program draws a house in the sun:

A window titled My House with a picture: a light blue sky
Figure 26. A picture drawn with lines, boxes, and a circle
  1. Start a new project called Scene, with the Caption My House.

  2. Place a PictureBox and name it picScene.

  3. Choose Form1 in the Code window’s Object list, and in Form1_Load give the drawing its size:

    Sub Form1_Load ()
       picScene.Resize 300, 200
    End Sub
  4. Choose picScene in the Object list and [Paint] in the Function list:

    Sub picScene_Paint ()
       ' The sky and the grass
       picScene.Line (0, 0)-(299, 139), RGB(160, 200, 255), BF
       picScene.Line (0, 140)-(299, 199), RGB(60, 160, 60), BF
    
       ' The sun: a circle filled with yellow
       picScene.FillStyle = vbFSSolid
       picScene.FillColor = vbYellow
       picScene.Circle (250, 40), 25, vbYellow
    
       ' The house, its door, and its roof
       picScene.Line (60, 90)-(160, 160), RGB(200, 80, 60), BF
       picScene.Line (95, 120)-(125, 160), RGB(100, 50, 20), BF
       picScene.Line (50, 90)-(110, 40), vbBlack
       picScene.Line -(170, 90), vbBlack
    
       ' And a caption
       picScene.CurrentX = 190
       picScene.CurrentY = 170
       picScene.Print "My house"
    End Sub
  5. Press F5.

The sky is a filled box across the top 140 rows of pixels, from (0, 0) to (299, 139); the last pixel of a 300-pixel-wide drawing is number 299. The grass fills the rest. The roof is two lines: the second, Line -(170, 90), goes on from where the first ended.

16.5. Drawing with the Mouse

A PictureBox’s MouseDown event happens when a mouse button goes down over it, and MouseMove each time the mouse moves over it. Both are told which buttons are down (Button), which of Shift, Ctrl, and Alt are held (Shift), and where the mouse is (X and Y), in the drawing’s coordinates: pixels, unless the program has changed the drawing’s scale (its ScaleMode). A sketch pad needs nothing more: when the button goes down, remember the point; each time the mouse moves with the button down, draw a line from the remembered point to the new one, and remember that one.

The Sketch Pad window: Black
Figure 27. Drawing with the mouse
  1. Start a new project called Sketch, with the Caption Sketch Pad, the Width 440, and the Height 400.

  2. Place an HBox, and in it four OptionButtons captioned Black, Red, Green, and Blue, as the control array optColor (Section 12.4).

  3. Below it, another HBox with a Label &Width:, a SpinButton named spnWidth, and two CommandButtons, cmdClear (&Clear) and cmdSave (&Save).

  4. Below the rows, a PictureBox named picPad.

  5. The code, in (General): the pen’s color and the point the pen was last at:

    Dim penColor As Long
    Dim lastX As Integer
    Dim lastY As Integer
  6. The form’s Load procedure makes the drawing big, sets up the width box, and chooses black:

    Sub Form1_Load ()
       picPad.Resize 400, 240
       spnWidth.SetRange 1, 20
       spnWidth.Value = 2
       optColor(0).Value = True
    End Sub
  7. The colors and the width:

    Sub optColor_Click (Index As Integer)
       Select Case Index
          Case 0
             penColor = vbBlack
          Case 1
             penColor = vbRed
          Case 2
             penColor = RGB(0, 160, 0)
          Case 3
             penColor = vbBlue
       End Select
    End Sub
    
    Sub spnWidth_Change ()
       picPad.DrawWidth = spnWidth.Value
    End Sub

The drawing itself is two event procedures of picPad (choose [MouseDown] and [MouseMove] in the Function list):

Sub picPad_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)
   lastX = X
   lastY = Y
   picPad.PSet (X, Y), penColor
End Sub

Sub picPad_MouseMove (Button As Integer, Shift As Integer, X As Single, Y As Single)
   If Button = vbLeftButton Then
      picPad.Line (lastX, lastY)-(X, Y), penColor
      lastX = X
      lastY = Y
   End If
End Sub

Button says which mouse buttons are down: vbLeftButton while the left one is. Without that check, the program would draw whenever the mouse merely passed over the pad. (Shift adds up vbShiftMask (1), vbCtrlMask (2), and vbAltMask (4) for the keys held, should a program want the pen to do something else with Shift down.)

The two buttons:

Sub cmdClear_Click ()
   picPad.Cls
End Sub

Sub cmdSave_Click ()
   If picPad.Save(App.User & "\sketch.png") = 0 Then
      MsgBox "Saved as sketch.png."
   Else
      MsgBox "Could not save the picture.", vbExclamation
   End If
End Sub

Save writes the drawing to a picture file, a PNG file unless the name ends in .bmp, and gives back 0 when it worked. Any picture viewer, DVX’s own Image Viewer among them, shows the file.

16.6. Pictures from Files

To show a picture from a file (a BMP, PNG, JPEG, or GIF file), use an Image control (the third tool in the third row) and set its Picture property to the file: in the Properties window, where Browse…​ beside the box picks the file, or in code:

imgLogo.Picture = LoadPicture(App.Data & "\logo.png")

The Image control takes the picture’s size; with Stretch set to True, a picture bigger than the control is shrunk to fit. A PictureBox shows pictures too, with the same Picture property, and its drawing statements then draw on the picture: arrows on a map, a score over a game’s background.

A program’s own pictures belong in a folder called DATA in its project’s folder: App.Data names it while the program runs, and the program’s package takes it along (Chapter 29). picScene.PaintPicture LoadPicture("ship.png"), x, y copies a picture into a drawing at a point of your choice, which is how a game moves its pieces about (Chapter 19).

16.7. Try It Yourself

  • Add a tree to the house picture: a brown box for the trunk and a green filled circle on top.

  • Draw a bar chart: a Function that draws a bar for each number of an array, as tall as the number, with the number printed above it.

  • Give the sketch pad a Fill check box: when it is ticked, a click draws a filled circle of the pen’s color, DrawWidth times 5 across, instead of starting a line.

  • Make the sketch pad read the picture it saved back when it starts, with picPad.Load(App.User & "\sketch.png"), so the drawing is still there next time.

Chapter 17. Objects and Class Modules

You have been using objects since your first program. A TextBox is one: it has properties (Text, Enabled), it can do things when you ask (SetFocus, its methods), and it tells you when something happens (Change, its events). A class module lets you make objects of your own, with the properties, methods, and events you give them. This chapter makes a bank account class and uses it.

17.1. Why Objects?

A program about a bank could keep its accounts in arrays, as the address book kept its contacts: one array of names, one of balances. Every procedure that changes a balance then has to know how the arrays work, and it is easy for one to forget a rule, such as not taking out more than the account holds.

An object keeps its data and the code that looks after that data together. An Account object holds its own name and balance, and the only way to change the balance is through the account’s own methods, Deposit and Withdraw, which keep the rules. The rest of the program says what it wants, ann.Withdraw 30, and the account decides whether it can.

A class is the plan; the objects made from it are its instances. One Account class can make as many accounts as the program needs, each with its own name and balance, as one TextBox tool puts as many text boxes on a form as you like.

17.2. A Class Module

To try classes, start a project without a form, like the Practice project of Section 4.1: start a new project called Bank, remove Form1.frm from it, and add a module with File › New Module. Then:

  1. Choose File › New Class Module. DVX BASIC adds Class1.cls under Classes in the Project window and opens it.

  2. A class’s name is the name of its kind of object. Select Class1.cls in the Project window, choose File › Rename File…​, and type Account. The class is called Account now.

  3. Type the class’s code below its Option Explicit line, in the parts shown in the rest of this chapter.

First, the account’s own data, its member variables: every Account object gets its own copy of them. They are Private, so only the class’s own code can use them:

Private mName As String
Private mBalance As Currency

mName and mBalance start with m for member, a custom that tells them apart from the names other code uses.

17.3. Properties

A property of your own is a pair of procedures: Property Get gives its value when code reads it, and Property Let gets the new value when code sets it. So the class can check or change a value on its way in:

Public Property Get Name () As String
   Name = mName
End Property

Public Property Let Name (ByVal text As String)
   ' Without spaces at its ends
   mName = Trim$(text)
End Property

ann.Name = " Ann " runs Property Let Name with " Ann " as text, and the account keeps "Ann". Print ann.Name runs Property Get Name.

A property with only a Property Get can be read but not set: nobody outside the class can change a balance by just storing a new one.

Public Property Get Balance () As Currency
   Balance = mBalance
End Property

17.4. Methods

The class’s Public Subs and Functions are its methods. Deposit adds money; Withdraw takes it out only when there is enough, and says whether it did:

Public Sub Deposit (ByVal amount As Currency)
   mBalance = mBalance + amount
End Sub

Public Function Withdraw (ByVal amount As Currency) As Boolean
   If amount > mBalance Then
      RaiseEvent Overdrawn(amount - mBalance)
      Withdraw = False
   Else
      mBalance = mBalance - amount
      Withdraw = True
   End If
End Function

RaiseEvent tells whoever is listening that the account was overdrawn; Section 17.7 shows how. The class declares the event at its top:

Public Event Overdrawn (ByVal missing As Currency)

17.5. Making and Using Objects

An object variable is declared with the class’s name as its type. It holds no object until New makes one:

Dim a As Account       ' no account yet: a is Nothing
Set a = New Account    ' now it holds a new account
Dim b As New Account   ' declared and made at once

Objects are given to variables with Set. Set b = a does not copy the account: both variables then refer to the same one, and a deposit through either shows in both. An object goes away, by itself, when no variable refers to it any more; Set a = Nothing lets go of it.

In the project’s Module1, make two accounts and use them:

Dim WithEvents ann As Account
Dim ben As New Account

Set ann = New Account
ann.Name = "  Ann  "
ann.Deposit 100
ben.Name = "Ben"
ben.Deposit 20

Print ann.Name; " has"; ann.Balance
Print ben.Name; " has"; ben.Balance

If ann.Withdraw(30) Then
   Print ann.Name; " took out 30 and has"; ann.Balance
End If
If Not ann.Withdraw(500) Then
   Print ann.Name; " still has"; ann.Balance
End If

(ann is declared WithEvents so that this module can listen to her account’s events; see below.) Each account keeps its own name and balance, and code outside the class uses only the members the class makes Public: writing ann.mBalance = 1000000 does not even compile.

17.6. Many Objects

A program with many objects keeps them in an array of the class’s type, or in a Collection (Section 9.7), which holds objects as well as it holds numbers:

Dim bank As New Collection
Dim acct As Variant
Dim total As Currency

bank.Add ann
bank.Add ben
For Each acct In bank
   total = total + acct.Balance
Next acct
Print "The bank holds"; total

For Each gives acct each account in turn, and acct.Balance is that account’s balance.

17.7. Events of Your Own

A class can have events, as controls do. It declares each one with Event and its parameters, and its code raises it with RaiseEvent when that something happens. Code that wants to hear an object’s events declares its variable WithEvents, and writes a procedure named after the variable and the event, as for a control:

Sub ann_Overdrawn (ByVal missing As Currency)
   Print "Ann is"; missing; "short!"
End Sub

When Withdraw raises Overdrawn for Ann’s account, ann_Overdrawn runs, with missing set to what the account was short of, and then Withdraw goes on. The account does not need to know who listens, or what they do about it: a form might show a message, a log might write a line. A WithEvents variable in a form’s code is chosen in the Code window’s Object list, and its events in the Function list, as for a control.

Running the program prints:

Ann has 100 
Ben has 20 
Ann took out 30 and has 70 
Ann is 430 short!
Ann still has 70 
The bank holds 90 

17.8. When Objects Start and End

A class can have two procedures that run on their own: Class_Initialize when an object is made, the place to give its member variables their starting values, and Class_Terminate when it goes away. Both are `Private Sub`s without parameters:

Private Sub Class_Initialize ()
   mName = "(no name)"
End Sub

“Objects and Class Modules” in the DVX BASIC Language Reference describes everything a class can do, including properties that hold objects (Property Set), Implements, and default members.

17.9. Try It Yourself

  • Add a Transfer method to Account that moves an amount to another account given as a parameter (ByVal toAccount As Account), using Withdraw and Deposit.

  • Give Account a Class_Initialize that starts every account with a 5-dollar welcome bonus, and check that ben now has 25.

  • Write a Die class with a Roll method that gives a random number from 1 to its Sides property (6 to start with), and roll a 6-sided and a 20-sided die ten times each.

  • Make a form with a ListBox of accounts and buttons to deposit and withdraw with an InputBox$, keeping the accounts in a Collection, and show a message box when one is overdrawn.

Chapter 18. Databases

A text file is fine for a short list. For a long one that the program searches, sorts, and changes, a database is better: it finds the rows you ask for at once, keeps them in any order you ask for, and changes one row without writing the whole file again. DVX has SQLite, a small database that keeps everything in one file, and a language for talking to it, SQL. This chapter shows the SQL you need, uses it from a program, and then shows two controls that show a database with no code at all.

Databases are an optional part of DVX. If the Toolbox has no Data and DBGrid tools, the Databases part is not installed: run Setup again, choose Upgrade or repair DVX, and check Databases (the DVX User’s Guide tells more).

18.1. Tables, Rows, and SQL

A database holds tables. A table is like a list on squared paper: each row is one thing, a book, and each column one fact about it, its title or its author. SQL (Structured Query Language, said "sequel" or "S-Q-L") is a language of short statements that tell the database what to do. These five are most of what a program needs:

SQL Does

CREATE TABLE books (title TEXT, author TEXT)

Makes a table with two columns of text.

INSERT INTO books (title, author) VALUES ('Emma', 'Jane Austen')

Adds a row.

SELECT title, author FROM books ORDER BY title

Gives every row’s title and author, in title order.

UPDATE books SET author = 'J. Austen' WHERE title = 'Emma'

Changes the rows that match.

DELETE FROM books WHERE title = 'Emma'

Removes the rows that match.

Text in SQL goes between single quotes. WHERE picks rows: WHERE author = 'Jane Austen', or WHERE title LIKE 'The%' for titles starting with The (% stands for any text). ORDER BY sorts; ORDER BY title DESC sorts backwards. SELECT * gives every column. SQLite understands much more; its own documentation, on the web at sqlite.org, describes all of it.

18.2. SQL from BASIC

A program talks to a database through the functions of the sql.bas library: add it with File › Add Library…​ (Section 14.4).

Function Does

db = SQLOpen(path)

Opens a database file, making it when it is not there. Gives back a number for it, 0 when it could not.

SQLExec db, sql

Runs a statement that gives back no rows: CREATE, INSERT, UPDATE, DELETE.

rs = SQLQuery(db, sql)

Runs a SELECT and gives back a number for its rows, its result.

SQLNext(rs)

Moves to the result’s next row; False when there are no more.

SQLField$(rs, column)

The value in the current row’s column, as text.

SQLFreeResult rs

Frees a result when the program is done with it.

SQLClose db

Closes the database.

SQLError$(db)

Why the last thing that failed did.

SQLEscape$(text)

The text with every single quote doubled, ready to go between quotes in a statement.

SQLEscape$ matters for text the user typed: a title such as Charlotte’s Web has a quote of its own, which would end the SQL text early. SQLEscape$ writes it Charlotte''s Web, which SQL reads back as one quote.

18.3. A Book List

This program keeps a list of books in a database: add a title and an author, and the list shows every book in title order, also the next time the program runs.

The Books window with Title and Author boxes
Figure 28. The book list, kept in a database
  1. Start a new project called Books. Give Form1 the Caption Books and, as in the sign-up form of Section 11.5, a row with a Label &Title: and a TextBox txtTitle, a row with a Label &Author: and a TextBox txtAuthor (both with no Text), and a row at the right with two CommandButtons: cmdAdd (Caption &Add, Default True) and cmdTable (Caption Ta&ble...).

  2. Below the rows, a ListBox named lstBooks with Weight 1.

  3. Add the sql.bas library (File › Add Library…​).

  4. The form’s code. In (General), the number of the open database, and a Sub that fills the list from it:

    Dim db As Long
    
    Sub ShowBooks ()
       Dim rs As Long
       Dim book As String
    
       lstBooks.Clear
       rs = SQLQuery(db, "SELECT * FROM books ORDER BY title")
       Do While SQLNext(rs)
          book = SQLField$(rs, "title") & ", "
          lstBooks.AddItem book & SQLField$(rs, "author")
       Loop
       SQLFreeResult rs
    End Sub
  5. Form1_Load opens the database in the program’s own folder, and makes the table the first time:

    Sub Form1_Load ()
       Dim sql As String
    
       db = SQLOpen(App.User & "\books.db")
       If db = 0 Then
          MsgBox "No database: " & SQLError$(0), vbExclamation
          End
       End If
       sql = "CREATE TABLE IF NOT EXISTS books"
       sql = sql & " (id INTEGER PRIMARY KEY,"
       sql = sql & " title TEXT, author TEXT)"
       SQLExec db, sql
       ShowBooks
    End Sub

    CREATE TABLE IF NOT EXISTS makes the table only when it is not there yet, so the books of last time stay. The id column, INTEGER PRIMARY KEY, gives every row a number of its own, which SQLite fills in by itself; a table should always have one, so that each row can be found even when two books have the same title. When the database cannot be opened, End ends the program at once.

  6. Form1_Unload (choose Form1, then [Unload]) closes the database:

    Sub Form1_Unload (Cancel As Integer)
       SQLClose db
    End Sub
  7. Add puts the book in the table, with SQLEscape$ on what was typed, and shows the list again:

    Sub cmdAdd_Click ()
       Dim sql As String
    
       If Trim$(txtTitle.Text) = "" Then
          Exit Sub
       End If
       sql = "INSERT INTO books (title, author) VALUES ('"
       sql = sql & SQLEscape$(txtTitle.Text) & "', '"
       sql = sql & SQLEscape$(txtAuthor.Text) & "')"
       SQLExec db, sql
       txtTitle.Text = ""
       txtAuthor.Text = ""
       txtTitle.SetFocus
       ShowBooks
    End Sub

Run it and add a few books; then close it and run it again.

18.4. Showing a Table Without Code

Two controls show a database with hardly any code. A Data control (the fourth tool in the first row) opens a database and reads the rows of a table or of a query (one that begins with SELECT, WITH, or VALUES); its four arrow buttons move from row to row. A DBGrid (the first tool in the second row) shows a Data control’s rows as a table, with a column for each column, and sorts them when you click a column’s heading. Controls bound to a Data control show its current row: a TextBox, a TextArea, or a Label with the Data control as its DataSource and a column as its DataField shows that column, and what the user types in it goes back into the database: into the Data control’s current row as it is typed, and into the database when the box loses the focus, when another row becomes the current one, or when the form closes.

The book list’s Table…​ button shows its books in a DBGrid:

The Book Table window: the Data control’s bar with its arrow buttons and the caption Books
Figure 29. The books in a DBGrid
  1. Choose File › New Form. Give Form2 the Caption Book Table.

  2. Place a Data control on it, and below it a DBGrid. Select the DBGrid, set its DataSource to Data1 (the row offers the form’s Data controls in a list), and its Weight to 1.

    The Book Table form in the designer with the Data control’s bar and the empty DBGrid below it
  3. In Form2_Load, tell the Data control which database and which rows, and give the grid’s columns their headings:

    Sub Form2_Load ()
       Dim query As String
    
       query = "SELECT title, author FROM books ORDER BY title"
       Data1.DatabaseName = App.User & "\books.db"
       Data1.RecordSource = query
       Data1.Caption = "Books"
       Data1.Refresh
       DBGrid1.SetColumnHeader "title", "Title"
       DBGrid1.SetColumnHeader "author", "Author"
    End Sub

    DatabaseName and RecordSource can also be set in the Properties window, when the database’s place is known while you design the form; this one is in App.User, which only the running program knows. Refresh reads the rows, and the DBGrid fills itself.

  4. Back in Form1, Table…​ shows the form as a dialog box:

    Sub cmdTable_Click ()
       Form2.Show vbModal
       Unload Form2
    End Sub

Before the Data control leaves a row, or saves one, it raises its Validate event, as Visual Basic’s does. Sub Data1_Validate (Action As Integer, Save As Integer) is told why in Action (vbDataActionMoveNext, vbDataActionUnload when the form closes, and the other vbDataAction constants), and in Save whether the row was changed. Set Action = vbDataActionCancel to stay on the row with its changes (when the form is closing, that throws the changes away, and the form closes all the same), or Save = False to throw the changes away and go on; leave both alone and the row is saved. When something fails, a save the database refuses, say, the Data control raises no error: its LastError property says why, and is "" after an operation that worked.

“Data Binding” in the DVX BASIC Language Reference tells more about binding, also of one table to another (master and detail), and “Data” in the DVX BASIC Language Reference about the Data control’s methods for adding, changing, and deleting rows.

18.5. Try It Yourself

  • Add a Search box and button to the book list: show only the books whose title contains what was typed, with WHERE title LIKE '% & SQLEscape$(…​) & %'.

  • Add a Delete button that removes the book picked in the list. (Keep each book’s id in the ListBox’s ItemData when filling the list, with SQLField$(rs, "id"), and delete WHERE id = that number.)

  • Add a year column and show the books in the order they were written. (An existing table needs ALTER TABLE books ADD COLUMN year INTEGER; or delete books.db from App.User and start again.)

  • Put two TextBoxes on Form2, bound to Data1 with the DataFields title and author, and see them follow the grid’s current row.

Chapter 19. Sound, Music, and Games

Programs make sounds: a beep when something went wrong, a little tune when a game is won. DVX BASIC plays sound on whatever the computer has, a sound card or only the PC’s own speaker; on a computer with neither, the program runs just the same, in silence. This chapter makes beeps, tones, and tunes, plays sound and music files, and then writes a game. A game needs two things other programs do not: a loop that runs at a steady speed, and a way to know which keys are being held down.

19.1. Beeps and Tones

Beep sounds a short beep. Sound plays a tone of the frequency you give, in hertz (vibrations a second), for as long as you say, in ticks of the PC’s clock, 18.2 to the second:

Beep                  ' a short beep
Sound 440, 9          ' an A, for half a second
Sound 880, 9          ' the A an octave higher

The higher the frequency, the higher the tone: 440 is the A above middle C, and doubling a frequency goes up an octave. People hear from about 20 to 20,000 hertz.

19.2. Playing Tunes

Play plays a tune written as a string of notes and commands, the music macro language of the BASICs of the 1980s. Letters can be upper or lower case, and spaces are ignored:

Play "T160 O4 L4 C C G G A A G2 F F E E D D C2"
Command Means

A to G

Play that note. # or + after it makes it sharp, - flat, and a number after it is its own length, as for L: G2 is a half note.

P n

A pause (a rest) of length n.

O n

The octave of the notes that follow, from 0 to 6. O3 starts at middle C; tunes start in O4.

> and <

Up or down one octave.

L n

The length of the notes that follow: 1 is a whole note, 2 a half, 4 a quarter (the length to start with), 8 an eighth, up to 64.

T n

The tempo, in quarter notes a minute, from 32 to 255 (120 to start with).

MB

Music background: the program goes on while the tune plays.

MF

Music foreground: the program waits until the tune has played (the way to start with).

I n

Play on General MIDI instrument n: 1 is the piano, 41 the violin, 74 the flute. I0 goes back to plain tones.

V n

The volume, from 0 to 100 percent.

Without MB, Play waits until the whole tune has played, and while it waits the program does nothing else: a form does not even answer a click. In a program with forms, put MB at the start of every tune, so it plays in the background while the program goes on. A command such as MB, O, or T stays in force from one Play to the next (and MB covers Sound and Beep too), but writing it into each tune keeps the tunes from depending on each other.

Play "MB T120 L4 C D E F G A B > C"    ' a scale, in the background
Play "MB I74 O4 L8 G A B > C"          ' on the flute

Play(0) tells how many notes are still waiting to be played in the background. “Sound, Joysticks, and Frames” in the DVX BASIC Language Reference describes every command.

19.3. Sound Files and Music Files

Recorded sounds, a cheer or a crash, come in sound files: WAV files (uncompressed ones) and VOC files. With the sound.bas library in the project (File › Add Library…​), PlayWave plays one, in the background:

Dim voice As Long

voice = PlayWave(App.Data & "\cheer.wav")
If voice = SOUND_FAILED Then
   lblStatus.Caption = SoundError$()
End If

PlayWave gives back a number for the sound playing, its voice, or SOUND_FAILED when it could not play it, and SoundError$() says why. PlayWaveLoop plays a sound over and over, until StopWave voice stops it. Sound files need a sound card (or the PC speaker set to play recorded sound, on the Control Panel’s Sounds page), so a program should never depend on them: it should work, in silence, when one cannot play.

Music files, MIDI files (.mid) and music modules (.mod, .s3m, .xm, and .it files), play with the music.bas library. MusicLoad loads one and gives back a number for it, or MUSIC_FAILED; MusicPlay plays it, over and over when its second argument is True; MusicStop stops it:

Dim tune As Long

Sub Form1_Load ()
   tune = MusicLoad(App.Data & "\theme.mid")
   If tune <> MUSIC_FAILED Then
      MusicPlay tune, True
   End If
End Sub

MusicLoadMacro makes music out of a string written for Play. It plays alongside Play and Sound, which makes it the way to give a game a tune that goes on while its sound effects play.

A program’s sounds and music belong in the DATA folder of its project, where App.Data finds them (Section 13.1), and its package takes them along (Chapter 29).

19.4. A Game Loop

A program with forms waits for events: nothing happens until the user does something. A game cannot wait. Its apple falls whether or not the player presses a key. So a game runs a loop, and each time round, a frame, it moves everything a step, draws everything where it is now, and waits for the next frame:

Do
   MoveEverything
   DrawEverything
   FrameWait 30
Loop Until quitting

FrameWait 30 waits until the next frame of a clock that ticks 30 times a second. Meanwhile DVX and the other programs go on, and so do the program’s own events, as during DoEvents (Section 12.9). Because the clock sets the pace, the game runs at the same speed on a fast computer and a slow one; when a computer is too slow to draw every frame, FrameWait skips the frames it missed, instead of letting the game fall behind.

The KeyDown event tells when a key is pressed. A game wants to know something else: which keys are down now, at every frame, for as long as the player holds them. With the game.bas library in the project, GameKeyDown(GAMEKEY_LEFT) is True while the left arrow key is held down (and one of the program’s windows is active). The GAMEKEY_ constants name the arrow keys, Space, Enter, Esc, Tab, Shift, Ctrl, and Alt (the left and right ones apart, as GAMEKEY_LSHIFT and GAMEKEY_RSHIFT), F1, and the letters W, A, S, D, Z, and X.

19.5. Apple Catch

In this game, apples fall from the sky, and the player catches them in a basket, moving it with the left and right arrow keys. Each apple caught scores a point, and every fifth one makes the apples fall faster. Three apples missed, and the game is over.

The Apple Catch window: Score 0
Figure 30. Apple Catch
  1. Start a new project called Catch, with the Caption Apple Catch.

  2. Place a Label named lblScore with the Caption Score: 0, and below it a PictureBox named picField.

  3. Place a Timer (the last tool in the eighth row) named tmrStart, with the Interval 100.

    The Apple Catch form in the designer: the score label and the small empty PictureBox
  4. Select the form (click an empty part of it) and set its AutoSize to True: the window then takes the size of what is in it, which is the 320 by 200 field the code makes. (Set it last: in the designer, an AutoSize form is only as big as its controls.)

  5. Add the game.bas library (File › Add Library…​).

19.5.1. Constants and Variables

Press F7. The game’s sizes, in pixels, and its colors are constants in (General), so that each is written once and the code says what it means: BASKET_W, not 40. A constant can be worked out from others, as BASKET_Y is, and RGB works in a constant too. Then the variables every part of the game shares: where the basket and the apple are, how fast the apple falls, the score, the lives left, whether a game is on, and whether the window is closing:

' The field, the basket, and the apple, in pixels
Const FIELD_W = 320
Const FIELD_H = 200
Const BASKET_W = 40
Const BASKET_H = 12
Const BASKET_Y = FIELD_H - 20
Const BASKET_SPEED = 6
Const APPLE_R = 6
Const FRAME_RATE = 30
Const SKY = RGB(160, 200, 255)
Const BROWN = RGB(150, 90, 40)

Dim basketX As Integer
Dim appleX As Integer
Dim appleY As Integer
Dim appleSpeed As Integer
Dim score As Integer
Dim lives As Integer
Dim playing As Boolean
Dim quitting As Boolean

19.5.2. Starting and Ending

Form1_Load makes the field 320 by 200, sets the color Cls clears it to, and makes circles filled with red. The basket starts in the middle, and the score shows:

Sub Form1_Load ()
   Randomize
   picField.Resize FIELD_W, FIELD_H
   picField.BackColor = SKY
   picField.FillStyle = vbFSSolid
   picField.FillColor = vbRed
   basketX = (FIELD_W - BASKET_W) / 2
   lives = 3
   ShowScore
End Sub

Sub ShowScore ()
   lblScore.Caption = "Score: " & score & "    Lives: " & lives
End Sub

lives is 3 before the first game, which is how the field knows to say Press Space to start rather than Game over!. When the window closes, Form1_Unload tells the game loop to stop:

Sub Form1_Unload (Cancel As Integer)
   quitting = True
End Sub

19.5.3. The Loop

The game loop runs in the Timer’s Timer procedure (choose tmrStart in the Object list):

Sub tmrStart_Timer ()
   tmrStart.Enabled = False

   ' The game loop: it runs until the window closes
   Do
      If playing Then
         MoveBasket
         MoveApple
      ElseIf GameKeyDown(GAMEKEY_SPACE) Then
         NewGame
      End If

      DrawField
      FrameWait FRAME_RATE
   Loop Until quitting
End Sub

Why in a Timer? Form1_Load runs before the window appears, so a loop there, which runs until the window closes, would never let it appear at all. The Timer goes off a tenth of a second after the form has appeared, and its first line stops it: it is needed only once. Each time round the loop, when a game is on, the basket and the apple move; between games, the loop watches for Space, which starts a new one. Then it draws the field and waits for the next frame. When the window closes, Form1_Unload sets quitting, the loop ends, and so does the program.

19.5.4. Moving

A new game, and a new apple at the top of the field, somewhere across it (Int(Rnd * …​) picks a whole number of pixels, Section 5.7, so that the whole apple is on the field):

Sub NewGame ()
   score = 0
   lives = 3
   appleSpeed = 2
   playing = True
   NewApple
   ShowScore
   Play "MB T200 O4 L16 C E G > C"
End Sub

Sub NewApple ()
   appleX = APPLE_R + Int(Rnd * (FIELD_W - 2 * APPLE_R))
   appleY = 0
End Sub

The basket moves BASKET_SPEED pixels each frame for as long as an arrow key is held, but never off the field:

Sub MoveBasket ()
   If GameKeyDown(GAMEKEY_LEFT) Then
      basketX = basketX - BASKET_SPEED
   End If
   If GameKeyDown(GAMEKEY_RIGHT) Then
      basketX = basketX + BASKET_SPEED
   End If

   ' Keep it on the field
   If basketX < 0 Then
      basketX = 0
   ElseIf basketX > FIELD_W - BASKET_W Then
      basketX = FIELD_W - BASKET_W
   End If
End Sub

The apple falls appleSpeed pixels each frame. When its bottom reaches the top of the basket, it is caught if it is over the basket; if not, it falls on, and once it has dropped off the bottom of the field, it is missed:

Sub MoveApple ()
   Dim bottom As Integer

   appleY = appleY + appleSpeed
   bottom = appleY + APPLE_R

   ' At the top of the basket: caught if it is over it
   If bottom >= BASKET_Y And bottom < BASKET_Y + BASKET_H Then
      If appleX >= basketX And appleX <= basketX + BASKET_W Then
         Caught
      End If
   ElseIf appleY - APPLE_R > FIELD_H Then
      Missed
   End If
End Sub

Sub Caught ()
   score = score + 1
   ShowScore
   Play "MB T200 O5 L32 C E G"

   ' Every fifth apple, they fall faster
   If score Mod 5 = 0 Then
      appleSpeed = appleSpeed + 1
   End If
   NewApple
End Sub

Sub Missed ()
   lives = lives - 1
   ShowScore

   If lives > 0 Then
      Play "MB T200 O2 L16 C"
      NewApple
   Else
      Play "MB T120 O3 L8 G E C2"
      playing = False
   End If
End Sub

score Mod 5 is the remainder when the score is divided by 5, which is 0 at every fifth apple. Every sound starts with MB, so the game goes on while it plays: a sound without it would stop the apple in the air until the sound had played.

19.5.5. Drawing

Each frame, the field is drawn afresh: cleared to the sky, then the basket, then the apple, or between games a message in the middle:

Sub DrawField ()
   Dim x2 As Integer
   Dim y2 As Integer

   picField.Cls

   ' The basket: a brown box
   x2 = basketX + BASKET_W
   y2 = BASKET_Y + BASKET_H
   picField.Line (basketX, BASKET_Y)-(x2, y2), BROWN, BF

   ' The apple, or between games a message
   If playing Then
      picField.Circle (appleX, appleY), APPLE_R, vbRed
   ElseIf lives = 0 Then
      ShowMessage "Game over! Press Space to play again."
   Else
      ShowMessage "Press Space to start."
   End If
End Sub

Sub ShowMessage (message As String)
   picField.CurrentX = (FIELD_W - picField.TextWidth(message)) / 2
   picField.CurrentY = FIELD_H / 2 - 20
   picField.Print message
End Sub

TextWidth tells how many pixels wide a text is in the PictureBox’s font, which centers the message.

Press F5, then Space, and catch some apples.

The Apple Catch window with Lives 0
Figure 31. The end of a game

19.6. More for Games

Pictures as pieces. A game’s pieces can be pictures drawn in a paint program instead of circles and boxes. PaintPicture copies a picture into a PictureBox; with vbTransparentCopy it leaves out every pixel of one color, so the piece’s corners do not hide the sky. A statement this long can go on to the next line when its line ends with a space and an underscore:

picField.PaintPicture App.Data & "\apple.bmp", appleX, appleY, _
   16, 16, 0, 0, 16, 16, vbTransparentCopy, vbMagenta

Here the picture is 16 pixels square, and its magenta pixels are left out. The file is read from the disk only the first time.

Joysticks. STICK(0) gives where the first joystick points across, from 1 (all the way left) to 200 (all the way right), about 100 in the middle, and then STICK(1) where it points up and down; STRIG(1) is True while its first button is held. When no joystick is connected, the keyboard stands in for one. The joystick.bas library reads every joystick and game pad connected, in more detail (“Include Libraries” in the DVX BASIC Language Reference).

Every key for the game. While a form whose GameInput property is True has the keyboard, every key goes to it: F1 does not open help, and Alt and F10 do not open the menus. Only Alt+Tab, Ctrl+Esc, and Alt+F4 still reach DVX.

The whole screen. FullScreen = True, in the form’s code, gives the form the whole screen: the form without its title bar, enlarged as much as fits, centered on black. The mouse works on it as in the window, and every key goes to it. When the user switches to another program, or the program shows a message box, the desktop comes back; the form has the whole screen again when it gets the focus back.

19.7. Try It Yourself

  • Make the basket move twice as fast while Shift is held down (GameKeyDown(GAMEKEY_LSHIFT)).

  • Give the apple a green stalk: a short line up from its top.

  • Keep a high score in a settings file (Section 13.6), and show it below Game over!.

  • Give the game a tune that plays over and over while a game is on, with music.bas: MusicLoadMacro in Form1_Load, MusicPlay tune, True in NewGame, and MusicStop tune when the game ends.

  • Drop two apples at once. (Arrays for appleX and appleY, and a For loop in MoveApple and DrawField.)

Chapter 20. Printing

Some things belong on paper: a letter, a shopping list, a certificate for a job well done. DVX prints on the printer chosen on the Control Panel’s Printer page, which says what model the printer is and where it is connected, or prints into a file instead. A DVX BASIC program prints in three ways: text laid out on pages for it, whole pages it draws itself with the Printer object, and lines sent straight to the printer with LPrint.

20.1. Printing Text

The easiest way to print is the print.bas library’s (File › Add Library…​). PrintTextDialog shows the Print dialog, where the user chooses the printer, how many copies, and which pages, and then prints the text on pages laid out the way DVX’s own programs lay them out: with margins, a header, and a footer with the document’s name, the date, and the page number. PrintPageSetup shows the Page Setup dialog, where the user chooses those margins, header, and footer; the choices are kept for every program. A text editor such as TinyPad (Section 14.5) needs two menu items and two lines of code to print:

Sub mnuPrint_Click ()
   PrintTextDialog txtDoc.Text, "TinyPad"
End Sub

Sub mnuPageSetup_Click ()
   PrintPageSetup
End Sub

The second argument is the document’s name, which the header or footer shows. PrintText prints the same way without asking first, and PrintForm "Form1" prints a picture of what a form shows. “Include Libraries” in the DVX BASIC Language Reference lists everything print.bas can do.

20.2. Drawing Pages: the Printer Object

For a page laid out your own way, a program draws it with the Printer object, as it draws on a PictureBox (Chapter 16). Printer.Print prints text where CurrentX and CurrentY say, Printer.Line draws lines and boxes, Printer.Circle circles, Printer.PSet dots, and Printer.PaintPicture pictures, all with the colors, DrawWidth, FillStyle, and FillColor you know already.

A page is measured in twips, 1440 to the inch, unless the program chooses otherwise; Printer.ScaleMode = vbInches measures it in inches. The part of the page the printer can print on is 8 inches wide and 10 inches high, with (0, 0) its top-left corner.

Text prints in Printer.FontName, at Printer.FontSize points (72 to an inch: 12 points is the size of a book’s text), with FontBold, FontItalic, and FontUnderline as on a control. Printer.TextWidth and Printer.TextHeight say how much room a text takes, in the page’s measure.

Nothing is printed while the program draws. Printer.NewPage prints the page drawn so far and starts the next, and Printer.EndDoc prints the last page and ends the document. Printer.KillDoc stops the document instead, throwing away what has not been printed yet. While a document prints, DVX shows a Printing window with a Cancel button.

The Printer object needs a printer that can print pictures: most can, but some models only print letters, a line at a time. PrintCanPrintPictures() (in print.bas) is True when the chosen model can. On a color printer, colors print as they are; on the others, in shades of gray.

20.3. A Certificate

This program prints a certificate: type a name and a course, click Print…​, and choose a printer.

A printed page with a double blue border: Certificate of Achievement in large letters
Figure 32. The certificate as it prints
  1. Start a new project called Cert, with the Caption Certificate and the Height 200.

  2. As in the sign-up form of Section 11.5, give it a row with a Label &Name: and a TextBox txtName, a row with a Label &Course: and a TextBox txtCourse (both with no Text), and a row at the right with a CommandButton cmdPrint, with the Caption &Print... and Default True.

    The Certificate form in the designer: the Name and Course rows and the Print button at the right
  3. Add the print.bas library (File › Add Library…​).

  4. Press F7. In (General), the certificate’s two colors:

    Const NAVY = RGB(0, 0, 128)
    Const GOLD = RGB(230, 180, 40)

A Sub prints a line of text centered across the page at a height you give, in inches. TextWidth measures the text in the page’s measure, so the room left over, split in two, is where the text starts:

Sub PrintCentered (text As String, y As Single)
   Dim across As Single

   across = Printer.ScaleWidth - Printer.TextWidth(text)
   Printer.CurrentX = across / 2
   Printer.CurrentY = y
   Printer.Print text
End Sub

Another Sub draws the whole certificate on the page: the border, the words in the sizes they need, the seal, and the line to sign on:

Sub DrawCertificate (who As String, course As String)
   ' Measure in inches, on a page 8 wide and 10 high
   Printer.ScaleMode = vbInches

   ' A double border
   Printer.Line (0.25, 0.25)-(7.75, 9.75), NAVY, B
   Printer.Line (0.35, 0.35)-(7.65, 9.65), NAVY, B

   ' The words, centered
   Printer.FontName = "DejaVu Serif"
   Printer.FontBold = True
   Printer.FontSize = 40
   PrintCentered "Certificate", 1.5
   Printer.FontBold = False
   Printer.FontSize = 20
   PrintCentered "of Achievement", 2.3
   Printer.FontSize = 14
   PrintCentered "This certifies that", 3.6
   Printer.FontSize = 32
   Printer.FontItalic = True
   PrintCentered who, 4.3
   Printer.FontItalic = False
   Printer.FontSize = 14
   PrintCentered "has completed the course", 5.4
   Printer.FontSize = 20
   PrintCentered course, 6

   ' A gold seal, and a line to sign on
   Printer.FillStyle = vbFSSolid
   Printer.FillColor = GOLD
   Printer.Circle (6, 8.2), 0.6, GOLD
   Printer.Line (1, 8.6)-(3.5, 8.6), vbBlack
   Printer.FontSize = 11
   Printer.CurrentX = 1
   Printer.CurrentY = 8.7
   Printer.Print "Signed"
End Sub

Print…​ checks that there is a name and a printer that can print pages, and then shows the Print dialog with PrintChoose. Its first argument is the dialog’s title; the second, 0, says the dialog need not ask which pages. PrintChoose gives back False when the user clicks Cancel; otherwise the page goes to the printer and the number of copies the user chose:

Sub cmdPrint_Click ()
   If Trim$(txtName.Text) = "" Then
      MsgBox "Type a name first.", vbExclamation
      txtName.SetFocus
      Exit Sub
   End If
   If Not PrintCanPrintPictures() Then
      MsgBox "This printer cannot print pages.", vbExclamation
      Exit Sub
   End If
   If Not PrintChoose("Print Certificate", 0) Then
      Exit Sub
   End If

   DrawCertificate Trim$(txtName.Text), txtCourse.Text
   Printer.EndDoc
End Sub
The Print Certificate dialog: Print to File
Figure 33. The Print dialog

Press F5, type a name and a course, and print.

The Certificate window with Ann Brown and Programming in DVX BASIC typed in
Figure 34. Ready to print

On a PostScript printer, the printer draws the letters itself, in its own Times, Helvetica, or Courier, whichever is nearest the FontName: here, Times for DejaVu Serif. Other printers print DVX’s own letters, as dots.

20.4. A Line at a Time: LPrint

LPrint is Print for the printer: each LPrint sends a line to the printer at once, as plain text, with ;, ,, Tab, and LPrint Using working as they do on the screen. Nothing is laid out: there are no margins and no new pages, unless the program sends one with LPrint Chr$(12). It is the quickest way to print a list on a printer that prints a line at a time:

LPrint "Shopping list"
LPrint
For i = 0 To lstItems.ListCount - 1
   LPrint "  "; lstItems.List(i)
Next i
LPrint Chr$(12)                ' out with the page

When the printer has a problem, such as no paper, DVX asks the user to fix it and choose Retry; after Cancel, LPrint stops with error 57, which On Error can catch.

20.5. Try It Yourself

  • Print the date under the line to sign on: Format$(Date, "mmmm d, yyyy") writes it as November 3, 2026.

  • Print certificates for a whole class: names in a ListBox, DrawCertificate for each, Printer.NewPage between them, and one Printer.EndDoc at the end.

  • Give TinyPad File › Print…​ and File › Page Setup…​.

  • Draw a star on the seal: five lines from point to point.

Chapter 21. Using DVX’s Libraries

DVX can do much more than BASIC’s own statements: play music, print, keep a database, fetch a web page, start other programs. Each of these comes in a library, which you add to a project with File › Add Library…​ (Section 14.4). This chapter shows what a library is, how to find out what one can do, and what libraries there are, and builds a program with two of them.

21.1. What a Library Is

A library such as game.bas is a file of BASIC, which you can read like any other. Most of it is declarations: lines that tell DVX BASIC about functions that a part of DVX itself carries out, with a comment above each that says what it does. Here are a few lines of game.bas:

CONST GAMEKEY_LEFT   = &HCB
CONST GAMEKEY_RIGHT  = &HCD

DECLARE LIBRARY "game"
    ' True while the key is held down and one of this program's windows
    ' is active, else False.
    DECLARE FUNCTION GameKeyDown(BYVAL keyCode AS LONG) AS LONG
  • The constants give names to numbers the functions take: GAMEKEY_LEFT is the left arrow key’s number.

  • DECLARE LIBRARY "game" names the part of DVX that does the work, and the declarations up to its END DECLARE are the functions it has.

  • DECLARE FUNCTION GameKeyDown(BYVAL keyCode AS LONG) AS LONG says that GameKeyDown takes one number, keyCode, and gives back a number. BYVAL means the function gets the value and cannot change your variable. A function that answers yes or no gives back True (-1) or False (0), so If GameKeyDown(GAMEKEY_LEFT) Then works as you would expect.

  • DECLARE SUB lines declare procedures that give back nothing.

Once the library is in the project, its functions are called like BASIC’s own: GameKeyDown(GAMEKEY_LEFT) in an expression, or, for a Sub, its name and arguments. A Function’s answer can be left unused by calling it like a Sub, without parentheses.

21.2. Finding Out What a Library Can Do

A library tells about itself. Double-click it under Modules in the Project window, and the Code window shows it: the comments above each declaration say what the function does, what its arguments mean, and what it gives back, and related functions are grouped together under headings. Read, but do not change it: a library’s text must stay as it came.

The DVX BASIC Help (F1, or Help › DVX BASIC Help) describes each library in its language reference, under Include Libraries, with examples; “Include Libraries” in the DVX BASIC Language Reference has the same pages.

21.3. The Libraries

These come with DVX BASIC:

For Library Gives your program

Dialog boxes

commdlg.bas

Open, Save As, choosing a folder, a color, or a font, and message boxes with buttons of your own.

Files

fileops.bas

Folder listings, file and folder sizes, free disk space, copying and deleting whole folders, paths, and saving a file safely.

Settings

prefs.bas

Settings files with sections, read, changed, and saved, and DVX’s own settings.

Data

sql.bas

Databases (Chapter 18).

json.bas

Reading JSON, the format web services answer in.

Sound and games

sound.bas, music.bas, game.bas, joystick.bas

Sound files, music files, held keys, and joysticks (Chapter 19).

Printing

print.bas

Printing text and pictures, and the Print and Page Setup dialogs (Chapter 20).

Text and fonts

font.bas

The fonts DVX has and their sizes.

richtext.bas

RTF, the text of word processors, as plain text and back.

layout.bas

Control sizes in characters or percent instead of pixels.

Help

help.bas

Showing DVX Help or your program’s help file (Chapter 26), and making help files.

hlpfile.bas

Reading help files, for a help viewer of your own.

Resources

resource.bas

Pictures, text, and data kept inside a program file (Chapter 28).

Networks

net.bas

Network connections and the network’s settings.

http.bas

Fetching web pages and files from the web.

comm.bas, conn.bas, xfer.bas

Serial ports and modems, connections like Terminal’s, and file transfers.

DVX itself

shell.bas

Starting programs and opening documents, and everything Program Manager and Task Manager do.

system.bas

What the Control Panel changes: the screen mode, colors, wallpaper, and the mouse.

pkg.bas, pkgnet.bas

Add-on packages, and the software server (Chapter 30).

Security

security.bas

Random numbers good enough for keys, hashes, signatures, and ciphers.

Programming tools

compiler.bas, debug.bas, designer.bas, listhelp.bas

What DVX BASIC itself is made of: the compiler, the debugger, form designers, and lists drawn by hand.

21.4. Folder Sizes

This program shows how much room a folder’s files take, and how much room is left on the disk. It uses two libraries: commdlg.bas for the dialog box that chooses a folder, and fileops.bas for the folder’s listing and sizes.

The Folder Sizes window: the Folder button and the path C:\DVX\SHARED\SOUNDS
Figure 35. The sizes of the files in a folder
  1. Start a new project called Sizes, with the Caption Folder Sizes.

  2. Place an HBox, and in it a CommandButton cmdFolder with the Caption &Folder... and a Label lblFolder with no Caption.

  3. Below the row, a ListBox lstItems with Weight 1, and below that a Label lblTotal with no Caption. (A Label with no caption cannot be seen in the designer; the Properties window still lists it.)

    The Folder Sizes form in the designer: the Folder button
  4. Add commdlg.bas and fileops.bas (File › Add Library…​, twice).

Press F7. A Sub shows a folder: its name at the top, each of the folder’s files and folders in the list with its size, and the totals at the bottom:

Sub ShowFolder (folder As String)
   Dim list As Long
   Dim i As Long
   Dim itemName As String
   Dim bytes As Double
   Dim total As Double
   Dim summary As String

   lstItems.Clear
   lblFolder.Caption = folder
   list = FileOpsList(folder, "")
   If list = 0 Then
      lblTotal.Caption = "This folder cannot be read."
      Exit Sub
   End If

   For i = 0 To FileOpsListCount(list) - 1
      itemName = FileOpsListName$(list, i)
      If FileOpsListIsFolder(list, i) Then
         ' A folder's size is the size of everything in it
         FileOpsTreeSize FileOpsPathJoin$(folder, itemName)
         bytes = FileOpsTreeBytes()
         itemName = itemName & "\"
      Else
         bytes = FileOpsListSize(list, i)
      End If
      total = total + bytes
      lstItems.AddItem itemName & "   " & FileOpsFormatSize$(bytes)
   Next i
   FileOpsListFree list

   summary = FileOpsFormatSize$(total) & " bytes, "
   summary = summary & FileOpsFormatSize$(FileOpsFreeBytes(folder))
   lblTotal.Caption = summary & " free"
End Sub
  • FileOpsList(folder, "") reads the folder ("" for all its files) and gives back a number for the listing, or 0 when the folder cannot be read. FileOpsListCount, FileOpsListName$, FileOpsListIsFolder, and FileOpsListSize tell about its entries, numbered from 0, and FileOpsListFree lets go of the listing at the end.

  • A folder’s own size in the listing is nothing; what it holds is what counts. FileOpsTreeSize adds up everything in a folder and the folders inside it, and FileOpsTreeBytes() then gives the total. The program calls FileOpsTreeSize like a Sub, leaving its answer (whether every part could be read) unused.

  • FileOpsFormatSize$ writes a number of bytes with commas, 61,582, and FileOpsFreeBytes gives the free space on the disk that holds a folder.

When the program starts, it shows its own folder:

Sub Form1_Load ()
   ShowFolder App.Path
End Sub

Folder…​ shows the dialog box for choosing a folder, which starts in the folder shown. DlgFolder$ gives back the folder chosen, or "" after Cancel:

Sub cmdFolder_Click ()
   Dim folder As String

   folder = DlgFolder$("Choose a Folder", lblFolder.Caption)
   If folder <> "" Then
      ShowFolder folder
   End If
End Sub
The Choose a Folder dialog box: the Path and Drive boxes
Figure 36. Choosing a folder

In the dialog box, double-click a folder to go into it, and click OK to choose the folder shown; or type the folder’s path in Folder name and press Enter.

21.5. Try It Yourself

  • Add an Up button that shows the folder the shown one is in, with FileOpsPathParent$.

  • Show the biggest files first: FileOpsListSort list, FILEOPS_SORT_SIZE, True right after FileOpsList (folders still come first).

  • Add a ProgressBar that shows how full the disk is, from FileOpsFreeBytes and FileOpsTotalBytes (the disk’s whole size).

  • Make a double-click on a folder in the list show that folder. (Keep the entries' names in an array as the list fills, since the list’s lines also hold the sizes.)

Chapter 22. Making Your Own Controls

The Toolbox’s controls are made for every program. When a program needs one that is not there, a switch, a gauge, a row of stars to rate something with, you can write it in DVX BASIC, as a UserControl. Once written, it is in the Toolbox like the others: you place it on a form, set its properties in the Properties window, and write procedures for its events. This chapter makes an on/off switch and uses it on a form.

22.1. What a Control Is Made Of

A UserControl is a class module (Chapter 17) that can draw itself and that a form can hold:

  • Its properties are Property Get and Property Let procedures, as in a class, and so are its methods: its Public Subs and Functions.

  • Its events are declared with Event and raised with RaiseEvent. The program that has the control writes procedures for them, as for a button’s Click.

  • It draws itself, in its UserControl_Paint procedure, with the drawing statements of a PictureBox (Chapter 16).

  • It hears the mouse and the keyboard in procedures of its own, UserControl_Click, UserControl_KeyPress, and the others. The program does not see those; it sees only the events the control raises.

  • A header at the top of its file says how big it is to start with, whether it takes the keyboard, and what the Toolbox shows for it. The Properties window sets it; the Code window shows only the code, as it does for a form.

22.2. A Switch

The switch is green with its knob at the right when it is on, and gray with the knob at the left when it is off. A click, or Space while it has the keyboard, turns it the other way. Its Value property is True when it is on, and it raises a Changed event each time it is turned.

The Switches window: the label Sound and a green switch with its knob at the right
Figure 37. The Switch on a form
  1. Start a new project called Switches, and give Form1 the Caption Switches.

  2. Choose File › New UserControl. DVX BASIC adds UserControl1.ctl under Controls in the Project window and opens it in the Code window.

  3. Choose File › Rename File…​ and type Switch. The file is Switch.ctl now, and the control is called Switch: the name forms use for it, as they use CommandButton.

  4. The Properties window shows the control’s header while its file is open (Window › Properties brings it to the front). Set its Width to 50 and its Height to 24, the switch’s natural size, and its Description to An on/off switch, the tooltip of its tool in the Toolbox. A size there can also be a percentage of the container a form places the control in (50%) or a number of characters of its font (20ch), typed as text, as a control’s sizes are on a form.

    The Properties window showing the Switch header: Width 50

22.2.1. Its Property and Its Event

In the Code window, below Option Explicit, the control’s event, the variable that holds whether it is on, and its Value property:

Option Explicit

Public Event Changed ()

Private mValue As Boolean

Public Property Get Value () As Boolean
   Value = mValue
End Property

Public Property Let Value (ByVal newValue As Boolean)
   If newValue <> mValue Then
      mValue = newValue
      Invalidate
      RaiseEvent Changed
   End If
End Property

A switch turned on again when it is on already does nothing. Otherwise the property remembers the new value, asks for the control to be drawn again with Invalidate, and tells the program with RaiseEvent Changed. In a control’s own code, the control’s members need no name in front: Invalidate is the control’s, as Hide is a form’s in the form’s code.

22.2.2. Drawing It

Choose UserControl in the Object list and Paint in the Function list. DVX runs UserControl_Paint when the control first appears, when its size changes, and after Invalidate, so it draws everything the control shows:

Private Sub UserControl_Paint ()
   Dim track As Long
   Dim r As Single
   Dim knobX As Single

   ' The track: green when on, gray when off
   BackColor = Ambient.BackColor
   Cls
   If mValue Then
      track = vbGreen
   Else
      track = RGB(160, 160, 160)
   End If
   Line (2, 2)-(ScaleWidth - 3, ScaleHeight - 3), track, BF

   ' The knob: a white circle at the end the switch is at
   r = ScaleHeight / 2 - 3
   If mValue Then
      knobX = ScaleWidth - 3 - r
   Else
      knobX = 2 + r
   End If
   FillStyle = vbFSSolid
   FillColor = vbWhite
   Circle (knobX, ScaleHeight / 2), r, vbBlack

   ' The dotted frame while it has the keyboard
   If HasFocus Then
      DrawFocusRect 0, 0, ScaleWidth, ScaleHeight
   End If
End Sub
  • Ambient.BackColor is the color of the form or frame the control is on, so the corners around the track match it.

  • ScaleWidth and ScaleHeight are the control’s size in pixels, whatever size the form gives it, so it draws itself at any size.

  • HasFocus is True while the control has the keyboard, and DrawFocusRect draws the dotted frame that DVX’s own controls show then.

22.2.3. The Mouse and the Keyboard

The control’s own Click and KeyPress turn the switch, through its Value property, so a click raises Changed as setting Value in code does. GotFocus and LostFocus draw it again, with or without the dotted frame (choose each in the Function list):

Private Sub UserControl_Click ()
   Value = Not mValue
End Sub

Private Sub UserControl_KeyPress (KeyAscii As Integer)
   If KeyAscii = Asc(" ") Then
      Value = Not mValue
   End If
End Sub

Private Sub UserControl_GotFocus ()
   Invalidate
End Sub

Private Sub UserControl_LostFocus ()
   Invalidate
End Sub

The control’s mouse events come in Visual Basic’s order: MouseDown when the button goes down, MouseUp and then Click when it comes up over the control. Two clicks close together make a double-click, and the second of them raises DblClick instead: MouseDown, MouseUp, Click, DblClick, MouseUp. So a quick double-click turns the switch only once. A control that should act on every press, a scroll bar it draws, say, does it in DblClick too.

Press Ctrl+S to save Switch.ctl. DVX BASIC compiles the control, and the Toolbox has a tool for it now: a plain control picture, with the tooltip An on/off switch. Last, in the Properties window, set the header’s DefaultEvent to Changed: the event whose procedure a double-click on a placed switch opens.

22.3. Using the Switch

  1. In the Project window, double-click Form1.frm.

  2. Place an HBox, and in it a Label with the Caption &Sound: and, with the new tool, a Switch named swSound. Below the row, place a Label named lblState with no Caption.

    The Switches form in the designer: the Sound label and a gray switch

    The switch in the designer is a real one: its code runs and draws it (it is off), while your clicks go to the designer as they do for any control. The Properties window lists its Value property among the others.

  3. In the form’s code, the switch starts on, and its Changed procedure (choose swSound, then [Changed]) tells what it is:

    Sub Form1_Load ()
       swSound.Value = True
    End Sub
    
    Sub swSound_Changed ()
       If swSound.Value Then
          lblState.Caption = "The sound is on."
       Else
          lblState.Caption = "The sound is off."
       End If
    End Sub

Press F5, and click the switch.

The Switches window with the gray switch
Figure 38. The switch turned off

22.4. Controls for Every Program

A UserControl in a program’s project belongs to that program. A control that many programs should have goes in a project of its own, a control project: in File › Project Properties…​, set its Type to Control. Then File › Make Control builds a control file (.wgt). Copy it into a folder of its own inside DVX’s WIDGETS folder, and DVX registers it when it starts: every program has the control, in the Toolbox too. “UserControls: Your Own Controls” in the DVX BASIC Language Reference tells everything about UserControls.

22.5. Try It Yourself

  • Give the switch an OnColor property (a Long, vbGreen to start with, set in UserControl_Initialize), the color of the track when it is on.

  • Make the right arrow key turn the switch on and the left arrow key turn it off, in UserControl_KeyDown (vbKeyRight and vbKeyLeft).

  • Make a quick double-click turn the switch twice: turn it in UserControl_DblClick too.

  • Give the switch a picture of its own in the Toolbox: a 24 by 24 picture in the project’s folder, named in the header’s ToolboxIcon (Chapter 25 shows how to draw one).

  • Make a Gauge control: a bar that fills from the left as its Level property goes from 0 to 100.

Part III: Finishing and Sharing a Program

Chapter 23. Planning a Real Program

A program you write for yourself is done when it works. A program for other people needs more: it must say who made it and which version it is, explain itself, show an icon in Program Manager, and come in one file they can install, from you or from the software server. This part of the book takes one program all the way: a to-do list, from an idea to everyone’s DVX. This chapter decides what the program will do; the chapters after it build it and get it ready to share.

23.1. What It Will Do

Start with what the program is for, in a sentence: To-Do keeps a list of the things I have to do, and remembers it. Then the things it must do, and no more; a small program that works is worth more than a big one that is never finished:

  • Add a task: type it and press Enter.

  • Mark a task done: it moves from the To do list to a Done list, so you can see what you got done.

  • Delete a task that will not be done, after asking.

  • Empty the Done list from the File menu.

  • Keep the lists from one time to the next, without the user having to save.

  • Show a tip about using it, a different one each time it starts.

  • Explain itself with a help file, and say which version it is in an About box.

The To-Do window: a box to type in and the Add button
Figure 39. The finished To-Do program

23.2. Its Window and Its Parts

Sketch the window before you open DVX BASIC, on paper or in your head, and give each part that the code will use a name. The names follow the custom of Section 12.1:

Control Name What it is for

TextBox

txtTask

Where a new task is typed.

CommandButton

cmdAdd

Adds the task (the default button, so Enter presses it).

ListBox

lstTodo

The tasks still to do.

CommandButton

cmdDone

Moves the chosen task to the Done list.

CommandButton

cmdDelete

Deletes the chosen task.

ListBox

lstDone

The tasks that are done.

Label

lblTip

The tip at the bottom.

Menu items

mnuClearDoneList, mnuExit, mnuContents, mnuAboutToDo

File > Clear Done List and Exit, Help > Contents and About To-Do.

23.3. What It Keeps, and Where

The program keeps one file: todo.txt in its user folder, App.User (Section 13.1), one task to a line. A line that starts with - is a task to do, one that starts with + a task that is done:

-Buy milk
-Write the report
+Call Ann

A plain text file like this is easy to check with Notepad when something goes wrong. The program writes it whenever a list changes, so nothing is lost if DVX is switched off.

The tips are a file the program comes with, tips.txt in its DATA folder (App.Data), one tip to a line. Anyone can add tips with Notepad, without changing the program.

23.4. The Steps Ahead

A program to share needs more than its code. The rest of this part takes them one at a time:

Chapter Step

Chapter 24

Build and test the program.

Chapter 25

Draw its icon.

Chapter 26

Write its help file.

Chapter 27

Give it a version and build the program file to hand out.

Chapter 28

What its program file carries, and the files it comes with.

Chapter 29

Make a package that anyone can install.

Chapter 30

Offer it to everyone on the software server.

Chapter 31

Bring out a new version, and help the people who use it.

The project is called To-Do, the name people will see. Its folder and its files need a short name that DOS can use, and DVX BASIC makes one from the project’s name: TODO.

Chapter 24. Building the To-Do List

With the plan of Chapter 23 in hand, building To-Do takes the skills of Part II: a form with rows of controls, menus, a file in App.User, and a library. This chapter builds it and tests it the way the people who will use it are going to.

24.1. The Window

  1. Choose File › New Project…​ and type the project’s name, To-Do. DVX BASIC suggests the folder TODO for it in your PROJECTS folder; press Enter to take it.

  2. Give Form1 the Caption To-Do and the Height 480. Set its HelpTopic to todo.overview too: the page of the help file that F1 will open, which Chapter 26 writes.

  3. Place an HBox, and in it a TextBox named txtTask, with no Text, and a CommandButton named cmdAdd, with the Caption &Add and Default True, so that Enter adds the task just typed.

  4. Below the row, a Label named lblTodoHead with the Caption &To do:, and a ListBox named lstTodo. A label’s access key moves the focus to the control placed after it, so Alt+T goes to the list.

  5. Below the list, another HBox, with two CommandButtons: cmdDone, with the Caption &Done, and cmdDelete, with the Caption De&lete. Set the row’s Alignment to Right.

  6. Below that row, a Label named lblDoneHead with the Caption D&one:, and a ListBox named lstDone.

  7. Last, at the bottom, a Label named lblTip with no Caption, for the tip. A label is as wide as its text, so a long tip would make the form wider than its window. Set its WordWrap to True and its MinWidth to 360, a little less than the form is wide: a long tip then wraps onto a second line at that width instead.

  8. Set the Weight of lstTodo to 2 and that of lstDone to 1. The lists share the room the other controls leave, and the To do list, the one that matters, gets twice as much: when the user makes the window taller, it grows twice as fast.

24.2. The Menus

With the form in the designer, open the Menu Editor (Ctrl+E) and make the two menus, as in Section 14.1:

Menu Item Name DVX BASIC gives it

&File

&Clear Done List

mnuClearDoneList

- (a separator)

E&xit

mnuExit

&Help

&Contents

mnuContents

&About To-Do...

mnuAboutToDo

The To-Do form in the designer: the File and Help menus
Figure 40. The To-Do form in the designer

Then add the help.bas library (File › Add Library…​): it has HelpView, which Help > Contents uses to open the program’s help.

24.3. Keeping the Lists

Press F7 for the form’s code. In (General), a variable that holds the name of the file the lists are kept in, for every procedure of the form to use:

Dim todoFile As String

Two Subs of your own read the lists from the file and write them to it. Type Sub LoadList and press Enter, then the lines of LoadList; then SaveList the same way:

Sub LoadList ()
   Dim f As Integer
   Dim lineText As String

   If Dir$(todoFile) = "" Then
      Exit Sub
   End If
   f = FreeFile
   Open todoFile For Input As #f
   Do While Not EOF(f)
      Line Input #f, lineText
      ' "+" starts a task that is done, "-" one to do
      If Left$(lineText, 1) = "+" Then
         lstDone.AddItem Mid$(lineText, 2)
      Else
         lstTodo.AddItem Mid$(lineText, 2)
      End If
   Loop
   Close #f
End Sub

Sub SaveList ()
   Dim f As Integer
   Dim i As Integer

   f = FreeFile
   Open todoFile For Output As #f
   For i = 0 To lstTodo.ListCount - 1
      Print #f, "-" & lstTodo.List(i)
   Next i
   For i = 0 To lstDone.ListCount - 1
      Print #f, "+" & lstDone.List(i)
   Next i
   Close #f
End Sub
  • The first time the program runs there is no file yet, and Dir$ gives "" for a file that is not there, so LoadList stops before it tries to open it.

  • Each line starts with - or +, and the rest of it, from the second character (Mid$(lineText, 2)), is the task.

  • SaveList writes the whole file again, both lists, each time anything changes. For Output starts the file empty, so nothing old is left at its end.

24.4. The Tip

ShowTip shows one line of the tips file, picked at random:

Sub ShowTip ()
   Dim path As String
   Dim f As Integer
   Dim lineText As String
   Dim count As Integer
   Dim tip As String

   path = App.Data & "\tips.txt"
   If Dir$(path) = "" Then
      Exit Sub
   End If
   ' Each line is a tip; every one has the same chance
   Randomize
   f = FreeFile
   Open path For Input As #f
   Do While Not EOF(f)
      Line Input #f, lineText
      count = count + 1
      If Rnd * count < 1 Then
         tip = lineText
      End If
   Loop
   Close #f
   lblTip.Caption = "Tip: " & tip
End Sub

The tips are in tips.txt, in the program’s DATA folder, which Chapter 28 makes; until then there is no tip, and ShowTip stops at its If. The way it picks a line is worth a look, because it needs only one pass through the file and does not have to know how many lines there are. The first line is always taken (Rnd * 1 is less than 1). The second line replaces it half the time (Rnd * 2 < 1), the third a third of the time, and so on. At the end, every line has had the same chance of being the one kept.

24.5. The Event Procedures

When the form loads, it names the file in the program’s own folder for what it writes, App.User (Section 13.1), and reads the lists and the tip. Choose Form1 in the Object list:

Sub Form1_Load ()
   todoFile = App.User & "\todo.txt"
   LoadList
   ShowTip
End Sub

Add adds what was typed, unless it was only spaces, and empties the box for the next task. SetFocus puts the cursor back in the box, so the user can type the next task at once:

Sub cmdAdd_Click ()
   Dim task As String

   task = Trim$(txtTask.Text)
   If task <> "" Then
      lstTodo.AddItem task
      SaveList
   End If
   txtTask.Text = ""
   txtTask.SetFocus
End Sub

Done moves the chosen task to the Done list. ListIndex is -1 when no task is chosen, and a message says what to do:

Sub cmdDone_Click ()
   Dim i As Integer

   i = lstTodo.ListIndex
   If i < 0 Then
      MsgBox "Choose a task in the To do list first.", vbInformation
      Exit Sub
   End If
   lstDone.AddItem lstTodo.List(i)
   lstTodo.RemoveItem i
   SaveList
End Sub

Delete asks first, because a deleted task cannot be brought back (Section 14.2). With no task chosen it does nothing:

Sub cmdDelete_Click ()
   Dim i As Integer
   Dim question As String

   i = lstTodo.ListIndex
   If i < 0 Then
      Exit Sub
   End If
   question = "Delete " & lstTodo.List(i) & "?"
   If MsgBox(question, vbYesNo + vbQuestion) = vbYes Then
      lstTodo.RemoveItem i
      SaveList
   End If
End Sub

A double-click on a task in the To do list marks it done. Choose lstTodo, then [DblClick] in the Function list. An event procedure is a Sub like any other, so this one calls Done's rather than doing the same work twice:

Sub lstTodo_DblClick ()
   cmdDone_Click
End Sub

The menu items, each chosen in the Object list. HelpView opens a help file in DVX Help, and App.HelpFile is the program’s help file, which Chapter 26 gives it:

Sub mnuClearDoneList_Click ()
   lstDone.Clear
   SaveList
End Sub

Sub mnuExit_Click ()
   Unload Me
End Sub

Sub mnuContents_Click ()
   HelpView App.HelpFile
End Sub

The About box tells the program’s name, its version, what it does, and who made it, from the App object. Chapter 27 gives the project those details; until then the version is 0.0.0 and the lines below it are empty:

Sub mnuAboutToDo_Click ()
   Dim msg As String

   msg = App.ProductName & " " & App.Major & "." & App.Minor
   msg = msg & "." & App.Revision & vbCrLf
   msg = msg & App.FileDescription & vbCrLf
   msg = msg & App.LegalCopyright
   MsgBox msg, vbInformation, "About " & App.ProductName
End Sub

24.6. Testing It

Press F5. Type Buy milk and press Enter, then Call Ann, Write the report, and Paint the fence. Click Call Ann and press Alt+D: it moves to the Done list. Click Paint the fence and press Alt+L:

The To-Do window with Paint the fence chosen and a box titled To-Do asking Delete Paint the fence?
Figure 41. Deleting a task

The question’s box has the program’s name for its title, To-Do: a MsgBox given no title of its own is titled with App.Title, the project’s name. Click Yes, then add Water the plants.

The To-Do window: the To do list with Buy milk
Figure 42. The lists, after a run and after the next

Close the window and press F5 again: the lists are as you left them.

A program for other people meets things its programmer never tried. Before you give it away, use it as they will, and especially as they will by mistake:

  • Click Add with the box empty, or with only spaces in it. Nothing should be added.

  • Click Done and Delete with no task chosen.

  • Add a task too long for the list to show, and enough tasks to need the list’s scroll bar.

  • Use only the keyboard: Tab, the access keys, Enter, and the menus with Alt.

  • Make the window bigger and smaller.

  • Choose File › Clear Done List, then close and start the program again.

When something goes wrong with the saved lists, look at the file itself, with Notepad. To find out where it is, put a breakpoint on the line LoadList in Form1_Load and start the program with Shift+F5 (Section 10.4.2). When it stops there, type ? todoFile in the Immediate window. Run from DVX BASIC, the program has a folder of its own for testing in, so what you try never touches the lists of the To-Do you install later.

24.7. Try It Yourself

  • Make the Done button do nothing, rather than show the message, when no task is chosen. Which way is better for the user?

  • Add an Edit menu with an Undo item that brings back the last task deleted. (Keep the task in a variable in (General) before deleting it.)

  • Show how many tasks are left in the window’s caption: To-Do (3). Where do you have to update it?

Chapter 25. Giving Your Program an Icon

People find a program by its picture: Program Manager shows each installed program as an icon with its name under it. A program without an icon of its own gets a plain one, the same as every other such program. This chapter draws To-Do’s icon with the Icon Editor and gives it to the project.

25.1. Drawing It

An icon is a picture 32 dots wide and 32 high. That is very small: there is room for one simple thing, drawn with a strong outline and a few colors, and no room for words. To-Do’s icon is a sheet of paper with three boxes to tick, two of them ticked.

The Icon Editor: the enlarged grid with the white sheet
Figure 43. To-Do’s icon in the Icon Editor
  1. In Program Manager’s Installed Programs group, double-click Icon Editor. A new picture is 32 by 32, all light gray, the color of the background the icon is shown on.

  2. The line at the bottom of the window shows the position of the dot under the pointer, counting from 0 at the top-left corner, across and then down. Click black in the Palette, and draw the sheet’s outline: a box with its corners at 5, 2 and 25, 29. Click a dot to paint it, or hold the mouse button down and drag across a row of dots.

  3. Click white, and fill the inside of the box.

  4. Click the middle gray (darker than the background, lighter than the darkest gray), and draw the shadow: a line one dot to the right of the box, from 26, 3 down to 26, 30, and one along the bottom, from 6, 30 to 26, 30.

  5. Black again: three small boxes, 5 dots on a side, with their top-left corners at 8, 7, at 8, 15, and at 8, 23.

  6. Dark blue: a line two dots thick to the right of each box, from 15 to 22 across.

  7. Dark green: a tick in each of the first two boxes, two dots thick, going down from the box’s left side and up past its top-right corner.

There is no Undo: to fix a dot, paint over it. Tools › Color Picker makes the color of a dot you click the current color, and Tools › Eraser paints the background’s light gray. Look at the Preview as you go: it shows the icon at the size people will see it, and a detail too small to see there is better left out.

Choose File › Save…​, go to the project’s folder (TODO, in the PROJECTS folder of your user folder), and save the picture as todo.png.

25.2. Giving It to the Project

In DVX BASIC, with To-Do’s project open, choose File › Project Properties…​. On the General page, click Browse…​ beside Icon and choose todo.png. The icon appears beside the button.

The Project Properties window’s General page: Name To-Do
Figure 44. Project Properties with the icon

The icon must be 32 by 32, and it must be in the project’s folder, so that the project still finds it when the folder is copied somewhere else; DVX BASIC offers to copy one from another folder into it. Click OK, and save the project.

The icon goes into the program file each time the program is made (Chapter 27), and Program Manager shows it once the program is installed (Chapter 29).

25.3. Smaller Pictures

The Icon Editor’s Size menu also makes pictures of 24 by 24 dots, the size of a control’s picture in the Toolbox (the ToolboxIcon of a UserControl, Chapter 22), and 16 by 16. Changing the size starts a new, empty picture.

25.4. Try It Yourself

  • Draw an icon for a program of your own from Part II: the TinyPad of Section 14.5, say. Look at the icons in Program Manager first, and keep yours in the same style: light gray around it and a black outline.

  • Open todo.png in the Icon Editor, change the ticks' color, and save it. Make the program again: does Program Manager show the new icon after you install it again?

Chapter 26. Writing a Help File

A program for other people has to explain itself, because you will not be there to do it. DVX’s own programs do it with help: F1 opens the help at the page about what you are doing, and Help › Contents opens it at its beginning. A DVX BASIC program can have help just like theirs: a help file (.hlp), shown by DVX Help. This chapter writes To-Do’s.

26.1. What to Write

Write for someone who has never seen the program. They want to know what it is for, how to do each thing it does, and what each menu command does, in that order. Each subject is a topic, a page of its own in DVX Help, short enough to read at a glance, with links to the others. To-Do needs three:

  • What To-Do is, the topic F1 opens.

  • How to add tasks, mark them done, and delete them.

  • What each menu command does.

26.2. The Help Source

A help file is made from a help source, a text file whose name ends in .dhs. In Program Manager’s Installed Programs group, double-click Help Editor. It starts with a small example; choose File › Save As…​ and save it in the project’s folder as todo.dhs, then replace the example with To-Do’s help. The first topic:

.topic todo.overview
.title To-Do
.toc 0 To-Do
.default
.index To-Do

.h1 To-Do

To-Do keeps a list of the things you have to do.
Add each task as it comes up,
and mark it done when it is finished.
The lists are saved as you go,
so they are still there the next time you start To-Do.

.link todo.tasks Adding and finishing tasks
.link todo.menus The menus

Lines that start with a period are commands; the Help Editor shows them in color. Every other line is text:

Command What it does

.topic todo.overview

Starts a topic, and gives it a name. The program opens a topic by its name, so make the names short and keep them: todo. and a word.

.title To-Do

The topic’s title, in DVX Help’s title bar.

.toc 0 To-Do

Puts the topic in the table of contents, the tree at the left of DVX Help. The number is how far in: 0 at the left, 1 under the 0 before it.

.default

Makes this the topic DVX Help shows when the help file opens.

.index To-Do

Puts a word in the help’s index, which leads to this topic.

.h1 To-Do

A heading.

.link todo.tasks Adding…​

A link to the topic named todo.tasks, with the rest of the line as the text the reader clicks.

Lines of text next to each other make one paragraph, and DVX Help fits it to the width of its window, so where your lines end does not matter. Leave an empty line between paragraphs.

The second topic is a list, each .item a point of it, between .list and .endlist. An item goes on until the next command:

.topic todo.tasks
.title Adding and Finishing Tasks
.toc 1 Adding and Finishing Tasks
.index tasks

.h1 Adding and Finishing Tasks

.list
.item To add a task, type it in the box at the top
and press Enter (or click Add).
.item To mark a task done, choose it in the To do list
and click Done, or double-click it.
It moves to the Done list.
.item To take a task off the list without doing it,
choose it and click Delete.
.endlist

The third is a table. The lines between .table and .endtable are shown just as they are typed, with letters all the same width, so columns lined up with spaces stay lined up:

.topic todo.menus
.title The Menus
.toc 1 The Menus
.index menus

.h1 The Menus

.table
  Menu    Command            What it does
  ----    -------            ------------
  File    Clear Done List    Empty the Done list.
  File    Exit               Close To-Do.
  Help    Contents           Open this help.
  Help    About To-Do        Show the version and copyright.
.endtable
The Help Editor showing todo.dhs: the commands .topic
Figure 45. To-Do’s help source in the Help Editor

Help › Help File Format in the Help Editor shows every command there is, among them .note for a box that stands out, .image for a picture, and .code for lines shown as they are typed.

26.3. Compiling and Trying It

Choose Build › Compile. The Help Editor saves the source and turns it into the help file, todo.hlp, in the same folder; the line at the bottom of the window says whether it worked. Build › Preview compiles it and opens it in DVX Help, as the program’s users will see it:

DVX Help showing the To-Do topic: the table of contents at the left with To-Do
Figure 46. The help in DVX Help

Click every link, and look at each topic in the table of contents. When something is wrong, fix the source, and choose Build › Preview again.

26.4. Connecting It to the Program

In DVX BASIC, choose File › Project Properties…​, click Browse…​ beside Help File, and choose todo.hlp (the picture in Section 25.2 shows it chosen). Now:

  • App.HelpFile is the help file, so Help › Contents in To-Do, which says HelpView App.HelpFile, opens it.

  • F1 opens it at the topic named by the HelpTopic of the control that has the focus or, when that control has none, of the form. To-Do’s form has todo.overview (Section 24.1).

Press F5, and then F1: DVX Help opens in front of To-Do, at the To-Do topic.

When the program is made (Chapter 27), the help file is copied next to the program file, and a package of the program carries it (Chapter 29). After a change to the help source, compile it again before you make the program.

26.5. Try It Yourself

  • Give the two lists the HelpTopic todo.tasks. Press F1 while a list has the focus, and then while the text box has it.

  • Add a topic that tells where the lists are kept and that they are saved as you go, with a link to it from the first topic.

  • Add a tip to the first topic: .note tip before it and .endnote after.

Chapter 27. Version Information and Release Builds

A program you hand out says what it is, which version it is, and who made it, and it comes as a program file that runs without DVX BASIC. This chapter gives To-Do its version information and makes its program file.

27.1. Version Information

Choose File › Project Properties…​ and click the Make tab:

The Make page of Project Properties: Version 1.0.0
Figure 47. The Make page of Project Properties

Fill it in with your own name where the picture has Your Name:

Box What it is The program reads it as

Version

Which version this is: 1.0.0 for the first one people get.

App.Major, App.Minor, App.Revision

Author

Who wrote the program.

Publisher

Who puts it out: you, or your company.

App.CompanyName

Copyright

Who owns it, and since when.

App.LegalCopyright

Trademarks

Any trademarks it uses.

App.LegalTrademarks

Product

The program’s name as people see it; with none, the project’s Name.

App.ProductName

Description

What it does, in one line.

App.FileDescription

Comments

Anything else worth saying, in one line.

App.Comments

A version has three numbers with dots between them. The custom is to raise the last one for a version that only fixes mistakes (1.0.1), the middle one for a version that adds something (1.1.0), and the first one for a big change (2.0.0). Each version you hand out must have a higher number than the one before, so that people, and DVX, can tell which is newer (Chapter 31).

Click OK, and save the project. Press F5, and choose Help › About To-Do…​: the About box of Section 24.5 now has something to say.

A box titled About To-Do over the To-Do window: To-Do 1.0.0
Figure 48. The About box

The program file carries the version information too (Chapter 28).

27.2. Making the Program File

So far To-Do has run only inside DVX BASIC. To make the program file that runs on its own, choose File › Make Executable…​. The Save box suggests TODO.APP in the project’s folder; press Enter to take it. DVX BASIC then asks which kind of build:

The Build Mode box: Select build mode
Figure 49. Debug or release

A debug build keeps what DVX BASIC needs to tell where in the code an error happened, which makes it bigger. A release build leaves that out, so it is smaller, and the names of your forms and controls inside it are shortened as well. Programs you hand out are release builds, and File › Make Package…​ (Chapter 29) always makes one. Choose Release and click OK.

The line at the bottom of DVX BASIC’s window says Created, with the program file’s name. DVX BASIC also puts a copy of the help file and of the DATA folder (Chapter 28) next to the program file, where the program looks for them; in the project’s folder they are there already. Start the program from File Manager: double-click TODO.APP in the project’s folder. It runs just as it did in DVX BASIC, but on its own.

It finds the lists you made while testing: a program file in the project’s folder has the same App.User as the project run from DVX BASIC. Once To-Do is installed (Chapter 29), it has a folder of its own, and starts with empty lists.

27.3. Try It Yourself

  • Make a debug build too, under another name such as TODOD.APP, and compare the two files' sizes in File Manager.

  • Change Version to 1.0.1, make the program again, and look at the About box.

Chapter 28. Program Resources

A program file holds more than the program. DVX BASIC puts things in it that DVX reads without running the program, such as the icon Program Manager shows, called resources. And a program can come with files of its own, which go beside the program file in its DATA folder. This chapter looks inside TODO.APP, gives To-Do its tips, and shows how a program carries files inside its program file.

28.1. Inside the Program File

The Resource Editor shows a program file’s resources. In Program Manager’s Installed Programs group, double-click Resource Editor, choose File › Open…​, and open TODO.APP in the project’s folder:

The Resource Editor listing the resources of TODO.APP
Figure 50. TODO.APP in the Resource Editor

Each line is a resource, with its name, its type (Text, Icon, or Binary), and its size:

Resource What it holds

icon32

The icon of Chapter 25, which Program Manager shows.

name

The project’s Name, which Program Manager shows under the icon.

description

The Description of Chapter 27, the tip Program Manager shows when the pointer rests on the icon.

author, publisher, copyright, version

The rest of the version information.

helpfile

The name of the program’s help file, which F1 opens.

MODULE, FORM0

The program itself: its code, and its form (a program with more forms has FORM1 and so on, and a debug build has DEBUG too). Never change or remove these.

The Resource Editor can change a resource, add one, or take one out, but leave your own programs' resources to DVX BASIC: File › Make Executable…​ writes the program file afresh each time, from the project, and a change made with the Resource Editor is lost at the next Make. To change the icon or the version information, change the project.

28.2. Files That Come with the Program

Many programs need files of their own: pictures, sounds, the levels of a game, a list of words. They go in a folder named DATA in the project’s folder. A running program finds that folder as App.Data (Section 13.1), and DVX BASIC copies it next to the program file when it makes one, and into the package (Chapter 29), so the files are wherever the program is.

To-Do’s tips are such a file:

  1. In File Manager, go to the project’s folder and choose File › New Folder…​. Name the folder DATA.

  2. In Notepad, type the tips, one to a line:

    Double-click a task to mark it done.
    Press Enter to add the task you typed.
    Empty the Done list from the File menu.
    Press F1 for help.
  3. Save them in the DATA folder as tips.txt.

Press F5 in DVX BASIC. ShowTip (Section 24.4) finds the file now, and the tip line at the bottom of the window has one of the tips. Start the program a few more times to see others.

The To-Do window with a tip at the bottom
Figure 51. To-Do with a tip

A program reads its DATA files but never writes them: once installed, the program’s folder may be one the user cannot write, such as on a CD-ROM, and a new version of the program replaces them. What the program writes goes in App.User, as To-Do’s lists do.

28.3. Files Inside the Program

A program can also carry files inside its program file, as resources of its own, as a Visual Basic program carries its resource file. Then they go wherever the program goes, and can never be lost or left behind. The Resources page of File › Project Properties…​ lists them:

The Resources page of Project Properties: an empty Files list with Add…​ and Remove buttons beside it
Figure 52. The Resources page of Project Properties
  • Add…​ beside Files picks a file for the program to carry: a picture, a level of a game, any file at all. A file outside the project’s folder is copied into it first. Remove takes the chosen file off the list; the file itself stays.

  • String Table names a text file of the texts the program shows (see below).

Make Executable builds them all into the program file. When the program runs from DVX BASIC, it reads them from the project’s folder, so a file you change is seen at the next F5.

The program reads a file it carries with LoadResPicture, for a picture, and LoadResData, for any other file, giving the file’s name without its extension:

imgLogo.Picture = LoadResPicture("logo")    ' logo.png
level = LoadResData("level1")               ' every byte of level1.dat

That is why two files a program carries cannot have the same name before the dot, such as logo.png and logo.bmp: DVX BASIC refuses the second when you add it.

The string table is a text file, made in Notepad, in which each line gives a text a number or a name:

' To-Do's texts
1 = Nothing to do. Add a task!
Welcome = Welcome to To-Do

LoadResString(1) gives Nothing to do. Add a task!, and LoadResString("Welcome") gives Welcome to To-Do. A line that starts with ' is a note. With all its texts in one table, a program’s words are easy to check and change, and a translation of the program needs only another table.

Asking for a resource the program does not carry raises error 326 (Resource with identifier not found), which On Error can catch (Section 10.5). “Miscellaneous Functions” in the DVX BASIC Language Reference has all the details.

Which to use? A resource is part of the program: only a new Make changes it. A DATA file is a file of its own: the program can open a folder full of them, and a new one can replace the old without a new program. To-Do’s tips could be either; they stay in DATA.

A program carries fonts the same way, so its text looks the same on every DVX: the Fonts list on the General page puts them in the program file. “Project System” in the DVX BASIC Language Reference tells how.

28.4. Try It Yourself

  • Add three tips of your own to tips.txt. Do you have to make the program again to see them when it runs from DVX BASIC? And when it runs from TODO.APP?

  • Open another program in the Resource Editor, such as Notepad (NOTEPAD.APP, in DVX’s APPS\KPUNCH\NOTEPAD folder), and compare its resources with To-Do’s.

  • Put To-Do’s tips in a string table instead: the lines 1 = to 4 =, one tip each, and Count = 4. Then ShowTip needs only n = Val(LoadResString("Count")) and lblTip.Caption = "Tip: " & LoadResString(Int(Rnd * n) + 1). Make the program, and look for the table in the Resource Editor: it is the resource named STRINGS.

Chapter 29. Packaging Your Program

A program file, its help, and its DATA folder are several things to hand out, and the person who gets them has to know where to put them. A package is all of it in one file, whose name ends in .DPK. Anyone can install it with the Software program: Software puts the files in a folder of the program’s own, adds the program to Program Manager’s Installed Programs, and takes it all away again when the person no longer wants it. This chapter makes To-Do’s package and installs it.

29.1. Your Key

A package should be signed. A signature is like the seal on a letter: it tells the people who install the package that it came from you, and that nobody changed it on the way. You sign with a key of your own, which you make once, with Package Builder:

  1. In Program Manager’s Installed Programs group, double-click Package Builder.

  2. Click its Signing tab, and click New Key…​.

  3. Type the name people will see on what you sign, your own or your company’s, such as Your Name, and click OK.

  4. Package Builder suggests saving the key in your KEYS folder. Type a short file name for it, such as yourname, and press Enter.

Package Builder’s Signing page and a message: Your key is made. Give yourname.KEY to the people who install your packages: it tells DVX that they are yours. Keep yourname.SEC private: anyone who has it can sign packages as you.
Figure 53. Your key is made

A key is two files:

  • YOURNAME.KEY is the one you give away. People who have it can tell your packages from everyone else’s.

  • YOURNAME.SEC is the secret one you sign with. Keep it to yourself, and keep a copy somewhere safe, on a floppy disk, say. Anyone who has it can sign packages as you, and if you lose it, you can no longer sign new versions of your packages (Chapter 31).

Close Package Builder. It can make packages of anything, but DVX BASIC makes a program’s package by itself.

29.2. Making the Package

In DVX BASIC, with To-Do’s project open, choose File › Make Package…​. The first time, it asks for the package name: who made the package and what it is, with a dot between them, each part 1 to 8 lowercase letters or digits. It suggests one from the project’s Publisher and Name:

The Package Name box: The package name: who made it and what it is
Figure 54. The package name

The package name is how Software tells one package from another, so choose it once and keep it: every later version of To-Do must have the same package name. DVX BASIC saves it in the project (File › Project Properties…​, the Package page). Click OK.

The Save box suggests TODO.DPK in the project’s folder; press Enter. Then choose the key to sign with: the list has your keys, after Not signed.

The Sign Package box: Sign the package with
Figure 55. The key to sign with

DVX BASIC makes a release build of the program and puts it, the help file, and the DATA folder in the package. The package takes the rest from the project: its name, Version, Description (Software shows it as the package’s summary), Publisher, and Author. The line at the bottom says Created, with the package’s file name, and signed.

A program that needs another add-on package to work, one that does not come with DVX, names it under File › Project Properties…​, on the Package page, in Needs. To-Do needs nothing that DVX does not have.

29.3. Installing It

Try the package as the people who get it will. Start Software (in Program Manager’s Installed Programs), choose File › Install from File…​, and open TODO.DPK. Before it installs anything, Software shows what it will do:

The Install Software window: This is what will be installed
Figure 56. What Software will install

Click Install. Software puts To-Do in its own folder in DVX, APPS\YOURNAME\TODO, made from the package name, and tells you when it is done. Now look in Program Manager’s Installed Programs group, or type To-Do in its Search box:

Program Manager with To-Do typed in its Search box and the To-Do icon found
Figure 57. To-Do in Program Manager

There is To-Do, with its icon and its name. Double-click it: it starts with empty lists, because the installed program has a user folder of its own (Section 27.2). Press F1 and try Help › About To-Do…​ too.

To take To-Do away again, choose it in Software’s Installed list and click Remove. Its user folder, with the lists, stays.

29.4. Giving It Away

The package is ready to give to anyone with DVX: copy TODO.DPK onto a floppy disk, or send it any other way. On their DVX, opening the file in File Manager installs it with Software.

Give them your YOURNAME.KEY too, once. In Software, File › Trust a Publisher’s Key…​ with it tells their DVX that packages signed with your key are yours; until they do, Software marks your packages as signed by nobody they trust.

To give the program to everyone at once, publish it on the package server: the next chapter.

29.5. Try It Yourself

  • Install To-Do, add a few tasks, and remove it with Software. Install it again: are the tasks still there?

  • Choose To-Do in Software’s Installed list, then Package › Details…​: which files did the package put in DVX?

Chapter 30. Publishing to the Package Server

Everyone whose DVX is on a network can get packages from DVX’s package server: Software’s Available page lists what it offers, and its Updates page tells people when a newer version of what they have is there. Publishing a package puts it on that list, for everyone. This chapter publishes To-Do.

30.1. Your Account

To publish, you need an account on the package server. Software makes it: choose File › Package Server…​ in Software, type your email address and the password you want (at least 10 characters) in the boxes for your account, and click Create Account…​. Leave the server’s address and port empty, for DVX’s own server. Software asks you to type the password once more, to be sure of it: type it in the Confirm password box, and click OK.

The server sends a mail to your address with a code in it, such as ABCD-EFGH, to make sure the address is yours. You can read the mail on any computer. Type the code into the window Software shows, and click OK. Software says “Your account is ready. Software has saved the account in the package server’s settings.”, so you do this only once.

If you already have an account, type its email address and password in the same boxes and click OK instead. If you ever forget the password, type the email address there and click Forgot Password…​: the server mails you a code, and you type it with a new password (twice, to be sure of it).

Getting and updating packages needs no account; only publishing does. Software keeps the password scrambled in DVX’s settings, but scrambled is not locked, so give it only on a computer you trust.

30.2. Publishing the Package

Choose File › Publish a Package…​ in Software and open TODO.DPK. Software sends the package to the package server, which checks it the way DVX checks a package before installing it, and keeps it for review:

Software with a message that the package was published and is waiting for review
Figure 58. The package sent

Software’s Published page lists every version you have sent, and how its review went:

Software’s Published page listing To-Do 1.0.0
Figure 59. The Published page

A person, the server’s operator, looks at each package before it is offered to everyone: that it installs and runs, that it does what its summary says, and that it does nothing it should not. Then:

  • Published: the operator approved it and signed it with DVX’s own key, which every DVX trusts. To-Do is on everyone’s Available page now, and anyone can install it with a click.

  • Turned down: the operator’s note says why. Fix what it says, raise the Version (a version once sent cannot be sent again), make the package again, and publish that.

Click Refresh on the Published page to see how the review is going.

A package name belongs to the account that first published it: nobody else can publish a package named yourname.todo, and your later versions of To-Do must come from your account.

30.3. Try It Yourself

  • After To-Do is published, find it on Software’s Available page by typing to-do in the Find box.

  • Write the summary you would want to read about To-Do if you came across it on the Available page. Is your project’s Description as good?

Chapter 31. Updates and Support

A published program is not finished: its users find mistakes, and ask for things it does not do yet. This last chapter brings out a new version of To-Do, and helps the people who use it.

31.1. A New Version

Say To-Do should show how many tasks are left, in its caption. Make the change in the project, and test it as in Section 24.6. Then:

  1. Raise the Version in File › Project Properties…​, on the Make page. The change adds something, so the middle number goes up: 1.1.0 (Section 27.1). Update the help too, if the change is something users should know about.

  2. Choose File › Make Package…​. It does not ask for the package name again: it is the same package, a newer version of it. Sign it with the same key as the first version. Software installs a new version over the old only when the same key signed both, so nobody else can replace your program with one of theirs.

  3. Install the new package with Software, over the old one. Software says it is an upgrade of the version you have. Check that the program still has its lists: a new version never touches App.User, which is why To-Do keeps them there.

  4. Publish it (Section 30.2). Once it is approved, everyone who has To-Do sees it on Software’s Updates page, and gets it with Update All.

When the new version leaves out a file the old one had, Software removes that file in the upgrade, so a package never has to clean up after an older version of itself.

Your secret key, the .SEC file, is what lets you do this. Keep the copy you made in Section 29.1 safe, apart from the computer it is on, and make a new copy when you change computers.

31.2. Helping the People Who Use It

People who use your program will have questions, and some will find mistakes. Make it easy for them:

  • Tell them how to reach you. The Comments of the version information (App.Comments) can hold your email address or web site, and the About box can show it.

  • Answer in the help. A question asked twice belongs in the help file, so the next person finds the answer with F1.

  • When someone reports a mistake, find out which version they have (the About box says), what they did, and what happened. A run-time error is also written in DVX’s log, the file DVX.LOG in the user folder, with the error and where it happened; ask them to send it.

  • Do what you can to find the mistake yourself: run the program in DVX BASIC and do what they did, with the debugger ready (Chapter 10).

  • Fix it, raise the last number of the version (1.1.1), and publish again.

31.3. What Next

You have gone all the way from your first MsgBox to a program anyone with DVX can install. From here:

  • This book’s companion, the DVX BASIC Language Reference, describes every statement, function, control, property, and event of DVX BASIC, and every window of DVX BASIC itself. When you want to know what something can do, look there.

  • DVX BASIC’s help (F1 in DVX BASIC) has the same reference, while you work.

  • Look at the programs you like using, DVX’s own among them: how their windows are laid out, what their menus hold, how their dialog boxes ask and their help answers. Many of them, Notepad, the Icon Editor, and the Help Editor among them, are written in DVX BASIC, so everything they do, yours can do too.

  • Write the program you wanted when you started this book.

31.4. Try It Yourself

  • Make the change of this chapter: show the number of tasks left in To-Do’s caption, as To-Do (3). Bring it out as version 1.1.0, and install it over 1.0.0.

  • Put your email address in Comments, and show it in the About box.

Index

A B C D E F G H I J K L M N O P Q R S T U V W

A

B

C

D

E

F

G

H

I

J

K

L

M

N

O

P

Q

R

S

T

U

V

W