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.
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 : 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.
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
-
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.
-
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:
- 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.
2.3. Design and Code
-
Design view shows the form in the designer, with the Toolbox and the Properties window: , or Shift+F7.
-
Code view shows the form’s code in the Code window: , or F7.
The two buttons at the right end of the toolbar do the same.
2.4. The Toolbar
| Button | What it does |
|---|---|
Open |
Opens a project (). |
Save |
Saves the file you are working on (, Ctrl+S). |
Run |
Runs your program (, F5). |
Stop |
Stops your program (, 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
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 , 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:
-
Choose . (With the keyboard: Alt+F, then P.)
-
DVX BASIC asks for the project’s name. Type
Helloand click OK (or press Enter). -
DVX BASIC then asks where to save the project, and suggests a folder of its own for it:
HELLO, in thePROJECTSfolder of your user folder (usuallyC:\DVX\USER\PROJECTS\HELLO), with the project filehello.dbpin it. Click Save to take the suggestion.
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:
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:
-
In the Properties window, click Caption in the list (it is the third line).
-
Double-click it, or press Enter. The Edit Property box opens with the caption in it, already selected.
-
Type
My First Program. What you type replaces the old caption. Click OK.
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.
-
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.
-
Click the tool, then click anywhere on the form. A button named
Command1appears.
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:
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:
Click Say Hello. The message appears in a box titled with the project’s name:
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.
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.
-
Go back to the form: press Shift+F7 ().
-
In the Toolbox, click the Label tool (the first one in the fourth row; its tooltip says Label), then click the form.
Label1goes below the button. -
A label shows its Caption. Clear it, so the label starts empty: in the Properties window, double-click Caption, press Delete, and click OK.
-
Double-click the button to go back to its code, and change the line inside
Command1_Clickto: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:
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
-
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 , 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.
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.
-
Choose , type
Practice, and click OK; then click Save to take the folder DVX BASIC suggests. -
You do not need the form this time. In the Project window, click
Form1.frm, then choose . DVX BASIC asks whether to remove it from the project: click Yes. It then asks whether to save it first: click No. -
Choose . 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. -
Click below
Option Explicit, leave an empty line, and type these two lines:Print "Hello from Module1" Print 2 + 3 -
Press F5. The Output window shows:
Hello from Module1 5
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 |
|
|
Subtract |
|
|
Multiply |
|
|
Divide |
|
|
Divide, and drop what is left over (whole-number division) |
|
|
What is left over after whole-number division (the remainder) |
|
|
Raise to a power: |
|
\ 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.
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 |
|---|---|---|
A whole number from -32,768 to 32,767 |
|
|
A whole number from about -2 billion to 2 billion |
|
|
A number that can have decimals, with about 15 digits of precision |
|
|
An amount of money: exact to four decimal places, so totals never drift |
|
|
Text of any length |
|
|
|
|
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
-
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, orIf.
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 . Do that for every project you start from now on in one step: choose , 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 |
|---|---|
|
The number at the start of the text: |
|
The number as text, without the spaces |
|
The number as text, with as many decimals as the format has zeros after the point: |
|
The whole number at or below it: |
|
The nearest whole number: |
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.
-
Choose , name the project
TempConv, and click Save to take the suggested folder. (DVX BASIC closes the Practice project; you can open it again with .) -
Set the form’s Caption to
Temperature Converter. -
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
Label1Caption:
Degrees Fahrenheit:TextBox
Text1Text: nothing (delete the
Text1that is there)CommandButton
Command1Caption:
ConvertLabel
Label2Caption: 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:
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.
-
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 -
Press F5. Type
98.6in the box and click Convert:
Read the procedure line by line:
-
The two
Dimlines 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 / 9is 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
\andMod).
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
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
| Operator | Asks | Example that is true |
|---|---|---|
|
Equal to? |
|
|
Not equal to? |
|
|
Less than? |
|
|
Greater than? |
|
|
Less than or equal to? |
|
|
Greater than or equal to? |
|
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.
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(Isstands for the value being tested); -
Case Elsefor every value no otherCasematched.
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.
-
Start a new project called
Guess. Set the form’s Caption toGuess the Number. -
Place a Label, a TextBox, a CommandButton, and another Label, as in the temperature converter, and set:
Control Name Set this property Label
Label1Caption:
I am thinking of a number from 1 to 100.TextBox
Text1Text: nothing
CommandButton
Command1Caption:
GuessLabel
Label2Caption: 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.
-
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 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 -
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 -
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.SetFocusis 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, andExit Subleaves the procedure at once: none of the lines below it run. -
guesses = guesses + 1counts the guess. Becauseguessesis a shared form-level variable, it still holds the count from the last click. -
The
If ... ElseIf ... Elseblock compares the guess with the secret number and puts the answer inLabel2.
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
guessesback to 0, and clearsLabel2. -
Make the game say "Very close!" when the guess is within 3 of the secret number. (Hint:
Abs(guess - secret) <= 3.Absgives a number without its minus sign.) -
In the Practice project, make a variable
hourfrom 0 to 23 and print "Good morning", "Good afternoon", or "Good evening" withSelect Caseand 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
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
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
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
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 (). 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.
-
Start a new project called
Tablesand set the form’s Caption toTimes Tables. -
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. -
Place a Label, a TextBox, a CommandButton, and a ListBox, and set:
Control Name Set this property Label
Label1Caption:
The times table for:TextBox
Text1Text: nothing
CommandButton
Command1Caption:
ShowListBox
List1MinHeight:
200The ListBox tool is the third one in the fourth row of the Toolbox. A control stands as tall as its MinHeight says (
30when 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. -
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 -
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 anIfwithModinside 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
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:
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.
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.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.
-
Start a new project called
Converter, and set the form’s Caption toTemperature Converter. -
Place a Label, a TextBox, two CommandButtons, and another Label, and set:
Control Name Set this property Label
Label1Caption:
Temperature:TextBox
Text1Text: nothing
CommandButton
Command1Caption:
To CelsiusCommandButton
Command2Caption:
To FahrenheitLabel
Label2Caption: nothing
-
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 -
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 -
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 -
Press F5, type a temperature, and try both buttons.
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 Doublethat gives back the larger of its two numbers, and printLarger(3, 7)andLarger(-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 |
|---|---|
|
The number of characters in |
|
The first |
|
The last |
|
|
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.
-
Start a new project called
WordCountand set the form’s Caption toWord Counter. -
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
TextArea1Text: nothing
Label
Label1Caption:
0 words, 0 charactersThe TextArea grows to fill the room the label leaves.
-
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 -
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 -
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 Longthat counts how many times the characterchappears ins, 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 (
levelis one;stressedis not). Ignore capitals withLCase$. -
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
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.
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 |
|---|---|
|
Add a value at the end. |
|
Get how many values it holds. |
|
Get value number |
|
Remove value number |
|
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).
-
Start a new project called
HighScores. Set the form’s Caption toHigh Scoresand its Height to400. -
Place the controls and set:
Control Name Set this property Label
Label1Caption:
Name:TextBox
Text1Text: nothing
Label
Label2Caption:
Score:TextBox
Text2Text: nothing
CommandButton
Command1Caption:
AddListBox
List1MinHeight:
150 -
Press F7 and type the shared variables in (General):
Dim players() As String Dim points() As Integer Dim entries As Integer -
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 -
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 -
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
entriesback to 10. -
Write a Function
Average(values() As Integer) As Doublethat gives the average of any array of scores. (A parameter writtenvalues()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.ListIndexis 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 |
|---|---|
|
A misspelled variable, or one you forgot to make with |
|
A word or a sign is missing where the message says: here the |
|
A block that is not closed: an |
|
A word where it makes no sense, such as a |
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 |
|---|---|
|
A function was given a value it cannot use, such as |
|
A number too big for its variable’s type (40000 in an |
|
An array index outside the array’s range. |
|
A division by 0. |
|
Text that is not a number where a number is needed ( |
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
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:
-
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. -
Start the program with (Shift+F5) instead of F5. A program started with F5 runs straight through; one started with Debug stops at its breakpoints.
-
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:
iis 1 andtotalis 0. -
Press F8 () to run that one line. The yellow line moves to
Next i, and in the Locals windowtotalis now 70. Press F8 again and again, and watchiandtotalchange. -
While the program is stopped, the Immediate window can show any value: click in it, type
? total / 4and press Enter. (?is short forPrint.) You can even change a variable there:total = 0. -
When
iis 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 () 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 Expliciton, 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.Printor 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
Integerand type a huge number. Then make it handle the error withOn Error GoToand show a message instead. -
Write a program with a
Forloop 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:
-
When it starts, DVX BASIC loads the project’s startup form (
Form1, unless names another) and runs itsForm1_Loadprocedure, if it has one, before the window appears. -
Then the program waits. It does nothing at all until the user does something.
-
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.
-
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 |
|---|---|
|
The name your code uses for the control. Set it in the Properties window only. |
|
What a label, button, or check box shows ( |
|
|
|
|
|
The colors of its text and its background, made with |
|
The font of its text. The Font row of the Properties window sets them all at once. |
|
A hint shown when the mouse rests on the control. |
|
How it is sized on the form (see Section 11.4). |
|
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 |
|---|---|
|
The control is clicked: the mouse button goes down and comes up over it. For a list, an item is picked. |
|
The control is double-clicked. |
|
The text or value of the control changes, by the user or by your code. |
|
A key that types a character is pressed in the control. |
|
Any key goes down or comes up, the arrow keys too. |
|
The control gets the keyboard, or loses it. |
|
A mouse button goes down, the mouse moves, a button comes up. A click is |
|
(The form) It is loaded, before it appears. |
|
(The form) The window changes size. |
|
(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.
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
Weight0 keeps its size. Labels, buttons, and check boxes start with 0. -
Controls with a
Weightabove 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
-
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%and20chsizes too. -
Alignment: where the controls go when they do not fill the container:
Left,Center, orRight(for a column,Leftis the top andRightthe bottom). A row of buttons withAlignmentset toRightsits 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.
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.
11.5.1. Designing It
-
Start a new project called
SignUp. Set the form’s Caption toJoin the Cluband its Height to200. -
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.
-
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; theNis shown underlined.) -
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.
-
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. -
Make the third row: an HBox below the second, and in it two CommandButtons. Set their captions to
OKandCancel. -
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 DefaultTrueis pressed by Enter, wherever the cursor is on the form. Select the Cancel button and set its Cancel toTruethe same way: Esc presses it. -
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
LefttoCentertoRight. The buttons move to the right.
The controls and their settings, for checking:
| Control | Name | Set this property |
|---|---|---|
HBox |
|
|
Label |
|
Caption: |
TextBox |
|
Text: nothing |
HBox |
|
|
Label |
|
Caption: |
TextBox |
|
Text: nothing |
HBox |
|
Alignment: |
CommandButton |
|
Caption: |
CommandButton |
|
Caption: |
11.5.2. The Code
-
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 -
Press Shift+F7 to go back to the designer, and double-click the name box. Its
Changeevent 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 SubTrim$(Text1.Text) <> ""isTrueorFalse, and a property that takesTrueorFalsecan be set to it directly: noIfis needed. -
The phone box should take only digits, spaces, and dashes. In the Code window, choose
Text2in the Object list, and then[KeyPress]in the Function list. (ChoosingText2first makes an emptyText2_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 SubBackspace 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,InStrlooks for its character in the string of the allowed ones (Section 8.2), and when it is not there,KeyAscii = 0throws the key away. -
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 -
And the Cancel button:
Sub Command2_Click () Unload Me End Sub -
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.
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.SetFocusmoves 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'Changeprocedures can call one Sub that decides.) -
Give the phone box a Mask of
() -##instead of theKeyPressprocedure, 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 isTrue). Then put a TextArea for comments between the second and third rows, and see who gets the room now. -
Give the form a
Form1_Resizeprocedure 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 |
|
|
Label |
|
|
TextBox |
|
|
CheckBox |
|
|
OptionButton |
|
|
ListBox |
|
|
ComboBox, DropDown |
|
|
SpinButton |
|
|
ProgressBar |
|
|
Timer |
|
|
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
| Use | To |
|---|---|
|
Add a line at the end. |
|
Get how many lines it has. |
|
Get the number of the line picked, counting from 0; -1 when none is. |
|
Get the text of the line picked. |
|
Get the text of line |
|
Remove line |
|
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.
12.5.1. Designing It
-
Start a new project called
PizzaOrder. Set the form’s Caption toPizza Orderand its Height to400. -
Place an HBox, then a Frame in it (the third tool in the second row). Set the frame’s Caption to
Size. -
Click the OptionButton tool (the first in the fifth row) and click inside the frame. Set the button’s Caption to
Small, its Name tooptSize, and its Index to0. -
Place two more option buttons in the same frame (clicking anywhere inside the frame puts the new one below the others). Caption them
MediumandLarge, and name bothoptSize: they becomeoptSize(1)andoptSize(2). -
Place a second Frame in the HBox, to the right of the first, with the Caption
Toppings. Put three CheckBoxes in it, captionedCheese,Mushrooms, andOlives, as the control arraychkTop: name the firstchkTopwith the Index0, then the otherschkTop. -
Below the frames, place another HBox with a Label (Caption
Crust:) and a DropDown (the second tool in the second row) namedcboCrust. -
Below that, a third HBox with a Label named
lblPrice(no Caption) and a CommandButton namedcmdAddwith the Caption&Add to Order. -
Below the rows, place a ListBox named
lstOrder, and below it a Label namedlblTotalwith the CaptionTotal: $0.00. -
The order list should take the room the other controls leave. Select it and set its Weight to
1(Section 11.4.2).
12.5.2. The Code
-
Press F7. In (General), type the variable that holds the order’s total, which every procedure needs to see:
Dim total As Currency -
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 FunctionThe loops go through the control arrays. A size costs 8 dollars, plus 2 for each size up:
8 + 2 * iis 8, 10, or 12. -
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 -
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 -
Choose
Form1in the Code window’s Object list. ItsLoadprocedure 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 -
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
Clickprocedure the lineShowPrice, as shown in Section 12.4. Every choice now shows the new price at once. -
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 SubThe pizza’s price goes with its line as its ItemData. ItemData holds whole numbers only, so the price goes in cents:
price * 100. -
Choose
lstOrderin 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 -
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.
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:
Truewhile it runs. Set it toFalsein the Properties window and the timer waits until your code sets it toTrue.
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.
-
Start a new project called
EggTimer, with the CaptionEgg Timerand the Height200. -
Place an HBox, and in it a Label with the Caption
&Minutes:and a SpinButton (the fourth tool in the sixth row) namedspnMinutes. -
Below the row, place a Label named
lblLeftwith the Caption3:00, a ProgressBar (the third tool in the fifth row) namedprgTime, and a CommandButton namedcmdStartwith the Caption&Start. -
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 ittmrTick, set its Interval to1000, and set its Enabled toFalse(select it and press Enter). -
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 SubsecondsLeft \ 60is the whole minutes left andsecondsLeft Mod 60the seconds after them (Section 4.2);Format$with"00"writes the seconds with two digits,3:05and not3:5. The bar is full when no seconds are left. -
The form’s
Loadprocedure sets the spin button’s range and its starting value:Sub Form1_Load () spnMinutes.SetRange 1, 60 spnMinutes.Value = 3 End Sub -
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 -
Choose
tmrTickin the Code window’s Object list. ItsTimerprocedure 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 -
Press F5, set 1 minute, and click Start.
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 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 largesize to the pizza order: a fourth option button,optSize(3), for 14 dollars. Which lines of the code must change? (The loops sayTo 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
Timerprocedure showsTime$, 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 |
|---|---|
|
Everything the program writes: its settings, its lists, saved games, documents. DVX makes the folder the first time the program uses |
|
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. |
|
The |
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 #fmakes the file, or empties it if it is there already, ready for writing.fis the file’s number: every statement that works on the file says which one with#f. -
FreeFilegives 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 asPrintwould show it. -
Close #ffinishes 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 Inputopens a file for reading.Line Input #f, lineTextreads its next line intolineText, andEOF(f)(for end of file) isTrueonce every line has been read, which is what theDo 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
DVX BASIC has a statement for most things you do with files in a file manager:
| Statement | Does |
|---|---|
|
Delete a file. |
|
Rename a file, or move it to another folder on the same disk. |
|
Copy a file. |
|
Make a folder, or remove an empty one. |
|
The size of a file, in bytes. |
|
The first file whose name fits a pattern such as |
“File System Statements” in the DVX BASIC Language Reference and “File I/O” in the DVX BASIC Language Reference describe them all, with the error each one can give.
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.
-
Start a new project called
Shopping, with the CaptionShopping List. -
Place an HBox, and in it a TextBox named
txtItem(no Text) and a CommandButton namedcmdAddwith the Caption&Addand DefaultTrue, so Enter adds what was typed. -
Below the row, place a CheckBox named
chkSortedwith the Caption&Sorted, and a ListBox namedlstItemswith Weight1. -
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 SubSaveListwrites every line of the list, fromList(0)toList(ListCount - 1), into the fileFor Output, which replaces what the file held before: the file always holds the list as it is now. -
The form’s
Loadprocedure (chooseForm1in 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 Subsaved = "True"isTrueorFalse, just what a check box’sValuetakes. The setting is checked before the list is read, so the list is sorted as its lines come in. -
Double-click the check box. Its
Clickprocedure 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 -
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 -
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 -
Press F5, add a few things, tick Sorted, and close the window. Press F5 again: the list is back, sorted.
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 withInput #inForm1_Load. -
Give the shopping list a Clear button that empties the list, after asking with
MsgBox "Clear the whole list?", vbYesNo(the answer isvbYesorvbNo). -
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.txtfile inApp.Userin a ListBox.
Chapter 14. Menus and Dialog Boxes
A program with more than a few commands puts them in menus: , , . 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 (Ctrl+E).
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 |
Name |
The name the code uses. DVX BASIC makes one from the caption, |
Shortcut |
A key that chooses the item at once, without opening the menu, such as |
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.
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 |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 and pick it from the list:
| Library | Gives your program |
|---|---|
|
The common dialog boxes: Open, Save As, a folder, a color, a font, and message boxes with buttons of your own. |
|
Files and folders: listing them, copying and deleting whole folders, free disk space, and saving a document safely. |
|
Databases (Chapter 18). |
|
Sound effects and music (Chapter 19). |
|
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.
| Function | Shows |
|---|---|
|
An Open box, starting in the current folder. |
|
An Open box starting in |
|
A Save box starting in |
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.
14.5.1. The Form and Its Menus
-
Start a new project called
TinyPad, with the CaptionTinyPad. -
Place a TextArea (the second tool in the eighth row), name it
txtDoc, and set its Text to nothing. It fills the form. -
Choose 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&NewCtrl+N&Open...Ctrl+O&SaveCtrl+SSave &As...-E&xit&EditCu&tCtrl+X&CopyCtrl+C&PasteCtrl+V-Select &AllCtrl+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.) -
Choose , pick
commdlg.bas, and click OK. Do the same forfileops.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
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.
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
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.
14.6. Try It Yourself
-
Gray out while there is nothing to save: set
mnuSave.Enabled = changedinShowTitle. -
Add a item with the shortcut F3 that searches for
lastFindagain without asking. -
Add a Format menu with a item that lets the user choose the TextArea’s font with
DlgFontfromcommdlg.bas. GiveDlgFontthe flagDLG_FONT_FIXED, so it offers only the fonts a TextArea can show (“Include Libraries” in the DVX BASIC Language Reference describesDlgFont). -
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
15.2. Showing, Hiding, and Unloading
| Statement | Does |
|---|---|
|
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. |
|
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 |
|
Hides the form. It is still loaded: its controls keep what is in them, ready to read. |
|
Closes the form and frees its controls. |
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: 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.
15.5.1. The Main Form
-
Start a new project called
Contacts, with the CaptionContacts. -
Place an HBox and in it three CommandButtons:
cmdAdd(Caption&Add...),cmdEdit(&Edit...), andcmdDelete(&Delete). -
Below the row, place a ListBox named
lstContactsand set its Weight to1.
15.5.2. The Dialog Box
-
Choose . Set
Form2’s Caption to `Contactand its Height to200. -
Give it the rows of the sign-up form of Section 11.5: a row with a Label
&Name:and a TextBoxtxtName, a row with a Label&Phone:and a TextBoxtxtPhone(both with no Text), and a row at the right withcmdOK(CaptionOK, DefaultTrue) andcmdCancel(CaptionCancel, CancelTrue). -
Press F7. In (General), the variable that tells the main form which button was clicked:
Public accepted As Boolean -
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 -
Choose
Form2in 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
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.
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 SubbeforeHide). -
Save the contacts to a file when the program ends (the main form’s
Unloadevent) and read them back inForm1_Load, withWrite #andInput #(Section 13.4). -
Add an About box: a third form with a Label and an OK button, shown with
Show vbModalfrom a ? button on the main form. -
Show the dialog box modeless (
Form2.ShowwithoutvbModal) and see what goes wrong: the code afterShowgoes 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.
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 |
|---|---|---|---|
|
|
|
|
A color is a number (a Long), so a variable can hold one: Dim penColor As Long.
16.3. Points, Lines, Boxes, and Circles
| Statement | Draws |
|---|---|
|
One point. |
|
A line from one point to another. |
|
A line on from where the last drawing ended. |
|
A box with those two corners. |
|
A box filled with the color. |
|
A circle around a center point. |
|
Nothing: it clears the drawing to its background color. |
-
DrawWidthis the width of the pen, in pixels (1 to start with). -
FillStyleset tovbFSSolid(0) fills circles and boxes withFillColor;vbFSTransparent(1, the start) leaves them empty. -
BackColoris the colorClsclears to.
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.
-
Start a new project called
Scene, with the CaptionMy House. -
Place a PictureBox and name it
picScene. -
Choose
Form1in the Code window’s Object list, and inForm1_Loadgive the drawing its size:Sub Form1_Load () picScene.Resize 300, 200 End Sub -
Choose
picScenein 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 -
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.
-
Start a new project called
Sketch, with the CaptionSketch Pad, the Width440, and the Height400. -
Place an HBox, and in it four OptionButtons captioned
Black,Red,Green, andBlue, as the control arrayoptColor(Section 12.4). -
Below it, another HBox with a Label
&Width:, a SpinButton namedspnWidth, and two CommandButtons,cmdClear(&Clear) andcmdSave(&Save). -
Below the rows, a PictureBox named
picPad. -
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 -
The form’s
Loadprocedure 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 -
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.)
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,
DrawWidthtimes 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.
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 . Then:
-
Choose . DVX BASIC adds
Class1.clsunder Classes in the Project window and opens it. -
A class’s name is the name of its kind of object. Select
Class1.clsin the Project window, choose , and typeAccount. The class is calledAccountnow. -
Type the class’s code below its
Option Explicitline, 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
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
Transfermethod toAccountthat moves an amount to another account given as a parameter (ByVal toAccount As Account), usingWithdrawandDeposit. -
Give
AccountaClass_Initializethat starts every account with a 5-dollar welcome bonus, and check thatbennow has 25. -
Write a
Dieclass with aRollmethod that gives a random number from 1 to itsSidesproperty (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 |
|---|---|
|
Makes a table with two columns of text. |
|
Adds a row. |
|
Gives every row’s title and author, in title order. |
|
Changes the rows that match. |
|
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 (Section 14.4).
| Function | Does |
|---|---|
|
Opens a database file, making it when it is not there. Gives back a number for it, 0 when it could not. |
|
Runs a statement that gives back no rows: |
|
Runs a |
|
Moves to the result’s next row; |
|
The value in the current row’s column, as text. |
|
Frees a result when the program is done with it. |
|
Closes the database. |
|
Why the last thing that failed did. |
|
The text with every single quote doubled, ready to go between quotes in a statement. |
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.
-
Start a new project called
Books. GiveForm1the CaptionBooksand, as in the sign-up form of Section 11.5, a row with a Label&Title:and a TextBoxtxtTitle, a row with a Label&Author:and a TextBoxtxtAuthor(both with no Text), and a row at the right with two CommandButtons:cmdAdd(Caption&Add, DefaultTrue) andcmdTable(CaptionTa&ble...). -
Below the rows, a ListBox named
lstBookswith Weight1. -
Add the
sql.baslibrary (). -
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 -
Form1_Loadopens 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 SubCREATE TABLE IF NOT EXISTSmakes the table only when it is not there yet, so the books of last time stay. Theidcolumn,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,Endends the program at once. -
Form1_Unload(chooseForm1, then[Unload]) closes the database:Sub Form1_Unload (Cancel As Integer) SQLClose db End Sub -
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:
-
Choose . Give
Form2the CaptionBook Table. -
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 to1. -
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 -
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
idin the ListBox’sItemDatawhen filling the list, withSQLField$(rs, "id"), and deleteWHERE id =that number.) -
Add a
yearcolumn and show the books in the order they were written. (An existing table needsALTER TABLE books ADD COLUMN year INTEGER; or deletebooks.dbfromApp.Userand start again.) -
Put two TextBoxes on
Form2, bound toData1with the DataFieldstitleandauthor, 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 |
|---|---|
|
Play that note. |
|
A pause (a rest) of length n. |
|
The octave of the notes that follow, from 0 to 6. |
|
Up or down one octave. |
|
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. |
|
The tempo, in quarter notes a minute, from 32 to 255 (120 to start with). |
|
Music background: the program goes on while the tune plays. |
|
Music foreground: the program waits until the tune has played (the way to start with). |
|
Play on General MIDI instrument n: 1 is the piano, 41 the violin, 74 the flute. |
|
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 (), 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.
-
Start a new project called
Catch, with the CaptionApple Catch. -
Place a Label named
lblScorewith the CaptionScore: 0, and below it a PictureBox namedpicField. -
Place a Timer (the last tool in the eighth row) named
tmrStart, with the Interval100. -
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.) -
Add the
game.baslibrary ().
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
Press F5, then Space, and catch some apples.
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:MusicLoadMacroinForm1_Load,MusicPlay tune, TrueinNewGame, andMusicStop tunewhen the game ends. -
Drop two apples at once. (Arrays for
appleXandappleY, and aForloop inMoveAppleandDrawField.)
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 (). 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.
20.3. A Certificate
-
Start a new project called
Cert, with the CaptionCertificateand the Height200. -
As in the sign-up form of Section 11.5, give it a row with a Label
&Name:and a TextBoxtxtName, a row with a Label&Course:and a TextBoxtxtCourse(both with no Text), and a row at the right with a CommandButtoncmdPrint, with the Caption&Print...and DefaultTrue. -
Add the
print.baslibrary (). -
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
Press F5, type a name and a course, and print.
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 asNovember 3, 2026. -
Print certificates for a whole class: names in a ListBox,
DrawCertificatefor each,Printer.NewPagebetween them, and onePrinter.EndDocat the end. -
Give TinyPad and .
-
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 (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_LEFTis the left arrow key’s number. -
DECLARE LIBRARY "game"names the part of DVX that does the work, and the declarations up to itsEND DECLAREare the functions it has. -
DECLARE FUNCTION GameKeyDown(BYVAL keyCode AS LONG) AS LONGsays thatGameKeyDowntakes one number,keyCode, and gives back a number.BYVALmeans the function gets the value and cannot change your variable. A function that answers yes or no gives backTrue(-1) orFalse(0), soIf GameKeyDown(GAMEKEY_LEFT) Thenworks as you would expect. -
DECLARE SUBlines declare procedures that give back nothing.
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 ) 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 |
|
Open, Save As, choosing a folder, a color, or a font, and message boxes with buttons of your own. |
Files |
|
Folder listings, file and folder sizes, free disk space, copying and deleting whole folders, paths, and saving a file safely. |
Settings |
|
Settings files with sections, read, changed, and saved, and DVX’s own settings. |
Data |
|
Databases (Chapter 18). |
|
Reading JSON, the format web services answer in. |
|
Sound and games |
|
Sound files, music files, held keys, and joysticks (Chapter 19). |
Printing |
|
Printing text and pictures, and the Print and Page Setup dialogs (Chapter 20). |
Text and fonts |
|
The fonts DVX has and their sizes. |
|
RTF, the text of word processors, as plain text and back. |
|
|
Control sizes in characters or percent instead of pixels. |
|
Help |
|
Showing DVX Help or your program’s help file (Chapter 26), and making help files. |
|
Reading help files, for a help viewer of your own. |
|
Resources |
|
Pictures, text, and data kept inside a program file (Chapter 28). |
Networks |
|
Network connections and the network’s settings. |
|
Fetching web pages and files from the web. |
|
|
Serial ports and modems, connections like Terminal’s, and file transfers. |
|
DVX itself |
|
Starting programs and opening documents, and everything Program Manager and Task Manager do. |
|
What the Control Panel changes: the screen mode, colors, wallpaper, and the mouse. |
|
|
Add-on packages, and the software server (Chapter 30). |
|
Security |
|
Random numbers good enough for keys, hashes, signatures, and ciphers. |
Programming tools |
|
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.
-
Start a new project called
Sizes, with the CaptionFolder Sizes. -
Place an HBox, and in it a CommandButton
cmdFolderwith the Caption&Folder...and a LabellblFolderwith no Caption. -
Below the row, a ListBox
lstItemswith Weight1, and below that a LabellblTotalwith no Caption. (A Label with no caption cannot be seen in the designer; the Properties window still lists it.) -
Add
commdlg.basandfileops.bas(, 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, andFileOpsListSizetell about its entries, numbered from 0, andFileOpsListFreelets go of the listing at the end. -
A folder’s own size in the listing is nothing; what it holds is what counts.
FileOpsTreeSizeadds up everything in a folder and the folders inside it, andFileOpsTreeBytes()then gives the total. The program callsFileOpsTreeSizelike a Sub, leaving its answer (whether every part could be read) unused. -
FileOpsFormatSize$writes a number of bytes with commas,61,582, andFileOpsFreeBytesgives 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
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, Trueright afterFileOpsList(folders still come first). -
Add a ProgressBar that shows how full the disk is, from
FileOpsFreeBytesandFileOpsTotalBytes(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 GetandProperty Letprocedures, as in a class, and so are its methods: itsPublicSubs and Functions. -
Its events are declared with
Eventand raised withRaiseEvent. The program that has the control writes procedures for them, as for a button’sClick. -
It draws itself, in its
UserControl_Paintprocedure, 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.
-
Start a new project called
Switches, and giveForm1the CaptionSwitches. -
Choose . DVX BASIC adds
UserControl1.ctlunder Controls in the Project window and opens it in the Code window. -
Choose and type
Switch. The file isSwitch.ctlnow, and the control is calledSwitch: the name forms use for it, as they useCommandButton. -
The Properties window shows the control’s header while its file is open ( brings it to the front). Set its Width to
50and its Height to24, the switch’s natural size, and its Description toAn 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.
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.BackColoris the color of the form or frame the control is on, so the corners around the track match it. -
ScaleWidthandScaleHeightare the control’s size in pixels, whatever size the form gives it, so it draws itself at any size. -
HasFocusisTruewhile the control has the keyboard, andDrawFocusRectdraws 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
-
In the Project window, double-click
Form1.frm. -
Place an HBox, and in it a Label with the Caption
&Sound:and, with the new tool, a Switch namedswSound. Below the row, place a Label namedlblStatewith no Caption.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
Valueproperty among the others. -
In the form’s code, the switch starts on, and its
Changedprocedure (chooseswSound, 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.
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 , set its Type to Control. Then 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
OnColorproperty (aLong,vbGreento start with, set inUserControl_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(vbKeyRightandvbKeyLeft). -
Make a quick double-click turn the switch twice: turn it in
UserControl_DblClicktoo. -
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
Gaugecontrol: a bar that fills from the left as itsLevelproperty 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.
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 |
|
Where a new task is typed. |
CommandButton |
|
Adds the task (the default button, so Enter presses it). |
ListBox |
|
The tasks still to do. |
CommandButton |
|
Moves the chosen task to the Done list. |
CommandButton |
|
Deletes the chosen task. |
ListBox |
|
The tasks that are done. |
Label |
|
The tip at the bottom. |
Menu items |
|
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.
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 |
|---|---|
Build and test the program. |
|
Draw its icon. |
|
Write its help file. |
|
Give it a version and build the program file to hand out. |
|
What its program file carries, and the files it comes with. |
|
Make a package that anyone can install. |
|
Offer it to everyone on the software server. |
|
Bring out a new version, and help the people who use it. |
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
-
Choose and type the project’s name,
To-Do. DVX BASIC suggests the folderTODOfor it in yourPROJECTSfolder; press Enter to take it. -
Give
Form1the CaptionTo-Doand the Height480. Set its HelpTopic totodo.overviewtoo: the page of the help file that F1 will open, which Chapter 26 writes. -
Place an HBox, and in it a TextBox named
txtTask, with no Text, and a CommandButton namedcmdAdd, with the Caption&Addand DefaultTrue, so that Enter adds the task just typed. -
Below the row, a Label named
lblTodoHeadwith the Caption&To do:, and a ListBox namedlstTodo. A label’s access key moves the focus to the control placed after it, so Alt+T goes to the list. -
Below the list, another HBox, with two CommandButtons:
cmdDone, with the Caption&Done, andcmdDelete, with the CaptionDe&lete. Set the row’s Alignment toRight. -
Below that row, a Label named
lblDoneHeadwith the CaptionD&one:, and a ListBox namedlstDone. -
Last, at the bottom, a Label named
lblTipwith 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 toTrueand its MinWidth to360, a little less than the form is wide: a long tip then wraps onto a second line at that width instead. -
Set the Weight of
lstTodoto2and that oflstDoneto1. 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 |
|---|---|---|
|
|
|
|
||
|
|
|
|
|
|
|
|
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, soLoadListstops 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. -
SaveListwrites the whole file again, both lists, each time anything changes.For Outputstarts the file empty, so nothing old is left at its end.
24.4. The Tip
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 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.
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 , 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.
-
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.
-
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.
-
Click white, and fill the inside of the box.
-
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.
-
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.
-
Dark blue: a line two dots thick to the right of each box, from 15 to 22 across.
-
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.
25.2. Giving It to the Project
In DVX BASIC, with To-Do’s project open, choose . On the General page, click Browse… beside Icon and choose todo.png. The icon appears beside the button.
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.pngin 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 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 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 |
|---|---|
|
Starts a topic, and gives it a name. The program opens a topic by its name, so make the names short and keep them: |
|
The topic’s title, in DVX Help’s title bar. |
|
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. |
|
Makes this the topic DVX Help shows when the help file opens. |
|
Puts a word in the help’s index, which leads to this topic. |
|
A heading. |
|
A link to the topic named |
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
26.3. Compiling and Trying It
Choose . 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. compiles it and opens it in DVX Help, as the program’s users will see it:
Click every link, and look at each topic in the table of contents. When something is wrong, fix the source, and choose again.
26.4. Connecting It to the Program
In DVX BASIC, choose , click Browse… beside Help File, and choose todo.hlp (the picture in Section 25.2 shows it chosen). Now:
-
App.HelpFileis the help file, so in To-Do, which saysHelpView 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 tipbefore it and.endnoteafter.
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
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: |
|
Author |
Who wrote the program. |
|
Publisher |
Who puts it out: you, or your company. |
|
Copyright |
Who owns it, and since when. |
|
Trademarks |
Any trademarks it uses. |
|
Product |
The program’s name as people see it; with none, the project’s Name. |
|
Description |
What it does, in one line. |
|
Comments |
Anything else worth saying, in one line. |
|
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 : the About box of Section 24.5 now has something to say.
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 . The Save box suggests TODO.APP in the project’s folder; press Enter to take it. DVX BASIC then asks which kind of build:
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 (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.
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 , and open TODO.APP in the project’s folder:
| Resource | What it holds |
|---|---|
|
The icon of Chapter 25, which Program Manager shows. |
|
The project’s Name, which Program Manager shows under the icon. |
|
The Description of Chapter 27, the tip Program Manager shows when the pointer rests on the icon. |
|
The rest of the version information. |
|
The name of the program’s help file, which F1 opens. |
|
The program itself: its code, and its form (a program with more forms has |
The Resource Editor can change a resource, add one, or take one out, but leave your own programs' resources to DVX BASIC: 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:
-
In File Manager, go to the project’s folder and choose . Name the folder
DATA. -
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. -
Save them in the
DATAfolder astips.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.
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 lists them:
-
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 fromTODO.APP? -
Open another program in the Resource Editor, such as Notepad (
NOTEPAD.APP, in DVX’sAPPS\KPUNCH\NOTEPADfolder), and compare its resources with To-Do’s. -
Put To-Do’s tips in a string table instead: the lines
1 =to4 =, one tip each, andCount = 4. ThenShowTipneeds onlyn = Val(LoadResString("Count"))andlblTip.Caption = "Tip: " & LoadResString(Int(Rnd * n) + 1). Make the program, and look for the table in the Resource Editor: it is the resource namedSTRINGS.
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:
-
In Program Manager’s Installed Programs group, double-click Package Builder.
-
Click its Signing tab, and click New Key….
-
Type the name people will see on what you sign, your own or your company’s, such as
Your Name, and click OK. -
Package Builder suggests saving the key in your
KEYSfolder. Type a short file name for it, such asyourname, and press Enter.
-
YOURNAME.KEYis the one you give away. People who have it can tell your packages from everyone else’s. -
YOURNAME.SECis 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 . 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 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 (, 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.
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.
29.3. Installing It
Try the package as the people who get it will. Start Software (in Program Manager’s Installed Programs), choose , and open TODO.DPK. Before it installs anything, Software shows what it will do:
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:
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 too.
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, 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.
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 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 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:
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.
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:
-
Raise the Version in , 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. -
Choose . 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.
-
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. -
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.LOGin 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.
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
- About box, 24.5. The Event Procedures, 27.1. Version Information
- access keys, 11.6. The Keyboard on a Form
- Activate event, 15.2. Showing, Hiding, and Unloading
- Add Library, 14.4. Libraries: More Dialog Boxes
- + (add), 4.2. Numbers and Arithmetic
- AddItem, 6.6. Times Tables, 12.3. Lists of Items
- Alignment
- containers, 11.4.3. Space and Alignment
- Ambient, 22.2.2. Drawing It
- And, 5.5. And, Or, and Not
- .app files, 1.3. What a DVX BASIC Program Is Made Of, 27.2. Making the Program File
- App.Data, 13.1. Where Files Go, 16.6. Pictures from Files, 24.4. The Tip, 28.2. Files That Come with the Program
- planning, 23.3. What It Keeps, and Where
- read only, 28.2. Files That Come with the Program
- App.HelpFile, 24.5. The Event Procedures, 26.4. Connecting It to the Program
- App.Major, 24.5. The Event Procedures
- App.Path, 13.1. Where Files Go
- App.ProductName, 24.5. The Event Procedures
- App.User, 13.1. Where Files Go, 23.3. What It Keeps, and Where
- after Make, 27.2. Making the Program File
- finding, 24.6. Testing It
- To-Do, 24.5. The Event Procedures
- Append, 13.3. Adding to a File
- arguments, 7.2. Giving a Procedure Values
- arithmetic, 4.2. Numbers and Arithmetic
- arrays, 9. Lists of Things: Arrays and Collections
- bounds, 9.3. Counting from 0
- dynamic, 9.4. Arrays That Grow
- Asc, 8.5. Characters and Their Numbers
- = (assign), 4.4. Variables
- assignment, 4.4. Variables
B
- BackColor, 11.4.3. Space and Alignment
- .bas files, 1.3. What a DVX BASIC Program Is Made Of
- BASIC
- history, 1.1. Programming Languages and BASIC
- Beep, 12.8. An Egg Timer, 19.1. Beeps and Tones
- Boolean, 4.5. Kinds of Values
- conditions, 5.5. And, Or, and Not
- breakpoints, 10.4.2. Stopping to Look: Breakpoints and Stepping
- bugs, 10. Finding and Fixing Mistakes
- Build
- Help Editor, 26.3. Compiling and Trying It
- ByRef, 7.4. Changing the Caller’s Variable
- ByVal, 7.4. Changing the Caller’s Variable
C
- Call, 7.2. Giving a Procedure Values
- Call Stack window, 10.4.2. Stopping to Look: Breakpoints and Stepping
- Cancel
- QueryUnload, 14.5.2. The Code
- Cancel property, 11.5.1. Designing It
- Caption property, 3.2. Changing a Property
- Case, 5.6. Select Case
- Change event, 8.6. A Word Counter
- character codes, 8.5. Characters and Their Numbers
- check boxes
- in a list, 12.3. Lists of Items
- CheckBox, 12.2. Choices: Check Boxes and Option Buttons
- Checked property, 14.1. Menus
- Chr$, 8.5. Characters and Their Numbers
- Circle method, 16.3. Points, Lines, Boxes, and Circles
- class modules, 17. Objects and Class Modules
- Class_Initialize, 17.8. When Objects Start and End
- Class_Terminate, 17.8. When Objects Start and End
- classes
- why, 17.1. Why Objects?
- Clear method, 6.6. Times Tables
- Click event
- forms, 11.3. Events
- Close, 13.2. Writing and Reading a Text File
- Cls, 16.3. Points, Lines, Boxes, and Circles
- Code view, 2.3. Design and Code
- Code window, 2.2. The Windows of a Project
- adding a procedure, 7.1. Your Own Sub
- Function list, 11.3. Events
- General, 5.8. A Guessing Game
- Object list, 11.3. Events
- opening, 3.4. Writing the Code
- Collection, 9.7. Collections
- of objects, 17.6. Many Objects
- Color Picker, 25.1. Drawing It
- colors, 16.2. Colors
- columns, 18.1. Tables, Rows, and SQL
- ComboBox, 12.3. Lists of Items
- CommandButton, 3.3. Adding a Button
- ' (comment), 4.9. Comments
- comments, 4.9. Comments
- comparison operators, 5.2. Comparing Values
- compile errors, 4.7. Option Explicit: Catching Typing Mistakes, 10.1. Three Kinds of Mistakes
- conditions, 5.1. If ... Then
- Const, 4.8. Constants
- constants, 4.8. Constants
- containers, 11.4.1. Columns and Rows
- control arrays, 12.4. Control Arrays
- Count
- LBound
- UBound, 12.4. Control Arrays
- LBound
- Count
- control projects, 22.4. Controls for Every Program
- controls, 11. Forms, Controls, and Events
- arranging, 11.4. Laying Out a Form
- common, 12. The Controls You Will Use Most
- naming, 12.1. Good Names for Controls
- placing, 3.3. Adding a Button
- what they are, 1.3. What a DVX BASIC Program Is Made Of
- your own, 22. Making Your Own Controls
- conversion
- text and numbers, 4.10. Turning Text into Numbers and Back
- coordinates, 16.1. Where to Draw
- counter variable, 6.1. For ... Next: Counting
- Create Account, 30.1. Your Account
- CStr, 4.10. Turning Text into Numbers and Back
- Currency, 4.5. Kinds of Values
- CurrentX, 16.3. Points, Lines, Boxes, and Circles
- CurrentY, 16.3. Points, Lines, Boxes, and Circles
D
- data
- planning, 23.3. What It Keeps, and Where
- data binding, 18.4. Showing a Table Without Code
- Data control, 18.4. Showing a Table Without Code
- DATA folder, 28.2. Files That Come with the Program
- or resources, 28.3. Files Inside the Program
- data types, 4.5. Kinds of Values
- DatabaseName, 18.4. Showing a Table Without Code
- databases, 18. Databases
- Databases part, 18. Databases
- DBGrid, 18.4. Showing a Table Without Code
- DblClick, 24.5. The Event Procedures
- .dbp files, 1.3. What a DVX BASIC Program Is Made Of
- Debug
- debug builds, 27.2. Making the Program File
- Debug.Print, 10.4.1. Printing What Happens
- debugging, 10. Finding and Fixing Mistakes
- decisions, 5. Making Decisions
- Declare Function, 21.1. What a Library Is
- Declare Library, 21.1. What a Library Is
- Default property, 11.5.1. Designing It
- DefaultEvent, 22.2.3. The Mouse and the Keyboard
- Design view, 2.3. Design and Code
- .dhs files, 26.2. The Help Source
- dialog boxes, 14. Menus and Dialog Boxes
- your own, 15. Programs with More Than One Form
- Dim, 4.4. Variables
- arrays, 9.1. Arrays
- Dir$, 13.5. Is the File There?, 24.3. Keeping the Lists
- / (divide), 4.2. Numbers and Arithmetic
- DlgFileOpen$, 14.4. Libraries: More Dialog Boxes
- DlgFileSaveAs$, 14.4. Libraries: More Dialog Boxes
- DlgFolder$, 21.4. Folder Sizes
- Do, 6.2. Do ... Loop: Repeating Until Something Happens
- Do Until, 6.2. Do ... Loop: Repeating Until Something Happens
- Do While, 6.2. Do ... Loop: Repeating Until Something Happens
- DoEvents, 12.9. Long Jobs
- dot
- in names, 3.6. Changing a Property from the Code
- dot notation, 11.2. Properties in Code
- Double, 4.5. Kinds of Values
- double-click
- UserControls, 22.2.3. The Mouse and the Keyboard
- .DPK files, 29. Packaging Your Program
- DrawFocusRect, 22.2.2. Drawing It
- drawing, 16. Drawing and Pictures
- DrawWidth, 16.3. Points, Lines, Boxes, and Circles
- DropDown, 12.3. Lists of Items
- DVX BASIC, Before You Start
- main window, 2.1. Starting DVX BASIC
- starting, 2. A Tour of DVX BASIC
- what it is, 1.1. Programming Languages and BASIC
- DVX BASIC Help, 21.2. Finding Out What a Library Can Do
E
- elements, 9.1. Arrays
- Else, 5.3. Several Lines, and Else
- ElseIf, 5.4. ElseIf: More Than Two Choices
- Enabled
- forms, 11.2. Properties in Code
- Enabled property
- menus, 14.1. Menus
- End, 13.5. Is the File There?
- End If, 5.3. Several Lines, and Else
- EndDoc, 20.2. Drawing Pages: the Printer Object
- EOF, 13.2. Writing and Reading a Text File
- = (equal), 5.2. Comparing Values
- Eraser, 25.1. Drawing It
- Err object, 10.5. Handling Errors in Your Program
- Err.Description, 10.5. Handling Errors in Your Program
- Err.Number, 10.5. Handling Errors in Your Program
- error 326, 28.3. Files Inside the Program
- Error$, 14.5.2. The Code
- errors
- File not found, 13.5. Is the File There?
- handling, 10.5. Handling Errors in Your Program
- Overflow, 4.5. Kinds of Values
- Subscript out of range, 9.1. Arrays
- Variable not declared, 4.7. Option Explicit: Catching Typing Mistakes
- Esc
- stopping a program, 6.4. When a Loop Never Ends
- event procedures
- names, 11.3. Events
- Event statement, 17.7. Events of Your Own
- event-driven programs, 11.1. How a Form Program Runs
- events, 11. Forms, Controls, and Events
- Change, 8.6. A Word Counter
- choosing, 11.3. Events
- Click, 3.4. Writing the Code
- during a long job, 12.9. Long Jobs
- Index parameter, 12.4. Control Arrays
- Load, 5.8. A Guessing Game
- of a class, 17.7. Events of Your Own
- parameters, 11.3. Events
- procedures, 11.3. Events
- what they are, 1.2. Programs That Wait for You
- examples
- address book, 15.5. An Address Book
- Apple Catch, 19.5. Apple Catch
- book list, 18.3. A Book List
- certificate, 20.3. A Certificate
- drawn scene, 16.4. When to Draw: the Paint Event
- egg timer, 12.8. An Egg Timer
- Folder Sizes, 21.4. Folder Sizes
- guessing game, 5.8. A Guessing Game
- high scores, 9.8. A High Score List
- pizza order, 12.5. A Pizza Order
- shopping list, 13.7. A Shopping List That Remembers
- sign-up form, 11.5. A Sign-Up Form
- sketch pad, 16.5. Drawing with the Mouse
- Switch, 22.2. A Switch
- temperature converter, 4.11. A Temperature Converter
- times tables, 6.6. Times Tables
- TinyPad, 14.5. TinyPad, a Text Editor
- two-way converter, 7.7. A Converter That Goes Both Ways
- word counter, 8.6. A Word Counter
- Exit Do, 6.3. Leaving a Loop Early
- Exit For, 6.3. Leaving a Loop Early
- Exit Function, 7.6. Leaving Early
- Exit Sub, 5.8. A Guessing Game, 7.6. Leaving Early
F
- F1, 2.6. Getting Help
- help, 26. Writing a Help File
- F5, 3.5. Running the Program
- F8, 10.4.2. Stopping to Look: Breakpoints and Stepping
- F9, 10.4.2. Stopping to Look: Breakpoints and Stepping
- False, 5.2. Comparing Values
- file dialogs, 14.4. Libraries: More Dialog Boxes
- FileLen, 13.5. Is the File There?
- FileOpsList, 21.4. Folder Sizes
- FileOpsSaveText, 14.5.2. The Code
- files, 13. Files and Settings
- adding to, 13.3. Adding to a File
- checking, 13.5. Is the File There?
- reading, 13.2. Writing and Reading a Text File
- records, 13.4. Numbers and Text Together
- saving safely, 13.7. A Shopping List That Remembers
- writing, 13.2. Writing and Reading a Text File
- FillColor, 16.3. Points, Lines, Boxes, and Circles
- FillStyle, 16.3. Points, Lines, Boxes, and Circles
- FindNext, 14.5.2. The Code
- first program, 3. Your First Program
- focus, 11.6. The Keyboard on a Form
- folders
- for a program’s files, 13.1. Where Files Go
- FontName
- fonts
- a program carries, 28.3. Files Inside the Program
- FontSize
- For, 6.1. For ... Next: Counting
- For Each, 9.7. Collections
- control arrays, 12.4. Control Arrays
- objects, 17.6. Many Objects
- ForeColor
- Forgot Password, 30.1. Your Account
- form designer, 2.2. The Windows of a Project
- form-level variables, 5.8. A Guessing Game
- Form1, 3.1. Starting a Project
- Form_Load
- To-Do, 24.5. The Event Procedures
- Format$, 4.10. Turning Text into Numbers and Back
- money, 12.5.2. The Code
- forms, 11. Forms, Controls, and Events
- AutoSize, 11.4.3. Space and Alignment
- BackColor, 11.4.3. Space and Alignment
- drawing on, 16.1. Where to Draw
- Enabled, 11.2. Properties in Code
- Me, 11.2. Properties in Code
- more than one, 15. Programs with More Than One Form
- mouse events, 11.3. Events
- properties of your own, 15.3. Using One Form from Another
- Resizable, 11.4.3. Space and Alignment
- using controls of another, 15.3. Using One Form from Another
- what they are, 1.3. What a DVX BASIC Program Is Made Of
- Frame, 11.4.1. Columns and Rows
- frames, 19.4. A Game Loop
- FrameWait, 19.4. A Game Loop
- FreeFile, 13.2. Writing and Reading a Text File
- frequency, 19.1. Beeps and Tones
- .frm files, 1.3. What a DVX BASIC Program Is Made Of
- FullScreen, 19.6. More for Games
- Function, 7. Subs and Functions
- Function list, 7.1. Your Own Sub
- functions
- as statements, 14.5.2. The Code
- what they are, 4.10. Turning Text into Numbers and Back
G
- game loop, 19.4. A Game Loop
- game.bas, 19.4. A Game Loop
- GameInput, 19.6. More for Games
- GameKeyDown, 19.4. A Game Loop
- games, 19. Sound, Music, and Games
- General section, 5.8. A Guessing Game
- graphics, 16. Drawing and Pictures
H
- HasFocus, 22.2.2. Drawing It
- HBox, 11.4.1. Columns and Rows
- Height property, 6.6. Times Tables
- help
- DVX BASIC, 2.6. Getting Help
- Help Editor, 26.2. The Help Source
- Help File Format, 26.2. The Help Source
- help files, 26. Writing a Help File
- compiling, 26.3. Compiling and Trying It
- in the program, 26.4. Connecting It to the Program
- planning, 26.1. What to Write
- help source, 26.2. The Help Source
- commands, 26.2. The Help Source
- paragraphs, 26.2. The Help Source
- help.bas, 24.2. The Menus
- HelpTopic, 26.4. Connecting It to the Program
- HelpView, 24.5. The Event Procedures
- Hide, 15.2. Showing, Hiding, and Unloading
- in a form’s code, 15.5.2. The Dialog Box
- HScrollBar, 12.6. Numbers: Spin Buttons, Scroll Bars, and Progress Bars
I
- Icon Editor, 25. Giving Your Program an Icon
- position, 25.1. Drawing It
- saving, 25.1. Drawing It
- Size, 25.3. Smaller Pictures
- icons, 25. Giving Your Program an Icon
- in the program file, 25.2. Giving It to the Project
- IDE, 2. A Tour of DVX BASIC
- If, 5. Making Decisions
- block, 5.3. Several Lines, and Else
- single-line, 5.1. If ... Then
- Image control, 16.6. Pictures from Files
- Immediate window, 2.1. Starting DVX BASIC
- trying, 2.5. Trying the Immediate Window
- while paused, 10.4.2. Stopping to Look: Breakpoints and Stepping
- include libraries, 14.4. Libraries: More Dialog Boxes, 21. Using DVX’s Libraries
- index, 9.1. Arrays
- Index property, 12.4. Control Arrays
- INI files, 13.6. Remembering Settings
- IniRead, 13.6. Remembering Settings
- IniWrite, 13.6. Remembering Settings
- Input #, 13.4. Numbers and Text Together
- InputBox$, 14.3. Asking for Text
- instances, 17.1. Why Objects?
- InStr, 8.2. Searching
- InStrRev, 14.5.2. The Code
- Integer, 4.5. Kinds of Values
- rounding, 4.5. Kinds of Values
- Interval, 12.7. Timers
- Invalidate, 22.2.1. Its Property and Its Event
- IsNumeric, 5.8. A Guessing Game
- ItemCheck, 12.3. Lists of Items
- ItemData, 12.3. Lists of Items
J
- Join, 9.5. Text into Arrays and Back
- & (join), 4.3. Text
- joysticks, 19.6. More for Games
K
- .KEY files, 29.1. Your Key
- KeyAscii, 11.3. Events
- keyboard
- on a form, 11.6. The Keyboard on a Form
- keys, 29.1. Your Key
- held down, 19.4. A Game Loop
- keeping safe, 31.1. A New Version
- Kill, 13.5. Is the File There?
- KillDoc, 20.2. Drawing Pages: the Printer Object
L
- Label, 3.6. Changing a Property from the Code
- labels, 10.5. Handling Errors in Your Program
- LastError, 18.4. Showing a Table Without Code
- layout, 11.4. Laying Out a Form
- rows and columns, 11.4.1. Columns and Rows
- VBox, 3.3. Adding a Button
- LBound, 9.3. Counting from 0
- LCase$, 8.3. Capitals and Spaces
- Left$, 8.1. Length and Pieces
- Len, 8.1. Length and Pieces
- libraries, 14.4. Libraries: More Dialog Boxes, 21. Using DVX’s Libraries
- calling, 21.1. What a Library Is
- reading, 21.2. Finding Out What a Library Can Do
- LIKE, 18.1. Tables, Rows, and SQL
- line breaks
- in messages, 14.2. Message Boxes
- line continuation, 19.6. More for Games
- Line Input #, 13.2. Writing and Reading a Text File
- Line method, 16.3. Points, Lines, Boxes, and Circles
- ListBox, 6.6. Times Tables, 12.3. Lists of Items
- ListIndex, 24.5. The Event Procedures
- lists, 9. Lists of Things: Arrays and Collections
- controls, 12.3. Lists of Items
- Load event, 5.8. A Guessing Game, 11.5.2. The Code, 15.2. Showing, Hiding, and Unloading
- LoadList, 24.3. Keeping the Lists
- LoadPicture, 16.6. Pictures from Files
- LoadResData, 28.3. Files Inside the Program
- LoadResPicture, 28.3. Files Inside the Program
- LoadResString, 28.3. Files Inside the Program
- local variables, 7.5. Where Variables Live
- Locals window, 10.4.2. Stopping to Look: Breakpoints and Stepping
- logic errors, 10.1. Three Kinds of Mistakes
- finding, 10.4. When the Answer Is Wrong
- Long, 4.5. Kinds of Values
- long jobs, 12.9. Long Jobs
- Loop, 6.2. Do ... Loop: Repeating Until Something Happens
- loops, 6. Doing Things Again: Loops
- counting down, 6.1.1. Counting by Other Steps
- endless, 6.4. When a Loop Never Ends
- For, 6.1. For ... Next: Counting
- nested, 6.5. Loops Inside Loops
- LPrint, 20.4. A Line at a Time: LPrint
- LTrim$, 8.3. Capitals and Spaces
M
- Make Control, 22.4. Controls for Every Program
- Make Executable, 27.2. Making the Program File
- Make Package, 29.2. Making the Package
- MaxWidth, 11.4.2. Who Gets the Room
- MB
- music background, 19.2. Playing Tunes
- Me, 11.2. Properties in Code
- member variables, 17.2. A Class Module
- menu bar, 14.1. Menus
- Menu Editor, 14.1. Menus
- menus, 14. Menus and Dialog Boxes
- at run time, 14.1. Menus
- Click event, 14.1. Menus
- DVX BASIC, 2.1. Starting DVX BASIC
- popup, 14.5.2. The Code
- shortcut keys, 14.1. Menus
- message boxes, 14.2. Message Boxes
- methods
- of a class, 17.4. Methods
- what they are, 5.8. A Guessing Game
- Mid$, 8.1. Length and Pieces
- MIDI files, 19.3. Sound Files and Music Files
- MinHeight, 11.4.2. Who Gets the Room
- MinHeight property, 6.6. Times Tables
- MinWidth, 11.4.2. Who Gets the Room
- mistakes, 10. Finding and Fixing Mistakes
- Mod, 4.2. Numbers and Arithmetic
- modal forms, 15.2. Showing, Hiding, and Unloading
- module-level variables, 7.5. Where Variables Live
- Module1, 4.1. A Practice Project
- modules, 15.4. Code Every Form Shares: Modules
- music, 19.3. Sound Files and Music Files
- practicing in, 4.1. A Practice Project
- mouse
- drawing with, 16.5. Drawing with the Mouse
- MouseDown, 16.5. Drawing with the Mouse
- MouseMove, 16.5. Drawing with the Mouse
- MouseUp, 14.5.2. The Code
- MsgBox, 3.4. Writing the Code, 14.2. Message Boxes
- buttons, 14.2. Message Boxes
- icons, 14.2. Message Boxes
- in a check, 9.8. A High Score List
- * (multiply), 4.2. Numbers and Arithmetic
- music, 19. Sound, Music, and Games
- music macro language, 19.2. Playing Tunes
- music.bas, 19.3. Sound Files and Music Files
- MusicLoad, 19.3. Sound Files and Music Files
- MusicLoadMacro, 19.3. Sound Files and Music Files
- MusicPlay, 19.3. Sound Files and Music Files
N
- Name property, 12.1. Good Names for Controls
- names
- planning, 23.2. Its Window and Its Parts
- rules, 4.6. Naming Variables
- naming conventions, 12.1. Good Names for Controls
- New, 17.5. Making and Using Objects
- New Class Module, 17.2. A Class Module
- New Form, 15.1. Adding a Form
- New Module, 4.1. A Practice Project, 15.4. Code Every Form Shares: Modules
- New Project, 3.1. Starting a Project
- NewIndex, 12.3. Lists of Items
- NewPage, 20.2. Drawing Pages: the Printer Object
- Next, 6.1. For ... Next: Counting
- Not, 5.5. And, Or, and Not
- <> (not equal), 5.2. Comparing Values
- notes, 19.2. Playing Tunes
- Nothing, 17.5. Making and Using Objects
O
- Object list
- the form, 12.5.2. The Code
- objects, 17. Objects and Class Modules
- making, 17.5. Making and Using Objects
- On Error, 10.5. Handling Errors in Your Program
- files, 13.5. Is the File There?
- On Error Resume Next, 10.5. Handling Errors in Your Program
- Open, 13.2. Writing and Reading a Text File
- operators
- arithmetic, 4.2. Numbers and Arithmetic
- comparison, 5.2. Comparing Values
- option buttons
- Option Explicit, 4.7. Option Explicit: Catching Typing Mistakes
- OptionButton, 12.2. Choices: Check Boxes and Option Buttons
- Or, 5.5. And, Or, and Not
- ORDER BY, 18.1. Tables, Rows, and SQL
- order of operations, 4.2.1. Which Comes First
- Output window, 2.1. Starting DVX BASIC
- errors, 10.2. When the Program Does Not Start
- practice programs, 4.1. A Practice Project
- Overflow, 4.5. Kinds of Values
P
- Package Builder
- New Key, 29.1. Your Key
- package names, 29.2. Making the Package
- owner, 30.2. Publishing the Package
- package server, 30. Publishing to the Package Server
- account, 30.1. Your Account
- packages, 29. Packaging Your Program
- needs, 29.2. Making the Package
- Padding, 11.4.3. Space and Alignment
- Page Setup, 20.1. Printing Text
- pages
- Paint event, 16.4. When to Draw: the Paint Event
- PaintPicture, 16.6. Pictures from Files
- sprites, 19.6. More for Games
- parameters, 7.2. Giving a Procedure Values
- by reference, 7.4. Changing the Caller’s Variable
- parentheses, 4.2.1. Which Comes First
- calling a Sub, 7.2. Giving a Procedure Values
- function arguments, 4.10. Turning Text into Numbers and Back
- paths, 13.1. Where Files Go
- Picture property, 16.6. Pictures from Files
- PictureBox, 16.1. Where to Draw
- pictures, 16. Drawing and Pictures
- pixels, 16.1. Where to Draw
- planning, 23. Planning a Real Program
- Play
- in the background, 19.2. Playing Tunes
- Play statement, 19.2. Playing Tunes
- PlayWave, 19.3. Sound Files and Music Files
- PNG files, 16.5. Drawing with the Mouse
- PopupMenu, 14.5.2. The Code
- PostScript, 20.3. A Certificate
- ^ (power), 4.2. Numbers and Arithmetic
- Practice project, 4.1. A Practice Project
- Preferences
- OPTION EXPLICIT, 4.7. Option Explicit: Catching Typing Mistakes
- PRIMARY KEY, 18.3. A Book List
- PRINT, 4.1. A Practice Project
- ; and, 4.3. Text
- spaces around numbers, 4.2. Numbers and Arithmetic
- Print
- on a picture, 16.3. Points, Lines, Boxes, and Circles
- Print #, 13.2. Writing and Reading a Text File
- print.bas, 20.1. Printing Text
- PrintCanPrintPictures, 20.2. Drawing Pages: the Printer Object
- PrintChoose, 20.3. A Certificate
- Printer object, 20.2. Drawing Pages: the Printer Object
- printers
- printing, 20. Printing
- PrintPageSetup, 20.1. Printing Text
- PrintTextDialog, 20.1. Printing Text
- Private, 17.2. A Class Module
- procedures, 7. Subs and Functions
- program files, 27.2. Making the Program File
- programming languages, 1.1. Programming Languages and BASIC
- programs
- ending, 11.1. How a Form Program Runs, 15.2. Showing, Hiding, and Unloading
- finishing, 23. Planning a Real Program
- how they run, 11.1. How a Form Program Runs
- testing, 24.6. Testing It
- what they are, 1. What Is a Program?
- ProgressBar, 12.6. Numbers: Spin Buttons, Scroll Bars, and Progress Bars
- project name, 23.4. The Steps Ahead
- Project Properties
- Help File, 26.4. Connecting It to the Program
- Icon, 25.2. Giving It to the Project
- Make page, 27.1. Version Information
- OPTION EXPLICIT, 4.7. Option Explicit: Catching Typing Mistakes
- Resources page, 28.3. Files Inside the Program
- startup form, 15.1. Adding a Form
- Project window, 2.2. The Windows of a Project
- forms, 15.1. Adding a Form
- projects
- files, 3.7. What You Made
- folder, 3.1. Starting a Project
- new, 3.1. Starting a Project
- what they are, 1.3. What a DVX BASIC Program Is Made Of
- PROJECTS folder, 3.1. Starting a Project
- properties
- in code, 11.2. Properties in Code
- of a class, 17.3. Properties
- setting in code, 3.6. Changing a Property from the Code
- what they are, 3.2. Changing a Property
- Properties window, 2.2. The Windows of a Project
- finding a property, 4.11. A Temperature Converter, 6.6. Times Tables
- Property Get, 17.3. Properties
- Property Let, 17.3. Properties
- PSet, 16.3. Points, Lines, Boxes, and Circles
- Public
- form variables, 15.3. Using One Form from Another
- module variables, 15.4. Code Every Form Shares: Modules
- Publish a Package, 30.2. Publishing the Package
- Published page, 30.2. Publishing the Package
- publishing, 30. Publishing to the Package Server
Q
- QueryUnload, 14.5.2. The Code
- unsaved changes, 14.5.2. The Code
- quotes
- in a string, 4.3. Text
R
- RaiseEvent, 17.4. Methods
- random lines, 24.4. The Tip
- random numbers, 5.7. Random Numbers
- Randomize, 5.7. Random Numbers
- read-only properties, 17.3. Properties
- RecordSource, 18.4. Showing a Table Without Code
- ReDim, 9.4. Arrays That Grow
- ReDim Preserve, 9.4. Arrays That Grow
- references, 17.5. Making and Using Objects
- Refresh, 16.4. When to Draw: the Paint Event
- release builds, 27. Version Information and Release Builds
- debug builds and, 27.2. Making the Program File
- Rem, 4.9. Comments
- Rename File, 17.2. A Class Module
- repetition, 6. Doing Things Again: Loops
- Replace, 8.4. Changing and Building Text
- Resize
- PictureBox, 16.1. Where to Draw
- Resource Editor, 28.1. Inside the Program File
- changes, 28.1. Inside the Program File
- resources, 28. Program Resources
- a program carries, 28.3. Files Inside the Program
- of a program, 28.1. Inside the Program File
- return value, 7.3. Functions: Procedures That Give a Value Back
- review
- of packages, 30.2. Publishing the Package
- RGB, 16.2. Colors
- Right$, 8.1. Length and Pieces
- Rnd, 5.7. Random Numbers
- rounding
- into a whole number, 4.5. Kinds of Values
- rows, 18.1. Tables, Rows, and SQL
- RTrim$, 8.3. Capitals and Spaces
- Run to Cursor, 10.4.2. Stopping to Look: Breakpoints and Stepping
- running
- a program, 3.5. Running the Program
- stopping, 3.5. Running the Program
- runtime errors, 10.1. Three Kinds of Mistakes
- reading, 10.3. When the Program Stops
S
- Save
- PictureBox, 16.5. Drawing with the Mouse
- Save on Run, 3.5. Running the Program
- SaveDoc
- as a statement, 14.5.2. The Code
- SaveList, 24.3. Keeping the Lists
- saving
- safely, 14.5.2. The Code
- saving data, 13. Files and Settings
- ScaleHeight, 16.1. Where to Draw
- ScaleMode
- ScaleWidth, 16.1. Where to Draw, 22.2.2. Drawing It
- scope, 7.5. Where Variables Live
- searching text, 8.2. Searching
- .SEC files, 29.1. Your Key
- Select Case, 5.6. Select Case
- Selected, 12.3. Lists of Items
- SelLength, 15.5.2. The Dialog Box
- SelStart, 15.5.2. The Dialog Box
- Set, 17.5. Making and Using Objects
- objects, 17.5. Making and Using Objects
- SetFocus, 5.8. A Guessing Game, 11.6. The Keyboard on a Form, 15.5.2. The Dialog Box
- SetRange, 12.6. Numbers: Spin Buttons, Scroll Bars, and Progress Bars
- settings, 13.6. Remembering Settings
- Shift
- mouse events, 16.5. Drawing with the Mouse
- Shift+F5, 10.4.2. Stopping to Look: Breakpoints and Stepping
- Show, 15.2. Showing, Hiding, and Unloading
- ShowTip, 24.4. The Tip
- signing packages, 29.1. Your Key
- Software
- installing, 29.3. Installing It
- removing, 29.3. Installing It
- Sorted property, 12.3. Lists of Items
- sorting, 9.6. Putting Things in Order
- sound, 19. Sound, Music, and Games
- Sound statement, 19.1. Beeps and Tones
- sound.bas, 19.3. Sound Files and Music Files
- Space$, 8.4. Changing and Building Text
- Spacer, 11.4.3. Space and Alignment
- Spacing, 11.4.3. Space and Alignment
- SpinButton, 12.6. Numbers: Spin Buttons, Scroll Bars, and Progress Bars
- Split, 9.5. Text into Arrays and Back
- sprites, 19.6. More for Games
- SQL, 18. Databases
- sql.bas, 18.2. SQL from BASIC
- SQLEscape$, 18.2. SQL from BASIC
- SQLExec, 18.2. SQL from BASIC
- SQLField$, 18.2. SQL from BASIC
- SQLite, 18. Databases
- SQLNext, 18.2. SQL from BASIC
- SQLOpen, 18.2. SQL from BASIC
- SQLQuery, 18.2. SQL from BASIC
- startup form, 15.1. Adding a Form
- Static, 7.5. Where Variables Live
- status line
- DVX BASIC, 2.1. Starting DVX BASIC
- Step, 6.1.1. Counting by Other Steps
- Step Into, 10.4.2. Stopping to Look: Breakpoints and Stepping
- Step Out, 10.4.2. Stopping to Look: Breakpoints and Stepping
- Step Over, 10.4.2. Stopping to Look: Breakpoints and Stepping
- STICK, 19.6. More for Games
- Stop
- a running program, 6.4. When a Loop Never Ends
- Stretch, 16.6. Pictures from Files
- STRIG, 19.6. More for Games
- String, 4.5. Kinds of Values
- string table, 28.3. Files Inside the Program
- String$, 8.4. Changing and Building Text
- strings, 4.3. Text
- building in a loop, 8.4. Changing and Building Text
- comparing, 5.2. Comparing Values
- comparing without case, 8.3. Capitals and Spaces
- functions, 8. Working with Text
- what they are, 3.4. Writing the Code
- Style property
- ListBox, 12.3. Lists of Items
- Sub, 7. Subs and Functions
- event, 3.4. Writing the Code
- writing, 7.1. Your Own Sub
- Subscript out of range, 9.1. Arrays
- - (subtract), 4.2. Numbers and Arithmetic
- support, 31. Updates and Support
- Swap, 9.6. Putting Things in Order
T
- Tab key, 11.6. The Keyboard on a Form
- tables, 18.1. Tables, Rows, and SQL
- testing, 24.6. Testing It
- text, 8. Working with Text
- joining, 4.3. Text
- text editor, 14.5. TinyPad, a Text Editor
- Text property, 4.11. A Temperature Converter
- TextArea, 8.6. A Word Counter
- TextBox, 4.11. A Temperature Converter
- TextWidth, 19.5.5. Drawing
- Timer, 12.7. Timers
- starting a loop, 19.5.3. The Loop
- Timer event, 12.7. Timers
- To-Do program, 23.1. What It Will Do
- building, 24. Building the To-Do List
- toolbar
- buttons, 2.4. The Toolbar
- DVX BASIC, 2.1. Starting DVX BASIC
- Toolbox, 2.2. The Windows of a Project
- using, 3.3. Adding a Button
- ToolboxIcon, 25.3. Smaller Pictures
- totals
- keeping, 6.1.2. Adding Things Up
- tray
- designer, 12.7. Timers
- Trim$, 8.3. Capitals and Spaces
- True, 5.2. Comparing Values
- Trust a Publisher’s Key, 29.4. Giving It Away
- twips, 20.2. Drawing Pages: the Printer Object
- types
- choosing, 4.5. Kinds of Values
- typing
- examples, How to Read This Book
U
- UBound, 9.3. Counting from 0
- UCase$, 8.3. Capitals and Spaces
- Unload, 11.1. How a Form Program Runs, 15.2. Showing, Hiding, and Unloading
- updates, 31. Updates and Support
- upgrades
- files removed, 31.1. A New Version
- upper and lower case, Conventions
- UserControl_DblClick, 22.2.3. The Mouse and the Keyboard
- UserControls, 22. Making Your Own Controls
V
- Val, 4.10. Turning Text into Numbers and Back
- Validate event
- Data control, 18.4. Showing a Table Without Code
- Value property, 12.2. Choices: Check Boxes and Option Buttons
- values, 4. Values and Variables
- variables, 4. Values and Variables
- changing, 4.4.1. Changing a Variable
- in a procedure, 4.11. A Temperature Converter
- local, 7.5. Where Variables Live
- naming, 4.6. Naming Variables
- Static, 7.5. Where Variables Live
- what they are, 4.4. Variables
- Variant, 9.7. Collections
- vbCrLf, 14.2. Message Boxes
- vbDataAction constants, 18.4. Showing a Table Without Code
- vbInches, 20.2. Drawing Pages: the Printer Object
- vbKeyBack, 11.5.2. The Code
- vbLeftButton, 16.5. Drawing with the Mouse
- vbLf, 14.5.2. The Code
- vbModal, 15.2. Showing, Hiding, and Unloading
- VBox, 11.4.1. Columns and Rows
- version information, 27. Version Information and Release Builds
- version numbers, 27.1. Version Information
- raising, 31.1. A New Version
- versions
- new, 31.1. A New Version
- Visual Basic, 1.1. Programming Languages and BASIC
W
- Watch window, 10.4.2. Stopping to Look: Breakpoints and Stepping
- WAV files, 19.3. Sound Files and Music Files
- Weight, 11.4.2. Who Gets the Room, 24.1. The Window
- using, 12.5.1. Designing It
- WHERE, 18.1. Tables, Rows, and SQL
- While and Wend, 6.2. Do ... Loop: Repeating Until Something Happens
- \ (whole-number division), 4.2. Numbers and Arithmetic
- WIDGETS folder, 22.4. Controls for Every Program
- Window menu, 2.2. The Windows of a Project
- WithEvents, 17.5. Making and Using Objects, 17.7. Events of Your Own
- WordWrap, 24.1. The Window
- Write #, 13.4. Numbers and Text Together