About This Reference
This book describes all of DVX BASIC: every statement and function of the language, the include libraries, every form and control with its properties, methods, and events, and every window, menu, and command of DVX BASIC itself. It is a book to look things up in, not to read from front to back.
To learn to program with DVX BASIC, start with its companion, the the DVX BASIC Programming Guide. It teaches one idea at a time, with programs you type in and run, takes a program all the way to a published package, and points into this book for the details.
How This Book Is Organized
-
Chapter 1 describes the language: its data types and operators, its statements and functions, files, objects and classes, the objects every program has (such as
App,Screen, andPrinter), and the include libraries that give programs more of DVX. -
Chapter 2 describes forms, what all controls have in common, drawing, data binding, menus, control arrays, the form file format, and UserControls.
-
Chapter 3 has a section for each control, in alphabetical order, with its properties, methods, and events.
-
Chapter 4 describes DVX BASIC itself: the code editor, the form designer, projects, the debugger, and the other windows, menus, and keys.
DVX BASIC’s own help has the same text: press F1 in DVX BASIC, or choose . Press F1 while a control is chosen in the form designer to go straight to that control’s section, or while the cursor is on a keyword in the Code window to go to that keyword.
To find something by its name, use the index at the back.
Chapter 1. The BASIC Language
1.1. Data Types
DVX BASIC supports the following data types. Each type has a corresponding type suffix character that can be appended to variable names.
1.1.1. Primary Types
| Type | Size | Suffix | Range / Description |
|---|---|---|---|
Byte |
1 byte |
(none) |
0 to 255 |
Integer |
2 bytes |
% |
-32768 to 32767 |
Long |
4 bytes |
& |
-2147483648 to 2147483647 |
Single |
4 bytes |
! |
32-bit float, approximately 7 digits precision |
Double |
8 bytes |
# |
64-bit float, approximately 15 digits precision |
Currency |
8 bytes |
@ |
-922337203685477.5808 to 922337203685477.5807, exact to four decimal places |
String |
variable |
$ |
Variable-length, reference-counted, dynamic string |
Boolean |
2 bytes |
(none) |
True (-1) or False (0) |
Date |
8 bytes |
(none) |
A date and time of day from 1/1/100 to 12/31/9999 |
Variant |
varies |
(none) |
Any value at all: a number, text, a date, an object, an array, or the special values Empty and Null (see Variants) |
1.1.2. Object Types
An object variable does not hold a value of its own; it refers to an object that lives elsewhere, so two variables can refer to the same object. Store a reference with Set, use the object’s properties and methods with a dot, and set the variable to Nothing when you are done with it.
| Declared As | Holds |
|---|---|
Control |
A control on a form, of any type, or a menu item |
ControlType |
A control of that type: TextBox, CommandButton, ListBox, Label, PictureBox, Timer, Menu ... (see Control Types below) |
UserControlName |
A control of that UserControl of the program (see UserControls: Your Own Controls) |
Form |
A form of the program, or a copy of one |
Object |
Any object: a form, a control, an instance of a class module, or a Collection |
ClassName |
An instance of that class module (see Objects and Class Modules) |
FormName |
That form of the program, or a copy of it New made (see Several Copies of a Form in the Form topic) |
Collection |
A Collection object (see Collection Object) |
Dim c As Control
Set c = Text1
c.Text = "Hello"
Dim t As TextBox
Set t = Text1
t.SelStart = 0
Dim people As New Collection
people.Add "Ann"
An object variable that has not been Set holds Nothing. A variable declared As Object holds any object. One declared As Control, As a control type, As Form, As a class name, As a form’s name, or As Collection accepts only an object of that kind, or Nothing, as in Visual Basic: As Control any control (a menu item too), As TextBox only a TextBox, As Form any form, and so on. An object of another kind raises error 13 (Type mismatch) — Set c = Me with c As Control, Set t = Label1 with t As TextBox — and SET of a value that is not an object at all raises error 424 (Object required); without SET such a value goes to the default member of the object the variable holds (see Default Member). The same holds for an array declared As a class, a FUNCTION’s result, a parameter (an argument of another kind raises error 13 as the procedure is entered, whatever called it: a late-bound call, an event), and a Public member variable of a class or a form declared As a class (Set acct.Owner = x, through any variable), and for what a procedure stores through a parameter without BYVAL that was given such a variable, element, or member (with Sub S(o As Object) doing Set o = New ClassB, S a raises error 13 when a is declared As ClassA, and a keeps its object), and for SWAP. When the compiler knows that an object can never fit — Set a = New ClassB, Set a = b, or Set a = MakeB() with a declared As ClassA and b or MakeB As ClassB, Set f = Form3 with f declared As Form2, Set c = Me in a form’s code with c As Control, Set t = New ClassA with t As TextBox, an argument for a parameter As ClassA, Set FunctionName = ... in a FUNCTION As ClassA — the program does not compile ("Type mismatch: SET needs ClassA here, got ClassB"). A variable As a class can hold an object of a class that Implements that class, so an object from a variable As an interface fits a class when one of the program’s classes Implements both. A value the compiler cannot know (an Object variable, a Form variable, a control named on a form for a variable As a control type) is checked when the program runs. The Source parameter of the DragDrop and DragOver events is a Control. New makes no control (Dim t As New TextBox does not compile): place a control on a form, or make one with Load or CreateControl.
A variable declared As a class name or As a form’s name knows its object’s members, as in Visual Basic: a name after the dot is looked up in that class’s or form’s declarations (for a form: its Public variables and procedures, its controls and menus, and the properties and methods every form has) when the program is compiled, and a misspelled or Private one is reported then, just as it is through the form’s own name (Form2.Cout), whether the program is compiled in the IDE or with the command-line compiler. A member read with arguments may be a method’s result or a property’s item (Form2.Controls(0)). A control made with CreateControl while the program runs is no member the compiler knows: reach it through the reference CreateControl gives, or Form2.Controls("name"). Through a variable As Object, As Form, As Control, or As a control type the member is found by its name when the program runs; in the IDE a variable As a control type has its members checked when the program is compiled, as the control’s own name does (t.Txet is reported).
1.1.3. Control Types
The types of DVX’s controls are object types, by the names a form’s .frm file gives them (Begin TextBox Text1), as in Visual Basic: Dim t As TextBox, ByVal lst As ListBox, Function Current() As Label, and TypeOf obj Is TextBox. DVX uses Visual Basic’s names where it has the control: CheckBox, ComboBox, CommandButton, Data, DBGrid, Frame, HScrollBar, Image, Label, Line, ListBox, ListView, Menu, OptionButton, PictureBox, ProgressBar, StatusBar, TabStrip, TextBox, Timer, Toolbar, and TreeView. The types of DVX’s own controls are DropDown, HBox, HelpPane, ImageButton, RichEdit (Visual Basic’s RichTextBox), RichLabel, ScrollPane, Spacer, SpinButton, Splitter, TabPage, Terminal, TextArea, VBox, and WrapBox.
The names of Visual Basic’s global objects, App, Screen, Clipboard, and Printer, are their objects' types (Dim p As Printer), each holding that object only. A UserControl of the program is a control type by its name too (Dim g As Gauge; see UserControls: Your Own Controls), and so is a control installed in DVX (a control file in WIDGETS: Dim iv As IconView) when one of the program’s forms has a control of it, or in the IDE, any one installed: an object stored there must be a control of that type, as for DVX’s own types. TypeOf obj Is Control is True for any control and menu item (not a form), TypeOf obj Is Form for any form.
A variable declared As a control type may be WithEvents, as in Visual Basic (Dim WithEvents t As TextBox): the control it holds sends its events to the variable’s handlers (t_Change) as well as to its own (see Events). So may a variable declared As a form (Dim WithEvents f As Form2, or As Form). As Control is no WithEvents type.
See also: Objects and Class Modules (Section 1.8).
1.1.4. Internal Types
These types are not directly declarable but are used internally by the runtime.
| Internal Type | Description |
|---|---|
Array |
Reference-counted multi-dimensional array (up to 8 dimensions) |
UDT |
User-defined type instance (created with TYPE...END TYPE) |
Object |
Reference to a form, a control, a class instance, or a Collection; declarable as Control, Form, Object, a class name, or Collection |
Ref |
Reference to a variable, array element, TYPE field, or member variable of a class or form (what a ByRef parameter holds) |
1.1.5. Type Suffixes
Type suffixes can be appended to variable names to declare their type implicitly:
count% = 42 ' Integer
total& = 100000 ' Long
rate! = 3.14 ' Single
pi# = 3.14159265 ' Double
price@ = 19.99 ' Currency
name$ = "Hello" ' String
A suffix that names the type a name has already is part of no name, as in QBasic and Visual Basic: a variable declared As Integer (Dim n As Integer, a parameter n As Integer), or given its type by DEFINT, is n% as well as n, and under DEFINT n alone is n%. A FUNCTION, and a CONST, with a suffix is its name without one too: FUNCTION Total% is called Total or Total%, and inside it Total = x sets its result (a FUNCTION without a type is a Single’s, so Total! is its name too). Another type’s suffix on such a name does not compile ("Type-declaration character does not match declared data type"): Dim n As Integer then n&, FUNCTION Total% then Total$. A name never declared and given no DEFtype is its own variable, apart from the same name with a suffix (QBasic: x and x% are two variables unless DEFINT gives x its type).
DefInt I-N
Dim total As Long
total& = 5 ' total
i% = 3 ' i, by DEFINT
Function Twice%(ByVal n)
Twice = n * 2 ' Twice%'s result
End Function
Print Twice(total); i ' 10 3
1.1.6. Numeric Literals
| Form | Example | Description |
|---|---|---|
Decimal integer |
42 |
Values -32768..32767 are Integer, larger ones Long, and ones past the Long range Double (3000000000 is a Double, as Visual Basic types it) |
Hex integer |
&HFF, &H1234 |
Hexadecimal literal (0-9, A-F) |
Octal integer |
&O10, &O77 |
Octal literal (0-7) |
Binary integer |
&B1010, &B11111111 |
Binary literal (0-1) |
Integer suffix |
42%, &HFF% |
Force Integer type (an &H, &O, or &B number’s digits are its 16 bits: &HFFFF% is -1) |
Long suffix |
42&, &HFF& |
Force Long type (an &H, &O, or &B number’s digits are its 32 bits: &HFFFFFFFF& is -1) |
Floating-point |
3.14, 1.5E10, 2.5D3 |
Any number containing a decimal point or exponent is Double by default |
Single suffix |
3.14! |
Force Single type |
Double suffix |
3.14# |
Force Double type |
Currency suffix |
19.99@, 5@ |
Force Currency type (more than four decimal places round, halves to even) |
|
Note
|
Both E and D can introduce an exponent (e.g. 1.5E10 and 2.5D3 are equivalent forms of a scientific-notation double). |
As in Visual Basic, a type suffix goes only on a literal its type can hold. % and & go only on a whole number: 50.5%, 1.5&, and 1E3% do not compile ("Expected end of statement"). A value past the type’s range does not compile either ("Overflow"): 70000%, 3000000000&, &H10000%, 1E39!, 1E400#, and 1E400 without a suffix. An &H, &O, or &B number takes % or & but not !, #, or @. The most negative values -32768% and -2147483648& are valid. A trailing decimal point is allowed (1. is the Double 1). A numeric literal too long to read is a compile error.
1.1.7. Type Promotion
When mixing types in expressions, +, -, and * give the wider of their two types, as in Visual Basic, in the order Byte -> Integer -> Long -> Single -> Double (a Boolean counts as an Integer, and text that holds a number as a Double). A Single with a Single, an Integer, or a Byte stays a Single, so with x! = 1.1, x! * 3 is the Single 3.3 and PRINT shows it with a Single’s 7 digits; a Single with a Long gives a Double. A Currency with a Byte, Integer, Long, or Currency stays Currency, and with a Single or Double gives a Double (see Byte and Currency below). / gives a Double, except that a Single divided by a Single, an Integer, or a Byte (or one of those divided by a Single) gives a Single; 1 / 3 is a Double. \ and MOD give an Integer for Byte, Integer, and Boolean operands (a Byte for two Bytes) and a Long for any other, and ^ always gives a Double. Negating a Single gives a Single, a Boolean or a Byte an Integer. + and - of a Date and a number give a Date (5 - #1/2/2000# too), and - of two Dates a Double. Whole-number arithmetic keeps the type of its operands: an Integer result too large for an Integer becomes a Long (32767 + 1 is the Long 32768) and a Byte result outside 0 to 255 becomes an Integer, but a Long result too large for a Long, and a Single result past the Single range, raise error 6 (Overflow), as in Visual Basic. Convert an operand when a larger result is expected: CDBL(2147483647) + 1 is 2147483648.
+ joins two strings. When a string meets a number in an arithmetic operator (including +) or a comparison, the string must hold a number, as in Visual Basic: "1" + 2 is 3, " 2.5 " * 2 is 5, and "1,000" + 1 is 1001 (see Numbers in Text under Conversion Functions for the forms text may take), but text that is not a number ("abc" + 2, "12abc" + 2) raises error 13 (Type mismatch). VAL reads the number at the start of any text instead (VAL("12abc") is 12). Use & to join text and numbers, and VAL / STR$ to convert explicitly.
1.1.8. Assignment Conversion
Storing a value into a variable declared as Byte, Integer, Long, Single, Double, Currency, String, Boolean, or Date (by suffix, by AS clause, by DEFtype, or as a typed parameter, STATIC variable, FUNCTION result, TYPE field, or array element) converts the value to that type: a number stored in a String variable becomes its text as CSTR gives it ("5", "0.25"). Text stored in a numeric variable must be a number, as in Visual Basic: "12", " 3.5 ", and "1,234" convert (see Numbers in Text under Conversion Functions), while text that is not a number ("abc", "12abc", "") raises error 13 (Type mismatch) and the variable keeps its value. DEFtype statements also give parameters, STATIC variables, and FUNCTION results their default type. Byte, Integer, and Long round to the nearest whole number, with halves rounding to the nearest even number (2.5 becomes 2, 3.5 becomes 4), and raise error 6 (Overflow) when the result does not fit (so does a number given where a built-in takes a whole number: see Whole-Number Arguments); Currency rounds to four decimal places the same way. Single keeps about 7 significant digits, so PRINT shows at most 7 digits of it; a number past the Single range (about 3.4E+38) stored in a Single, or given to CSNG, raises error 6. Boolean stores True for any non-zero number and False for 0; text must be "True" or "False" (in any letter case), #TRUE# or #FALSE#, or a number, as CBOOL reads it, and other text ("yes", "") raises error 13. Date takes a number as a date’s number of days and reads a string as a date (error 13 when the text is not a date, error 6 outside 1/1/100 to 12/31/9999); INPUT into a Date variable reads the date the same way. A variable declared with DIM but without a type is Single (or the DEFtype for its first letter). A variable that is never declared keeps whatever type the assigned value has. A variable declared with a type holds that type from the start, before anything is stored in it: VARTYPE of a Long that was never assigned is 3 (vbLong) and of a String 8 (vbString).
Dim n As Integer
n = 3.7 ' n is 4
n = 40000 ' Error 6: Overflow
n = "12" ' n is 12
n = "twelve" ' Error 13: Type mismatch (n is still 12)
Dim b As Boolean
b = 3 ' b is True
Dim s
s = 1 / 3 ' s is Single: prints 0.3333333
x = 1 / 3 ' never declared: keeps the Double, prints 0.333333333333333
1.1.9. Whole-Number Arguments
A number given where a built-in function, statement, or property takes a whole number — a string function’s position or count, a character code, a file number, a column for TAB or SPC, a color, a coordinate of the program screen, a bound’s dimension, an error number, a property such as Left, Width, or Interval — is rounded as CLNG rounds it, half to even, as in Visual Basic: MID$(s$, 2.5) starts at 2, MID$(s$, 3.5) at 4, SPACE$(2.6) is three spaces, TAB(5.6) goes to column 6. One past the Long range raises error 6 (Overflow) before anything else can go wrong with it (SPACE$(-1E10) is error 6, not 5). INT and FIX cut a number toward a whole one as their own work, and CHOOSE’s index and DATEADD’s count of intervals drop their fractions (as Visual Basic’s do).
1.1.10. Boolean Values
Boolean values use -1 for True and 0 for False. Any non-zero numeric value is treated as True in a conditional context. The keywords True and False are reserved and may be used anywhere a Boolean value is expected.
1.1.11. Byte and Currency
A Byte holds a whole number from 0 to 255 in one byte. Storing a value outside that range raises error 6 (Overflow). Arithmetic on two Bytes gives a Byte when the result is 0 to 255 and an Integer otherwise; negating a Byte gives an Integer. CBYTE converts a value to a Byte.
A Currency holds an amount of money exactly: it counts ten-thousandths, so it has four decimal places and adding, subtracting, or multiplying amounts never drifts (adding 0.1@ ten times gives exactly 1). A value with more decimal places is rounded to four, halves to the nearest even digit (CCUR(2.00005) is 2, CCUR(2.00015) is 2.0002), and a result outside the Currency range raises error 6 (Overflow). +, -, and * on a Currency and a Byte, Integer, Long, or Currency give a Currency; with a Single or Double they give a Double, and / always gives a Double. Comparisons of Currency values are exact. PRINT and STR$ show a Currency with only the decimals it needs (12.5); FORMAT$ lays it out like any other number. A FOR loop with a Currency counter steps exactly. CCUR converts a value to a Currency.
Dim total As Currency
Dim i As Integer
For i = 1 To 3
total = total + 19.99@
Next
Print total ' 59.97
Print FORMAT$(total, "0.00")
GET and PUT store a Byte in 1 byte and a Currency in 8 (see GET / PUT).
1.1.12. Date Values
A Date holds a calendar date and a time of day, as in Visual Basic: the whole part of its number counts days from 12/30/1899 and the fraction is the time (0.5 is noon, so 36526.5 is noon on 1/1/2000). Days before 12/30/1899 are negative numbers whose time still counts forward from midnight: -1.25 is 6:00 AM on 12/29/1899. CDBL gives a date’s number and CDATE turns a number back into a date.
Write a date literal between # signs. The month comes before the day; a year can also come first, and month names (full or abbreviated) work too. A time can follow the date or stand alone:
Dim d As Date
d = #1/15/2000# ' January 15, 2000
d = #2000-01-15 15:30# ' year first, 24-hour time
d = #Jan 15, 2000 3:30:00 PM#
d = #3:30 PM# ' a time alone is on 12/30/1899
Two-digit years 00 to 29 are 2000 to 2029 and 30 to 99 are 1930 to 1999. Date is not a reserved word, so a program may still use Date (or any of the date function names) for its own variables and procedures; the program’s own name wins.
PRINT, STR$, CSTR, and the & operator show a date as m/d/yyyy h:mm:ss AM (1/15/2000 3:30:00 PM). A date at midnight shows only the date and a time on 12/30/1899 only the time; a Date variable that was never assigned is 12:00:00 AM. Use FORMAT$ for any other layout.
Adding a number of days to a date, or subtracting one, gives a date (fractions are parts of a day, so d + 0.25 is six hours later); subtracting one date from another gives the number of days between them as a Double. The other operators (*, /, \, MOD, ^) take a date as its number (CDBL), as Visual Basic does, and give a number. Comparisons put dates in time order, and a string compared with a date is read as a date:
Dim due As Date
due = Date + 30 ' thirty days from today
If due > #12/31/2025# Then Print "Next year"
Print #3/1/2000# - #2/1/2000# ' 29 (2000 is a leap year)
If due = "1/15/2026" Then Print "Match"
A Date variable has no Empty or Null state (a Variant does): a date that is out of range is error 6 (Overflow), and text that is not a date is error 13 (Type mismatch).
See also: Conversion Functions (Section 1.6.12).
1.2. Variants
A Variant is a variable that can hold any kind of value: a number, text, a date, True or False, an object, or a whole array. It takes on the type of whatever is stored in it, and can change type each time something new is stored. A Variant can also hold two special values that no other type has: Empty (nothing has been stored yet) and Null (the value is unknown or missing).
Dim v As Variant
Print TypeName(v) ' Empty
v = 42
Print TypeName(v) ' Integer
v = "forty-two"
Print TypeName(v) ' String
v = #1/15/2000#
Print TypeName(v) ' Date
v = Null
Print IsNull(v) ' True
Declare a Variant with AS VARIANT. Arrays of Variants (DIM list(10) AS VARIANT), Variant parameters, and FUNCTIONs and properties AS VARIANT work the same way; each element of a Variant array starts Empty. A variable declared with DIM but no AS clause, or never declared at all, is not a Variant: it keeps the older rules described under Assignment Conversion. PUT and GET store a Variant as Visual Basic does, its VarType first (see GET / PUT).
Storing a Variant in a variable of another type converts the value to that type, as for any other assignment. A Variant given an object holds it only through SET (Set v = Text1); a plain v = Text1 stores the object’s default value, Text1’s text, as in Visual Basic (see Default Member). A Variant that is given an array gets its own copy of the array, as in Visual Basic: after v = list, changing list(1) does not change v(1), and w = v copies again. The same holds when a Variant holding an array is passed BYVAL, stored in an object’s member, or added to a Collection. Index it like the array itself, v(1). The copy keeps the array’s element type: v(1) = 5 stores "5" when list is a String array, v(1) = "x" raises error 13 when it is an Integer array, and when it is an array As Object or a class v(1) = 5 stores 5 in the default member of the object v(1) holds (error 91 when it holds Nothing), as in any element of such an array (see Default Member; the copy keeps Object as its element type but not the class, so SET v(1) takes an object of any class).
Dim list(2) As Integer, v As Variant
list(0) = 1
v = list ' v holds a copy
list(0) = 5
Print v(0); list(0) ' 1 5
1.2.1. Empty
Empty means that nothing has been stored in the Variant yet. A new Variant is Empty, and assigning Empty makes it Empty again. In arithmetic Empty counts as 0 and in text as "", so a counter kept in a Variant needs no starting value; PRINT shows nothing for it.
Dim total As Variant
total = total + 5 ' Empty counts as 0: total is 5
If IsEmpty(v) Then Print "Nothing stored yet"
1.2.2. Null
Null means "no valid value" — for example a field that was never filled in. Null spreads through most expressions: anything calculated from a Null is Null too, so a missing value is not mistaken for a real one.
| Expression | Result |
|---|---|
Null + 1, Null * x, -Null, Not Null |
Null |
Null = 1, Null < x, Null = Null |
Null (a comparison with Null is never True) |
Abs(Null), Int(Null), Fix(Null), Sgn(Null) |
Null |
Left(Null, 1), UCase(Null), Len(Null), ... |
Null (the Variant string functions; see below) |
"Name: " & Null |
"Name: " (& treats Null as "") |
Null & Null |
Null |
False And Null |
False |
True Or Null |
True |
False Imp Null, Null Imp True |
True |
Any other And, Or, Xor, Eqv, or Imp with Null |
Null |
An IF, ELSEIF, WHILE, DO, or LOOP condition that is Null counts as False. Any other use that needs a real number — storing Null in a numeric, Boolean, or Date variable, CINT(Null) and the other conversion functions, a string function ending in $ such as UCASE$ or LEFT$, or an array subscript — raises error 94 (Invalid use of Null).
As in Visual Basic, the string functions without $ are Variant functions that pass Null through: LEFT, RIGHT, MID, UCASE, LCASE, TRIM, LTRIM, RTRIM, CHR, HEX, OCT, STR, SPACE, and STRING give Null when their text (or number) argument is Null, and so do LEN, INSTR, INSTRREV, STRCOMP, LIKE, and the date parts YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, WEEKDAY, and DATEPART. Their $ forms (LEFT$, UCASE$ ...) always give text and raise error 94 for Null.
Because Null = Null is itself Null, test for Null with ISNULL, never with =:
If IsNull(price) Then
Print "No price yet"
Else
Print "Price: "; price
End If
Empty and Null are not reserved words: a program that declares its own variable or constant named Empty or Null keeps using it.
1.2.3. Variant Functions
| Function | Returns | Description |
|---|---|---|
VARTYPE(v) |
Integer |
A number for the kind of value v holds (see VarType Constants): vbEmpty (0), vbNull (1), vbInteger (2), vbString (8), vbObject (9), and so on. For an array it is vbArray (8192) plus the element type, so an Integer array is 8194 and a Variant array 8204. |
TYPENAME(v) |
String |
The name of the kind of value: "Byte", "Integer", "Long", "Single", "Double", "Currency", "String", "Boolean", "Date", "Empty", "Null", "Error" (a left-out OPTIONAL argument), the name of a TYPE, "Integer()" for an array, and for objects the class name, "Collection", "Nothing", a form’s own name ("Form1", for a copy NEW made of it too; TypeName(Form1) does not load the form), or a control’s type ("TextBox", "Menu" for a menu or menu item). |
ISEMPTY(v) |
Boolean |
True when v is Empty. |
ISNULL(v) |
Boolean |
True when v is Null. |
ISNUMERIC(v) |
Boolean |
True when v is a number, True or False, Empty, or text that reads as a number ("12", "1.5", "1,234", "$5", "(5)": see Numbers in Text). False for Null, dates, "", and other text. |
ISOBJECT(v) |
Boolean |
True when v is an object reference, including Nothing. |
ISARRAY(v) |
Boolean |
True when v is an array. |
ISMISSING(v) |
Boolean |
True when v is an OPTIONAL Variant parameter the caller left out (see Procedures). |
ISDATE(v) |
Boolean |
True for a Date or text holding a date (see Date and Time Functions). |
CVAR(v) |
Variant |
v unchanged, as a Variant. |
ARRAY(a, ...) |
Variant |
A Variant holding an array of copies of the values, numbered from OPTION BASE (0 unless OPTION BASE 1); ARRAY() is empty (UBOUND -1). |
Dim days As Variant
days = Array("Mon", "Tue", "Wed")
Print days(1) ' Tue
For Each d In Array(1, 2, 3)
Print d;
Next
Sub Describe(ByVal v As Variant)
Select Case VarType(v)
Case vbEmpty
Print "(empty)"
Case vbNull
Print "(unknown)"
Case vbString
Print "Text: "; v
Case Else
Print TypeName(v); ": "; v
End Select
End Sub
See also: Data Types (Section 1.1); VarType Constants (Section 1.16).
1.3. Operators
Operators listed from highest precedence (evaluated first) to lowest precedence (evaluated last). Parentheses override precedence and may be nested freely.
| Precedence | Operator | Description |
|---|---|---|
1 (highest) |
^ |
Exponentiation |
2 |
- (unary), + (unary) |
Negation (unary plus is a no-op) |
3 |
* / |
Multiply, float divide |
4 |
\ |
Integer divide |
5 |
MOD |
Modulus |
6 |
+ - |
Addition, subtraction (+ also concatenates strings) |
7 |
& |
String concatenation |
8 |
= <> < > <= >= Is Like |
Comparison (returns Boolean) |
9 |
NOT |
Logical/bitwise NOT |
10 |
AND |
Logical/bitwise AND |
11 |
XOR |
Logical/bitwise exclusive-or |
12 |
OR |
Logical/bitwise OR |
13 |
EQV |
Logical/bitwise equivalence |
14 (lowest) |
IMP |
Logical/bitwise implication |
1.3.1. Arithmetic Operators
| Operator | Description |
|---|---|
+ |
Addition (or string concatenation when both operands are strings) |
- |
Subtraction (or negation when used as a unary prefix) |
* |
Multiplication |
/ |
Floating-point division (a Double; a Single for Singles, or a Single with an Integer or Byte) |
\ |
Integer division (the operands rounded to whole numbers, the quotient’s fraction dropped: an Integer for Integers and Bytes, else a Long) |
MOD |
Integer modulus (remainder) |
^ |
Exponentiation (result is Double) |
1.3.2. Comparison Operators
Comparison operators return True (-1) or False (0).
| Operator | Description |
|---|---|
= |
Equal to |
<> |
Not equal to |
< |
Less than |
> |
Greater than |
<= |
Less than or equal to |
>= |
Greater than or equal to |
Is |
Both sides refer to the same object (objects only) |
Like |
The text on the left matches the pattern on the right |
String comparisons are controlled by OPTION COMPARE. With OPTION COMPARE BINARY (the default) strings are compared by byte value. With OPTION COMPARE TEXT comparisons are case-insensitive. As in Visual Basic, the setting is the one of the file the comparison is written in (a module, a form, a class, or a UserControl): a SUB or FUNCTION of a module with OPTION COMPARE TEXT compares ignoring case whatever code calls it, and another module’s code keeps comparing by byte value (see OPTION). A comparison with Null gives Null (see Variants).
Is compares object references, not values: a Is b is True when both refer to the very same object, and x Is Nothing tests for an object variable that holds no object. Either side may be a form or control name. Using Is on something that is not an object raises error 424 (Object required).
text Like pattern is True when the whole of text matches the pattern. In the pattern, ? stands for any one character, * for any run of characters (none too), # for one digit 0 to 9, [list] for one character in the list, and [!list] for one character not in it; anything else stands for itself. A list holds characters and ranges such as a-z ([A-Za-z0-9_]); to match a literal ?, *, #, or [, put it in brackets ([*]). OPTION COMPARE TEXT (of the file the Like is in) makes the match ignore case. Like with Null gives Null, and a pattern with a [ that has no ] raises error 93.
If name$ Like "A*" Then Print "Starts with A"
If code$ Like "[A-Z]##" Then Print "A letter and two digits"
If file$ Like "*.[!b]*" Then Print "Not a .b... extension"
TypeOf object Is TypeName is True when the object is of that type. TypeName can be a class module’s name, Collection, Form, Control (any control, a menu too), Object (any object that is not Nothing), a control type such as TextBox or a UserControl of the program (see Control Types), Menu (a menu or menu item, which a form’s Controls also lists), or the name of one of the program’s forms: TypeOf f Is Form2 is True for Form2 (a reference to it does not load it) and for a copy New made of it, as in Visual Basic. It is False for Nothing. Use Not TypeOf ... Is ... for the opposite test.
If player Is Nothing Then Set player = New Player
If a Is b Then Print "Same object"
If TypeOf Source Is TextBox Then Print Source.Text
1.3.3. Logical / Bitwise Operators
The logical operators work on Boolean values and also perform bitwise operations on integer values. As in Visual Basic, two Booleans give a Boolean (True And False is False, Not True is False, and Print (a > 1) Or (b > 1) prints True); when either side is a number they work on the bits and give a number (an Integer, or a Long when a side is Long): True And 3 is 3. With Null they give Null unless the other side decides the answer (False And Null is False, True Or Null is True, a Boolean as the other side is); see Variants.
| Operator | Description |
|---|---|
NOT |
Logical/bitwise complement |
AND |
Logical/bitwise AND |
OR |
Logical/bitwise OR |
XOR |
Logical/bitwise exclusive-or |
EQV |
Logical/bitwise equivalence (same as NOT (a XOR b)) |
IMP |
Logical/bitwise implication (same as (NOT a) OR b) |
1.3.4. String Concatenation
Use & to concatenate strings. The + operator also concatenates when both operands are strings. Prefer & because it does not depend on operand types.
result$ = "Hello" & " " & "World"
result$ = firstName$ & " " & lastName$
' + also concatenates when both operands are strings
greeting$ = "Hi " + name$
1.4. Statements Overview
1.4.1. Statements
Multiple statements can appear on one line separated by : (colon). A line can be continued onto the next physical line by ending it with an underscore (_) preceded by whitespace. Comments start with ' (apostrophe) or the REM keyword and run to the end of the line. The character ? is a shorthand for PRINT.
A string literal is text between double quotes, on one line. Two double quotes in a row inside it stand for one, as in Visual Basic: "Say ""hi""" is the text Say "hi", and """" is a single double quote.
a = 10 : b = 20 : c = a + b ' three statements on one line
total = price * quantity _
+ shipping + tax ' one statement continued across lines
REM This is a comment
' So is this
? "Hello" ' same as PRINT "Hello"
PRINT "She said ""hi""" ' She said "hi"
See also: Conditional Statements (IF, SELECT CASE) (Section 1.4.3); Loop Statements (FOR, DO, WHILE) (Section 1.4.4); Procedures (SUB, FUNCTION, DEF FN) (Section 1.4.5); Flow Control (EXIT, CALL, GOTO, GOSUB, ON) (Section 1.4.6); Input/Output (PRINT, INPUT, DATA/READ) (Section 1.4.7); Miscellaneous Statements (ON ERROR, SHELL, SLEEP, END) (Section 1.4.8); Sound, Joysticks, and Frames (BEEP, SOUND, PLAY, STICK, STRIG, FRAMEWAIT) (Section 1.4.9); Objects and Class Modules (NEW, PROPERTY, Class_Initialize, Me) (Section 1.8); Collection Object (Add, Remove, Item, Count) (Section 1.8.15).
1.4.2. Declaration Statements
DIM
Declares variables and arrays with an explicit type. If no type is given, the type defaults to whatever DEFtype (if any) is in effect for the variable’s first letter; without a DEFtype statement the default is Single.
DIM variable AS type
DIM variable(upperBound) AS type
DIM variable(lower TO upper) AS type
DIM variable(dim1, dim2, ...) AS type
DIM variable() AS type
DIM variable AS UdtName
DIM variable AS STRING * n
DIM variable AS NEW ClassName
DIM SHARED variable AS type
DIM variable1 [AS type], variable2 [AS type], ...
An array declared with constant bounds (numbers and constants: Dim a(10), Dim b(1 To MAXN)) is a fixed-size array, as in Visual Basic: it keeps its bounds wherever it is reached from. REDIM of it does not compile ("Array already dimensioned"), and neither does assigning another array to it ("Can’t assign to array"); through an array parameter given it, REDIM and such an assignment raise error 10 (This array is fixed or temporarily locked), and ERASE resets its elements. DIM variable() with empty parentheses declares a dynamic array that has no bounds until a REDIM gives it some. It is an array of its type all the same, as in Visual Basic — ISARRAY is True, VARTYPE is vbArray plus its type, and TYPENAME gives Integer() — but LBOUND, UBOUND, and every element of it raise error 9 (Subscript out of range), and FOR EACH over it raises error 92 (For loop not initialized). A DIM that runs again (in a loop) leaves an array it holds as it is; a STATIC dynamic array and a dynamic array member of a class start without bounds too. A bound or a subscript with a fraction is rounded as CLNG rounds it (half to even, as in Visual Basic and QBasic): Dim a(2.6) has 3 as its upper bound, and a(1.5) is a(2). An array first created by REDIM, one declared with bounds that are not constant (Dim a(n) with n a variable, as in QBasic), and a copy of an array (b = a with b dynamic, a Variant given an array) are dynamic too (see ERASE for the difference). An array parameter is the caller’s array, fixed-size or dynamic as the caller declared it. A Public array member of a class or a form declared with bounds is fixed-size whatever its bounds.
One DIM can declare several variables, separated by commas. Each one takes its own AS clause; a name without one gets its suffix or DEFtype type (Single by default), so DIM a, b AS STRING makes only b a String. Arrays can have up to 8 dimensions; more is a compile error. A variable declared with type suffix does not need the AS clause:
Dim name$, count%, total& ' suffixes infer the types
Dim first, last As String, list(10) As Integer
Examples:
Dim name As String
Dim count As Integer
Dim values(100) As Double
Dim matrix(1 To 10, 1 To 10) As Single
Public globalFlag As Boolean
Dim record As PersonType
Dim fixedStr As String * 20
|
Note
|
A variable declared at module level (outside every SUB and FUNCTION) is visible inside every SUB and FUNCTION of its file, as in Visual Basic. See Variable Scope below. Inside a SUB or FUNCTION, DIM declares a local variable that is recreated on each call (use STATIC to retain its value between calls). A SUB or FUNCTION holds at most 64 parameters and local variables together, including a few hidden ones that statements such as ON ... GOTO, SWAP, and READ into array elements use while they run; a procedure that needs more fails to compile with "Too many local variables". A program holds at most 512 module-level variables, a form at most 65536 form-level variables, and a class at most 65536 member variables; more fails to compile. |
Fixed-length strings (STRING * n) are padded with spaces and truncated when assigned so their length is always exactly n. So is every element of an array of STRING * n (Dim codes(10) As String * 4, a dynamic one REDIM sizes, a Public member array of a class or a form): its elements start as n spaces, and whatever stores into one — an assignment, a procedure’s parameter (a whole array parameter too), INPUT, READ, LSET, RSET, MID$, SWAP — keeps n characters; ERASE of a fixed array sets them back to spaces. As in Visual Basic, n is a number or a constant (Const NAME_LEN = 20: Dim nm As String * NAME_LEN), in DIM, STATIC, REDIM, a TYPE’s fields, and a parameter alike; it must be 1 to 65535 (a constant with a fraction is rounded as a Long is).
A module’s and a form’s variables exist before any of their code runs, as in Visual Basic: when the program starts every module’s variables are made — a fixed array sized, a TYPE variable given its record, a STRING * n filled with n spaces, an object variable Nothing, a Variant Empty, a dynamic array an array of its type without bounds, any other variable its type’s zero — and a form’s when each copy of it loads, before its code. The code outside procedures of a module that comes before another in the project can so use the other module’s Public arrays and records, and a DIM at a module’s or a form’s level does nothing when it runs (it leaves the values the variables hold). An array whose bounds are not constant (Dim a(n)) is made when its DIM runs, as in QBasic.
DIM variable AS NEW ClassName (or AS NEW Collection) creates a new object at the DIM and stores it in the variable (until then a module’s or a form’s variable holds Nothing); without NEW an object variable starts as Nothing. See Objects and Class Modules. DIM variable AS NEW FormName makes a new copy of a form of the project (see Several Copies of a Form in the Form topic); DIM variable AS FormName declares a variable for that form or a copy of it, whose members are checked when the program is compiled (see Object Types).
Variable Scope and SHARED
DVX BASIC follows Visual Basic’s scope rules, inside a file and between the files of a project; QBasic’s SHARED is kept for variables made by their first use:
-
Variables declared (or first used) at module level — outside every SUB and FUNCTION — are module variables. The code section of a form (.frm) is module-level code of that form.
-
A module’s variables are its own unless they are declared PUBLIC (or GLOBAL), as in Visual Basic and in QBasic’s programs of several modules: a variable a module declares with DIM, DIM SHARED, or PRIVATE, or makes by its first use, is seen only by that module’s code. Another module’s, a form’s, or a class’s code that names it names a variable of its own (a new one, or with OPTION EXPLICIT a compile error), and ModuleName.Name reaches it only from its own module. A PUBLIC variable is seen by every file of the program; a module’s own variable may have the name of another module’s PUBLIC one, and its own code then means its own. A form’s DIM, DIM SHARED, and PRIVATE variables are the form’s own in the same way (see Several Copies of a Form in the Form topic).
-
A SUB or FUNCTION sees every module variable of its file that is declared at module level — with DIM, PRIVATE, PUBLIC, DIM SHARED, or REDIM — as in Visual Basic, arrays too. A form’s procedures see the form’s variables the same way. DIM SHARED is DIM: SHARED is allowed for QBasic’s programs and changes nothing.
-
A module variable made by its first use at module level (a name used there without a DIM) is seen inside a SUB or FUNCTION only when the procedure names it in a SHARED statement, as in QBasic.
-
Any other name used inside a SUB or FUNCTION is a local variable of that procedure, even when a module variable of the same name was made by its first use. With OPTION EXPLICIT, using such a name without a DIM is a compile error that says to declare the module variable with DIM.
-
A DIM inside a SUB or FUNCTION declares a local variable that hides a module variable of the same name in that procedure.
-
Indexing (name(...)) or dotting (name.member) a module variable the procedure cannot see is a compile error.
-
CONSTs declared at module level, TYPEs, SUBs, FUNCTIONs, class modules, forms, and controls are visible everywhere. A Private CONST, SUB, or FUNCTION of a module is seen only by that module’s code (see PUBLIC / PRIVATE). PUBLIC at module level declares a variable every file sees (see PUBLIC / PRIVATE).
-
A DEF FN is module-level code: its expression sees every module variable of its file.
PUBLIC grandTotal AS LONG ' every file's code, every SUB and FUNCTION
DIM total AS LONG ' this module's code and its SUBs and FUNCTIONs
count = 0 ' made by its first use: module code only
SUB AddUp(n AS INTEGER)
total = total + n ' the module variable
count = 1 ' a local variable, not the module's count
END SUB
SUB ShowCount
SHARED count ' this procedure uses the module's count
PRINT count
END SUB
DIM SHARED and REDIM SHARED are only allowed at module level. Inside a procedure, the SHARED statement names module variables the procedure would not see otherwise:
SHARED variable [()] [AS type] [, variable [()] [AS type] ...]
SHARED gives the procedure access to the named module variables of its file (write name() for an array). The AS type, when given, must match the module variable’s declaration. Naming a variable that does not exist at module level creates it there, as a variable of the procedure’s module (in a form’s code, of that form).
How Names Are Found
Every name in a program is looked up the same way, in this order:
-
A name the program declares is that declaration: first the procedure’s own parameters, local variables, and STATIC and SHARED names; then, in a class module, the class’s own members; then the variables, constants, ENUMs, controls, SUBs, and FUNCTIONs of the form whose code it is; then, in a form’s code, the properties and methods every form has (see below); then the variables of the module whose code it is, then every module’s PUBLIC variables, the SUBs, FUNCTIONs, constants, TYPEs, ENUMs, and classes, and the predefined vb constants; last, a SUB or FUNCTION of another form’s code (see below). Inside a procedure a module variable made by its first use counts only when the procedure names it in a SHARED statement (see above); a declared one, and a class’s members, always do.
-
Otherwise a built-in function of that name is used. Built-in names are not reserved: a variable, constant, SUB, or FUNCTION the program declares with the same name wins (a FUNCTION named StrReverse replaces the built-in one).
-
Otherwise, where an object is expected — before a dot (name.Caption), after SET, around Is or TypeOf, or as an argument for an Object or class parameter — the name is a control, or a form of that name. In a form’s code a control named alone is that form’s own, as in Visual Basic, whatever code called the procedure (a control its .frm declares is never another form’s, even after RemoveControl); a name its .frm does not declare (a control CreateControl made while the program runs) is looked for on the form first, then as in other code. In a module’s or a class’s code, which in Visual Basic cannot name a control without its form, it is the control of the one loaded form that has a control of that name: when several loaded forms have one, using the name raises error 1001 (Ambiguous control name) rather than picking one — write FormName.Control (Form2.Text1) there. A library function given a control’s name (ConnAttach, SerAttach, CommAttach) finds the control the same way: called from a form’s code, that form’s first, else the one loaded form’s that has one (error 1001 when several have). A form’s name is that form elsewhere in an expression too, as an object that does not load it (TypeName(Form1), CreateControl(Form1, ...)). Form1.Text1.Text names the control Text1 on the form Form1, and Form1.Total a SUB or FUNCTION of Form1’s code, run for that form (see Several Copies of a Form in the Form topic).
-
Otherwise the name is a new variable: local inside a procedure, a module variable of its file elsewhere (a DEF FN expression’s names are module variables). With OPTION EXPLICIT this is a compile error.
In a form’s code the form’s own properties and methods are used without Me, as in Visual Basic: Caption = "Ready" sets the form’s Caption, Width and ScaleWidth read the form’s, Hide, Show, Refresh, SetFocus, ZOrder, Move, Cls, Scale, and PopupMenu mnuEdit (Call Refresh too) are the form’s methods, Line (0, 0)-(10, 10), Circle, and PSet draw on the form in their statement syntax, Point(x, y) and TextWidth("abc") are the form’s, and Controls.Count, Controls(0).Name, and ActiveControl.Text use its object properties. Name reads the form’s name (NAME old AS new is still the statement), and Show, Hide, and Name are not reserved words. Only the form’s own members count — its properties, the drawing members, Show, Hide, Move, ZOrder, FitWidth, FitHeight, SaveScreenshot, SetFocus, Refresh, PopupMenu, and the menu methods (CreateMenu, AddMenu, AddMenuItem, and the others) — not the methods only controls or a Toolbar answer (Clear, AddButton, MoveBefore, Drag, SetEnabled, and the others), so a module’s SUB Clear is still called by its name. A procedure’s own names and the form’s own declarations come first — a local variable Height, a CONST Padding, a control, or a SUB Cls of the form’s code is the program’s own — and the form’s members come before a module’s names and the built-in functions, as in Visual Basic: in a form’s code a module’s PUBLIC Top or SUB Refresh is not reached by that name alone — write the module’s name in front, Module1.Top and Module1.Refresh (see Module Names below) — and FullScreen alone is the form’s FullScreen property. With an argument list only a method or Controls(i) is the form’s, since a property takes no arguments: Left(s, 2) is the built-in function, and Tag(i) an array (QBasic’s implicit one when the program declares none). A property is no variable: it cannot be a FOR or FOR EACH counter, nor what INPUT, LINE INPUT, READ, GET, SWAP, LSET, RSET, or MID$ store into ("Variable required"); declare a variable to use the name. PRINT (without #) stays the PRINT statement in a form’s code too, writing to the Output window or the program’s screen; Me.Print prints on the form. The console statements that are no form methods (COLOR, LOCATE, PRESET, WIDTH n, and the others) keep their meaning. In a module’s or a class module’s code none of these names is a form’s member: they are the program’s own names, or new variables. A UserControl’s code uses the members of its UserControl object alone the same way (Width, Refresh, Cls, Line, Ambient.UserMode, PropertyChanged "Level"; see UserControls: Your Own Controls).
Module Names
Every module of a project has a name, as in Visual Basic: its file’s name without .bas (TOOLS.BAS is the module Tools), or the name its Attribute VB_Name line gives — a Visual Basic .bas file starts with Attribute VB_Name = "Module1", and that line is no code. ModuleName.Name is that module’s own Public variable, constant, SUB, FUNCTION, or Property, as if the name were written alone in the module’s code: Tools.Count = 5, Tools.Limit, Tools.Reset, Call Tools.Reset, x = Tools.Twice(4), Tools.Items(2) = "two", Tools.Level = 3 (its Property Let), from any code of the program, a form’s or a class’s too. This is how a form’s code reaches a module’s name the form’s own members hide (Tools.Top, Tools.Refresh), and how a name two modules of the program have can be told apart where it is used.
' TOOLS.BAS
Public Top As Integer
Sub Refresh()
Top = 0
End Sub
' Form1's code
Sub Command1_Click()
Tools.Top = Top ' the module's Top, and the form's own Top
Tools.Refresh ' the module's SUB, not the form's Refresh method
End Sub
A module’s Private names (a variable declared with DIM, DIM SHARED, or PRIVATE at module level, one its code makes by its first use, a Private CONST, SUB, or FUNCTION) are its own: in its own code ModuleName.Name reaches them (from its procedures too, even a variable made by its first use, which they do not see by its name alone), and elsewhere ModuleName.Name is a compile error ("Method or data member not found: 'x' is Private in module 'Tools'"), as is a name the module does not have. A module’s name before a dot counts only when nothing else of that name exists — a variable, a constant, a procedure, a TYPE, an ENUM, a form, a class, or a control of a form — so a program’s own name always comes first; a module named like a form or class of its project (PARDEMO.BAS and the form ParDemo) cannot be named so. A class’s name before a dot is a compile error, as in Visual Basic: a class’s members need an object of it (Dim acct As New Account, then acct.Deposit). A form’s name before a dot reaches that form’s Public members (see Several Copies of a Form in the Form topic).
A module’s Public variables and constants (and its CONSTs declared without Private), and the members of every ENUM (a Private ENUM’s in its own file only), are known in the whole program, as in Visual Basic: the modules before it in the project, the forms, the classes, and procedures written above the declaration use them by their names alone (or as ModuleName.Name), also with OPTION EXPLICIT. A constant or ENUM member whose value uses a constant declared after it, and a variable As a TYPE declared after it, are known only from their declaration on. A module’s code outside procedures runs file by file in project order, and every module’s variables exist before the first of it runs (see DIM): the code outside procedures of a module before another can use the other’s Public arrays and records, and their DIMs leave what it stored.
A form’s SUBs and FUNCTIONs are its own, as in Visual Basic: two forms (and a module) can each have a procedure of the same name, event handlers such as Command1_Click too, and in a form’s code the name means the form’s own procedure. A SUB or FUNCTION of a form’s code called by its name alone from another form’s code or a module runs for its own form, with that form’s variables, controls, and Me, as in Visual Basic; by its name alone it is found when only one form has a Public procedure of that name (when several have, the compiler asks for the form’s name: Form2.Refill), and a PRIVATE one is never found outside its form. A SUB or FUNCTION can be called before its definition, and a TYPE, ENUM (with its members), or class — with its member variables and procedures — can be used before it is declared: the compiler reads every declaration first. A name after a dot is a member of the object before it: when that object’s class is known (see Objects and Class Modules) the member is looked up in the class when the program is compiled, else when it runs.
PUBLIC / PRIVATE
At module level, PUBLIC and PRIVATE can be used in place of DIM, as in Visual Basic. PUBLIC declares a variable that every file of the program and every SUB and FUNCTION can use; PRIVATE declares one that only its own module’s code and procedures see (the same as DIM; see Variable Scope and SHARED). GLOBAL, Visual Basic 3’s word, is PUBLIC at a module’s level (Global Count As Integer, Global Const LIMIT = 9); it is not allowed in a form’s or a class’s code, and is no reserved word (global = 1 is an assignment).
Public highScore As Long ' every file sees it, its SUBs and FUNCTIONs too
Global lives As Integer ' the same as Public lives As Integer
Dim level As Integer ' this module's code and its SUBs and FUNCTIONs
Private tries As Integer ' same as Dim tries As Integer
In a form’s code, a PUBLIC variable is also a member of the form, which other code uses as FormName.variable (Form2.Count), and the form’s DIM and PRIVATE variables are its own (see Several Copies of a Form in the Form topic).
PUBLIC and PRIVATE may also be written in front of SUB, FUNCTION, and PROPERTY. A procedure is Public unless it is marked Private. In a module PRIVATE keeps a procedure to the module’s own code, as in Visual Basic: other files cannot call it, by its name alone or as ModuleName.Proc, and another module can have a procedure of the same name (each with its own STATIC variables). A DECLARE SUB or DECLARE FUNCTION in the module names the module’s own. In a form’s code PRIVATE keeps a SUB or FUNCTION to the form’s own code: other code cannot call it, by its name alone or as FormName.Proc. In a class module they decide what code outside the class can use; see Objects and Class Modules. Inside a procedure, use DIM.
REDIM
Reallocates a dynamic array, optionally preserving existing data. The array may have been declared with DIM name() (or with bounds that are not constant), created by an earlier REDIM, or not declared at all (REDIM then declares a dynamic array). A fixed-size array (declared with constant bounds) keeps its bounds, as in Visual Basic: REDIM of it does not compile ("Array already dimensioned"), and through an array parameter given one REDIM raises error 10.
REDIM array(newBounds) AS type
REDIM PRESERVE array(newBounds) AS type
REDIM SHARED array(newBounds) AS type
A REDIM at module level declares the array, which every SUB and FUNCTION of the file then sees, as a DIM’s; REDIM SHARED (module level only) is the same. AS STRING * n makes the elements STRING * n, and a later REDIM without AS keeps that length.
REDIM PRESERVE keeps every element whose subscripts are in both the old and the new bounds, whichever dimension’s bounds change. It cannot change how many dimensions an array with bounds has: that raises error 9 (Subscript out of range), as in Visual Basic. An array without bounds yet (DIM name(), or one ERASE freed) takes any.
The array may also be a Public array member of an object or a form: ReDim acct.Rates(12), ReDim Preserve Form2.Names(n), ReDim .Rates(4) inside WITH. The member keeps the element type it is declared with: AS may be left out, and must repeat that type when given. Through a variable As Object or As Form the compiler takes the type from the program’s declarations — every class and form with a Public member of that name must declare it an array of the same type — or, when no class or form declares such an array, from AS (the member must then be a variable when the program runs, error 450 otherwise). While an element of the array is passed by reference or a WITH block holds it, REDIM raises error 10, as for any array. A member declared with bounds is fixed-size: REDIM of it does not compile.
ReDim items(newSize) As String
ReDim Preserve scores(1 To newCount) As Integer
ReDim acct.Rates(12)
CONST
Declares a named constant. The value is worked out once, when the program is compiled, and can never change — you cannot assign a new value to a constant or pass it by reference. Several constants can be declared in one CONST statement, separated by commas.
CONST name = expression
CONST name AS type = expression
CONST name = expression, name = expression, ...
Const MAX_SIZE = 100
Const PI = 3.14159265
Const APP_NAME = "DVX App"
Const DEBUG_MODE = True
Const HEADER As String = "=== Report ==="
Const LAUNCH = #7/20/1969 8:17 PM#
Const LAST_INDEX = MAX_SIZE - 1, HALF = MAX_SIZE \ 2
Const TITLE = APP_NAME & " " & "1.0"
Const CRLF = Chr$(13) & Chr$(10)
Const TEAL = RGB(0, 128, 128)
Const BIG = MAX_SIZE > 50
The value can be any expression built from:
-
literals (numbers, strings, True and False, #date# literals);
-
constants declared earlier, including ENUM members (Member or EnumName.Member);
-
the arithmetic operators + - * / \ MOD ^, the comparison operators, AND OR NOT XOR EQV IMP, and string joining with & or +;
-
these built-in functions: ABS, ASC, ATN, CBOOL, CDATE, CDBL, CHOOSE, CHR$, CINT, CLNG, COS, CSNG, CSTR, DATEADD, DATEDIFF, DATEPART, DATESERIAL, DATEVALUE, DAY, EXP, FIX, FORMAT$, FORMATCURRENCY, FORMATDATETIME, FORMATNUMBER, FORMATPERCENT, GETBLUE, GETGREEN, GETRED, HEX$, HOUR, IIF, INSTR, INSTRREV, INT, ISDATE, LCASE$, LEFT$, LEN, LOG, LTRIM$, MID$, MINUTE, MONTH, MONTHNAME, OCT$, REPLACE$, RGB, RIGHT$, ROUND, RTRIM$, SECOND, SGN, SIN, SPACE$, SQR, STR$, STRCOMP, STRING$, STRREVERSE$, TAN, TIMESERIAL, TIMEVALUE, TRIM$, UCASE$, VAL, WEEKDAY, WEEKDAYNAME, and YEAR.
Anything else — a variable, a FUNCTION of your own, or a built-in whose answer can change from run to run such as TIMER, NOW, RND, or DIR$ — is a compile error ("Constant expression required"). An expression that fails, such as a division by zero or a result too big for its type, is also reported when the program is compiled. Text comparisons in a constant follow the OPTION COMPARE setting in effect where the constant is declared. A string constant can be at most 255 characters long.
Without an AS clause the constant takes the type of its value: a whole number makes a Long constant, a number with a fraction a Double constant, and strings, Booleans, and dates keep their type. With an AS clause the value is converted to that type: Integer and Long values are rounded and must fit the type, and a string for a numeric type (or a number for String) is a compile error.
Constants declared at module level are visible to all procedures. A CONST declared inside a SUB or FUNCTION is local to that procedure; it may reuse the name of a module constant without changing it.
PUBLIC CONST and PRIVATE CONST work as in Visual Basic. A Private constant, and any constant of a form or class module, belongs to the file it is declared in: another module, form, or class of the project can declare its own constant of the same name, and does not see this one. A Public constant, or a plain CONST in a module, is seen by the whole program. A class module or form cannot have a Public constant ("Constants are not allowed as Public members of a class module or form").
Public Const APP_VERSION = "2.1" ' every file of the project
Private Const BUFFER_SIZE = 512 ' this file only
TYPE...END TYPE
Defines a user-defined type (record/structure).
TYPE TypeName
fieldName AS type
fieldName AS STRING * n
...
END TYPE
Type PersonType
firstName As String
lastName As String * 20
age As Integer
End Type
Dim p As PersonType
p.firstName = "Scott"
p.age = 30
UDT fields can themselves be UDTs (nested types), and field access chains through array elements too: shapes(i).origin.x = 5. A Public TYPE variable of a class or a form has its fields through the object as well: acct.origin.x, Form2.shapes(2).origin.y (see Using Objects). A new instance starts with numeric fields at 0, Boolean fields False, variable strings empty, and STRING * n fields padded to n spaces. TYPE variables can be written to and read from RANDOM and BINARY files with PUT and GET (see GET / PUT).
ENUM...END ENUM
Defines a set of named whole-number constants, and a type name for variables that hold one of them.
ENUM EnumName
member
member = expression
...
END ENUM
Enum Direction
North ' 0
East ' 1
South = 10
West ' 11
End Enum
Enum Style
Bold = 1
Italic = Bold * 2
Underline = Style.Italic * 2
AllStyles = Bold Or Italic Or Underline
End Enum
Dim heading As Direction
heading = West
If heading = Direction.West Then Print "Going west"
The first member is 0 and each member without a value is one more than the member before it. A value may be any constant expression (see CONST), including members declared earlier in the same ENUM or in another one. Members are Long constants and can be used on their own (West) or with the ENUM name in front (Direction.West). If two ENUMs have a member with the same name, that name must be written with its ENUM name.
The ENUM name can be used as a type wherever a type is allowed: DIM, parameters, FUNCTION results, and TYPE fields. Such a variable is a Long, so it can hold any whole number, not only the members. ENUMs are declared at module level (not inside a SUB or FUNCTION) and are visible everywhere in the program, the code before the ENUM too (a member whose value needs a constant declared after the ENUM only from the ENUM on; see Module Names). PRIVATE ENUM keeps the ENUM and its members to the file it is declared in, like PRIVATE CONST; PUBLIC ENUM (the same as a plain ENUM) is seen everywhere. Members are constants: Direction.West = 3 is a compile error ("Cannot assign to a constant").
DECLARE
Forward-declares a SUB or FUNCTION. This is rarely required because the compiler supports forward references within a module, but it is still accepted for compatibility:
DECLARE SUB name ([BYVAL] [OPTIONAL] param AS type, ...)
DECLARE FUNCTION name ([BYVAL] [OPTIONAL] param AS type, ...) AS returnType
A DECLARE must match the SUB or FUNCTION it declares: the same parameter types, BYVAL and OPTIONAL flags, and return type.
DECLARE LIBRARY
Declares external functions from a native library bundled with DVX. This is how BASIC programs reach operating-system services, serial ports, databases, and other native facilities. Rather than writing DECLARE LIBRARY blocks yourself, add one of the shipped include files (such as commdlg.bas or sql.bas) to your project; the include file contains the proper declarations.
DECLARE LIBRARY "libraryName"
DECLARE SUB name ([BYVAL] param AS type, ...)
DECLARE FUNCTION name ([BYVAL] param AS type, ...) AS returnType
END DECLARE
Declare Library "basrt"
Declare Function SQLOpen(ByVal path As String) As Long
Declare Sub SQLClose(ByVal db As Long)
End Declare
Arguments are always passed by value. Each argument is converted to the type its parameter is declared with before the call, so a Double passed to a Long parameter arrives as a whole number and a Single parameter receives a Single. Declare Integer only for native values that fit in 16 bits; use Long for 32-bit values, or large results are cut down to 16 bits. A Byte parameter or result is 8 bits. A Currency parameter receives the amount as a 64-bit whole number of ten-thousandths; a DECLARE FUNCTION cannot return a Currency.
A String parameter or result declared AS STRING is text: it ends at the first CHR$(0). To pass or receive any bytes, CHR$(0) included (network data, sound samples, encrypted data, checksums of binary data), the declaration says BINARY STRING instead. To the program it is an ordinary String; LEN, MID$, ASC, and the other string functions see every byte. BINARY STRING is allowed only in a DECLARE LIBRARY block, and the shipped include files already use it where a function works with bytes.
Declare Library "mylib"
Declare Function MyChecksum(ByVal bytes As Binary String) As Long
Declare Function MyRead$(ByVal handle As Long, _
ByVal maxLen As Long) As Binary String
End Declare
packet$ = "A" + Chr$(0) + "B"
Print MyChecksum(packet$)
See also: BASIC Runtime Libraries (Section 1.17).
STATIC
Declares a local variable that retains its value between calls.
STATIC variable AS type
Sub Counter()
Static count As Integer
count = count + 1
Print count
End Sub
Several variables can be declared in one STATIC statement, separated by commas, each with its own AS clause; STRING * n works as in DIM. Arrays and TYPE variables can be STATIC too and keep their contents between calls: a fixed-size array (Static hits(1 To 10) As Long) or a dynamic one sized later with REDIM (Static names() As String). In a class module each object has its own copy of a procedure’s STATIC variables, arrays, and TYPE variables, as in Visual Basic: two objects counting calls count separately. A STATIC AS NEW object or WithEvents variable is not supported (a compile error); use a module-level or member variable for those.
Sub Remember(ByVal word As String)
Static seen(1 To 3) As String
Static count As Integer
count = count + 1
seen((count - 1) Mod 3 + 1) = word
Print seen(1); " "; seen(2); " "; seen(3)
End Sub
Writing STATIC after a SUB or FUNCTION header makes every local variable of the procedure static, the ones declared with DIM and the ones used without a declaration (QBasic and Visual Basic):
Sub Tally(points As Integer) Static
total = total + points ' keeps its value between calls
Dim calls As Integer ' a STATIC variable too
calls = calls + 1
Print calls; total
End Sub
OPTION
Sets compiler options. Must appear before any executable code.
OPTION BASE 0 ' Arrays start at index 0 (default)
OPTION BASE 1 ' Arrays start at index 1
OPTION COMPARE BINARY ' Case-sensitive string comparisons (default)
OPTION COMPARE TEXT ' Case-insensitive string comparisons
OPTION EXPLICIT ' All variables must be declared with DIM
As in Visual Basic, OPTION BASE, OPTION COMPARE, OPTION EXPLICIT, and the DEFtype statements hold in the file they are written in (a module, a form, a class, or a UserControl) and nowhere else: OPTION BASE 1 at the top of one module leaves the arrays of the other files numbered from 0. The OPTION EXPLICIT setting in the IDE’s Project Properties works as an OPTION EXPLICIT at the top of every file.
OPTION COMPARE decides how the code of its own file compares text, when the program runs as in constant expressions: the comparison operators, SELECT CASE, Like, INSTR, and the compare argument vbUseCompareOption (or none) of INSTR, INSTRREV, STRCOMP, REPLACE$, SPLIT, and FILTER. A SUB, FUNCTION, or Property compares as its own file’s OPTION COMPARE says whatever code calls it, a form’s or class’s code too, and a module’s code outside procedures compares as its own file says; code that follows the statement in its file is what it holds for, so write it at the top of the file.
DEFtype Statements
Set the default type for variables based on their first letter. A DEFtype statement holds in its own file only (see OPTION).
DEFINT letterRange
DEFLNG letterRange
DEFSNG letterRange
DEFDBL letterRange
DEFSTR letterRange
DEFBYTE letterRange
DEFCUR letterRange
DefInt I-N ' Variables starting with I through N default to Integer
DefStr S ' Variables starting with S default to String
Assignment
Assigns a value to a variable, array element, or UDT field.
variable = expression
array(index) = expression
udt.field = expression
LET variable = expression
The LET keyword is optional and supported for compatibility.
Assigning a whole TYPE value to a TYPE variable, array element, or field copies the value’s fields into the record that is already there, as in Visual Basic: the two stay separate records (changing one later does not change the other), and a SUB that was passed one of the target’s fields by reference sees the new value. A record of another TYPE (one a Variant holds) raises error 13 (Type mismatch).
SWAP
Exchanges the values of two variables, array elements, TYPE fields, or Public member variables of objects or forms (Swap acct.Rates(1), acct.Rates(2)). The two operands should be the same type. SWAP works out both targets first (their subscripts and objects), then makes each value what the other target takes — converted to its type as an assignment converts, cut or padded to a STRING * n’s length, an object checked against the class the target is declared As (as SET checks it) — before it stores either. So a value one of them cannot take raises its error and neither target changes: text that is not a number for a numeric target (error 13), an object of another class found when the program runs (error 13), or an array for a fixed-size one (error 10). When the compiler knows two objects can never fit (Swap a, b with a As ClassA and b As ClassB) the program does not compile ("Type mismatch: SWAP needs ClassA here, got ClassB"). Two records of the same TYPE exchange their fields where they are, as in QBasic: a procedure that was passed a field of one by reference sees the field’s new value. A member that is no variable (a property) raises error 450.
SWAP variable1, variable2
SWAP array(index), variable
Swap a, b
Swap names(i), names(j)
LSET / RSET
Stores a string into a string variable without changing the variable’s length: LSET places the value at the left and RSET at the right, filling the rest with spaces. A value longer than the variable is cut off at the right.
LSET variable = expression
RSET variable = expression
Dim field As String
field = Space$(8)
LSet field = "Name" ' "Name "
RSet field = "42" ' " 42"
The target may be an array element, a TYPE field, or a Public member variable of an object or a form (LSet acct.Code = "AB"). It must hold a string; any other value raises error 13 (Type mismatch).
LSET also copies a whole record, as in Visual Basic: when the target is a TYPE record (a variable, an element, a field, or a member), the value must be another record — a TYPE variable, an element, a FUNCTION’s result (LSet rec = MakeRecord()), or a Variant or member that holds one when the program runs (error 13 when it does not; a value the compiler knows is no record does not compile) — and its bytes — laid out as PUT writes the record to a file — are copied into the target, even when the two are of different TYPEs. When the source is shorter the rest of the target is filled with spaces; when it is longer the extra bytes are dropped. This is meant for records of numbers and fixed-length strings (STRING * n), as used with random-access files; a variable-length string field does not copy meaningfully between different TYPEs. RSET cannot copy records.
Type Header
kind As String * 2
size As Integer
End Type
Type Raw
bytes As String * 4
End Type
Dim h As Header, r As Raw
r.bytes = "AB" + Chr$(10) + Chr$(0)
LSet h = r ' h.kind = "AB", h.size = 10
Statements That Write a Variable
INPUT, LINE INPUT, INPUT #, LINE INPUT #, READ, GET #, SWAP, LSET, RSET, and MID$ assignment store into the variables they are given. Each of those can be a variable, an array element (of an array a Variant holds too, v(2), which takes the type the array gives its elements), a field of a TYPE record (p.x, pts(2).y, or .x in a WITH block), or a member variable of an object or a form: a Public variable of a class’s or a form’s code (acct.Owner, Form2.Count, Me.Count), an element of a Public array (acct.Rates(1)), or a field of a Public TYPE variable (acct.Pos.X). The value is stored as an assignment to the member would store it: converted to the member’s type, and cut or padded with spaces to n characters for a STRING * n member. The object and the subscripts are worked out once, before the statement reads or stores anything.
Dim acct As New Account
Input "Owner"; acct.Owner
Read acct.Rates(1), acct.Rates(2)
Swap acct.Rates(1), acct.Rates(2)
Mid$(acct.Owner, 1, 3) = "Bob"
LSet Form2.Code = "AB"
Get #1, , acct.Pos
A property (a Property procedure, or a property of a form or control such as Form2.Caption or Text1.Text) and a SUB or FUNCTION are not variables: such a statement does not compile ("Variable required: 'Caption' is not a variable"). Read into a variable and assign that instead. Through a variable As Object, As Form, or As Control, whose members are found only when the program runs, a member that is not a variable raises error 450 when the statement runs.
SET
Stores an object reference — a form, a control, an instance of a class module, a Collection, or Nothing — in a variable, array element, TYPE field, or property. After SET both names refer to the same object; nothing is copied.
SET variable = objectExpression
SET variable = NEW ClassName
SET variable = NEW FormName
SET variable = Nothing
SET FormName = formObject
SET FormName = Nothing
Dim frm As Form
Set frm = CreateForm("MyForm", 320, 240)
frm.Caption = "Built in code"
Dim c As Control
Set c = Text1 ' a control on the form
c.Text = "Hello"
Dim list As Collection
Set list = New Collection ' a new, empty Collection
Set list = Nothing ' let it go
Dim w As Form1
Set w = New Form1 ' a second Form1 window
w.Show
The value must be an object or Nothing; anything else raises error 424 (Object required). SET is not used for ordinary numeric or string assignment.
SET FormName = ..., with the name of one of the program’s forms, sets the variable that name is, as Visual Basic’s predeclared form variable: SET Form1 = f makes Form1 mean the form f refers to from then on, which must be a Form1 (a copy NEW made, or the form the name let go; another form raises error 13), and SET Form1 = NEW Form1 gives the name a fresh copy. SET Form1 = Nothing lets go of the form the name held: a variable that still refers to it keeps it, with its form-level variables; one still loaded stays loaded, under no name; and once nothing refers to it and it is not loaded, its Terminate event runs (Form1_Terminate) and its variables are freed. The name’s next use then makes a new Form1, with its variables at their starting values, as in Visual Basic. A form’s name takes a form only with SET: Form1 = x without SET does not compile ("'Form1' is a form: assign a form to it with SET").
ERASE
Frees the memory of a dynamic array (declared with DIM name() or with bounds that are not constant, or created by REDIM) and leaves it without bounds, as DIM name() declares one: its bounds and elements raise error 9 until a REDIM gives it new bounds. A fixed-size array (declared with constant bounds) keeps its bounds and has every element reset to zero, an empty string (n spaces for STRING * n), False, or a fresh TYPE instance. ERASE of an array parameter erases the caller’s array as its kind says, as in Visual Basic: a fixed-size one is reset, a dynamic one freed.
ERASE arrayName
ERASE array1, array2, ...
One ERASE can name several arrays, separated by commas. An array can be a Public array member of an object or a form (Erase acct.Rates, Erase Form2.Names), erased as its declaration says (a fixed one keeps its bounds); through a variable As Object or As Form every class and form with a Public member of that name must declare it an array of the same kind, else the program does not compile.
1.4.3. Conditional Statements
IF...THEN...ELSE...END IF
Multi-line form
IF condition THEN
statements
ELSEIF condition THEN
statements
ELSE
statements
END IF
If x > 10 Then
Print "Large"
ElseIf x > 5 Then
Print "Medium"
Else
Print "Small"
End If
If ready Then Print "Go!"
The condition is a number (any value but 0 is true) or a Boolean, as in Visual Basic; text is true or false as CBOOL reads it ("True", "False", or a number: If "1" Then is true), and other text raises error 13 (Type mismatch). Null and Empty are false.
SELECT CASE
Multi-way branch based on an expression value.
SELECT CASE expression
CASE value
statements
CASE value1, value2
statements
CASE low TO high
statements
CASE IS operator value
statements
CASE ELSE
statements
END SELECT
Select Case grade
Case 90 To 100
Print "A"
Case 80 To 89
Print "B"
Case Is >= 70
Print "C"
Case 60, 65
Print "D (borderline)"
Case Else
Print "F"
End Select
CASE items can be combined with commas. The IS keyword allows comparison operators: <, >, <=, >=, =, <>.
1.4.4. Loop Statements
FOR...NEXT
FOR variable = start TO limit [STEP step]
statements
NEXT [variable]
For i = 1 To 10
Print i
Next i
For x = 10 To 0 Step -2
Print x
Next
The variable name after NEXT is optional. Use EXIT FOR to break out early.
With an Integer or Long counter a constant STEP must be a whole number (STEP 0.5 is a compile error); a STEP computed at run time is rounded to the counter’s type. A Single or Double counter takes any step.
FOR EACH...NEXT
Runs the loop once for every item in a Collection or every element of an array, without counting.
FOR EACH item IN group
statements
NEXT [item]
Dim names As New Collection
names.Add "Ann"
names.Add "Bob"
Dim person As Variant
For Each person In names
Print "Hello, "; person
Next person
Dim scores(1 To 3) As Integer
Dim s As Variant
For Each s In scores
total = total + s
Next
group can be a Collection, an array (of any number of dimensions; elements are visited in the order Visual Basic keeps them, the first subscript changing fastest: a(0, 0), a(1, 0), a(0, 1), ...), a Variant holding an array, or a ParamArray. On each pass item receives a copy of the next item: for a Collection of objects it refers to the object itself, but assigning a new value to item does not change the array or Collection. Declare item AS VARIANT, or as an object type for a Collection of objects.
The loop walks the array itself, not a copy, as in Visual Basic: an element changed inside the loop (scores(3) = 0) is seen when the loop reaches it. While the loop runs, the array is locked: REDIM of it, ERASE of it when it is a dynamic array, and assigning anything to the variable that holds it (scores = other, or v = 5 for a Variant that holds it) raise error 10 (This array is fixed or temporarily locked), and the array stays as it was (ERASE of a fixed-size array only clears its elements). The array is free again as soon as the loop is left, however it is left: at its end, by EXIT FOR, by a GOTO, EXIT SUB, or RESUME to a place outside it, by RETURN from the GOSUB subroutine the loop is in, or when an error ends the procedure. A GOSUB made from inside the loop, and an error handler that goes back into the loop with RESUME or RESUME NEXT, keep it locked. For a Collection the number of items is checked on every pass, so items added or removed inside the loop are taken into account.
EXIT FOR leaves the loop early. Looping over something that is not an array or Collection raises error 13 (Type mismatch), error 451 (Object not a collection) for an object that is not a Collection, and error 92 (For loop not initialized) for a dynamic array without bounds (see DIM), as in Visual Basic. EACH and IN are not reserved words.
DO...LOOP
General-purpose loop with pre-test, post-test, or infinite forms.
DO [WHILE condition | UNTIL condition]
statements
LOOP [WHILE condition | UNTIL condition]
' Pre-test
Do While count < 10
count = count + 1
Loop
' Post-test
Do
line$ = ReadLine()
Loop Until line$ = "quit"
' Infinite loop (exit with EXIT DO)
Do
DoEvents
If done Then Exit Do
Loop
1.4.5. Procedures
SUB...END SUB
SUB name ([BYVAL | BYREF] [OPTIONAL] param AS type, ...) [STATIC]
SUB name (arrayParam() AS type, ...)
statements
END SUB
Sub Greet(ByVal name As String)
Print "Hello, " & name
End Sub
A SUB, FUNCTION, or Property procedure stands on its own in the program: defining one inside another procedure, or inside an IF, FOR, DO, WHILE, SELECT CASE, or WITH block, is a compile error.
Parameters are passed by reference by default (nested calls pass the same variable on, so a SUB called from a SUB can still change the original); BYREF may be written out to say so, and BYVAL selects value semantics. A by-reference parameter is the caller’s variable itself, as in Visual Basic: a write to it changes the variable at once (the caller’s code, or another parameter naming the same variable, sees the new value straight away, even if the procedure later stops with an error), and what is stored is converted to the variable’s own type (a STRING * n keeps its length). This holds for a plain variable, an array element (`bump a(3)` changes `a(3)` in place), a TYPE field (`bump rec.count`, `bump recs(2).count`, `bump rec.inner.count`), inside a class one of the class’s own member variables, and a Public variable of an object — a class’s or a form’s — with its elements and fields (`bump acct.count`, `bump Form2.Count`, `bump acct.totals(2)`, `bump acct.origin.x`, and Me.count in the object’s own code). The object stays alive while the call has one of its variables, even when the program lets go of it meanwhile, and a form keeps the variable if it loads or unloads during the call. While an array element (or a field of one) is passed by reference, its array cannot be given a new size, erased, or replaced: REDIM of that array, ERASE of it when it is a dynamic array, and assigning another array to it (a = b, a = Split(s), a = MakeList(), or any value to a Variant that holds it) raise error 10 (This array is fixed or temporarily locked), as in Visual Basic, and the array stays as it was (ERASE of a fixed-size array only clears its elements and is allowed). The array is free again as soon as the call returns. Assigning a whole TYPE value to the variable (or element) whose field is being passed copies the value into the same record, so the parameter sees the new value (as in Visual Basic). A parameter written as name() receives a whole array by reference; the caller passes `arr()` (or just `arr`), and the SUB may index it, ERASE it, REDIM it, or assign another array to it — unless the caller’s array is a fixed-size one (declared with constant bounds), which keeps its bounds, as in Visual Basic: REDIM and the assignment raise error 10, and ERASE resets its elements. Use EXIT SUB to return early. A SUB is called either with or without parentheses; when used as a statement, parentheses are optional:
Greet "World"
Greet("World")
Call Greet("World")
As in Visual Basic and QBasic, a single argument in parentheses after the name of a SUB called without CALL (Bump (n), or Bump(n)) is an expression in parentheses, so it is passed by value: the SUB gets a copy and n is not changed. Write Bump n, or Call Bump(n), to pass n by reference.
An argument is converted to the type of a typed parameter (one declared with AS, a type suffix, or a DEFtype rule). A value — a literal, an expression, a variable in its own parentheses, or anything given to a BYVAL parameter — is converted the way an assignment would convert it (Report 3.7 gives an Integer parameter 4). A variable, array element, or TYPE field given to a by-reference parameter must have the parameter’s own type, as in Visual Basic: an Integer parameter cannot be the caller’s Double variable ("ByRef argument type mismatch" when the program is compiled); pass CINT(d), or (d) in its own parentheses, to pass a converted copy. A variable declared without a type (a Variant) holds any value and is passed as it is. Through an object variable declared As Object the procedure is only found when the program runs, so a variable of another type is passed as a converted copy instead. A member variable is passed as a variable is: one of another type than the parameter is a compile error when the compiler knows the object’s class (or the form, by its name), and is passed as a converted copy through an object variable declared As Object or As Variant, whose members are found when the program runs; a member that is no variable (a property, or a FUNCTION’s result) is passed as its value, converted.
Sub Fill(v() As Integer, ByRef count As Integer)
ReDim v(9) As Integer
v(9) = 7
count = count + 1
End Sub
Dim a(3) As Integer
Dim n As Integer
Fill a(), n
Optional Parameters
Mark a parameter OPTIONAL to allow callers to omit it. An optional parameter must be positioned after all required parameters. A caller can leave out the optional parameters at the end, or any optional parameter in the middle by writing nothing between the commas: Report a, , c. A left-out parameter of a type receives that type’s empty value (0, "", False, a date of 0, Nothing); a left-out Variant parameter is Missing, which ISMISSING detects. Leaving out a parameter that is not OPTIONAL is a compile error (Argument not optional).
Sub Announce(ByVal msg As String, Optional ByVal loud As Integer)
If loud Then
Print UCase$(msg)
Else
Print msg
End If
End Sub
Announce "hello" ' loud defaults to 0
Announce "hello", True ' loud is -1
An OPTIONAL parameter can also name the value it takes when it is left out, after an equals sign: Optional count As Integer = 10. The default is a constant expression, like the value of a CONST: numbers, strings, dates, other constants, and the built-in functions CONST allows, converted to the parameter’s type (a value that does not fit is a compile error). A parameter with a default is never Missing — ISMISSING is False for it — whether it is left out at the end, skipped between commas, or the procedure is reached through an object. Defaults work for SUB and FUNCTION procedures and for the procedures and Property procedures of class modules, including calls written before the procedure itself. As in Visual Basic the default is the one the declaration being called gives: a call through an interface (a variable declared As the interface class) passes the interface’s default, even when the implementing class declares another. An object parameter (As Object, As Control, As Form, or As a class) can only have the default Nothing, as in Visual Basic: Optional target As Object = Nothing; a Variant parameter may have Nothing too. A default cannot be given to a required parameter, an array, or a TYPE, or in DEF FN and DECLARE LIBRARY. A DECLARE SUB / FUNCTION line must say whether each parameter has a default, as its definition does.
Const SIDE = 10
Function Area(Optional w As Integer = SIDE, Optional h As Integer = SIDE * 2) As Long
Area = w * h
End Function
Print Area() ' 200
Print Area(2) ' 40
Print Area(, 3) ' 30
ISMISSING works as in Visual Basic: only an OPTIONAL Variant parameter without a default can be Missing, and a Missing value passed on to another procedure’s OPTIONAL Variant parameter is still Missing there. ISMISSING of anything else is False. Using a Missing value in any other way — in arithmetic, in text, or storing it in a typed variable — raises error 448.
Sub Greet(ByVal name As String, Optional title As Variant)
If IsMissing(title) Then
Print "Hello, "; name
Else
Print "Hello, "; title; " "; name
End If
End Sub
Greet "Ada" ' Hello, Ada
Greet "Ada", "Countess" ' Hello, Countess Ada
Named Arguments
An argument can be given by the name of its parameter, followed by := and the value, as in Visual Basic. Named arguments come after any positional ones, in any order; the parameters left out must be OPTIONAL.
Sub Report(ByVal title As String, Optional ByVal width As Integer = 40, _
Optional ByVal footer As String = "")
Print title; width; footer
End Sub
Report "Sales", footer:="(end)" ' width is 40
Report width:=60, title:="Stock"
Print Mid$(String:="hello", Start:=2) ' ello
MsgBox Prompt:="Saved", Title:="Notes"
Named arguments work for SUB and FUNCTION procedures, DEF FN functions, DECLARE LIBRARY procedures, and the procedures of class modules (through a variable of the class, or through an Object or Variant variable), and for the built-in functions that Visual Basic gives argument names to: MsgBox (Prompt, Buttons, Title), InputBox (Prompt, Title, Default), Mid (String, Start, Length), Left and Right (String, Length), InStr (Start, String1, String2), InStrRev (StringCheck, StringMatch, Start, Compare), Replace (Expression, Find, Replace, Start, Count, Compare), Split (Expression, Delimiter, Limit, Compare), Join (SourceArray, Delimiter), Filter (SourceArray, Match, Include, Compare), StrComp (String1, String2, Compare), String (Number, Character), Format (Expression, Format, FirstDayOfWeek, FirstWeekOfYear), FormatNumber, FormatCurrency, and FormatPercent (Expression, NumDigitsAfterDecimal, IncludeLeadingDigit, UseParensForNegativeNumbers, GroupDigits), FormatDateTime (Expression, NamedFormat), IIf (Expression, TruePart, FalsePart), DateAdd (Interval, Number, Date), DateDiff and DatePart (Interval, Date1 and Date2 or Date, FirstDayOfWeek, FirstWeekOfYear), DateSerial (Year, Month, Day), TimeSerial (Hour, Minute, Second), Weekday (Date, FirstDayOfWeek), WeekdayName (Weekday, Abbreviate, FirstDayOfWeek), MonthName (Month, Abbreviate), and a Collection’s Add (Item, Key, Before, After), Item, and Remove (Index).
A name the procedure does not have is a compile error (Named argument not found), and so is a parameter given twice. When the procedure is only found as the program runs (a method called through an Object or Variant variable) the same mistakes raise error 448 (Named argument not found) and error 450 (Wrong number of arguments). The methods of forms and controls do not take named arguments (error 446, Object doesn’t support named arguments), and neither does a ParamArray parameter.
ParamArray
The last parameter of a SUB or FUNCTION can be marked PARAMARRAY to accept any number of extra arguments. It is written as an array, name(), and receives every remaining argument as an array numbered from 0. With no extra arguments the array is empty: UBOUND returns -1.
Sub PrintAll(ByVal title As String, ParamArray items())
Dim i As Integer
Print title;
For i = 0 To UBound(items)
Print " "; items(i);
Next
Print
End Sub
PrintAll "Totals:", 1, "two", 3.5 ' three items: 0 To 2
PrintAll "Nothing:" ' UBound(items) is -1
Function Sum(ParamArray n() As Double) As Double
Dim i As Integer
Dim total As Double
For i = 0 To UBound(n)
total = total + n(i)
Next
Sum = total
End Function
Without an AS clause (and no type suffix or DEFtype rule for the name) the ParamArray is an array of Variants (TYPENAME gives "Variant()"): each element holds the argument that was passed with its own type, so numbers, strings, and objects can be mixed, and FOR EACH can walk it. With an AS clause every argument is converted to that type. An argument that is a variable, a whole array, an array element (a(i), m(i, j)), a TYPE field (rec.f, arr(i).f, rec.inner.f), inside a class one of the class’s own member variables, or a Public variable of an object (acct.count, Form2.Count, and their elements and fields) is passed by reference, as in Visual Basic: the element of the ParamArray is that variable, so a write to it changes the variable at once, converted to the variable’s type (a value that cannot be converted raises its error at the assignment), and passing the element on (Bump v(0)) passes the variable. With an AS clause an argument is passed by reference only when its own type is that type; others are converted and passed by value. The same holds for a class’s methods, whether the object variable is declared as the class or As Object / As Variant. While the call runs, the arrays whose elements were given are locked: REDIM of one of them, ERASE of a dynamic one, or another array assigned to one raises error 10, as for any array element passed by reference. Copying the ParamArray (keep = v) copies the values, not the variables. Expressions and object properties are passed by value. Leaving an argument out (Sum 1, , 3) gives a Missing element. A PARAMARRAY cannot be combined with OPTIONAL parameters, cannot be BYVAL or BYREF, cannot hold a TYPE, and takes at most 31 arguments. It is not available in DEF FN or DECLARE LIBRARY.
FUNCTION...END FUNCTION
Defines a function with a return value.
FUNCTION name ([BYVAL] [OPTIONAL] param AS type, ...) AS returnType [STATIC]
statements
name = returnValue
END FUNCTION
STATIC after the header keeps every local variable of the SUB or FUNCTION between calls (see STATIC).
Function Square(ByVal n As Double) As Double
Square = n * n
End Function
Assign to the function name to set the return value, with or without its type suffix (in FUNCTION Total%, Total = x sets it; see Type Suffixes). The value is converted to the function’s type (AS clause, type suffix, or DEFtype), so FUNCTION F AS INTEGER with F = 2.5 returns 2. Inside the function its name on its own reads the value set so far (Total = Total + n), as in Visual Basic, and given for a parameter without BYVAL (Bump Total) it is that result itself, which the procedure changes; with an argument list — F() or F(n - 1) — it calls the function again. Use EXIT FUNCTION to return early.
A FUNCTION may return a TYPE record (FUNCTION MakePoint(...) AS PointType). Its result starts as a new record of the TYPE, its fields at their zero values, so a function that never sets it returns that. Inside the function the fields of the result are set and read through its name (MakePoint.x = 5, Bump MakePoint.x passes the field itself), and MakePoint = rec copies a whole record into it. Elsewhere the result is a record: assign it (p = MakePoint(1, 2)), read a field of it (MakePoint(1, 2).x), hold it in a WITH block, or write it to a file with PUT. A store into a field of the result (MakePoint(1, 2).x = 5) does not compile, since the record is a copy that would be lost.
A FUNCTION can also be called as a statement, with or without parentheses; its result is discarded:
Function Beep2(ByVal n As Integer) As Integer
Beep2 = n * 2
End Function
Beep2 3 ' result discarded
name(...) in an expression calls a FUNCTION; using a SUB there is a compile error.
Labels, GOSUB, and Variables in Procedures
Labels belong to the SUB or FUNCTION they are written in (or to the module level). GOTO, GOSUB, ON ... GOTO/GOSUB, and ON ERROR GOTO can only reach a label of the same procedure, and different procedures can reuse the same label name. GOSUB and RETURN work inside a procedure; see GOTO / GOSUB / RETURN. A procedure sees its file’s declared module variables; see Variable Scope and SHARED.
DEF FN
Defines a single-expression function. The function name begins with FN and is invoked just like a normal function. DEF FN functions cannot span multiple statements. A DEF FN must be defined before it is used, and only at module level (not inside a SUB or FUNCTION). Names in the expression other than the parameters are module variables of its file, declared or made by their first use; the parameters are always passed by value.
DEF FNname(params) = expression
Def FnSquare(x) = x * x
Print FnSquare(5) ' prints 25
Def FnCelsius(f As Double) = (f - 32) * 5 / 9
Print FnCelsius(212) ' prints 100
1.4.6. Flow Control
EXIT
EXIT FOR
EXIT DO
EXIT SUB
EXIT FUNCTION
EXIT PROPERTY
EXIT PROPERTY leaves a Property Get, Let, or Set procedure of a class module (see Objects and Class Modules).
CALL
Explicitly calls a subroutine or function. The return value (if any) is discarded.
CALL name
CALL name(args)
CALL object.method
CALL object.method(args)
Normally you can omit CALL and just use the name directly. As in Visual Basic, CALL also takes a method or procedure reached through a name and a dot — Call Me.Refresh, Call obj.Update(x), Call Form2.Refill(n), Call Tools.Reset (a module’s procedure) — with its arguments, if any, in parentheses and passed as the procedure takes them (a variable by reference unless the parameter is BYVAL).
GOTO / GOSUB / RETURN
GOTO label
GOSUB label
RETURN
A label is a name followed by a colon at the start of a line, or a line number at the start of a line (see Line Numbers below). Labels belong to the SUB or FUNCTION they are in (module-level labels to the module level): a jump can only reach a label of the same procedure, the same label name can be used in several procedures, and a label may have the same name as a variable. A jump to a label that is not defined in the procedure, or to a SUB or variable name, is a compile error.
GOSUB records where it was called from, runs the code at the label, and RETURN goes back to the statement after the GOSUB. This works at module level and inside a SUB or FUNCTION alike. Each procedure call has its own set of pending GOSUBs: RETURN only returns from a GOSUB made in the same procedure call, and leaving the procedure (END SUB, EXIT SUB, EXIT FUNCTION, or an error handled in a caller) discards the ones still pending. RETURN with no pending GOSUB raises error 3 (RETURN without GOSUB). To leave a SUB or FUNCTION, use EXIT SUB / EXIT FUNCTION.
GoSub Initialize
Print "Done"
End
Initialize:
count = 0
name$ = ""
Return
Sub Report(n As Integer)
GoSub Heading
Print "value"; n
Exit Sub
Heading:
Print "--- report ---"
Return
End Sub
ON...GOTO / ON...GOSUB
Computed branch based on an integer expression.
ON expression GOTO label1, label2, ...
ON expression GOSUB label1, label2, ...
If the expression evaluates to 1, control goes to the first label; 2, the second; and so on. If out of range, execution falls through. The labels follow the same rules as GOTO and GOSUB (same procedure only).
Line Numbers
As in QBasic, a line can start with a line number, a whole number from 0 to 65529. A line number is a label: GOTO, GOSUB, ON ... GOTO / GOSUB, ON ERROR GOTO, RESUME, and RESTORE can name it, it belongs to its procedure like any other label, and the same number cannot start two lines of a procedure. Numbers need not be in order, lines without a number are fine, and the number is read as a value, so 010 and 10 name the same line. IF can branch to a line number directly: IF x THEN 100 ELSE 200 is IF x THEN GOTO 100 ELSE GOTO 200, and IF x GOTO 100 works too.
10 INPUT "Guess"; g
20 IF g = 7 THEN 50
30 PRINT "No"
40 GOTO 10
50 PRINT "Yes"
In a program with line numbers, ERL gives the number of the last numbered line at or before the statement where the error happened (0 when there is none); in a program without them it gives the source line.
1.4.7. Input/Output Statements
Writes expressions to the output window, or to a file channel. Once the program has used a console or graphics statement (see Console and Graphics), PRINT writes on the program’s screen instead, at the cursor, in the current COLOR. Debug.Print always writes to the output window (see Debug Object).
PRINT [expression [{; | ,} expression] ...]
PRINT #channel, expression [; expression] ...
PRINT USING format$; expression [; expression] ...
-
; between items — no separator: items appear next to each other (a number has its own spaces, below)
-
, between items — advance to the next 14-column tab zone
-
A trailing ; or , suppresses the newline normally written at the end of the statement (PRINT USING and PRINT # too)
-
? is an alias for PRINT
As in Visual Basic and QBasic, a number prints with a space before it, where its sign goes (a minus sign for one below zero), and a space after it: PRINT 1; -2 shows " 1 -2 ". A number between -1 and 1 prints without the 0 before its point, as in Visual Basic and QBasic: PRINT 0.25; -0.5 shows " .25 -.5 ". STR$ and WRITE # write such a number the same way, while CSTR, FORMAT$, and text made from a number with & keep the 0 (CStr(0.25) and "" & 0.25 are "0.25"). True and False, dates, text, and Null print as they are, with no spaces (PRINT True; False shows "TrueFalse"), and Empty prints nothing. PRINT # writes numbers exactly as PRINT shows them, so PRINT #1, 1; 2 writes " 1 2 "; so do LPRINT and the Print method of a form, a PictureBox, and the Printer. PRINT #n, with nothing after the comma writes an empty line. An array or a TYPE record has no text to print: PRINT, PRINT #, and LPRINT of one raise error 13 (Type mismatch), as in Visual Basic; print its elements or fields.
Special functions inside PRINT:
-
SPC(n) — print n spaces
-
TAB(n) — advance to column n (first column is 1); when the cursor is already past column n, a new line is started first
-
TAB alone, without (n) — advance to the next 14-column zone, as a comma does (Visual Basic’s Tab), in every kind of PRINT: PRINT, PRINT #, LPRINT, an object’s Print, and Debug.Print
Print "Name:"; Tab(20); name$
Print "X="; x, "Y="; y ' comma = next 14-column zone
Print #1, "Written to file"
LPRINT
Prints on the printer instead of the screen. Everything PRINT accepts works the same way: ; and , between items, SPC, TAB, and LPRINT USING. The printer keeps its own column for TAB and the 14-column zones.
LPRINT [expression [{; | ,} expression] ...]
LPRINT USING format$; expression [; expression] ...
The output goes to the printer chosen in the Control Panel (a printer port, or a file). Each LPRINT is sent at once, and lines end the way printers expect. Nothing starts a new page by itself: LPRINT CHR$(12) ejects the page. If the printer has a problem (out of paper, off line), the user is asked to fix it and choose Retry, or Cancel; after Cancel the LPRINT raises error 57. With no printer to print on, LPRINT raises error 68.
LPrint "Invoice"; Tab(40); Date$
LPrint Using "Total: $$####.##"; total
LPrint Chr$(12) ' eject the page
For a whole document with margins, a header, a footer, and page numbers, and for the Print dialog, use the Printing Library (print.bas, see Include Libraries).
PRINT USING
PRINT USING formats each following expression according to a format string and prints the result. The expressions after the format are separated by ; or , (both work the same here). The format string is a mix of fields and literal text: each expression consumes the next field, the literal text before it is printed as it is, and the literal text after the last field is printed at the end. If more expressions are supplied than there are fields, the format string is reused from the start. PRINT USING’s format characters are QBasic’s; FORMAT$ uses Visual Basic’s, which differ (see Format Function).
| Format character | Meaning |
|---|---|
# |
Digit position; unused positions on the left become spaces |
0 |
Digit position that is always printed (zero padded); the first 0 sets the minimum number of digits |
. |
Decimal-point position |
, |
Insert thousands separator |
+ |
At start or end: always show a sign character |
- |
At end: show a trailing minus sign only when negative |
** |
At start: fill leading spaces with asterisks |
$$ |
At start: floating dollar sign |
^^^^ |
Anywhere: format the value in scientific notation |
! |
First character of a string only |
& |
Entire string (variable length) |
\ ... \ |
Fixed-length string field (width = 2 + number of spaces between backslashes) |
_ |
The next character is printed literally |
A numeric field is as wide as its format characters; the value is right-aligned in it and a negative sign (or a leading +) floats directly in front of the first digit. A value that does not fit is printed in full with a leading %; a value too long to print in full is shown in scientific notation behind the %. A trailing + in a format with no digit positions is printed as literal text. A string expression must meet a string field and a numeric expression a numeric field, otherwise error 13 (Type mismatch) is raised.
Print Using "###.##"; -3.14159 ' " -3.14"
Print Using "+###"; 42 ' " +42"
Print Using "$$#,##0.00"; 1234.5 ' " $1,234.50"
Print Using "**#,##0.00"; 42.5 ' "*****42.50"
Print Using "###"; 12345 ' "%12345"
Print Using "####.####^^^^"; 0.000123 ' scientific notation
Print Using "\ \"; "Hello" ' fixed-width 4-char: "Hell"
Print Using "& likes &"; name$; food$ ' "Scott likes pizza"
Print Using "Total: ###.## units"; 7.5 ' "Total: 7.50 units"
Print Using "## and ##"; 1; 2; 3 ' " 1 and 2 3 and "
INPUT
Reads a line of text from the user or from a file channel. The user types it in a dialog box, or on the program’s screen once it has one (see Console and Graphics).
INPUT variable
INPUT "prompt"; variable
INPUT #channel, variable
Input "Enter your name: "; name$
Input #1, line$
The target may be a variable, an array element, a TYPE field, or a Public member variable of an object or a form (INPUT, INPUT #, LINE INPUT, LINE INPUT #, and READ alike; see Statements That Write a Variable in Declaration Statements). INPUT reads a number into a numeric target from the start of what was typed, up to a blank (12abc gives 12), and the text as it was typed into a String or a Variant, as LINE INPUT does; INPUT # reads its fields as Visual Basic’s Input # does (see INPUT #). A whole TYPE record, a whole array, or an object variable cannot take what these statements read: the program does not compile ("Type mismatch"), as in Visual Basic; read into the record’s fields or the array’s elements instead. A record member found only when the program runs (through As Object) raises error 13 there.
DATA / READ / RESTORE
Inline data pool for constants.
DATA value1, value2, "string", ...
READ variable1, variable2, ...
RESTORE [label]
DATA statements define a pool of values. READ reads the next value from the pool into a variable, array element, TYPE field, or Public member variable of an object or a form (Read acct.Rate, Form2.Count). RESTORE resets the read pointer to the beginning; RESTORE label (or a line number) makes the next READ take the first DATA item at or after that label. An item in quotes is a string; an unquoted item is taken as raw text up to the next comma, colon, comment, or end of line (so keywords, several words, and text such as 12abc are read as they are written) and converted when READ into a numeric variable, which raises error 13 (Type mismatch) when the item is not a number. The most negative Integer and Long values (-32768, -2147483648) are accepted.
Data 10, 20, 30, "Hello"
Read a, b, c, msg$
Print a; b; c; msg$
Restore
1.4.8. Miscellaneous Statements
Error Handling
ON ERROR GOTO label ' Enable error handler
ON ERROR GOTO 0 ' Disable error handler
ON ERROR RESUME NEXT ' Go on at the next statement after any error
RESUME ' Retry the statement that caused the error
RESUME NEXT ' Continue at the next statement after the error
RESUME label ' Continue at a label or line number (RESUME 0 is RESUME)
ERROR n ' Raise a runtime error with error number n
The ERR keyword returns the current error number (a Long) in expressions and ERL the source line the error was raised on, or in a program with line numbers the last line number at or before it (both are 0 when no error is active, and both reset after RESUME). RESUME or RESUME NEXT executed while no error is active raises error 20 (RESUME without error). ERROR n raises error n with its standard message (ERROR 11 reports "Division by zero"); numbers without a standard message report "User-defined error".
Each SUB and FUNCTION has its own ON ERROR handler:
-
An error is handled by the handler of the procedure it happens in; if that procedure has none, the calling procedures are searched outward.
-
A procedure called from a running handler can trap its own errors with its own handler.
-
Returning from a procedure that merely installed a handler leaves the caller’s ERR and handler alone.
-
An error raised inside a running handler passes to the calling procedure’s handler (untrapped if there is none).
-
The label named by ON ERROR GOTO must be in the same procedure.
An error that no handler traps ends the program, as in Visual Basic, wherever it happens: in module-level code or in an event handler (a Click, a Timer, a form’s Load ...). DVX shows it in a BASIC Runtime Error box — the error number, the line, and the message — and writes it to the DVX log; the program’s windows close once the box is dismissed. In the IDE the Output window shows the error and the editor goes to its line.
ON ERROR RESUME NEXT, as in Visual Basic, needs no handler: a statement that fails is abandoned and the program goes on at the next one, with ERR (Err.Number) and Err.Description telling what went wrong. An error in a procedure that has no handler of its own leaves that procedure, and the program goes on after the statement that called it. The statement clears ERR, and so does the end of the procedure that used it; check ERR right after the statements that may fail:
On Error Resume Next
Kill "old.tmp"
If Err.Number <> 0 Then Print "Not deleted: "; Err.Description
Err.Clear
On Error GoTo 0
The Err Object
Err holds the current error the way ERR and ERROR do:
| Member | Meaning |
|---|---|
Err or Err.Number |
The error number (0 when there is none); Err.Number = n sets it without raising it |
Err.Description |
The error’s message ("" when there is none) |
Err.Source |
Where the error comes from, as in Visual Basic: the source Err.Raise gave, else the program’s project name (the Name in Project Properties; "BASIC App" for a project without one), followed by a dot and the class’s name for an error in a class module’s or a UserControl’s code ("MyApp.Stack"); "" after Err.Clear or Err.Number = n |
Err.Raise number [, source [, desc]] |
Raises error number (1 to 65535, or a class’s own number counted from vbObjectError, below 0) with that source and description; either may be left out (Err.Raise 5, , "Size too small"): without a description the number’s standard message, without a source the project’s as for any error |
Err.Clear |
Clears the error: ERR becomes 0, the description and source "" |
ERROR$(n) (or ERROR(n)) gives the standard message of error number n, "User-defined error" for a number without one, and "" for 0; without an argument, the current error’s message.
On Error GoTo Failed
Err.Raise 1001, "Loader", "The file has no header"
Exit Sub
Failed:
Print Err.Number; Err.Description; " ("; Err.Source; ")"
Resume Next
RESUME NEXT continues after the failing statement; a loop’s NEXT, LOOP, and WEND are statements of their own, so after an error in the last statement of a loop’s body the loop goes on. When the error happened in the condition of an IF, ELSEIF, WHILE, DO, or LOOP, the condition counts as false (the block is skipped, the loop is left); after an error in a FOR statement the loop is skipped; after an error in the SELECT CASE expression the whole SELECT CASE block is skipped; after an error in a CASE test that test counts as false (the next value or CASE is tried); after an error in an ON ... GOTO/GOSUB selector no branch is taken and execution continues with the next statement.
On Error GoTo ErrorHandler
Open "missing.txt" For Input As #1
Exit Sub
ErrorHandler:
Print "Error number:"; Err; "on line"; Erl
Resume Next
Common Error Numbers
- 1
-
FOR loop error (NEXT without FOR, NEXT variable mismatch, FOR stack underflow)
- 3
-
RETURN without GOSUB
- 4
-
Out of DATA
- 5
-
Illegal function call (bad argument to a built-in function, to a control’s or a form’s method, or to a drawing method of a form, PictureBox, or the Printer, such as an index past the list given to AddItem item, index or RemoveItem, an angle past 2 pi, a Scale whose corners are on one line, Drag 9, Screen.Arrange 99, or CreateControl’s parent that is no container of the form; an undefined math result such as a negative number to a fractional power; GET of a Variant whose VarType in the file is none DVX has a value for, or of an array’s bounds that make no array)
- 6
-
Overflow (value does not fit the target type, a number VAL reads with a type-declaration character included — VAL("40000%"); EXP, ^, or other math leaving the numeric range; a file size or position past 2 GB in LOF, FILELEN, LOC, SEEK, GET, or PUT)
- 7
-
Out of memory (also no memory for a control, a picture, a font, or the Printer’s page)
- 9
-
Subscript out of range (an element, LBOUND, or UBOUND of an array outside its bounds, or of a dynamic array without bounds; REDIM PRESERVE to another number of dimensions; Form.Controls(n) of an n outside 0 to Count - 1) / invalid variable or field index
- 10
-
This array is fixed or temporarily locked (REDIM, ERASE of a dynamic array, or another array assigned to it — any value to a Variant that holds it — while one of its elements, or a field of one, is passed by reference to a procedure that is still running, a WITH block holds it, or a FOR EACH loop walks it; REDIM of a fixed-size array, or another array assigned to one, through an array parameter)
- 11
-
Division by zero
- 13
-
Type mismatch (text that is not a number where a number is needed, a type-declaration character a number cannot take given to VAL — VAL("50.5%") —, a numeric or Boolean property of a control, a form, a menu, the Screen, or the Printer and a method’s argument included — "" too, see Numbers in Text; text that is not True, False, or a number where a Boolean is needed: CBOOL, a Boolean variable, IF; an array or a TYPE record where text or a number is needed: PRINT, PRINT #, LPRINT, WRITE #, a form’s, PictureBox’s, or the Printer’s Print, a property, the string functions, and the operators; an object of another class SET where a class is declared, a member variable too, or stored through a parameter or by SWAP; PUT of an object; a TYPE record of another TYPE stored in a record) / not an array / not a TYPE instance
- 14
-
Out of string space (no memory to build a string)
- 18
-
User interrupt occurred (a control’s code ran too long without returning and was stopped)
- 20
-
RESUME without error
- 26
-
FOR loop nesting too deep
- 28
-
Out of stack space (calls or expressions nested too deeply)
- 51
-
Internal error (bad opcode)
- 52
-
Bad file number or file not open
- 53
-
File not found (OPEN for INPUT, KILL, FILECOPY, FILELEN, ...: a file missing from a folder that exists)
- 54
-
Bad file mode (also: a printer opened for anything but OUTPUT or APPEND; PRINT # or WRITE # to a file opened FOR INPUT; INPUT #, LINE INPUT #, or INPUT$ from a file opened FOR OUTPUT or APPEND)
- 57
-
Device I/O error (printing failed or was canceled; writing to an open file failed for a reason other than a full disk, such as a write-protected floppy or a CD-ROM refusing the write; a disk that cannot be read)
- 58
-
File already exists (NAME to a name another file or folder has)
- 59
-
Bad record length (OPEN ... LEN must be 1 to 32767; GET/PUT data longer than LEN)
- 61
-
Disk full (PRINT #, WRITE #, PUT, or CLOSE could not write all of its output; see File Output Errors)
- 62
-
Input past end of file (INPUT # or LINE INPUT # with nothing left in the file, INPUT$ with fewer characters left than it reads)
- 63
-
Bad record number (SEEK, GET, or PUT position below 1)
- 64
-
Bad file name (WIDTH of a device DVX does not have; OPEN of a name that is too long or not allowed)
- 67
-
Too many files open
- 68
-
Device unavailable (no printer to print on; CHDRIVE or CURDIR$ of a drive that is not there)
- 70
-
Permission denied (OPEN, KILL, or FILECOPY of a file another program is using)
- 71
-
Disk not ready (a drive with no disk in it, such as an empty floppy or CD-ROM drive: any file statement or function used there)
- 74
-
Can’t rename with different drive (NAME to a name on another drive)
- 75
-
Path/File access error (SaveScreenshot to a file that cannot be written; a read-only file or a folder opened to be written, killed, or copied over; a file made, killed, or renamed on a disk that cannot be written, such as a CD-ROM or a write-protected floppy; PUT, PRINT #, or WRITE # to a read-only file opened FOR RANDOM or BINARY; a folder that cannot be made or removed)
- 76
-
Path not found (the folder of a file, or the folder CHDIR names, does not exist)
- 91
-
Object variable not set (a property, method, or member variable of Nothing, early or late bound, or through a WITH block on Nothing; Show or Hide of Nothing; a form’s procedure through a variable that holds Nothing; a value that is not an object stored without SET in a variable, element, field, or member declared As Object or a class that holds Nothing: see Default Member)
- 92
-
For loop not initialized (FOR EACH over a dynamic array without bounds)
- 93
-
Invalid pattern string (a LIKE pattern with a [ that has no ])
- 94
-
Invalid use of Null (Null where a real number or text is needed, a property of a control, a form, the Printer, or the Screen included; see Variants; INPUT # of #NULL# into a variable that is neither a String nor a Variant)
- 326
-
Resource with identifier not found (LOADRESSTRING, LOADRESPICTURE, or LOADRESDATA of an id the program has no resource for: see Program Resources)
- 340
-
Control array element doesn’t exist (an index of a control array or menu control array that has no element there: Btn(5) when there is no Btn(5), Btn(-1); Unload of an element there is not; Load of an index below 0 or past 32767)
- 343
-
Object not an array (Load or Unload with an index of a control or menu item that is in no control array; Index of one)
- 360
-
Object already loaded (Load of a control array element that is there)
- 361
-
Can’t load or unload this object (Load or Unload of a control or menu item named without an index)
- 362
-
Can’t unload controls created at design time (Unload of a control array element the form’s .frm made)
- 364
-
Object was unloaded (a control RemoveControl removed, or a form that is gone, used through a reference to it)
- 380
-
Invalid property value (a property set to a value it cannot take, as Visual Basic’s controls refuse it: a Width or Height below 0 of a control or a form — MinWidth, MinHeight, MaxWidth, MaxHeight, and a UserControl’s MinWidth and MinHeight too —, a FontSize below 1, a DrawWidth below 1, a ListIndex below -1 or past the list — a ListBox’s, ComboBox’s, DropDown’s, ListView’s, or TreeView’s —, a ListBox’s, ComboBox’s, or DropDown’s TopIndex below 0 or past the list, a Value outside Min to Max of a scroll bar, a SpinButton (its RealValue in real mode too), or a ProgressBar (0 to 100), a SelStart, SelLength, MaxLength, or Timer Interval below 0, a RichEdit’s SelFontSize below 1, a SpinButton’s Decimals past 10, a TabStrip’s TabIndex past its tabs, a ListView’s SortColumn past its columns or SortOrder past 2, a DragMode other than 0 or 1, a number a named property — an Alignment, a SelAlignment, a MultiSelect, an Align, a BorderStyle — has no name for; a drawing property — DrawStyle, FillStyle, FontScale, ScaleMode, a ScaleWidth or ScaleHeight of 0 — the Printer’s Copies, FontSize, or Orientation, WindowState, MousePointer, an Alignment or other named value that is not one of its names, a menu’s Shortcut DVX has no key for, Visible = False of a menu that holds a submenu, a Container that is no container of the form, a picture made from bytes given to a control that cannot show one)
- 381
-
Invalid property array index (an indexed property of a control, such as a ListBox’s ItemData(i), Selected(i), or List(i) = text, given an index there is no item for: ItemData(ListIndex) with nothing selected; also a control’s method that names an item by its index given one there is no item for: a TreeView’s GetItemText, SetItemText, RemoveItem, and its other node methods, a ListView’s GetCell and SetCell, a ListBox’s or ListView’s IsItemSelected and SetItemSelected, a TabStrip’s SetActive, an OptionButton’s SetSelected — where Visual Basic’s TreeView, ListView, and TabStrip give their collections' Index out of bounds)
- 382
-
Property cannot be set at run time (Name, Index, or a form’s Layout: what only the .frm sets)
- 383
-
Property is read-only (a property that can only be read, such as ListCount, Parent, a form’s Controls or ActiveControl, Screen.Width, the Printer’s Page or DeviceName, a Picture’s Width, or a control’s own read-only property such as a TextArea’s CursorLine)
- 394
-
Property is write-only (a property that can only be set, read)
- 424
-
Object required (SET, Is, or TypeOf with a value that is not an object; a member, Show, Hide, or Unload of a value that is not an object; SWAP of a value that is not an object with a variable declared As Object or a class)
- 438
-
Object doesn’t support this property or method (the object has no member of that name, or it is Private — a control, a form, a menu, the Printer, the Screen, the Clipboard, a Picture, or an object of the program’s classes alike; a value stored without SET in a variable declared As Object or a class whose object has no default member; an object with no default member used as a value, or given without SET where a value is stored: see Default Member)
- 446
-
Object doesn’t support named arguments (a form or control method called with Name:=value)
- 448
-
Named argument not found (a Name:= the method does not have; a left-out OPTIONAL Variant argument, Missing, used as a value)
- 449
-
Argument not optional (a method call through an object left out a parameter that is not OPTIONAL; Screen.Arrange or Clipboard.SetText without its argument; a control’s method given fewer arguments than it takes, a UserControl’s and one that takes its arguments as they come, such as SetRealRange, included)
- 450
-
Wrong number of arguments or invalid property assignment (also a Collection given without SET where a value is stored: its default member, Item, needs an index; a control’s method given more arguments than it takes, a UserControl’s included, an indexed property given more index arguments than it takes, Screen.Arrange with more than one)
- 451
-
Object not a collection (FOR EACH over an object that is not a Collection)
- 453
-
Specified DLL function not found (a DECLARE LIBRARY function whose library is not on this computer, or that the library does not have; the description is "External function not found: " and its name; see Include Libraries)
- 457
-
This key is already associated with an element of this collection (Collection.Add with a key in use)
- 481
-
Invalid picture (LOADPICTURE of a file that is not a picture DVX can show; a form’s Icon set to a file that is not one)
- 482
-
Printer error (the Printer used without the printing library, with the printer’s driver missing, or drawing on a printer model that prints text only)
- 711
-
Invalid class string (CreateControl of a control type DVX does not have)
- 727
-
There is already a control with that name (CreateControl of a name a control, a menu, or the form has already; AddMenu of a menu name in use)
- 730
-
Control not found (Form.Controls("name") of a name no control of the form has)
- 1000
-
No form runtime (a form or control statement ran without the form runtime, e.g. under a headless runner)
- 1001
-
Ambiguous control name (a control named without its form, outside a form’s own code, that more than one loaded form has; also such a name given to a library function, as ConnAttach, SerAttach, and CommAttach take one)
SHELL
Executes an operating-system command.
SHELL "command"
When used as a function, SHELL returns the exit code of the command, or -1 when it did not run.
Shell "DIR /B"
exitCode = Shell("COPY A.TXT B.TXT")
DVX steps aside while the command runs, as it does for a DOS program started from Program Manager, but stays in memory, since your program waits for the command: the screen goes back to text, and the command has the keyboard, the mouse, and the hardware to itself. Nothing of DVX runs meanwhile, so the other programs that are running are named first and asked to close (your program stays and waits); choosing No, or a program that keeps a window open, means the command does not run (-1). When the command ends, the desktop comes back and your program goes on. A command that prints and ends at once is gone from the screen as soon as it ends: ShellRunDos (shell.bas) can wait for a key first.
The command goes to DOS as it is written. DOS commands read / as the start of a switch (DIR /B), so write the paths in a command with \ (SHELL "DEL C:\TEMP\X.TXT"); FileOpsPathNative$ (fileops.bas) turns a path built with / into that form. Everywhere else in DVX BASIC a path may use / or \.
SLEEP
Pauses execution for the given number of seconds. With no argument, sleeps for 1 second. The desktop and the program’s own forms keep running while it sleeps, SLEEP 0 just lets pending events run, and closing the program ends the sleep.
SLEEP [seconds]
RANDOMIZE
Seeds the random number generator. A program that never uses RANDOMIZE gets the same sequence from RND on every run. RANDOMIZE alone, as in Visual Basic, or RANDOMIZE TIMER, seeds it from the system clock, so each run gets a different sequence; RANDOMIZE seed gives the sequence of that seed, the same on every run.
RANDOMIZE ' Seed from system clock
RANDOMIZE TIMER ' The same
RANDOMIZE seed
1.4.9. Sound, Joysticks, and Frames
These statements work as they do in QBasic, on whatever sound hardware the computer has: a sound card, the PC speaker, or none at all, in which case the program runs the same but silently. Several programs can make sound at once. For sound files, tones of any shape, and music files, see the sound.bas and music.bas include libraries; for more joystick detail, joystick.bas.
SOUND
Plays a tone of frequency hertz (37 to 32767) for duration clock ticks; there are 18.2 ticks in a second, and fractions are allowed. A duration of 0 stops every sound the program has queued. Frequencies too high to hear (above 20000) are silent. Anything out of range is error 5 (Illegal function call).
SOUND frequency, duration
SOUND 440, 18.2 ' A for one second
SOUND 440, 0 ' stop
PLAY
Plays a tune written in the music macro language. Letters may be upper or lower case and spaces are ignored. The settings (octave, length, tempo, style, instrument, foreground or background) stay from one PLAY to the next.
PLAY commands$
PLAY "T160 O3 L8 E D C D E E E4"
| Command | Meaning |
|---|---|
A to G |
Play the note in the current octave. Follow it with # or + for sharp, - for flat, then optionally a length (1 to 64, as for L) and dots. |
N n |
Play note n (1 to 84, seven octaves from the lowest C); N0 is a rest. |
O n |
Octave 0 to 6 (default 4). Octave 3 starts at middle C. |
> and < |
Go up or down one octave. |
L n |
Length of the notes that follow: 1 a whole note, 2 a half, 4 a quarter (the default) ... 64. |
P n |
Pause (rest) of length n (1 to 64). |
. |
A dot after a note or pause makes it half as long again; each further dot adds half again. |
T n |
Tempo in quarter notes a minute (32 to 255, default 120). |
MN |
Music normal: each note sounds for 7/8 of its length (the default). |
ML |
Music legato: notes sound for their whole length. |
MS |
Music staccato: notes sound for 3/4 of their length. |
MF |
Music foreground: PLAY, SOUND, and BEEP wait until the sound has finished (the default). |
MB |
Music background: the program goes on while the music plays; it only waits when more than 32 notes are waiting. |
I n |
DVX’s own: play the notes that follow on General MIDI instrument n (1 to 128; 1 is the piano, 41 the violin, 74 the flute) through the music synthesizer. I0 goes back to plain tones (the default). |
V n |
Volume of the notes that follow, 0 to 100 percent (default 100), as in QB64. On an instrument it sets how hard the note is played. |
@ n |
Waveform of the tones that follow, as in QB64: @1 square (the default, like the PC speaker), @3 triangle (softer), @5 noise (drums, explosions). QB64’s @2 and @4 are not available. |
X |
"X" + VARPTR$(s$) plays the commands in s$ at that point (s$ may use X itself, up to 16 levels deep). |
= |
Any number above may be written as "=" + VARPTR$(n), n a numeric expression: "T=" + VARPTR$(tempo). |
A string with a mistake in it plays nothing and raises error 5 (Illegal function call). X and "=" work as in QBasic, with VARPTR$ as for DRAW (see the program screen’s DRAW): the value is taken when VARPTR$ runs. A whole tune may be at most 32767 characters once X and "=" are filled in.
verse$ = "L8 E D C D E E E4"
tempo = 160
PLAY "T=" + VARPTR$(tempo) + "O3 X" + VARPTR$(verse$) + "X" + VARPTR$(verse$)
Building the string with + works too, such as PLAY "O" + STR$(n). Without I, the notes are tones — square waves like the PC speaker’s unless @ chooses another — and with it, they play on the same synthesizer as MIDI music. The PC speaker plays only square tones at one volume: there V and @ make no difference, except that V0 is silent.
PLAY "MB T120 L4 CDEF GAB>C" ' a scale in the background
PLAY "I74 O4 L8 GAB>C" ' on the flute
PLAY "@3 V60 L8 CEG>C" ' softer, quieter
PLAY Function
PLAY(n) returns how many notes are still waiting to be played in the background (n is ignored). A game can use it to keep its music going:
If PLAY(0) < 4 Then PLAY "MB " + tune$
STICK and STRIG
STICK(n) returns where a joystick points, from 1 (all the way left or up) to 200 (all the way right or down), about 100 in the middle, or 0 when there is no such joystick. STICK(0) reads joystick A’s X and remembers A’s Y and joystick B’s X and Y, which STICK(1), STICK(2), and STICK(3) then return; so call STICK(0) first.
STRIG(n) returns True (-1) or False (0) for the buttons:
| n | Returns True when |
|---|---|
0 |
joystick A’s first button was pressed since the last STRIG(0) |
1 |
joystick A’s first button is down |
2 |
joystick B’s first button was pressed since the last STRIG(2) |
3 |
joystick B’s first button is down |
4 |
joystick A’s second button was pressed since the last STRIG(4) |
5 |
joystick A’s second button is down |
6 |
joystick B’s second button was pressed since the last STRIG(6) |
7 |
joystick B’s second button is down |
Joystick A is the first joystick; joystick B the second one, or the second stick of a joystick with four axes. When no joystick is connected the keyboard stands in for joystick A (see the Control Panel’s Game Controllers tab). STRIG ON, STRIG OFF, and ON STRIG are not supported; test STRIG in a Timer or a loop instead.
x = STICK(0)
y = STICK(1)
If STRIG(0) Then FireShot
FRAMEWAIT
Waits until the next frame of a steady clock of rate frames a second begins, keeping the desktop and the program’s forms running meanwhile. A game loop that calls it once a frame runs at the same speed on every computer. Frames the program was too busy for are skipped, not caught up; FrameMissed() in game.bas counts them. rate must be at least 1; rates above 1000 count as 1000. Changing the rate starts the clock over.
FRAMEWAIT rate
Do
MoveEverything
DrawEverything
FRAMEWAIT 30
Loop Until quitting
1.4.10. Console and Graphics
These statements work as they do in QBasic. The first one a program uses gives it a screen of its own: a window, titled with the program’s name, the size of the screen mode. From then on PRINT and INPUT use that screen too (before it, PRINT writes to the output window and INPUT asks in a dialog box, as always). Keys typed in the window go to INKEY$ and INPUT. The window stays open when the program’s code has finished, so its output can be read; closing it ends the program.
The names are not reserved: a program that has its own variable, SUB, or constant called Color, Cls, Draw, and so on keeps using it.
Screen Modes
| Mode | Size and colors | Text (WIDTH choices) | Pages |
|---|---|---|---|
SCREEN 0 |
Text only, 16 colors |
80 or 40 x 25, 43 or 50 |
8 (4 at 80 x 43, 80 x 50) |
SCREEN 1 |
320 x 200, 4 colors (two palettes) |
40 x 25 |
1 |
SCREEN 2 |
640 x 200, 2 colors |
80 x 25 |
1 |
SCREEN 7 |
320 x 200, 16 colors |
40 x 25 |
8 |
SCREEN 8 |
640 x 200, 16 colors |
80 x 25 |
4 |
SCREEN 9 |
640 x 350, 16 of 64 colors |
80 x 25 or 80 x 43 |
2 |
SCREEN 10 |
640 x 350, 4 shades (some blinking) |
80 x 25 or 80 x 43 |
2 |
SCREEN 11 |
640 x 480, 2 colors |
80 x 30 or 80 x 60 |
1 |
SCREEN 12 |
640 x 480, 16 colors |
80 x 30 or 80 x 60 |
1 |
SCREEN 13 |
320 x 200, 256 colors |
40 x 25 |
1 |
A program starts in SCREEN 0. SCREEN with a new mode (and WIDTH) clears the screen and restores the mode’s colors: the 16 standard colors, and in SCREEN 13 the standard 256-color palette. SCREEN with the mode the program is already in only changes the pages, so a program can flip pages in a loop. Other mode numbers, and graphics statements in SCREEN 0, are error 5 (Illegal function call). The color switch argument is accepted and ignored.
Text uses 16-pixel-high characters in SCREEN 0 (25 rows), 11 and 12 (30 rows), 14-pixel ones in SCREEN 9 and 10 (25 rows), and 8-pixel ones everywhere else. The window shows each mode in the shape it has on a monitor: the 640 x 200 modes with every line doubled, 40-column text with every column doubled; SCREEN 9 and 10 show at 640 x 350 as they are. On the whole screen the 320 x 200 modes use the computer’s 320 x 200 mode and the others the nearest mode, centered.
SCREEN mode [, [colorswitch] [, [activepage] [, visualpage]]]
WIDTH [columns] [, rows]
Screen Pages and PCOPY
The pages of a mode (see the table) are separate screens. Drawing and PRINT go to the active page; the window shows the visual page. Drawing on a page that is not shown and then showing it (or copying it to the shown page) gives smooth animation. A visual page left out follows the active page. In SCREEN 0 each page has its own text. Each page also keeps its own text cursor, as in QBasic: LOCATE and PRINT move the active page’s cursor, and switching pages brings back the cursor where it was on that page.
SCREEN 7, , 1, 0 ' draw on page 1, show page 0
Do
CLS
CIRCLE (x, 100), 20, 14
PCOPY 1, 0 ' show the finished picture
x = (x + 2) MOD 320
FRAMEWAIT 30
Loop
PCOPY source, destination copies one page (text and pixels) onto another. A page number the mode does not have is error 5.
FULLSCREEN
Shows the program’s screen on the whole screen, or back in its window. Alt+Enter in the window does the same. While the program has the whole screen, Alt+Tab brings the desktop back (the program keeps running in its window) and switching back to the program returns it to the whole screen. Other programs keep running either way. When the computer has no suitable video mode, the screen stays in its window.
FULLSCREEN [ON | OFF]
FULLSCREEN expression ' True: whole screen, False: window
isFull = FULLSCREEN ' True while the program's screen has the whole screen
Used as a value, FULLSCREEN tells whether the program’s screen has the whole screen (also while the desktop is shown for another program, since the screen comes back with the focus): False when no suitable video mode could be set, or before SCREEN or any drawing made a screen. A form takes the whole screen with its FullScreen property instead.
Text: CLS, LOCATE, COLOR, CSRLIN, POS, SCREEN( )
CLS [n]
LOCATE [row] [, [column] [, cursor]]
COLOR [foreground] [, background]
row = CSRLIN
column = POS(0)
code = SCREEN(row, column [, colorflag])
-
CLS clears the screen and puts the cursor in the top-left corner (the top of the text viewport). In a graphics mode with a VIEW set, CLS (or CLS 1) clears only the view; with a VIEW PRINT set, CLS (or CLS 2) clears only the text viewport; CLS 0 clears everything.
-
LOCATE moves the cursor (rows and columns count from 1). cursor 1 shows the text cursor in SCREEN 0, 0 hides it (the default). QBasic’s cursor size arguments are accepted and ignored.
-
COLOR in SCREEN 0 takes a foreground 0 to 31 and a background 0 to 15. Foregrounds 16 to 31 blink (color minus 16); as on a VGA, backgrounds 8 to 15 show as 0 to 7 and make the text blink too.
-
COLOR in SCREEN 1 takes a background color (0 to 15) and a palette: an even number gives green, red, and brown for colors 1 to 3, an odd one (the default) cyan, magenta, and white. SCREEN 2 has no COLOR statement. In SCREEN 7 to 10 COLOR takes a foreground and a background color (the color of attribute 0: 0 to 15 in SCREEN 7 and 8, an EGA color 0 to 63 in SCREEN 9, a shade 0 to 8 in SCREEN 10). In SCREEN 11 to 13 it takes only a foreground. The foreground is also the default color of the drawing statements.
-
CSRLIN is the cursor’s row and POS(0) its column. Before the program has a screen, POS(0) is the output window’s column.
-
SCREEN(row, column) is the character code shown there; with a colorflag of 1, its color (in SCREEN 0, foreground + 16 * background).
-
PRINT scrolls the screen (or the text viewport) up at the bottom. CHR$(13) and CHR$(10) start a new line and CHR$(9) moves to the next multiple of 8 columns.
VIEW PRINT
Makes rows top to bottom the text viewport: PRINT scrolls only those rows, so the rows around them stay as they are (a title, a status line). The cursor goes to the viewport’s first row. VIEW PRINT alone makes the whole screen the viewport again. LOCATE can still reach every row.
VIEW PRINT [top TO bottom]
INKEY$
Returns the next key typed in the program’s window without waiting: "" when there is none, one character for a character key, and CHR$(0) + CHR$(scan code) for other keys (arrows, function keys). Keys held with Alt, and function keys held with Shift, Ctrl, or Alt, give the codes QBasic gives: Alt+A is CHR$(0) + CHR$(30), Alt+1 CHR$(0) + CHR$(120), Shift+F1 CHR$(0) + CHR$(84), Ctrl+F1 CHR$(0) + CHR$(94), and Alt+F1 CHR$(0) + CHR$(104). Keys wait for INKEY$ in a queue of 64.
Do
k$ = INKEY$
Loop While k$ = ""
If k$ = Chr$(0) + Chr$(72) Then Print "Up arrow"
PEN
QBasic’s light pen; the mouse on the program’s screen stands in for it, as the mouse drivers of the time did. PEN ON lets the program read it, PEN OFF stops that (PEN STOP is accepted too). PEN(n) then tells:
| n | PEN(n) |
|---|---|
0 |
True (-1) if the left button went down since PEN(0) was last read, else 0 |
1, 2 |
x and y (pixels) where it last went down |
3 |
True (-1) while the left button is down, else 0 |
4, 5 |
x and y where the mouse last was over the screen |
6, 7 |
text row and column where it last went down |
8, 9 |
text row and column where it last was |
PEN(n) before PEN ON, after PEN OFF, or with another n raises error 5.
Screen 12
Pen On
Do
If Pen(0) Then PSet (Pen(1), Pen(2)), 14
Loop While InKey$ = ""
INPUT and LINE INPUT on the Screen
On the program’s screen INPUT shows its prompt at the cursor and reads what is typed there: Backspace takes back a character, Esc clears the line, and Enter ends it. LINE INPUT reads a whole line, commas included, without adding "? " to the prompt. Without the program’s screen LINE INPUT asks in a dialog box, like INPUT.
LINE INPUT ["prompt";] variable$
Graphics Coordinates
Points are (x, y) in pixels from the top-left corner. STEP(x, y) is relative to the last point drawn (the center of the screen at first). VIEW makes a smaller part of the screen the drawing area (coordinates start at its corner, and drawing stays inside it); WINDOW gives it coordinates of your own. Color numbers are attributes: 0 to 3 in SCREEN 1 and 10, 0 and 1 in SCREEN 2 and 11, 0 to 15 in SCREEN 7, 8, 9, and 12, 0 to 255 in SCREEN 13; anything else is error 5.
VIEW [[SCREEN] (x1, y1)-(x2, y2) [, [fill] [, border]]]
WINDOW [[SCREEN] (x1, y1)-(x2, y2)]
value = PMAP(coordinate, n)
-
VIEW with coordinates of its own sets the view; fill fills it and border draws a frame around it. VIEW SCREEN keeps coordinates counting from the screen’s corner. VIEW alone is the whole screen again.
-
WINDOW (x1, y1)-(x2, y2) maps the view to those coordinates with y going up; WINDOW SCREEN keeps y going down. WINDOW alone goes back to pixels.
-
PMAP converts between WINDOW coordinates and pixels of the view: n = 0 gives the pixel column of an x, 1 the pixel row of a y, 2 the x of a pixel column, and 3 the y of a pixel row. Without a WINDOW both are pixels.
PSET, PRESET, POINT
PSET [STEP](x, y) [, color]
PRESET [STEP](x, y) [, color]
c = POINT(x, y)
v = POINT(n)
PSET draws a point in the given color or the COLOR foreground, PRESET in the given color or color 0. POINT(x, y) is the color at a point, or -1 outside the view. POINT(0) and POINT(1) are the last point in pixels, POINT(2) and POINT(3) in WINDOW coordinates.
LINE
LINE [[STEP](x1, y1)]-[STEP](x2, y2) [, [color] [, [B | BF] [, style]]]
Draws a line, a box (B), or a filled box (BF). Without a start point the line starts at the last point. style is a 16-bit pattern: each set bit (from the top) draws a pixel, each clear one skips it.
LINE (10, 10)-(100, 50), 4, BF
LINE -STEP(20, 0), 15
LINE (0, 100)-(319, 100), 7, , &HF0F0
CIRCLE
CIRCLE [STEP](x, y), radius [, [color] [, [start] [, [end] [, aspect]]]]
Draws a circle, an ellipse, or an arc. start and end are angles in radians (0 to 2 * pi, counterclockwise from the right); a negative angle also draws the radius to that end, so CIRCLE can draw pie slices. aspect is the height divided by the width; the default makes circles round on a 4:3 monitor (0.83 in SCREEN 13, 1 in SCREEN 12), so in SCREEN 13 a circle in the window looks slightly flat and a round one needs aspect 1.
CIRCLE (160, 100), 50, 14
CIRCLE (160, 100), 50, 4, -0.0001, -1.5708 ' a quarter pie slice
CIRCLE (160, 100), 80, 2, , , 0.5 ' an ellipse
PAINT
PAINT [STEP](x, y) [, [color] [, border]]
PAINT [STEP](x, y), tile$ [, [border] [, background$]]
Fills the area around the point with color, up to pixels of the border color (by default the fill color itself).
With a string instead of a color, PAINT fills the area with a pattern, as in QBasic. Each row of the pattern is one byte for each color plane of the mode, and each bit is a pixel (the first bit is the left pixel): in SCREEN 2 and 11 one byte is eight pixels, color 0 or 1; in SCREEN 7, 8, 9, and 12 four bytes (the blue, green, red, and bright planes) make eight pixels of 16 colors; in SCREEN 10 two bytes. In SCREEN 1 each byte is four pixels of two bits, and in SCREEN 13 each byte is one pixel. A pattern has up to 64 rows and repeats over the screen. The fill stops at the border color (by default the COLOR foreground) and covers the whole area once, even where it already has the pattern’s colors. background$ is accepted as in QBasic: a pattern with more than two rows in a row equal to it is error 5.
SCREEN 12
LINE (0, 0)-(100, 100), 15, B
' blue and green stripes
PAINT (50, 50), CHR$(&HAA) + CHR$(&H55) + CHR$(0) + CHR$(0), 15
DRAW
Draws with a small command language. Letters may be upper or lower case; spaces and semicolons are ignored.
| Command | Meaning |
|---|---|
U n |
Up n (without n: 1). |
D n |
Down n. |
L n |
Left n. |
R n |
Right n. |
E n |
Diagonally up and right. |
F n |
Diagonally down and right. |
G n |
Diagonally down and left. |
H n |
Diagonally up and left. |
M x,y |
Move to x, y; with a sign (M+10,-5) move by that much. |
B |
Before a move: move without drawing. |
N |
Before a move: draw, then come back to where the move started. |
C n |
Color of the lines that follow. |
S n |
Scale: moves are n/4 pixels a unit (1 to 255, default 4). |
A n |
Turn the directions by n * 90 degrees (0 to 3). |
TA n |
Turn the directions by n degrees (-360 to 360). |
P c,b |
PAINT at the current point with color c up to border color b. |
The pen starts at the last point and stays where it ends. The color, scale, and turn stay from one DRAW to the next. A mistake in the string is error 5.
As in QBasic, X runs another DRAW string and "=" takes a number, both given with VARPTR$: DRAW "X" + VARPTR$(shape$) and DRAW "C=" + VARPTR$(c) + "R=" + VARPTR$(n). DVX BASIC has no memory addresses, so VARPTR$ packs the value itself into its result (taken when VARPTR$ runs), and it takes any expression. Building the string with + and STR$ works too, such as DRAW "R" + STR$(n).
DRAW "BM100,100 C14 R50 D50 L50 U50" ' a square
DRAW "BM160,100 TA45 C2 R40" ' a line at 45 degrees
box$ = "R10 D10 L10 U10"
FOR i = 1 TO 5
DRAW "BM" + STR$(i * 20) + ",20 X" + VARPTR$(box$)
NEXT i
PALETTE
PALETTE [attribute, color]
PALETTE USING array[(first)]
Changes the color an attribute shows. In SCREEN 11, 12, and 13, color is blue * 65536 + green * 256 + red with each part 0 to 63; in SCREEN 0 and 9 it is an EGA color number 0 to 63; in SCREEN 1, 2, 7, and 8 one of the 16 standard colors; in SCREEN 10 a shade 0 to 8 (0 off, 4 gray, 8 bright, and 1 to 3, 5 to 7 blinking between two of them). PALETTE alone restores the mode’s colors. PALETTE USING sets every attribute of the mode (256 in SCREEN 13) from a one-dimensional LONG array starting at element first (or its first element); -1 leaves that attribute as it is. On the whole screen a palette change shows at once, like on a VGA card; in the window, whatever is already drawn in that attribute changes color too.
SCREEN 13
PALETTE 1, 63 * 65536 ' attribute 1 becomes bright blue
FOR i = 0 TO 63
PALETTE 2, i ' a red that fades in
FRAMEWAIT 30
NEXT i
Example
SCREEN 13
CLS
COLOR 14
PRINT "Press a key"
CIRCLE (160, 100), 60, 4
PAINT (160, 100), 1, 4
LINE (0, 0)-(319, 199), 15, B
DRAW "BM150,90 C15 R20 D20 L20 U20"
Do
Loop While INKEY$ = ""
FULLSCREEN
Do
Loop While INKEY$ = ""
Writing a Screen Saver
A screen saver is a program with no form that shows its screen on the whole screen and draws until DVX closes it. Put the program (.app) in the SAVERS folder of your user folder (FileOpsKindDir$(FILEOPS_KIND_SAVERS, True)); it is then listed on Control Panel’s Desktop page by its project Name. DVX starts it with the command line /S after the wait with no input, and closes its screen at the next key or mouse movement, which ends the program, so it needs no INKEY$ of its own.
SCREEN 13
CLS
FULLSCREEN ON
DO
' draw a frame
FRAMEWAIT 30
LOOP
SysScreenSaver$, SysSetScreenSaver, SysScreenSaverStart, and SysIdleSeconds (system.bas) read and change the screen saver from a program.
1.5. File I/O
1.5.1. OPEN
OPEN filename$ FOR INPUT AS #channel
OPEN filename$ FOR OUTPUT AS #channel
OPEN filename$ FOR APPEND AS #channel
OPEN filename$ FOR RANDOM AS #channel [LEN = recordSize]
OPEN filename$ FOR BINARY AS #channel
| Mode | Description |
|---|---|
INPUT |
Open for sequential reading. File must exist. |
OUTPUT |
Open for sequential writing. Creates or truncates. |
APPEND |
Open for sequential writing at end of file. |
RANDOM |
Open for random-access record I/O. LEN sets the record size in bytes (default 128). |
BINARY |
Open for raw binary I/O. |
RANDOM and BINARY make the file when it does not exist. A file that cannot be written (a read-only file, or one on a disk that cannot be written, such as a CD-ROM) they open for reading only, as QBasic and Visual Basic do: GET, INPUT$, and the other ways of reading it work, and PUT, PRINT #, and WRITE # raise error 75 (Path/File access error). Some disks let such a file be opened for writing and refuse only the writing (a write-protected floppy, and some CD-ROM drives): then the PUT, PRINT #, or WRITE #, or the CLOSE that writes out what is left, raises error 57 (Device I/O error). An OPEN that fails raises an error that says why, numbered as in Visual Basic: 53 (File not found) for a missing file FOR INPUT, 76 (Path not found) when the folder does not exist, 75 (Path/File access error) for a read-only file opened FOR OUTPUT or APPEND, a folder, or a disk that cannot take the file (a CD-ROM, a write-protected floppy, or a floppy disk whose main folder is full), 70 (Permission denied) for a file another program is using, 67 (Too many files) when no more files can be open, 71 (Disk not ready) for a drive with no disk in it, 57 (Device I/O error) for a disk that cannot be read, and 64 (Bad file name) for a name that is too long or not allowed. OUTPUT empties an existing file at once; to replace a document only when the new one is complete, see File Output Errors.
Printing Through OPEN
The names LPT1:, LPT2:, LPT3: (a printer port) and PRN (the printer chosen in the Control Panel) open a printer, in any case and with or without the colon. Only OUTPUT and APPEND work (anything else raises error 54). PRINT # and WRITE # collect the output, and CLOSE sends it to the printer (so does the program’s end, when the program does not close it); a printer problem the user cancels makes CLOSE raise error 57, and a printer that cannot be reached makes OPEN raise error 68. A program ended from the Task Manager prints nothing more: what it collected is thrown away.
Open "LPT1:" For Output As #1
Print #1, "Line one"
Print #1, "Line two"
Close #1 ' now it prints
1.5.2. CLOSE
Closes open file channels.
CLOSE #channel
CLOSE #channel, #channel, ...
CLOSE
RESET
CLOSE with a list closes each channel in it (the # is optional); CLOSE alone, and RESET, close every open file. Closing a channel that is not open does nothing; a number outside the channels DVX has raises error 52.
1.5.3. PRINT #
Writes text to a file, formatted exactly as PRINT shows it: a number has a space before it (where its sign goes) and after it, a comma moves to the next 14-column zone, a semicolon keeps the line going, and TAB(n), SPC(n), and PRINT #channel, USING work as they do for PRINT. See PRINT. A line ends with a carriage return and a line feed (CHR$(13) & CHR$(10)), as in a DOS text file and as QBasic and Visual Basic write it; so do the lines a WIDTH # limit breaks. A line feed inside the text is written as it is. PRINT # to a file opened FOR INPUT raises error 54.
PRINT #channel, expression [; | , expression ...]
PRINT #channel, USING format$; expression [; expression ...]
1.5.4. WIDTH #
Sets the line width of an open file, the screen, or the printer: output longer than the width goes on in a new line, as in QBasic. 255 means no limit (the default).
WIDTH #channel, width
WIDTH "SCRN:", width
WIDTH "LPT1:", width
WIDTH LPRINT width
WIDTH "SCRN:" is the same as WIDTH width for the program’s screen. WIDTH "LPT1:" (LPT2:, LPT3:, PRN) and WIDTH LPRINT set the width of the printer’s lines, for LPRINT and for files opened on that printer afterwards. A width outside 1 to 255 raises error 5, a file number that is not open error 52, and a device DVX does not have (such as "COM1:") error 64.
1.5.5. INPUT #
Reads comma-delimited data from a file, one field per variable, as Visual Basic’s Input # does, so what WRITE # wrote comes back as it was. A field in double quotes is text, read without its quotes; any other field runs to the next comma or the end of the line, without the blanks around it. What a variable takes from a field depends on its type:
-
A String takes the field’s text as it is.
-
A Variant takes the value the field stands for: the text of a field in quotes; True or False for #TRUE# or #FALSE#; Null for #NULL#; a Date for a date or a time between # signs (#2026-10-28 15:04:05#, the form WRITE # writes); Empty for an empty field (two commas in a row, or a blank line); a number for a field that is a plain number (digits with a sign, a point, an exponent, or &H), an Integer, a Long, or a Double, the narrowest that holds it (12 is an Integer, 70000 a Long, 1.5 a Double); and the text of any other field (12abc, $5, (3)). DVX has no error values, so #ERROR 5# is read as text.
-
A number, a Boolean, or a Date takes #TRUE#, #FALSE#, a date between # signs, and an empty field as an assignment converts those values (#TRUE# is -1 in a number); #NULL# raises error 94 (Invalid use of Null). Of any other field a Date takes the text as CDATE reads it, and a number or a Boolean the number the field starts with, up to a blank (0 when there is none, as in Visual Basic: "1 2" gives 1).
A member variable, and an element of an array a Variant holds, take a field as they are declared when the program runs. Reading past the last field raises error 62 (Input past end of file), and reading a file opened FOR OUTPUT or APPEND error 54 (Bad file mode), as in Visual Basic; test EOF to stop at the end.
INPUT #channel, variable [, variable ...]
Open "data.txt" For Input As #1
Input #1, name$, age%, score#
Close #1
1.5.6. LINE INPUT #
Reads an entire line from a file into a string variable. The line ends at a line feed (CHR$(10)), which is not kept, and neither is a carriage return (CHR$(13)) just before it; every other character, a NUL (CHR$(0)) too, is part of the line. Reading when nothing is left in the file raises error 62 (Input past end of file), and reading a file opened FOR OUTPUT or APPEND error 54 (Bad file mode).
LINE INPUT #channel, variable$
1.5.7. WRITE #
Writes comma-delimited data to a file, as Visual Basic writes it, so INPUT # reads each value back as it was: numbers with no spaces, as STR$ gives them without its leading space (a number between -1 and 1 without the 0 before its point: .25, -.5), strings in double quotes, True and False as #TRUE# and #FALSE#, Null as #NULL#, a date as #yyyy-mm-dd hh:mm:ss# (the hour from 0 to 23; the date alone at midnight, the time alone for a time with no date), and Empty as nothing. An array or a TYPE record raises error 13 (Type mismatch). Each statement ends its line with a carriage return and a line feed, as PRINT # does.
WRITE #channel, expr1, expr2, ...
Write #1, "Scott", 42, 3.14, 0.5, True, #10/28/2026#
' Output: "Scott",42,3.14,.5,#TRUE#,#2026-10-28#
1.5.8. GET / PUT
Read and write records in RANDOM or BINARY mode files. When recordNum is omitted the transfer starts at the current file position.
GET #channel, [recordNum], variable
PUT #channel, [recordNum], variable
In RANDOM mode recordNum is a 1-based record number and each record is LEN bytes (see OPEN). Numbers are stored in their binary form (Byte 1 byte, Integer and Boolean 2, Long 4, Single 4, Double, Currency, and Date 8); a String is stored as a 2-byte length followed by its characters (one of 65535 characters or more as the length FFFF hexadecimal, then its length in 4 bytes), and a STRING * n variable or element as its n characters alone. PUT always writes a whole record, padding the unused part with zero bytes, and GET always advances to the next record; data longer than LEN raises error 59 before anything is written.
In BINARY mode recordNum is a 1-based byte position. Numbers and STRING * n are stored as in RANDOM mode. PUT writes the characters of a String with no length, and GET reads as many bytes as the String variable currently holds, so set its length first (for example with SPACE$ or by declaring it as STRING * n).
A Variant is stored as Visual Basic stores one, in both modes: 2 bytes holding its VarType (see Variants), then its value — a number in its binary form, a String with its 2-byte length, an array with its bounds and elements (see below), and nothing more for Empty and Null. GET into a Variant reads the VarType and then a value of that type; a VarType DVX has no value for (an object, Error, Decimal) raises error 5 (Illegal function call) and the Variant keeps its value. This holds for a variable, an array element, and a TYPE field declared As Variant, for a FUNCTION AS VARIANT given to PUT, and for a member PUT reaches through a variable As Object or As Variant, which is a Variant there as in Visual Basic; a variable declared without AS, or never declared, is no Variant, and its value is stored as its own type. What a built-in function gives is stored as a Variant too when Visual Basic’s function gives one: the forms without $ (LEFT, MID, UCASE, TRIM, CHR, STR, HEX, SPACE, STRING, FORMAT, ERROR, CURDIR, DIR, ENVIRON, COMMAND, and INPUT), DATE, TIME, NOW, and the other date functions that give a date or a part of one (DATESERIAL, DAY, DATEDIFF ...), IIF, CHOOSE, CVAR, INSTR, STRCOMP, SGN, CALLBYNAME, ARRAY, SPLIT, and FILTER: Put #1, , Left(s$, 3) writes the VarType 8 (vbString), the length, and the text, where Put #1, , Left$(s$, 3) writes a String as described above. An element of an array a Variant holds is stored as that array declares its elements. PUT of an object raises error 13.
PUT and GET also take a whole array (Put #1, , scores). Its elements are stored one after another in the order Visual Basic keeps them, the first subscript changing fastest, each as above (a String element always with its length). In a RANDOM file a dynamic array starts with its bounds: 2 bytes holding its number of dimensions, then for each dimension, the first one first, 4 bytes holding its number of elements and 4 its lower bound; GET gives a dynamic array the bounds it reads (error 10 while an element of it is passed by reference), and one without bounds is stored as no dimensions. A fixed-size array, and any array in a BINARY file, is stored without its bounds, and GET reads as many elements as the array has. An array a Variant holds is stored with its bounds in both modes, after the Variant’s VarType.
The variable may be a TYPE variable. Its fields are packed in declaration order as above, with nothing between them: a STRING * n field takes exactly n bytes (padded with spaces), a variable-length String field its 2-byte length and characters in both modes, a Variant field its VarType and value, and nested TYPE fields are packed inline. GET fills the fields of the existing variable in place. A field declared As an object cannot be stored (error 13).
The variable may also be an array element, arr(i), of any type including a TYPE: PUT writes that element and GET reads into it. The index expression is evaluated once. A field of a TYPE record (b.inner, itself a TYPE too) and a Public member variable of an object or a form (acct.Pos, acct.Rates(1)) work the same way. PUT also writes the record a FUNCTION of a TYPE returns (Put #1, , MakeRecord(5), Put #1, , acct.Snapshot()) as it writes a TYPE variable. A record knows its TYPE wherever it is, as in Visual Basic, so PUT writes, and GET reads into, one the compiler does not know too: a member reached through a variable As Object, or a record a Variant holds (which Visual Basic cannot store): its fields alone, as for any record, and GET into a Variant that holds a record fills that record.
Type RecT
id As Integer
score As Double
nm As String * 6
End Type
Dim r As RecT
Open "recs.dat" For Random As #1 Len = 32
r.id = 1
Put #1, 1, r ' 16 bytes of fields, padded to a 32-byte record
Get #1, 1, r
Close #1
Dim buf As String
Open "raw.bin" For Binary As #1
buf = Space$(16)
Get #1, 1, buf ' read bytes 1-16
Put #1, 33, "TAG" ' write 3 bytes at position 33
Close #1
1.5.9. File Output Errors
What PRINT #, WRITE #, and PUT write is collected in memory and goes to the disk a piece at a time, so a write that fails raises its error at the statement whose output could not be written, or at the CLOSE (or RESET) that writes what was left. A full disk raises error 61 (Disk full); any other failure, such as a disk taken out or a write-protected floppy, error 57 (Device I/O error). The file is then incomplete. A CLOSE of that file in the error handler does not raise the same error again.
Because OPEN FOR OUTPUT empties the old file first, a save that fails would lose the document. A text is saved safely in one call with FileOpsSaveText(path, text) (in fileops.bas): it writes the new copy beside the old file, every line end in text (a line feed, or CR LF) as CR LF, and only then swaps it in, so a failure leaves the old file as it was. It returns 0 when the file is saved, else the error number OPEN, PRINT #, or CLOSE would have raised (61 for a full disk, 76 for a missing folder, 75 for a read-only file, and so on); ERROR n raises it, and FileOpsError$ says why in words. While a long text is saved, the rest of DVX and the program’s own events go on, as with DoEvents (in a control’s code they wait until the save ends). Notepad and the Help Editor save like this:
Dim failure As Long
failure = FileOpsSaveText(path, Editor.Text & Chr$(10)) ' the last line ends too
If failure <> 0 Then
MsgBox "Could not save " & path & ": " & Error$(failure), vbOKOnly + vbExclamation
End If
For other files, write the new copy beside the old one yourself, into FileOpsTempPath$(path), then swap it in with FileOpsReplaceFile (both in fileops.bas). FileOpsTempPath$ makes a new, empty file every time it is called, never one that is already there, so call it once, keep the name, and Kill the file when the save is given up. The swap refuses a read-only file; raise FILEOPS_REPLACE_ERROR (75, Path/File access error, what OPEN gives for one) to report it the same way:
Function SaveText(path As String, text As String) As Boolean
Dim f As Integer
Dim failure As Integer
Dim tmpPath As String
SaveText = False
tmpPath = FileOpsTempPath$(path)
On Error GoTo saveFailed
f = FreeFile
Open tmpPath For Output As #f
Print #f, text
Close #f
If Not FileOpsReplaceFile(tmpPath, path) Then
Error FILEOPS_REPLACE_ERROR
End If
SaveText = True
Exit Function
saveFailed:
failure = Err
Resume saveCleanup
saveCleanup:
' Out of the handler, so the clean-up's own errors are ignored
On Error Resume Next
Close #f
Kill tmpPath
MsgBox "Could not save " & path & ": " & Error$(failure), vbOKOnly + vbExclamation
End Function
1.5.10. SEEK
Sets the file position. As a function, returns the current position. On a RANDOM file the position is a record number (statement and function); on other files it is a 1-based byte position. A position below 1 raises error 63 (Bad record number).
SEEK #channel, position ' Statement: set position
pos = SEEK(channel) ' Function: get current position
1.6. File System Statements
DVX BASIC provides statements for working with the file system — creating, deleting, renaming, and copying files and directories, and reading or setting file attributes.
Every one of them, and OPEN, used on a drive with no disk in it (an empty floppy or CD-ROM drive) raises error 71 (Disk not ready), as in Visual Basic, at once: DVX never stops at DOS’s question "Abort, Retry, Fail?".
A path may be written with / or \ between its parts, mixed too: OPEN "DATA/SCORES.TXT" and OPEN "DATA\SCORES.TXT" open the same file, and so do the FileOps, Shell, and other library functions that take a path (SHELL commands are the exception: see SHELL). Paths DVX gives back — CURDIR$, App.Path, App.Data, the file dialogs, FileOpsPathJoin$, and the other FileOps results — use \, the separator DOS shows; FileOpsPathNative$ gives a path of your own that form before you show it.
1.6.1. KILL
Deletes a file.
KILL filename$
A missing file raises error 53 (File not found), or 76 (Path not found) when its folder does not exist; a read-only file, a folder, or a file on a disk that cannot be written (a CD-ROM, a write-protected floppy) raises 75 (Path/File access error).
Kill "temp.bak"
1.6.2. NAME ... AS
Renames (or moves) a file or folder. As in Visual Basic, NAME never replaces anything: a new name that another file or folder already has raises error 58 (File already exists). Changing only the letter case of a name (NAME "My notes.txt" AS "My Notes.txt") renames the file, and so does giving it its own name another way, such as its short 8.3 form (the file then has that short name in place of its long one). DIR$ and the FileOps listings give a name in capitals that fits the 8.3 form in small letters, so a change of case shows only in a name that does not fit that form. NAME cannot move a file to another drive: a new name on another drive raises error 74 (Can’t rename with different drive), as in Visual Basic; copy the file there with FILECOPY, then KILL the old one. A missing file raises error 53 (File not found), a folder that does not exist (the file’s or the new name’s) raises 76 (Path not found), and a file that cannot be renamed for another reason, such as one on a CD-ROM or a write-protected floppy, raises 75 (Path/File access error).
NAME oldName$ AS newName$
Name "draft.txt" As "final.txt"
1.6.3. FILECOPY
Copies a file. If the destination already exists it is overwritten. While a big file copies, the rest of DVX and the program’s own events go on, as with DoEvents (in a control’s code they wait until the copy ends). A missing source raises error 53 (File not found), or 76 (Path not found) when its folder does not exist; a destination that cannot be made raises what OPEN would (76 for a missing folder, 75 for a read-only file); a copy the destination disk has no room for raises error 61 (Disk full). The copy is made beside the destination and takes its place only when it is complete, so a file already there is unchanged when the copy fails (replacing a file therefore needs room for the new copy beside the old one). The partial copy is removed, also when the program is ended from the Task Manager in the middle of the copy.
FILECOPY source$, destination$
FileCopy "data.db", "data.bak"
1.6.4. MKDIR / RMDIR
Creates or removes a directory. A directory that cannot be made or removed raises error 75 (Path/File access error); a drive with no disk in it raises 71 (Disk not ready).
MKDIR path$
RMDIR path$
MkDir App.Data & "\backups"
RmDir "C:\OLD"
1.6.5. CHDIR / CHDRIVE
CHDIR changes the current folder of the drive the path names (of the current drive when it names none), and CHDRIVE changes the current drive. As in Visual Basic, CHDIR leaves the current drive as it is: with C: current, CHDIR "D:\DATA" makes D:\DATA the folder D: is in (CURDIR$("D") gives it), and C: stays current until CHDRIVE "D". CHDIR to a directory that does not exist raises error 76 (Path not found), and CHDRIVE to a drive that is not there raises 68 (Device unavailable); either one on a drive with no disk in it raises 71 (Disk not ready) and leaves the current drive as it was.
CHDIR path$
CHDRIVE drive$
ChDir "C:\DVX\PROJECTS"
ChDrive "D"
ChDir "D:\DATA" ' D: stays current, now in D:\DATA
1.6.6. GETATTR / SETATTR
GETATTR returns the attributes of a file (as a function). SETATTR sets them (as a statement). Attributes are a bitmask of the vb file-attribute constants. A missing file raises error 53 (File not found); SETATTR raises error 75 when the attributes cannot be changed.
attrs = GETATTR(filename$)
SETATTR filename$, attrs
| Constant | Value | Attribute |
|---|---|---|
vbNormal |
0 |
Normal file (no attributes set) |
vbReadOnly |
1 |
Read-only |
vbHidden |
2 |
Hidden |
vbSystem |
4 |
System file |
vbDirectory |
16 |
Entry is a directory |
vbArchive |
32 |
File has been modified since last backup |
If (GetAttr("readme.txt") And vbReadOnly) <> 0 Then
Print "File is read-only."
End If
SetAttr "secret.dat", vbHidden + vbReadOnly
1.6.7. CURDIR$ / DIR$
CURDIR$ returns the current directory. CURDIR$(drive$) returns the current directory of the drive drive$ names (its first letter: CURDIR$("D") or CURDIR$("D:\")), as in Visual Basic; CURDIR$("") is CURDIR$. Each drive keeps its own current directory, which CHDIR on that drive sets; DVX reads what DOS keeps for the drive, so a drive with no disk in it gives the directory it last had. A drive that is not there raises error 68 (Device unavailable), and one that cannot be read when it is asked, error 71 (Disk not ready). DIR$ returns the first file matching a pattern; subsequent calls with no arguments return additional matches (or "" when done). DIR$ returns only files: never ".", "..", or subdirectories. The pattern uses DOS’s wildcards, as the file dialog does: * stands for any characters and ? for one, case does not matter, and *.* is every file, with or without an extension. DIR$("C:\*.*") lists the root of C: (DIR$("C:*.*") the drive’s current folder). A folder that does not exist lists nothing (""); a drive with no disk in it raises error 71 (Disk not ready). Looking through a big folder for a rare match lets the rest of DVX and the program’s own events go on, as with DoEvents; if one of those events starts a new DIR$ listing, the call returns "" (in a control’s code nothing else runs meanwhile).
cwd$ = CURDIR$
onD$ = CURDIR$("D") ' D:'s current directory
first$ = DIR$("*.txt")
WHILE first$ <> ""
Print first$
first$ = DIR$ ' next match, no argument
WEND
1.6.8. FILELEN
Returns the length of a file in bytes. A file that does not exist raises error 53 (File not found); one past 2 GB raises error 6 (Overflow).
bytes = FILELEN(filename$)
1.6.9. String Functions
A negative count or position passed to LEFT$, RIGHT$, MID$, SPACE$, or STRING$, or a count above 65535 passed to SPACE$ or STRING$, raises error 5 (Illegal function call). A count, position, or character code with a fraction is rounded first, as for every built-in (see Whole-Number Arguments): MID$(s$, 2.6) starts at 3, CHR$(65.5) is "B". INSTR without its compare argument follows the OPTION COMPARE of its file (TEXT: a case-insensitive search); its compare argument needs its start (INSTR(1, s$, find$, vbTextCompare)), as in Visual Basic. An INSTR start position below 1 raises error 5.
REPLACE$, JOIN$, and STRREVERSE$ may also be written without the $. Items in square brackets may be left out.
See also: Format Function (FORMAT$, FORMATNUMBER, FORMATCURRENCY, FORMATPERCENT, and FORMATDATETIME) (Section 1.6.10).
Comparing Text
The compare argument of FILTER, INSTR, INSTRREV, REPLACE$, SPLIT, and STRCOMP chooses how text is matched: vbBinaryCompare (0) matches exactly, vbTextCompare (1) ignores upper and lower case, and vbUseCompareOption (-1, the default) follows the OPTION COMPARE of the file the call is written in. Any other value raises error 5.
Print StrComp("apple", "Apple") ' 1 ("a" sorts after "A")
Print StrComp("apple", "Apple", vbTextCompare) ' 0
Print Replace$("Red red RED", "red", "blue", 1, -1, vbTextCompare) ' blue blue blue
Print InStrRev("C:\DVX\APPS\EDIT.APP", "\") ' 12
Print InStr(1, "Hello", "LL", vbTextCompare) ' 3
REPLACE$ Details
REPLACE$ returns the text from position start on, so REPLACE$("abcabc", "b", "x", 3) is "caxc" — the characters before start are left out, as in Visual Basic. A count of -1 replaces every occurrence. An empty find$ returns the text unchanged. A start below 1 or a count below -1 raises error 5.
SPLIT, JOIN$, and FILTER
SPLIT returns a string array numbered from 0. Assign it to a dynamic array (one declared with empty parentheses) and use UBOUND to find the last piece. The last piece keeps the rest of the text when limit stops the split. Splitting an empty string, or a limit of 0, gives an array with no elements: its UBOUND is -1. An empty delim$ gives the whole string as the only piece.
Dim parts() As String
Dim i As Integer
parts = Split("red,green,,blue", ",")
For i = 0 To UBound(parts)
Print i; "[" & parts(i) & "]" ' the empty third piece is kept
Next i
Print Join$(parts, " / ") ' red / green / / blue
JOIN$ works on any one-dimensional array; numbers are converted as CSTR converts them. FILTER returns a new string array holding the elements that contain match$ (include True, the default) or that do not contain it (include False), or an array with no elements when nothing matches. Passing JOIN$ or FILTER something that is not a one-dimensional array raises error 13 (Type mismatch).
INSTRREV Details
INSTRREV searches backward: INSTRREV("abcabc", "bc") is 5 and INSTRREV("abcabc", "bc", 4) is 2. A start of -1 (the default) searches from the end. It returns 0 when s$ is empty or start is past the end of s$, and start when find$ is empty. A start of 0 or below -1 raises error 5.
MID$ Assignment
MID$ can also be used on the left side of an assignment to replace a portion of a string without changing its length:
Mid$(s$, start [, length]) = replacement$
Dim s$
s$ = "Hello, World!"
Mid$(s$, 8, 5) = "DVX--"
Print s$ ' Hello, DVX--!
The target may be a variable, an array element, a TYPE field, or a Public member variable of an object or a form (Mid$(acct.Owner, 1, 3) = "Bob"). If length is omitted, MID$ replaces up to LEN(replacement$) characters; a length of 0 replaces nothing. The target string’s total length never changes — extra characters in replacement$ are truncated and shorter replacements leave trailing characters in place. A start position below 1 or a negative length raises error 5 (Illegal function call).
1.6.10. Format Function
s$ = FORMAT$(value [, format$ [, firstDayOfWeek [, firstWeekOfYear]]])
FORMAT$ lays out a number, a date or time, or text the way format$ describes, in Visual Basic’s format language: the characters described below, up to four sections separated by semicolons, and named formats such as "Currency" and "Long Date". FORMAT (without the $) is the same function. PRINT USING has a format language of its own, QBasic’s, and the two are not interchangeable: "###.##" pads with spaces in PRINT USING but not in FORMAT$.
DVX has no regional settings, so FORMAT$ always uses the United States ones: "." is the decimal point, "," the thousands separator, "$" the currency symbol (in front of the amount, a negative amount in parentheses), "/" the date separator, and ":" the time separator, and dates are written month first.
With no format, or an empty one, FORMAT$ gives the value’s plain text, as CSTR does: a number without the leading space STR$ puts before it, and with its 0 before the point (Format$(42) is "42", Format$(0.25) "0.25"), a date in the usual m/d/yyyy h:mm:ss AM form, text as it is, and True or False. Empty and Null give "" (Null gives "" with any format that has no section for it).
The first format character decides what kind of format format$ is: a digit placeholder (0, #, a point, a comma, or %) makes it a number format, a date or time code (d, w, m, q, y, h, n, s, c, ttttt, AM/PM) a date format, and @, &, <, >, or ! a text format. A character the kind of format gives no meaning to is copied as it is, so letters that are date codes, such as d, m, and s, are only safe in a number format after a backslash or in quotes: Format$(5, "0 \d\a\y\s") is "5 days", and so is Format$(5, "0 days"), but Format$(Date, "Date: yyyy") puts the day where the D is. A number format takes a date as its number of days and a date format a number as a date; text that holds a number (in the forms Numbers in Text lists: Format$("1,234", "0.00") is "1234.00") or a date is read as one, and text that holds none comes back unchanged (Format$("abc", "0.00") is "abc"). Only the first 257 characters of format$ are read, as in Visual Basic.
To copy a character as it is, write it after a backslash (\x), or put text between double quotes; in a program, each of those quotes is written twice: Format$(n, "0 ""kg""").
firstDayOfWeek and firstWeekOfYear choose how the w and ww codes count, as they do for DATEPART: vbSunday (the default) to vbSaturday, and vbFirstJan1 (the default), vbFirstFourDays, or vbFirstFullWeek; vbUseSystemDayOfWeek and vbUseSystem mean Sunday and the week that holds January 1. Another value raises error 5 (Illegal function call), as a Null format or Null week argument raises error 94.
Number Formats
| Character | Meaning |
|---|---|
0 |
A digit, or 0 where the number has none: leading and trailing zeros |
# |
A digit, or nothing where the number has none |
. |
The decimal point; with only # before it, a number below 1 starts with the point |
, |
Among the digits before the point: thousands separators. Right after them (before the point, or at the end of the digits): the number divided by 1000 for each comma, so "#,##0," shows 1234567 as 1,235 |
% |
The number times 100, the % written where it is in the format |
E+ E- e+ e- |
With a digit placeholder after it: scientific notation, the exponent with at least as many digits as there are 0s after the E; E+ always gives the exponent its sign, E- only a minus sign |
- + $ ( ) space |
Copied as they are |
\x |
The character x, copied as it is |
"text" |
The text between the double quotes, copied as it is |
The number is rounded to the places after the point that the format has, a half away from zero: Format$(2.5, "0") is "3" and Format$(0.125, "0.00") is "0.13". It is rounded as PRINT shows it (a Double’s 15 significant digits, a Single’s 7), so Format$(1.005, "0.00") is "1.01", where ROUND, which rounds the value as the computer holds it, gives 1. Digits before the point that the format has no placeholder for are shown all the same, at the first placeholder (Format$(12345, "00") is "12345"). A point written in the format is always shown, even with no digits after it (Format$(5, "#.##") is "5."). Literal characters may stand among the digits: Format$(5551234567, "(000) 000-0000") is "(555) 123-4567". In scientific notation the number has as many digits before the point as the format has placeholders there: Format$(123456, "0.0E+0") is "1.2E+5", and Format$(123456, "##0.0E+0") is "123.5E+3".
A number format can have up to four sections, separated by semicolons:
| Sections | Used for |
|---|---|
One |
Every number; a negative one gets a minus sign in front of everything: Format$(-5, "$0.00") is "-$5.00" |
Two |
Positive numbers and zero; then negative numbers, shown without the minus sign: Format$(-5, "$#,##0;($#,##0)") is "($5)" |
Three |
Positive; negative; zero |
Four |
Positive; negative; zero; Null |
A section left empty is the first section, with the minus sign for a negative number: "$#,##0;;\Z\e\r\o" shows -5 as "-$5" and 0 as "Zero". The value picks its section before it is rounded, so Format$(-0.001, "0.00") is "-0.00" and Format$(0.001, "0;-0;\n\o\n\e") is "0". A number with no section for Null gives "" for Null.
Print Format$(5459.4, "##,##0.00") ' 5,459.40
Print Format$(334.9, "###0.00") ' 334.90
Print Format$(5, "0.00%") ' 500.00%
Print Format$(-5, "$#,##0.00;($#,##0.00)") ' ($5.00)
Print Format$(0.5, "#.##") ' .5
Print Format$(100000000, "##0,,") ' 100
Print Format$(0.00012, "0.00E+00") ' 1.20E-04
Print Format$(0, "0;-0;\n\o\n\e") ' none
Named Number Formats
| Name | Format it is | 1234.5 | -1234.5 |
|---|---|---|---|
General Number |
The plain number |
1234.5 |
-1234.5 |
Currency |
$#,##0.00;($#,##0.00) |
$1,234.50 |
($1,234.50) |
Fixed |
0.00 |
1234.50 |
-1234.50 |
Standard |
#,##0.00 |
1,234.50 |
-1,234.50 |
Percent |
0.00% |
123450.00% |
-123450.00% |
Scientific |
0.00E+00 |
1.23E+03 |
-1.23E+03 |
Yes/No |
No for 0, else Yes |
Yes |
Yes |
True/False |
False for 0, else True |
True |
True |
On/Off |
Off for 0, else On |
On |
On |
The names may be written in any case ("percent"). Text that holds no number comes back unchanged.
Date and Time Formats
A date format takes a Date, a number (a date’s number of days), or text that holds a date (text that holds none comes back unchanged), and uses only its first section. The codes may be written in upper or lower case.
| Code | Result |
|---|---|
d / dd |
Day of the month (dd: two digits) |
ddd / dddd |
Weekday name, abbreviated (Mon) or full (Monday) |
ddddd |
Short date (m/d/yyyy) |
dddddd |
Long date (dddd, mmmm d, yyyy) |
w |
Day of the week (1 for firstDayOfWeek, Sunday unless it is given) |
ww |
Week of the year (week 1 as firstWeekOfYear says: the week holding January 1 unless it is given) |
m / mm |
Month number (mm: two digits); the minute when it comes right after an hour (h:mm), as in Visual Basic |
mmm / mmmm |
Month name, abbreviated (Jan) or full (January) |
q |
Quarter (1-4) |
y |
Day of the year (1-366) |
yy / yyyy |
Year as two or four digits |
h / hh |
Hour (hh: two digits); 1-12 when the format has AM/PM, else 0-23 |
n / nn |
Minute |
s / ss |
Second |
ttttt |
Long time (h:mm:ss AM/PM) |
c |
The usual date and time form: the date alone at midnight, the time alone for a time with no date |
AM/PM am/pm |
AM or PM in the case written; A/P and a/p give one letter; AMPM gives AM or PM |
/ and : |
The date and the time separators |
"text" |
Text in double quotes is copied as it is |
\x |
The character after a backslash is copied as it is |
Write nn for minutes where no hour comes before them: Format$(t, "nn:ss") gives the minutes and the seconds, but "mm:ss" gives the month and the seconds, as in Visual Basic. A run of one letter is the longest code it starts with and then the rest: "yyy" is yy and y (the year’s two digits, then the day of the year). Any other character, such as - , or a space, is copied as it is. These names give whole formats:
| Name | Format | Example |
|---|---|---|
General Date |
(the usual form) |
1/5/2000 3:04:05 PM |
Long Date |
dddd, mmmm d, yyyy |
Wednesday, January 5, 2000 |
Medium Date |
dd-mmm-yy |
05-Jan-00 |
Short Date |
m/d/yyyy |
1/5/2000 |
Long Time |
h:mm:ss AM/PM |
3:04:05 PM |
Medium Time |
hh:mm AM/PM |
03:04 PM |
Short Time |
hh:mm |
15:04 |
Dim d As Date
d = #1/5/2000 3:04:05 PM#
Print Format$(d, "yyyy-mm-dd hh:nn:ss") ' 2000-01-05 15:04:05
Print Format$(d, "dddd, mmmm d") ' Wednesday, January 5
Print Format$(d, "h:mm AM/PM") ' 3:04 PM
Print Format$(d, "Long Date") ' Wednesday, January 5, 2000
Print Format$(d, "w", vbMonday) ' 3
Print Format$(Now, "Short Time") ' the time now, e.g. 09:41
Text Formats
| Character | Meaning |
|---|---|
@ |
A character, or a space where the text has none |
& |
A character, or nothing where the text has none |
< |
The text in lower case |
> |
The text in upper case |
! |
Fill the placeholders from the left (they are filled from the right otherwise) |
A number or a date is formatted as its plain text. The placeholders take the text’s characters in order. When the text is shorter, the placeholders that get none are on the left, or with ! on the right: Format$("ab", "@@@@") is " ab" and Format$("ab", "!@@@@") is "ab ". When it is longer, the characters left over come after the last placeholder, or with ! the first ones are left out: Format$("123", "ab@c") is "ab1c23" and Format$("123", "!ab@c") is "ab3c". A text format can have two sections: the first is for text, the second for "" and Null (Format$("", "@;\n\o\n\e") is "none"); without a second section Null gives "".
Print Format$("465043799", "@@@-@@-@@@@") ' 465-04-3799
Print Format$("HELLO", "<") ' hello
Print Format$("This is it", ">") ' THIS IS IT
FORMATNUMBER, FORMATCURRENCY, FORMATPERCENT, and FORMATDATETIME
s$ = FORMATNUMBER(n [, digits [, leadingDigit [, parens [, group]]]])
s$ = FORMATCURRENCY(n [, digits [, leadingDigit [, parens [, group]]]])
s$ = FORMATPERCENT(n [, digits [, leadingDigit [, parens [, group]]]])
s$ = FORMATDATETIME(d [, namedFormat])
These are Visual Basic 6’s. FORMATNUMBER shows n with digits places after the point (-1, the default, means two), FORMATCURRENCY shows it as an amount of money, with $ in front, and FORMATPERCENT shows it times 100 with a % after it. leadingDigit, parens, and group are vbTrue, vbFalse, or vbUseDefault (the default): whether a number below 1 has a 0 before the point (by default it has), whether a negative number is in parentheses rather than after a minus sign (by default only an amount is), and whether thousands are separated by commas (by default they are). n must be a number or text that holds one (error 13 otherwise, error 94 for Null), and digits 0 to 99 (error 5 otherwise).
FORMATDATETIME shows date d (a Date, a number, or text that holds a date) as namedFormat says: vbGeneralDate (0, the default: the date and the time, the date alone at midnight, and the time alone on no date), vbLongDate (1), vbShortDate (2), vbLongTime (3), or vbShortTime (4, a 24-hour hh:mm). Another namedFormat raises error 5.
Print FormatNumber(1234.567) ' 1,234.57
Print FormatNumber(0.5, 2, vbFalse) ' .50
Print FormatNumber(-5, 0, , vbTrue) ' (5)
Print FormatCurrency(-1234.5) ' ($1,234.50)
Print FormatPercent(0.125, 1) ' 12.5%
Print FormatDateTime(#1/5/2000 3:04 PM#, vbLongDate) ' Wednesday, January 5, 2000
1.6.11. Math Functions
RND follows QBasic: RND or RND(n) with n > 0 returns the next number in the sequence, RND(0) repeats the last number, and RND(n) with n < 0 reseeds the generator from n (the same n always gives the same number). The result is a Single, 0 <= RND < 1, as in QBasic and Visual Basic.
ROUND is Visual Basic 6’s: it rounds a half to the even digit (banker’s rounding), so ROUND(2.5) is 2, ROUND(3.5) is 4, and ROUND(0.125, 2) is 0.12, and it rounds the value as the computer holds it, so ROUND(1.005, 2) is 1 (1.005 is held as a little less). d must be 0 or more (error 5 otherwise); a Currency is rounded exactly. Like ABS, it returns a value of its argument’s type, and Null gives Null. A program that has a FUNCTION Round of its own (written for Visual Basic 3, which had none) calls its own.
ABS, INT, and FIX return a value of their argument’s own type, as in Visual Basic: an Integer for an Integer, a Long for a Long, a Single for a Single, a Double for a Double, a Currency for a Currency (exactly), a Byte for a Byte, and a Date for a Date (INT(NOW) is today’s date); for a Variant the type it holds. A Boolean and Empty give an Integer, text the Double it reads (error 13 when it is not a number), and Null gives Null. ABS of the most negative Integer, Long, or Currency (ABS(-32768%)) raises error 6 (Overflow), since the result does not fit the type. SGN always returns an Integer. EXP, ^, and the other functions raise error 6 (Overflow) when the result leaves the numeric range, and error 5 when it is undefined (for example a negative number to a fractional power).
|
Note
|
Use RANDOMIZE or RANDOMIZE TIMER to seed the generator so you don’t get the same sequence each run. |
Color Functions
The color functions work with 24-bit colors packed into a Long the way Visual Basic packs them, &HBBGGRR: red is the low byte, green the middle byte, and blue the high byte. RGB(255, 0, 0) and &HFF are red, RGB(0, 0, 255) and &HFF0000 are blue. ForeColor, BackColor, FillColor, the drawing methods of forms and picture boxes (PSet, Line, Circle, Point), the Canvas control, and the color dialog all use this form (the console graphics statements of SCREEN modes use QBasic color numbers instead), as do the color constants vbBlack, vbRed, vbGreen, vbYellow, vbBlue, vbMagenta, vbCyan, and vbWhite (see Predefined Constants).
| Function | Returns | Description |
|---|---|---|
RGB(r, g, b) |
Long |
Combine red, green, and blue components (0-255) into a color: r + g * 256 + b * 65536 |
QBCOLOR(n) |
Long |
The color of QBasic color number n (0 to 15: 0 black, 1 blue, 2 green, 4 red, 7 white, 8 gray, 15 bright white, ...); error 5 for any other number |
GETRED(color) |
Integer |
Red component (0-255) of a color |
GETGREEN(color) |
Integer |
Green component (0-255) of a color |
GETBLUE(color) |
Integer |
Blue component (0-255) of a color |
Dim c As Long
c = RGB(255, 128, 0) ' bright orange, &H0080FF
Print GetRed(c); GetGreen(c); GetBlue(c) ' 255 128 0
Me.BackColor = RGB(0, 0, 128) ' dark blue background
Me.ForeColor = QBColor(14) ' yellow
1.6.12. Conversion Functions
Passing Null to any of these except CVAR raises error 94 (Invalid use of Null). Text passed to one that gives a number must hold a number (CINT("12") is 12); other text raises error 13 (Type mismatch). VARTYPE, TYPENAME, and the IS functions (ISNULL, ISEMPTY, ISNUMERIC, ...) are described under Variants.
Numbers in Text
Text converts to a number as in Visual Basic (with United States settings) wherever a number is needed from it: CBOOL, CBYTE, CCUR, CDBL, CINT, CLNG, CSNG, a store into a numeric variable, arithmetic and comparisons with text, ISNUMERIC, FORMAT$ given text, and text given to a numeric or Boolean property of a control. The text must be a number as a whole, and may have:
-
blanks before and after it, and between a leading sign and the digits (" - 12 " is -12)
-
a sign before or after the digits ("12-" is -12)
-
a dollar sign ("$1,234.50" is 1234.5)
-
commas between the digits of the whole part ("1,234,567" is 1234567)
-
parentheses for an amount below zero ("(12)" is -12)
-
a decimal point, and an E or D exponent ("1.5E3" and "1.5D3" are 1500)
-
&H or &O before hexadecimal or octal digits ("&HFF" is 255)
Text that is anything else, an empty string included, raises error 13 (Type mismatch). VAL is different, as in Visual Basic: it reads the number the text starts with and stops at the first character that cannot continue it (a comma, a dollar sign), and leaves out the blanks, tabs, and line feeds anywhere in the text: VAL("1,234") is 1, VAL(" 1 2 3") is 123, VAL("$5") is 0, and VAL("12abc") is 12. INPUT and INPUT # read a number into a numeric variable as far as a blank, so "1 2" reads as 1 (and a type-declaration character is no part of it).
VAL reads a type-declaration character right after the number (% Integer, & Long, ! Single, # Double, @ Currency, $ String) as Visual Basic’s does, as the type of a literal written with it: VAL("50%") is 50, VAL("12&abc") is 12, VAL("1.5!") is 1.5, VAL("1.1!") is the Single 1.1 (1.10000002384186 as the Double VAL gives), and VAL("1.23456@") is 1.2346. A form the type has no literal of raises error 13 (Type mismatch): a point or an exponent before % or & (VAL("50.5%"), the example Microsoft gives), an &H or &O number before !, #, or @, and any number before $. A value past the type’s range raises error 6 (Overflow): VAL("40000%"), VAL("3000000000&"). An &H or &O number before % is a 16-bit Integer, as in Visual Basic: VAL("&HFFFF%") is -1, while VAL("&HFFFF") and VAL("&HFFFF&") are 65535. (Visual Basic’s documentation gives only the 50% and 50.5% cases; the others follow its literal rules.)
See also: Variants (Section 1.2).
1.6.13. Date and Time Functions
These functions work with Date values (see Data Types). Wherever a date is expected, a Date, a number of days since 12/30/1899, or a string holding a date may be given; text that is not a date raises error 13 (Type mismatch).
| Function | Returns | Description |
|---|---|---|
NOW |
Date |
The current date and time |
DATE |
Date |
Today’s date (at midnight) |
TIME |
Date |
The current time of day (on 12/30/1899) |
DATESERIAL(year, month, day) |
Date |
The date with those parts |
TIMESERIAL(hour, minute, second) |
Date |
The time with those parts |
DATEVALUE(d) |
Date |
The date part of d (its time dropped) |
TIMEVALUE(d) |
Date |
The time part of d (on 12/30/1899) |
YEAR(d) |
Integer |
Year (100-9999) |
MONTH(d) |
Integer |
Month (1-12) |
DAY(d) |
Integer |
Day of the month (1-31) |
WEEKDAY(d [, firstDay]) |
Integer |
Day of the week, 1 for firstDay (default vbSunday) |
HOUR(d) |
Integer |
Hour (0-23) |
MINUTE(d) |
Integer |
Minute (0-59) |
SECOND(d) |
Integer |
Second (0-59) |
DATEADD(interval$, n, d) |
Date |
d moved by n intervals (n may be negative) |
DATEDIFF(interval$, d1, d2 [, firstDay [, firstWeek]]) |
Long |
Intervals from d1 to d2 (negative when d2 is earlier) |
DATEPART(interval$, d [, firstDay [, firstWeek]]) |
Integer |
One part of d |
ISDATE(v) |
Boolean |
True when v is a Date or a string holding a valid date |
MONTHNAME(month [, abbreviate]) |
String |
January ... December (Jan ... Dec when abbreviate is True) |
WEEKDAYNAME(n [, abbreviate [, firstDay]]) |
String |
Name of day n of the week counted from firstDay (default vbSunday) |
NOW, DATE, and TIME need no parentheses. DATE$ and TIME$ still return the date and time as text.
Intervals
DATEADD, DATEDIFF, and DATEPART take the interval as a string, in upper or lower case:
| Interval | Meaning |
|---|---|
"yyyy" |
Year |
"q" |
Quarter |
"m" |
Month |
"y" |
Day of the year |
"d" |
Day |
"w" |
Weekday |
"ww" |
Week |
"h" |
Hour |
"n" |
Minute |
"s" |
Second |
Any other interval raises error 5 (Illegal function call).
DATESERIAL and TIMESERIAL
A year from 0 to 29 means 2000 to 2029 and one from 30 to 99 means 1930 to 1999. Months, days, hours, minutes, and seconds outside their usual range carry into the next or previous unit, so DATESERIAL(2000, 13, 1) is 1/1/2001, DATESERIAL(2000, 3, 0) is the last day of February 2000, and TIMESERIAL(0, 90, 0) is 1:30 AM. Fractional arguments are rounded. A result before 1/1/100 or after 12/31/9999 raises error 5.
Dim lastDay As Date
lastDay = DateSerial(Year(Date), Month(Date) + 1, 0) ' last day of this month
Print Day(lastDay)
DATEADD
Adding months, quarters, or years keeps the day of the month where it can; when the new month is shorter the day becomes its last day, so DATEADD("m", 1, #1/31/2000#) is 2/29/2000. The time of day is kept. "y", "d", and "w" all add days and "ww" adds weeks. A fractional n drops its fraction. A result outside the Date range raises error 5.
Print DateAdd("m", 1, #1/31/2001#) ' 2/28/2001
Print DateAdd("h", -2, #1/1/2000#) ' 12/31/1999 10:00:00 PM
DATEDIFF
DATEDIFF counts how many interval boundaries lie between d1 and d2: DATEDIFF("yyyy", #12/31/1999#, #1/1/2000#) is 1 although the dates are a day apart, and DATEDIFF("d", ...) counts midnights, whatever the times of day. "w" counts whole weeks (7 days) and "ww" counts calendar weeks — the number of firstDay days (Sundays by default) after d1 up to and including d2. A result too large for a Long raises error 6 (Overflow).
Print DateDiff("d", #1/1/2000#, #3/1/2000#) ' 60
Print DateDiff("ww", #1/1/2000#, #1/2/2000#) ' 1 (1/2/2000 is a Sunday)
Print DateDiff("w", #1/1/2000#, #1/2/2000#) ' 0
DATEPART and Weeks of the Year
DATEPART returns the part of d the interval names: "w" is the day of the week (1 for firstDay) and "ww" the week of the year. firstDay is one of vbSunday (1, the default) to vbSaturday (7), or vbUseSystemDayOfWeek (0, meaning Sunday). firstWeek chooses which week is week 1:
| Constant | Value | Week 1 is |
|---|---|---|
vbUseSystem |
0 |
Same as vbFirstJan1 |
vbFirstJan1 |
1 |
The week holding January 1 (the default) |
vbFirstFourDays |
2 |
The first week with at least four days in the new year |
vbFirstFullWeek |
3 |
The first full week of the year |
Days before week 1 belong to the last week of the previous year. A firstDay or firstWeek outside these values raises error 5.
Print DatePart("q", #5/15/2000#) ' 2
Print DatePart("ww", #1/1/2000#, vbSunday, vbFirstFourDays) ' 52
ISDATE, MONTHNAME, and WEEKDAYNAME
ISDATE is True for a Date and for a string that holds a valid date or time; numbers are not dates to ISDATE. MONTHNAME with a month outside 1 to 12, and WEEKDAYNAME with n outside 1 to 7, raise error 5.
If IsDate(Text1.Text) Then due = CDate(Text1.Text)
Print MonthName(Month(Date)); " "; WeekdayName(Weekday(Date), True)
1.6.14. File I/O Functions
The dim argument of LBOUND and UBOUND may be any expression (a variable, a constant), rounded as CLNG rounds it; a dimension the array does not have raises error 9.
INPUT$, CURDIR$, and DIR$ may also be written without the $, as in Visual Basic: Input(n, #channel), CurDir, CurDir(drive$), Dir(pattern$), and Dir give the same text (PUT stores it as a Variant; see GET / PUT).
File sizes and positions are Longs, so they stop at 2 GB (2,147,483,647 bytes). A disk can hold bigger files (up to 4 GB on FAT32); LOF, FILELEN, LOC, and SEEK raise error 6 (Overflow) for a size or position past 2 GB rather than give a wrong number, and GET and PUT do the same for a record that would end past it. EOF stays right while the position is below 2 GB. FileOpsListSize and FileOpsTreeBytes (fileops.bas) give any file’s size as a Double.
1.6.15. Miscellaneous Functions
DATE$ and TIME$ return text; the Date and Time Functions return Date values. ENVIRON$ and COMMAND$ may also be written without the $, as in Visual Basic (Environ, Command; PUT stores what they give as a Variant).
IIF and CHOOSE
IIF and CHOOSE evaluate every argument before picking one, as in Visual Basic, so a function called in an argument runs even when its value is not chosen. A fractional n in CHOOSE drops its fraction (2.9 picks the second value). An n below 1 or past the end of the list gives Null, as in Visual Basic (test it with ISNULL; see Variants).
Print IIf(score >= 50, "Pass", "Fail")
Print Choose(Weekday(Date), "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
LOADPICTURE
LOADPICTURE(file$) reads a picture file (BMP, PNG, JPEG, or GIF) — or the icon of a DVX program, widget, or library file (.app, .wgt, .lib) — and returns a Picture object (TypeName "Picture") that can be given to a picture property: a control’s DragIcon, the Picture of an Image or ImageButton. Use SET, or a plain assignment, as with a file name; file names still work too. LOADPICTURE() or LOADPICTURE("") gives an empty picture, which clears the property. A missing file raises error 53 (File not found), a file that is not a picture error 481 (Invalid picture), so the check happens where the picture is loaded. The check reads the picture’s header only (the control that shows it reads the rest): a picture file damaged after its header shows nothing. Loading the same file again gives the same Picture object. Reading a picture property back gives a Picture object too (TypeName "Picture"), as in Visual Basic; used as a value (printed, joined to text, compared) it stands for its file name, so code that treats the property as a file name keeps working. The name of a program, widget, or library file works wherever a picture file’s name does (a Picture property, DragIcon, PaintPicture, a Toolbar’s AddButton) and shows its icon; such a file without an icon is not a picture (error 481).
The optional size and colordepth arguments are Visual Basic’s: size is vbLPSmall (0), vbLPLarge (1), vbLPSmallShell (2), vbLPLargeShell (3), or vbLPCustom (4, with x and y giving the size), colordepth vbLPDefault (0), vbLPMonochrome (1), vbLPVGAColor (2), or vbLPColor (3). They choose among the images of an icon file; every DVX picture is a single bitmap, so, as for a bitmap in Visual Basic, they are checked and otherwise make no difference. A value outside these, or a negative x or y, raises error 5.
A Picture object has three properties, which can only be read:
| Property | Type | Description |
|---|---|---|
Width |
Long |
The picture’s width in HiMetric units (hundredths of a millimeter), as in Visual Basic; 0 for an empty picture. |
Height |
Long |
The picture’s height in HiMetric units; 0 for an empty picture. |
Type |
Integer |
vbPicTypeBitmap (1) for a loaded picture, vbPicTypeNone (0) for an empty one. |
The HiMetric sizes assume a standard display of 96 pixels an inch (the same as ScaleMode), so a pixel is about 26.46 HiMetric units. Convert them to pixels or another scale with a form’s or PictureBox’s ScaleX and ScaleY methods (see Drawing on Forms and PictureBoxes). Visual Basic’s Handle property and Render method are not available: DVX pictures have no system handle.
Set Label1.DragIcon = LoadPicture("drag.bmp")
Image1.Picture = LoadPicture("logo.bmp")
Set Label1.DragIcon = LoadPicture() ' back to the dotted outline
Dim pic As Object
Set pic = LoadPicture("logo.bmp")
Print Me.ScaleX(pic.Width, vbHimetric, vbPixels); "x"; _
Me.ScaleY(pic.Height, vbHimetric, vbPixels)
LOADPICTUREDATA
LOADPICTUREDATA(bytes$) does what LOADPICTURE does for a picture held in a string rather than in a file: the bytes of a BMP, PNG, JPEG, or GIF file, such as HttpBody$ gives for a picture downloaded from the web, or ResGetData$ for a picture resource of a DVX program, widget, or library file (any of its resources, not only its icon). The Picture object it returns goes wherever a LOADPICTURE picture goes: the Picture of an Image, an ImageButton, or a PictureBox, a control’s DragIcon, a form’s Icon, and PaintPicture; reading such a property back gives the same object. Its Width, Height, and Type are a loaded picture’s; used as a value it stands for "", since it has no file name. Bytes that are not a picture raise error 481 (Invalid picture); LOADPICTUREDATA("") gives an empty picture. Giving one to a control that shows no picture (a Label’s Picture, for example) stops the program with an error.
A Picture object made this way keeps its bytes until the program ends, and the same bytes give the same object, so loading a picture again costs nothing. To show many different pictures one after another (a slide show, pictures from the web), use the SetPictureData method of the Image, ImageButton, or PictureBox instead: Image1.SetPictureData bytes$ shows the picture without keeping it, and returns True, or False when the bytes are not a picture.
Image1.Picture = LoadPictureData(HttpBody$(req))
' ResGetData$ is in resource.bas, which the project must have
Set Label1.DragIcon = LoadPictureData(ResGetData$("mygame.app", "card"))
If Not Picture1.SetPictureData(HttpBody$(req)) Then MsgBox "That is not a picture."
Program Resources
A program carries files of its own as resources, as a Visual Basic program carries its resource file: pictures, sounds, levels, any bytes, and a string table of the texts it shows. List them on the Resources page of Project Properties: the Files list (Add... and Remove), and the String Table, a text file. Make Executable builds them into the .app, so the program needs no other file to find them; a run from the IDE reads them from the project’s folder, where they are.
LOADRESPICTURE(id, format) gives a Picture object of the resource file named id, as LOADPICTUREDATA gives one of bytes; LOADRESDATA(id, format) gives the file’s bytes as a String (CHR$(0) included). id is the file’s name without its extension, in any case: "Logo" finds logo.bmp; a number finds the file named with it (LOADRESDATA(101) finds 101.dat). The name before the extension has at most 27 characters, and two files of the project cannot share it (Project Properties and Make refuse the second). format is Visual Basic’s resource type (vbResBitmap (0), vbResIcon (1), or vbResCursor (2) for LOADRESPICTURE; a number or a custom type’s name for LOADRESDATA); DVX’s resources know what they are, so it is accepted and makes no difference. It may be left out.
LOADRESSTRING(id) gives the text of id in the string table: a text file of lines id = text, where id is a number or a name (101 = Hello, or Greeting = Hello). Spaces around the = do not count; to keep spaces at the start or end of a text, put it in double quotes (" indented"). Blank lines and lines starting with ', ;, or # are left out, so the table can hold notes. A program translated into another language needs only another string table.
An id the program has no resource for raises error 326 (Resource with identifier not found), so ON ERROR can try one and fall back to another.
Image1.Picture = LoadResPicture("Logo", vbResBitmap)
Label1.Caption = LoadResString(101)
Me.Caption = LoadResString("Title")
Dim level As String
level = LoadResData("Level1")
Print Len(level); "bytes"
A string table:
' My program's texts
101 = Hello there
Title = " My Program "
COMMAND$
COMMAND$ returns the program’s arguments exactly as they were given, as in Visual Basic (QBasic turned them into capitals; DVX keeps them as they are). Arguments are separated by blanks; an argument with blanks in it is written in double quotes. COMMAND$(n) picks out one argument with its quotes removed, so a program that opens the document it was started with only needs:
IF COMMAND$(1) <> "" THEN
OpenFile COMMAND$(1)
END IF
A program gets arguments when a document of a type associated with it is opened (the document is the argument), from a Program Manager item’s Arguments, or from a command typed in a Run box. When the program runs in the IDE, COMMAND$ returns the Arguments set in Project Properties. A negative n is error 5 (Illegal function call).
1.7. Form and Control Statements
DVX BASIC supports Visual Basic-style forms and controls for building graphical user interfaces. A form is normally designed visually in the IDE and saved as a .frm file, but forms and their controls can also be built entirely in code.
1.7.1. Loading and Unloading Forms
LOAD FormName
LOAD Me
LOAD formVariable
UNLOAD FormName
UNLOAD Me
UNLOAD formVariable
LOAD ControlName(index)
UNLOAD ControlName(index)
LOAD and UNLOAD with a control’s or menu item’s name and an index (LOAD Text1(3), UNLOAD mnuRecent(i), LOAD Form2.Btn(1)) add and remove elements of a control array or a menu control array, as in Visual Basic; see Control Arrays.
LOAD creates the form and its controls in memory. It fires the form’s Load event (Form1_Load for a form named Form1) when the form is first loaded. UNLOAD destroys the form’s window and controls, firing its QueryUnload event and then its Unload event, as in Visual Basic; either can cancel the close (Sub Form1_Unload(Cancel As Integer): Cancel = 1 keeps the form loaded; a handler without the parameter just runs). QueryUnload’s UnloadMode is vbFormCode for UNLOAD (see Form Events in the Form topic). As in Visual Basic, the program’s form keeps its form-level variables: the next LOAD (or use of its name) runs its Load event with them as they were, until SET FormName = Nothing frees them (see SET). A copy made with New has its variables freed once nothing refers to it any more. A form instance’s Initialize event (Form1_Initialize) runs as the instance is made — the first use of the form’s name, New, or LoadFormText — before its Load, and its Terminate event once it is gone (see Form Events in the Form topic). The form name here is the literal name of the form as it appears in its .frm file; UNLOAD Me unloads the form whose event handler is running. The handler’s code goes on after UNLOAD Me, and Me still means the form, as in Visual Basic: Me.Show, or a use of one of its properties or controls, loads it again, with its Load event and the variables it kept. LOAD and UNLOAD also take Me, a Form variable (Dim f As Form2), an Object holding a form, or anything else that gives a form (for example a form made with CreateForm and kept in an object’s property): LOAD loads the form instance it refers to, as in Visual Basic — a copy New made (Set f = New Form2: Load f), or the program’s form taken as a reference (Set f = Form2) — running its Load event and not showing it; LOAD of a form that is loaded does nothing. LOAD of an object that is no form (a control, a class instance, a Collection) raises error 361 (Can’t load or unload this object), of Nothing error 91; a value that cannot be an object (a number, a string) does not compile. Once a form is unloaded, LOAD or any use of its name (a property, a control, Show) loads it again with its Load event, as in Visual Basic, even while code that ran the UNLOAD is still running; a second UNLOAD of the same form does nothing.
As in Visual Basic, a program starts with its startup form only (the project’s Startup Form, else its first form): that form is loaded, its Load event runs, and it is shown, before the program’s module-level code runs. Every other form is loaded the first time the program refers to it: LOAD, Show, or the use of any of its properties, methods, or controls (Form2.Caption, Form2.Text1.Text) loads it first, with its Load event, so a form the program never uses costs nothing. Taking it as an object does not load it, as in Visual Basic: Set f = Form2, Form2 given for an object parameter, and f Is Form2 make a reference to the form, which loads at the first use of a property, method, or control through it (f.Caption, f.Show); the reference means the form whether it is loaded or not, so after UNLOAD a use of it loads the form again. UNLOAD of a form that is not loaded does nothing (it is not loaded first). A form’s name always means the program’s own form of that name: a copy made with New (Dim f As New Form2, or Set f = New Form2) is a form of its own, and using the name Form2 afterwards loads the program’s Form2 if it is not loaded yet. A control’s name used without its form (Text1 rather than Form2.Text1) is the form’s own control in the form’s code; in other code it is looked for on the forms that are loaded and must be on exactly one of them (error 1001 otherwise; see How Names Are Found).
1.7.2. Showing and Hiding Forms
FormName.Show [mode]
FormName.Hide
Me.Show [mode]
Me.Hide
Pass vbModal (1) to Show for a modal dialog that blocks until the user closes it. Omit the mode for a modeless (non-blocking) window.
Form2.Show vbModal
Me.Hide
Show and Hide work the same through a variable that holds a form (f.Show). When the compiler knows the object is a form — the form’s name, Me in a form’s code, or a variable declared As the form’s name — they are the form’s own, and the mode must be a whole number, True or False, or a numeric CONST such as vbModal. Through a variable As Object or As Form they are found by their names when the line runs, as any method is (the mode may then be any expression): a form shows or hides, and an object of a class with a Public Show or Hide of its own runs that procedure.
1.7.3. Property Access
Read and write control properties using dot notation:
ControlName.Property = value
value = ControlName.Property
Text1.Text = "Hello"
Label1.Caption = "Name: " & name$
x = Text1.Left
A control on another form is reached through that form’s name, or through a variable holding a form reference: FormName.ControlName.Property works in both assignments and expressions, and so does FormName.ControlName.Method. Me.ControlName.Property does the same for the current form. A control named through a form is that form’s: another loaded form’s control of the name is never used.
Using a property or method (or Show or Hide) on a variable that holds Nothing raises error 91 (Object variable not set), and on a value that is not an object at all error 424 (Object required); Unload of Nothing does nothing. In the IDE, a property or method name that the control’s type does not have is reported when the program is compiled; a member no form has is reported for a form’s name (Form2.Xyzzy) or a variable As the form in every build.
Form2.Label1.Caption = "From Form1"
total = Form2.List1.ListCount
Form2.List1.Clear
A form has Enabled too: Form1.Enabled = False makes the whole form take none of the user’s input, its window’s title bar and close box included, and draws its controls disabled, as in Visual Basic (see Form Properties in the Form topic).
Setting a container’s Enabled (a Frame’s, a PictureBox’s) to False disables every control inside it: they take no mouse or keyboard input and are drawn disabled (grayed), and they come back when it is set to True again, each control’s own Enabled staying what it was. Visual Basic 6 leaves the controls in a disabled Frame looking enabled; DVX grays them, as Windows Forms does.
1.7.5. Me Keyword
Me refers to the current form — that is, the form whose event handler is running. Use it to access the form’s own properties, controls, and methods from within event handlers, especially when the form’s name may change or when the same code runs from multiple forms. In the code of a class module, Me is instead the object whose procedure is running (see Objects and Class Modules).
Me.Caption = "Updated Title"
Me.Text1.Text = ""
Me.Hide
1.7.6. Nothing
Nothing is a null object reference. Assign it with SET to an object variable to indicate "no object", and test for it with Is. An object variable that has not been Set holds Nothing, and using a property or method of Nothing raises error 91 (Object variable not set).
Set myCtrl = Nothing
If myCtrl Is Nothing Then Print "No control chosen"
Setting the last variable that refers to a class instance or Collection to Nothing frees the object; see Objects and Class Modules.
1.7.7. Control Arrays
Multiple controls can share a name with unique indices (the Index line of each in the .frm file, 0 to 32767), and so can menu items: a menu control array (see Menu System in the controls help). Access individual elements with parenthesized indices; an index the array has no element for raises error 340 (Control array element doesn’t exist), as in Visual Basic. An element’s Index property reads its index; Index of a control or menu item in no array raises error 343 (Object not an array), and setting it in code error 382 (only the .frm file sets it). The elements share their event handlers, which get the element’s Index first (Sub Btn_Click(Index As Integer)).
Option1(0).Value = True
Label1(idx).Caption = "Item " & idx
Me.Label1(i).Visible = True
LOAD name(index) adds an element to the array while the program runs, as in Visual Basic: a copy of the array’s lowest element as the form file made it (its design-time properties: what the program has changed since is not copied) that starts hidden (set its Visible to True to show it). A control gets those properties — its text, size, colors, font, Tag, and the others — and its place after the array’s last element in that element’s container; a menu item gets the caption, check mark, and Enabled (not the Shortcut: a key runs one item) and its place right after the array’s last element in its menu. UNLOAD name(index) removes an element LOAD made. LOAD of an element that is there raises error 360 (Object already loaded), UNLOAD of one that is not error 340, UNLOAD of one the .frm file made error 362 (Can’t unload controls created at design time), an index after a control or menu item in no array error 343, and LOAD or UNLOAD of a control named alone error 361 (Can’t load or unload this object). The array is looked for as a control named alone is (see How Names Are Found), or on the form named before it (LOAD Form2.Btn(1)).
' A recent-files list: mnuRecent(0) is a separator in the .frm file,
' Visible = False; each file gets an element after it
Dim recentCount As Integer
Sub ShowRecent(files() As String, count As Integer)
Dim i As Integer
For i = 1 To recentCount
Unload mnuRecent(i)
Next
mnuRecent(0).Visible = count > 0
For i = 1 To count
Load mnuRecent(i)
mnuRecent(i).Caption = "&" & i & " " & files(i)
mnuRecent(i).Visible = True
Next
recentCount = count
End Sub
Sub mnuRecent_Click(Index As Integer)
Print "Open file"; Index
End Sub
1.7.8. WITH
The WITH block provides a shorthand for setting several properties on the same control or for making several method calls. Inside the block, begin each property or method with a dot and omit the control name.
WITH ControlName
.Property1 = value1
.Property2 = value2
.Method arg1, arg2
END WITH
With Label1
.Caption = "Status: Ready"
.ForeColor = RGB(0, 128, 0)
.Visible = True
End With
WITH also takes a form (With Form2, With Me), an object, or a TYPE record, such as a form’s Public TYPE variable (With Form2.Pos); see WITH...END WITH in Objects and Class Modules. With Form2 holds the form it names when the block starts, whatever SET does to the name inside the block.
1.7.9. Building Forms in Code
In addition to loading forms from .frm files, you can build a form entirely from code with CreateForm, CreateControl, SetEvent, and RemoveControl. The returned reference should be stored with SET.
CreateForm
SET formVar = CreateForm(name$, width%, height%)
Creates a new form with the given name and initial size. Returns a form reference. If a form of that name is already loaded, CreateForm returns that form, and the name of one of the program’s own forms (a .frm of the project) always means that form: CreateForm loads it, with its Load event, when it is not loaded, and returns it with its own size. To open another copy of a form designed in a .frm file, use New FormName (see Several Copies of a Form in the Form topic).
CreateControl
SET ctrlVar = CreateControl(formRef, typeName$, ctrlName$ [, parentCtrlRef])
Creates a control on the given form: Me, a form variable, or a form’s name (CreateControl(Form2, ...) loads Form2 first when it is not loaded). typeName$ is the control type (e.g. "CommandButton", "Label", "TextBox"). ctrlName$ is the unique name for the new control: a name a control, a menu, or the form has already raises error 727 (There is already a control with that name), as Visual Basic’s Controls.Add does, and a type DVX does not have error 711 (Invalid class string). If a parentCtrlRef is supplied, the new control is nested inside it (useful for placing controls inside containers like HBox or Frame); the parent must be a container on the same form, otherwise error 5 (Illegal function call) is raised. ON ERROR traps each of them.
SetEvent
SETEVENT ctrlRef, eventName$, handlerName$
Wires an arbitrary SUB as the handler for an event of a control, a form (Me or a form reference), or a menu item. The default event-handler convention (ControlName_EventName) is used automatically for controls defined in a .frm file; SetEvent is for controls you create dynamically or for reusing a single handler across multiple controls. A handler declared without parameters is called without the event’s arguments. handlerName$ means what a call of that name would in the code that runs SetEvent: a SUB of that form’s code first, then a module’s — the module’s whose code runs SetEvent first, so two modules may each wire a Private SUB of the same name, then a Public one. A control or form made by a module’s code (CreateControl, CreateForm) finds its ControlName_EventName handlers the same way, in the file of the code that made it first. A SUB of a form’s code has that form’s variables wherever it is wired, also while its own form is not loaded (see Several Copies of a Form in the Form topic).
RemoveControl
REMOVECONTROL formRef, ctrlName$
Removes a control from a form. A later use of the removed control through a reference to it raises error 364 (Object was unloaded), as does one of a control of a form that has been unloaded.
LoadFormText
SET formVar = LOADFORMTEXT(frmText$)
Loads a form from the text of a .frm file — one a program made, read from a file, or got from somewhere else — and returns it, loaded but hidden like Load (its Load event runs; call Show). As for any form instance, its Initialize event runs before its Load, and its Terminate event as its Unload frees it. A form whose name is already loaded becomes another copy of its own, as with New, and so does one named like one of the program’s own forms, loaded or not: the name keeps meaning the program’s form. The form’s controls fire events to procedures named after them in the running program (Gen1_Load, Go_Click), as for any form; a code section after the form’s End is not compiled. Text that is not a form raises error 5 (Illegal function call). Form designers use it to show a .frm file being edited; Controls, CallByName, and the designer.bas functions then read and change it.
Dim f As Object
Dim n As Integer
Dim t As String
n = FreeFile
Open "PREVIEW.FRM" For Binary As #n
t = Input$(LOF(n), #n)
Close #n
Set f = LoadFormText(t)
f.Show
Print f.Controls.Count; f.Controls(0).Name
Dim frm As Form
Dim lbl As Control
Set frm = CreateForm("MyDlg", 300, 200)
frm.Caption = "Built in code"
Set lbl = CreateControl(frm, "Label", "StatusLabel")
StatusLabel.Caption = "Hello, world!"
Dim btn As Control
Set btn = CreateControl(frm, "CommandButton", "BtnClose")
BtnClose.Caption = "Close"
SetEvent btn, "Click", "OnCloseClick"
frm.Show
Sub OnCloseClick
Unload Me
End Sub
1.7.10. DoEvents
Lets your program’s waiting events (a click, a key, a Timer) run now. While your code runs, DVX and the other programs keep going (they get their turn many times a second), but your program’s own events wait until the code that is running ends or calls DoEvents, as in Visual Basic. A long loop that should answer a Cancel button, or let a Timer run, calls DoEvents now and then; after it, check whatever an event may have changed (a Cancel flag, a form that was closed). MsgBox, InputBox, a form shown with vbModal, SLEEP, and the statements that wait for sound or a frame run your program’s events too, as do the long calls described as working "as with DoEvents" (FileCopy, DIR$, long SQL statements, and others).
DOEVENTS
For i = 1 To 10000
' process data
If i Mod 100 = 0 Then DoEvents
Next
1.7.11. MsgBox
Displays a message-box dialog. Can be used as a statement (discards the result) or as a function (returns the button clicked).
MSGBOX message$ [, flags [, title$]]
result = MSGBOX(message$ [, flags [, title$]])
flags is the sum of a button-style constant and an icon constant. See Predefined Constants for the complete list. The message box plays the desktop sound chosen for its icon on the Control Panel’s Sounds tab (the default beep without an icon).
title$ is the text in the box’s title bar. Without it (or with an empty one) the box is titled with the program’s name, the name Program Manager shows for it, as Visual Basic titles it with the program’s title.
MsgBox "Operation complete"
answer = MsgBox("Continue?", vbYesNo + vbQuestion, "Confirm")
If answer = vbYes Then
' proceed
End If
1.7.12. InputBox$
Displays an input dialog and returns the user’s text entry. Returns an empty string if the user cancels.
result$ = INPUTBOX$(prompt$ [, title$ [, default$]])
Without title$ (or with an empty one) the box is titled with the program’s name, as a MsgBox is. default$ starts selected, as in Visual Basic: what the user types replaces it, and Enter keeps it.
name$ = InputBox$("Enter your name:", "Name Entry", "")
If name$ <> "" Then
Print "Hello, "; name$
End If
1.7.13. Event Handler Convention
Event handlers are named ControlName_EventName and defined as SUBs in the code of the control’s form. A form’s own events are named after the form: the Load event of a form named Form1 is Form1_Load (Visual Basic’s Form_Load spelling is not used). Each form’s handlers are its own: two forms can each have a Command1 button with a Command1_Click of its own. A form’s Click, DblClick, MouseDown, MouseUp, and MouseMove (Form1_Click ...) come from the mouse on the form itself, its background between and around the controls; a press on a control raises the control’s events only. A MouseDown, MouseUp, or MouseMove handler takes Visual Basic’s parameters, (Button As Integer, Shift As Integer, X As Single, Y As Single), and a DragDrop or DragOver handler (Source As Control, X As Single, Y As Single) or (Source As Control, X As Single, Y As Single, State As Integer), with Index As Integer first for a control array; another parameter list is a compile error. A form with no handler of the name in its code (one made with CreateForm, for example) has the module’s, or that of the one form whose code has it.
Sub Command1_Click()
MsgBox "Button clicked!"
End Sub
Sub Form1_Load()
Me.Caption = "My App"
End Sub
Sub Text1_Change()
Label1.Caption = "You typed: " & Text1.Text
End Sub
Common Events
| Event | Description |
|---|---|
Click |
Control was clicked: after MouseUp, when the button is released over the control, as in Visual Basic (also when the program’s code changes a CheckBox’s Value, an OptionButton’s Value to True, a ListBox’s, ComboBox’s, or ListView’s ListIndex, or a TabStrip’s tab, and when it sets a CommandButton’s Value to True) |
DblClick |
Control was double-clicked: MouseDown, MouseUp, Click, DblClick, MouseUp |
Change |
Control value or text changed (also when the program’s code changes it: Text, a CheckBox’s, OptionButton’s, scroll bar’s, or SpinButton’s Value, a Label’s Caption, a PictureBox’s Picture, a list’s ListIndex, a TabStrip’s tab) |
KeyPress |
A key that is a character was pressed (receives ASCII code): a printable key, Enter, Backspace, Esc, a Ctrl+letter, or Tab when no other control can take the focus |
KeyDown |
Any key was pressed (receives key code and shift state) |
KeyUp |
Key was released |
MouseDown |
Mouse button pressed (receives button, X, Y); not on a control’s scroll bars or a list’s column headers, as in Visual Basic |
MouseUp |
Mouse button released, to the control the left button was pressed on (not for a press on a scroll bar or column header) |
MouseMove |
Mouse moved over the control (none while a press on a scroll bar or column header is held) |
Scroll |
Control was scrolled (mouse wheel or scrollbar) |
GotFocus |
Control received input focus |
LostFocus |
Control lost input focus |
Form1_Initialize |
A form instance was made (the first use of the form’s name, New, or LoadFormText), before its Load |
Form1_Load |
Form is being loaded (fires once, after controls are created) |
Form1_QueryUnload |
Form is about to close (Cancel As Integer, UnloadMode As Integer): set Cancel = 1 to abort; UnloadMode says why (vbFormControlMenu, vbFormCode, vbAppWindows, vbAppTaskManager) |
Form1_Unload |
Form is being unloaded, after QueryUnload; set Cancel = 1 to keep it loaded |
Form1_Terminate |
A form instance is gone: not loaded, and nothing refers to it any more (or the program ended) |
Form1_Resize |
Form was resized |
Form1_Activate |
Form gained focus |
Form1_Deactivate |
Form lost focus |
Form1_NewArgs |
The running program was handed new arguments (COMMAND$ changed) |
Timer1_Timer |
Timer control interval elapsed (Timer control’s default event) |
1.8. Objects and Class Modules
A class module lets you define your own kind of object. The class describes what every object of that kind knows (its member variables and properties) and what it can do (its methods). Each object made from the class — an instance — has its own copy of the member variables, so you can have as many independent objects as you need, much as you can put several TextBoxes on a form.
1.8.1. A First Class
This class module, saved as Account.cls, describes a bank account:
VERSION DVX 1.00 CLASS
Attribute VB_Name = "Account"
Option Explicit
Public Owner As String
Private mBalance As Double
Public Sub Deposit(ByVal amount As Double)
mBalance = mBalance + amount
End Sub
Public Property Get Balance() As Double
Balance = mBalance
End Property
Private Sub Class_Initialize()
Print "Account created"
End Sub
Private Sub Class_Terminate()
Print "Account for "; Owner; " closed"
End Sub
Any other code in the project can then make and use Account objects:
Dim acct As Account
Set acct = New Account ' prints "Account created"
acct.Owner = "Scott"
acct.Deposit 100
acct.Deposit 50
Print acct.Owner & ": " & acct.Balance ' Scott: 150
Set acct = Nothing ' prints "Account for Scott closed"
Owner is Public, so code outside the class can read and change it. mBalance is Private: only the class’s own code can touch it, and the outside world reads it through the Balance property, which has no way to change it.
1.8.2. Class Module Files (.cls)
Each class module is kept in its own .cls file, listed in the project’s Classes group (see the IDE Guide). The file can begin with a few header lines, as a Visual Basic class file does; the IDE writes them for a new class module:
VERSION DVX 1.00 CLASS
Attribute VB_Name = "Account"
Option Explicit
The header is everything before the first line of code: blank lines, a VERSION line, a BEGIN ... END block, and Attribute VB_... lines, in that order. All of it is optional, and a Visual Basic .cls file can be added as it is. The class’s name comes from the Attribute VB_Name line; without one, the name is the file’s name without .cls (ACCOUNT.CLS makes a class named ACCOUNT). The class name is the type name used in DIM ... AS, NEW, TypeOf, and TYPENAME.
1.8.3. What a Class Contains
Outside its procedures, a class module may hold only declarations: member variables, CONSTs, OPTION and DEFtype statements, and Attribute lines. Statements that do something belong in a procedure, usually Class_Initialize. The members are:
| Member | Written as | Used from outside as |
|---|---|---|
Public member variable |
Public name As type |
obj.name (read and assign) |
Private member variable |
Private name As type, or Dim name As type |
not visible outside |
Method |
Sub or Function (Public unless Private) |
obj.Method args, x = obj.Func(args) |
Read property |
Property Get name(...) As type |
x = obj.name |
Write property |
Property Let name(..., value) |
obj.name = x |
Object property |
Property Set name(..., value) |
Set obj.name = someObject |
Friend procedure |
Friend Sub / Function / Property ... |
obj.name, by the program’s own code |
A Sub, Function, or Property is Public unless it is marked Private; Private procedures can be called only by the class’s own code. A Friend one, as in Visual Basic, can be called by the rest of the program through a variable declared as the class, but it is not part of the object’s late-bound interface: through As Object or As Variant it raises error 438, and an Implements interface does not include it. Inside the class’s procedures the member variables are used by name, with no SHARED needed, and each call works with the variables of the object it was called for. The class’s code can also use the program’s PUBLIC module variables (a module’s DIM and PRIVATE ones are that module’s own), procedures, and constants.
1.8.4. Properties
A property looks like a variable from outside, but reading or assigning it runs a procedure, so the class can check or calculate the value:
Private mC As Double
Public Property Get Celsius() As Double
Celsius = mC
End Property
Public Property Let Celsius(ByVal v As Double)
mC = v
End Property
Public Property Get Fahrenheit() As Double
Fahrenheit = mC * 9 / 5 + 32
End Property
Public Property Let Fahrenheit(ByVal v As Double)
mC = (v - 32) * 5 / 9
End Property
Dim t As New Thermometer
t.Celsius = 100
Print t.Fahrenheit ' 212
Property Get returns the value: assign it to the property name, as in a FUNCTION. Property Let receives the value being assigned as its last parameter; Property Set does the same for an object assigned with SET. A property can take arguments of its own before the value, such as Property Get Cell(r, c) and Property Let Cell(r, c, v), used as obj.Cell(1, 2) = 7. A property with only a Property Get is read-only: assigning it is a compile error through a variable of the class (error 438 through As Object). EXIT PROPERTY leaves a property procedure early.
Property procedures can also be written in an ordinary module, as in Visual Basic. The property is then used by its name like a variable, anywhere in the program: Size = 4 runs Property Let Size, Print Size runs Property Get Size, and Item(2) = "two" passes 2 and the value to Property Let Item.
1.8.5. Creating and Releasing Objects
An object variable starts as Nothing. NEW makes an object:
Dim a As Account ' Nothing so far
Set a = New Account ' now an Account
Dim b As New Account ' an Account is made right here, at the DIM
When an object is made, its Class_Initialize runs; when it is freed, its Class_Terminate runs. Both are Subs without parameters, usually Private, and both are optional.
An object stays alive as long as something refers to it: a variable, an array element, a TYPE field, a Collection, a Variant, or a member variable of another object. Each SET to another variable adds a reference; nothing is copied. When the last reference goes away — SET to Nothing or to another object, a local variable at the end of its SUB or FUNCTION, removal from a Collection, ERASE — the object is freed and its Class_Terminate runs right then, just after the statement that let go of it:
Dim a As New Account
Dim b As Account
Set b = a ' two references to one account
Set a = Nothing ' still alive: b refers to it
Set b = Nothing ' last reference gone: Class_Terminate runs now
Objects that refer to each other, directly or around a longer loop, keep each other alive even after the program’s own variables let them go. DVX BASIC finds such groups while the program runs: after every thousand or so new objects (more when the program keeps many objects), and when the program’s code runs to its end, it looks for objects that only the group itself still refers to. Each of those whose class has a Class_Terminate gets it called once, oldest object first, with every object of the group still intact; afterwards the group is freed. An object that a Class_Terminate stores somewhere (Set saved = Me) stays alive, and its Class_Terminate does not run again. Breaking the loop yourself (for example Set a.Partner = Nothing) still frees the objects at once instead of at the next check.
When the program ends normally — its code runs to the end, and with forms the last form is unloaded — the module variables, and the form-level variables the unloaded forms kept, are released as in Visual Basic, so the objects only they still hold get their Class_Terminate then. When the program ends with END (or is stopped), every object still alive is freed without running Class_Terminate, as with END in Visual Basic. Work that must always happen, such as saving a file, belongs in a method the program calls itself, not only in Class_Terminate.
1.8.6. Me
Inside a class’s procedures, Me is the object the procedure was called for. Use it to pass the object to other code, or to go through the object’s own properties (Me.Balance runs Property Get Balance):
Public Sub Move(ByVal dx As Double)
Me.X = Me.X + dx ' uses Property Get X and Property Let X
End Sub
1.8.7. Using Objects
When the compiler knows an object’s class — a variable, array, parameter, member variable, or FUNCTION declared As the class name or As Collection, New ClassName, or Me in a class module — its members are found when the program is compiled (early binding), as in Visual Basic. A misspelled member, a Private one, a Sub used where a value is needed, a property used as a statement, assigning a property that has no Property Let or Set, reading one that has no Property Get, and the wrong number of arguments are then compile errors that point at the member. Calls made this way are also faster. A class’s own members can be used anywhere in the class, also above the line that declares them, and through Me a class reaches its Private members as well (Me.mTotal).
Through a variable declared As Object or As Variant the member is found by name when the program runs (late binding): obj.Deposit 5 looks for a Public member named Deposit in whatever object obj holds at that moment. A misspelled or Private member then raises error 438 when the line runs, and the wrong number of arguments raises error 450. Using a member of Nothing raises error 91 (Object variable not set) either way, as in Visual Basic — a property, a method (also with arguments by name), a member given for a parameter or written by INPUT or READ, a WITH block on Nothing, and a form’s procedure through a variable As the form that holds Nothing alike — and a member of a value that is no object at all (a number, an Empty Variant) raises error 424 (Object required). An object of another class that reaches a variable of a class anyway (for example through a ByRef As Object argument) has its members found by name, as late binding would.
An argument that can never fit an object parameter of a SUB, FUNCTION, or method is a compile error too: a number or text, or an object of another class than the parameter’s (unless that class Implements it).
An object can be kept in a variable declared as its class name, As Object, or As Variant, in an array, in a TYPE field, in a Collection, or in another object’s member variable. It can be passed to a SUB or FUNCTION and returned from a FUNCTION (assign the result with SET inside the function, Set MakeAccount = acct). TYPENAME gives an object’s class name, and TypeOf obj Is ClassName tests it; Is tells whether two variables refer to the same object.
Arguments of a class’s procedures follow the rules of SUB and FUNCTION calls when the object variable is declared as the class name: a parameter without BYVAL gets the caller’s variable, so the procedure can change it, an omitted OPTIONAL argument gets its default, and a ParamArray collects the rest. When the object is reached through a variable declared As Object or As Variant, a variable or array element given as an argument is passed by reference too if the procedure’s parameter is not BYVAL (Visual Basic’s rule; other expressions go by value). What the procedure stores in such a parameter is converted to the type of the caller’s variable (an Integer stays an Integer, as in Visual Basic). A TYPE field given as an argument (obj.Move rec.x, obj.Move pts(1).x) is passed by reference as well (a BYVAL parameter gets its value). A form’s own SUBs and FUNCTIONs reached through such a variable follow these rules too, and its PUBLIC variables are read and set as a class’s are; the methods every form and control has (Show, Refresh, AddItem ...) take their arguments by value. An argument left out in the middle of a call (obj.Report a, , c) or at the end is an OPTIONAL parameter’s default value, else its empty value: 0, "", and so on for a typed parameter, Missing for a Variant (ISMISSING is True). Leaving out a parameter that is not OPTIONAL raises error 449 (Argument not optional).
A Public member variable of an object is a variable to the code that uses it, and so is one of a form (see the Form topic). Given for a parameter without BYVAL — of a SUB or FUNCTION of the program’s, or of a method — obj.Count, an element of a Public array (obj.Totals(2)), and a field of a Public TYPE variable (obj.Origin.X) are the variable itself, which the procedure changes, as are Me.Count and Me.Origin.X in the object’s own code. While the call has the variable, the object stays alive even when the program lets go of it (SET obj = Nothing during the call), and the array of an element cannot be given a new size (error 10), as for any array element passed by reference. When the compiler knows the object’s class the variable must have the parameter’s type, as any variable must; through As Object or As Variant the member is found when the call is made, and one of another type than a typed parameter, a property, or a FUNCTION gives a converted copy (Visual Basic’s late binding). The member in its own parentheses, (obj.Count), is passed by value.
A value stored in a member variable — obj.Count = x, an element (obj.Totals(2) = x), early bound or through As Object — is converted to the member’s type, as a store into any variable of that type is: obj.Totals(2) = 2.7 stores 3 in an element of an Integer array, a value too large for it raises error 6 (Overflow), text that is not a number raises error 13 (Type mismatch), and a STRING * n member keeps its length (the value is cut, or padded with spaces, to n characters). A member declared As a class, a form, or Collection takes only such an object, or Nothing: Set obj.Owner = x with an object of another class raises error 13, and SET of a value that is no object error 424, early bound or through As Object, as for a variable of that class (without SET such a value goes to the default member of the object the member holds: see Default Member) (and when the compiler knows the object’s class and the value’s, the program does not compile). INPUT, READ, SWAP, LSET, and the other statements that write a variable take member variables as well (see Statements That Write a Variable in Declaration Statements); REDIM and ERASE take a Public array member (ReDim obj.Totals(12), see REDIM).
The fields of a Public TYPE variable are reached through the object as a variable’s are: obj.Origin.X = 5, n = obj.Points(2).Y, obj.Box.Inner.Width, With obj.Origin ... End With, and obj.Origin = rec, which copies rec’s fields into the record that is there. Through a variable declared As Object, As Form, or As Variant the compiler takes the TYPE from the program’s declarations: every class and form with a Public member (or a form with a control) of that name must declare it a variable of the same TYPE, an array or not. When they declare such variables with different TYPEs the field cannot be compiled ("Ambiguous member"): declare the object variable As its class or form (a variable As Form2 takes the TYPE from Form2’s declaration). When the name is something else somewhere (a property, an object variable, a control), obj.name is reached by name as any other member.
An object parameter is itself passed like any other parameter: without BYVAL, SET on the parameter changes the caller’s variable (a SUB can make a new object for the caller); with BYVAL, the procedure gets its own reference to the same object, and SET on it does not affect the caller.
1.8.8. CALLBYNAME
result = CALLBYNAME(object, memberName$, callType [, arguments...])
CALLBYNAME object, memberName$, callType [, arguments...]
Uses the member of an object whose name the program has in a string, as if it had been written after a dot: a form (its properties and methods, and the SUBs, FUNCTIONs, and PUBLIC variables of its code), a control, a class instance, or a Collection. callType says what to do: vbGet reads a property (with arguments, a property that takes them), vbLet assigns it the last argument, vbSet assigns it an object (the last argument), vbMethod calls a method or function with the arguments. The function gives the property’s value or the method’s result (Empty for vbLet and vbSet); as a statement the result is dropped. Another callType raises error 5 (Illegal function call), as does vbLet or vbSet without a value; a member the object does not have raises the error the same member written after a dot would. A form designer’s property window uses it to read and set the properties designer.bas lists for a control type.
Dim prop As String
prop = "Caption"
Print CallByName(Command1, prop, vbGet) ' Command1.Caption
CallByName Command1, prop, vbLet, "OK" ' Command1.Caption = "OK"
CallByName List1, "AddItem", vbMethod, "one" ' List1.AddItem "one"
Print CallByName(acct, "Balance", vbGet) ' a class instance's property
1.8.9. Default Member
A class can name one property or method as its default member, used when the object is written with parentheses directly after it. Put this line in the class, inside the procedure (as Visual Basic writes it) or on its own at the top of the class:
Attribute Item.VB_UserMemId = 0
With Item as the default member, obj(3) means obj.Item(3), and obj(3) = x calls Property Let Item. Collection’s default member is Item, which is why c(1) and c("key") work. A call’s result can be indexed directly, too: c(1)(0) is element 0 of the array item 1 holds, and Split(s, ",")(2) the third part.
Where a value is needed — in arithmetic, a comparison, text, PRINT, a typed variable, or a typed parameter — an object stands for its default member’s value, as in Visual Basic: with Value as the default member, total = obj + 1 reads obj.Value, and obj = 9 (without SET) stores 9 through it. An assignment without SET (a Let) always gives a value, as in Visual Basic: an object given that way — to a Variant or any other variable, an array element, a TYPE field, a FUNCTION’s result, a control’s property, a member variable or Property Let of an object (early or late bound), or a parameter that is neither Object nor Variant — stands for its default member’s value (v = Text2 stores Text2’s text in v, Label1.Caption = Text2 copies it). When the default member is a Property Get or a Function it runs first, wherever the value goes — a control’s property or method too (Text1.Text = acct, List1.AddItem acct), a member found through an Object variable (o.Total = acct), CallByName with vbLet, or a typed parameter of a procedure called through an Object variable — and an error in it is raised at the Let. An object with no default member raises error 438 there, a Collection error 450 (its default member, Item, needs an index), and Nothing error 91; a Let of the word Nothing does not compile (assign it with SET). Only SET stores the object itself; a picture given to a picture property (Image1.Picture = LoadPicture(f)) and a control given to Container go as they are, and a Variant parameter, Collection.Add, and IIF pass an object on. Any value given without SET to a variable, an array element, a TYPE field, a FUNCTION’s result, a parameter, or an object’s member variable declared As Object or a class goes to the default member of the object it holds, early or late bound alike, as in Visual Basic (Dim o As Object: Set o = Text1: o = n sets Text1.Text, and o = Text2 sets Text1.Text to Text2.Text): error 91 (Object variable not set) when it holds Nothing, 438 when its object has no default member. A member variable can be the default member too (Attribute Label.VB_UserMemId = 0). An object without a default member used as a value raises error 438 (a Collection 450, Nothing 91), as in Visual Basic. The object name on its own still means the object itself wherever an object is expected: SET, Is, passing it to an object parameter, adding it to a Collection. Controls have default properties as well (Text1 means Text1.Text); see the control overview.
1.8.10. WITH...END WITH
WITH names an object or a TYPE record (an object’s Public TYPE variable too: With acct.Origin) once for a block of statements; inside it, a name starting with a dot (.Value, .Add 3) is that object’s member or that record’s field:
With acct
.Owner = "Ada"
.Deposit 100
Print .Balance
End With
With shapes(i).origin ' a TYPE record: its fields
.x = 5
.y = .x * 2
End With
The expression after WITH is worked out once, when the block starts, as in Visual Basic: With New Account makes one object that lives until End With, With list(i) keeps the element it named even if i changes inside, and so do With shapes(i).origin and a record that is an object’s or a form’s member (With acct.Origin, With Form2.Pos, With accts(i).Origin): the object stays alive until End With even if the program lets go of it inside the block. While the block runs, the array whose element it names is locked: REDIM of that array, ERASE of it when it is a dynamic array, or another array assigned to it raises error 10, as while the element is passed by reference. A form’s name is worked out once too (With Form2): Set Form2 = New Form2 inside the block does not change the form the dots mean, and WITH itself does not load the form — the first use of one of its members through the block does, as in Visual Basic. WITH blocks can be nested; a dot then means the innermost one. A word after a space that starts with a dot is a new argument of its own (Bump .Count passes the member to Bump). Me works too (With Me). Leaving the block by GOTO or EXIT is allowed; as in Visual Basic, a block left without reaching End With keeps its object or record (and the array locked) until the block starts again or the procedure ends (for code outside any procedure, until that code ends), so avoid jumping out of a WITH on an array element whose array is given a new size later.
1.8.11. Errors in a Class
A class reports a problem with ERROR, normally numbered from vbObjectError so that its numbers cannot be mistaken for the built-in ones. The error is handled by the ON ERROR handler of the code that called the class, as with any procedure:
' in the class
Public Sub Withdraw(ByVal amount As Double)
If amount > mBalance Then Error vbObjectError + 1
mBalance = mBalance - amount
End Sub
' in the program
On Error GoTo NoMoney
acct.Withdraw 500
Exit Sub
NoMoney:
If Err = vbObjectError + 1 Then MsgBox "Not enough money"
Resume Next
As in Visual Basic, Err.Source of an error raised in a class’s code — a run-time error, or Err.Raise without a source — is the project’s name and the class’s, "MyApp.Account", also once the error reaches the code that called the class; Err.Raise vbObjectError + 1, "Account" names the source itself.
1.8.12. Rules and Limits
-
A member’s name cannot be a reserved word. Names such as Load, Print, Open, Close, Line, Input, Get, Put, Type, Error, and Timer are keywords in DVX BASIC and cannot be used; Text, Caption, Value, Count, Item, Add, Name, Show, and Hide are fine.
-
SHARED and DIM SHARED cannot be used in a class module; a class’s code reaches the program’s module variables that are declared PUBLIC.
-
A STATIC variable in a class procedure is kept per object, as in Visual Basic: each object has its own copy.
-
A class has at most 65536 member variables, its procedures' STATIC variables included; more fails to compile with "Too many member variables in ClassName".
-
Class_Initialize and Class_Terminate take no parameters.
-
A class module cannot hold statements outside its procedures; the compiler reports "Only declarations are allowed outside procedures in a class module".
-
NEW, PROPERTY, PUBLIC, PRIVATE, and TYPEOF are reserved words. VARIANT, OBJECT, COLLECTION, EMPTY, NULL, EACH, IN, and GLOBAL are not.
1.8.13. Events
A class module can announce that something happened — a download finished, a value changed, a step of a long job was done — and let the code that uses its objects react, the way a form reacts to a button’s Click. The class declares the event and raises it; the program declares a variable WithEvents and writes a SUB for each event it wants to handle. A form’s code can declare and raise events of its own the same way (see A Form’s Own Events below).
Declaring and Raising an Event
In the class module, declare each event at the top with EVENT, then raise it from any of the class’s procedures with RAISEEVENT:
' class module Downloader
Public Event Progress(ByVal percent As Integer, cancel As Boolean)
Public Event Done()
Public Sub Start()
Dim stopNow As Boolean
Dim p As Integer
For p = 10 To 100 Step 10
RaiseEvent Progress(p, stopNow)
If stopNow Then Exit Sub
Next
RaiseEvent Done
End Sub
An event may have parameters but no return value. Its parameters cannot be OPTIONAL or a PARAMARRAY, and an event is always public (Public Event and Event mean the same; Private Event is an error). RAISEEVENT can only be used inside the class’s (or the form’s) own procedures, with exactly the arguments the event declares. A parameter without BYVAL is passed by reference, so a handler can change the variable given for it — the cancel flag above is how a handler asks the class to stop. This holds for a variable, an array element (a(i)), and a TYPE field (rec.f, arr(i).f), as in Visual Basic. When several handlers get the event they all get the same variable, so each sees what the one before it stored; every store is converted to the variable’s or field’s type at once, as an assignment would be. While the handlers run, the arrays whose elements (or elements' fields) were given are locked: REDIM of one of them, ERASE of a dynamic one, or another array assigned to one raises error 10. An expression, or a variable in its own parentheses, given for a by-reference parameter is passed as one temporary value that every handler shares, as in Visual Basic: the variable itself does not change, but a handler sees what the one before it stored. An argument is converted to the type of a typed event parameter, with the rules of SUB calls (a variable of another type given by reference is a compile error).
Handling Events
In a module, a form, or another class module, declare a variable of the class WithEvents, outside any procedure, and write a SUB named variable_EventName with the same parameters as the event:
Dim WithEvents dl As Downloader
Sub StartDownload()
Set dl = New Downloader
dl.Start
End Sub
Sub dl_Progress(ByVal percent As Integer, cancel As Boolean)
Label1.Caption = percent & "%"
If percent >= 50 And StopWanted Then cancel = True
End Sub
Sub dl_Done()
MsgBox "Finished"
End Sub
The handler’s parameters must match the event’s: the same number, the same types, and the same BYVAL / BYREF choice, or the program does not compile. A handler is optional: an event nobody handles does nothing. RAISEEVENT calls the handler of every WithEvents variable that holds the raising object at that moment — two variables holding the same object both get the event, in the order they were declared — and waits for them to finish before the class’s code continues. Setting the variable to another object (or to Nothing) moves the handlers to the new object at once.
A WithEvents variable in a form belongs to that form: its handlers run with the form’s own variables and controls, even when the event is raised while another form’s code is running, and a form that is loaded twice gets its own variable each time. Unloading the form stops its handlers; the variable keeps its object with the form’s other variables, and its handlers run again once the form is loaded again.
Events in a Class Module
A class can handle the events of objects it holds. The variable is a member variable (usually Private) and the handlers are the class’s own procedures; each object of the class handles the events of the object in its own variable, and the handler runs for that object (Me):
' Class module Logger
Private WithEvents source As Downloader
Private lines As Integer
Public Sub Watch(d As Downloader)
Set source = d
End Sub
Private Sub source_Progress(ByVal percent As Integer, cancel As Boolean)
lines = lines + 1
Print "log"; lines; percent
End Sub
Lifetime rule: listening never keeps an object alive. The object that raises an event does not hold a reference to its listeners; only the listener’s own variable refers to the source. So:
-
A listener lives as long as the program holds it, like any other object. When its last reference goes, its Class_Terminate runs and it hears nothing more — an event is never delivered to an object that has ended.
-
While a handler runs, the listener is held for the call, so a handler may drop the last outside reference to its own object (or Set its WithEvents variable to Nothing) safely; Class_Terminate then runs after the handler returns.
-
A cycle — the source holding a reference back to its listener, for example a Parent or Owner member — is collected like any other cycle of objects: when nothing outside refers to them, both Class_Terminate procedures run (the older object first) and the objects are freed. An event raised during those Class_Terminate calls still reaches listeners that have not been freed yet.
-
Several listeners may hold the same source: RAISEEVENT calls the module and form handlers first, then those of listening objects, the most recently created first.
Events of a Control
A variable declared As a control type (TextBox, CommandButton, a UserControl, a control installed in DVX: see Control Types) may be WithEvents too, as in Visual Basic: the control the variable holds sends each of its events to the variable’s handler of it (variable_EventName, a SUB taking the event’s arguments, or none), after the control’s own handler on its form (Text1_Change). The variable takes no Index for an element of a control array. A module, a form, and a class module may each handle a control this way — several controls one after another through one variable, or one control in several places:
' class module Watcher: counts the clicks of any button it is given
Private WithEvents btn As CommandButton
Private clicks As Integer
Public Sub Watch(b As CommandButton)
Set btn = b
End Sub
Private Sub btn_Click()
clicks = clicks + 1
Print btn.Caption; clicks
End Sub
A control’s handlers run in the order their variables were declared (the modules' and the forms' first, then those of objects), each with its own form’s variables, or as its object (Me). Setting the variable to another control, or to Nothing, moves its handlers at once. An argument a handler may change (KeyAscii, Cancel) reaches each handler as the handlers before it left it, as in Visual Basic: the control’s own handler setting KeyAscii = 0 is seen by the variable’s handler, and the last value left is the one the control takes.
Events of a Form
A variable declared As one of the program’s forms (Dim WithEvents f As Form2), or As Form for any form, may be WithEvents too, as in Visual Basic: the form instance the variable holds sends each of its events — Load, Unload, QueryUnload, Resize, Activate, Deactivate, Click, the mouse and key events, Paint, and the others — to the variable’s handler of it (f_Load, f_QueryUnload), after the form’s own handler (Form2_Load). The variable may hold the form its name means (Set f = Form2) or a copy New made (Set f = New Form2); neither is loaded by the Set, so f_Load runs when the form loads at its first use (f.Show), as in Visual Basic. A handler of QueryUnload (or Unload) gets the Cancel the form’s own handler left, and either may set it to keep the form loaded; QueryUnload’s UnloadMode says why the form closes (a handler may take Cancel alone, as for the form’s own handler):
' module: keep the settings form from closing while it has unsaved changes
Public WithEvents settings As SettingsForm
Sub ShowSettings()
Set settings = New SettingsForm
settings.Show
End Sub
Sub settings_QueryUnload(Cancel As Integer, UnloadMode As Integer)
If settings.Dirty And UnloadMode <> vbAppWindows Then Cancel = 1
End Sub
Sub settings_Unload()
Set settings = Nothing
End Sub
A class module can watch any form the same way (Private WithEvents frm As Form, Sub frm_Resize), for example to lay out the controls of whichever form it is given.
A form’s Initialize and Terminate events reach the form’s own handlers only, as in Visual Basic: no variable can hold an instance as it is being made, and Terminate runs once nothing refers to it any more.
A Form’s Own Events
A form’s code can declare events of its own and raise them, exactly as a class module does: EVENT (or PUBLIC EVENT) at the top of the form’s code, outside its procedures, and RAISEEVENT in its procedures. A variable declared WithEvents As that form (Dim WithEvents f As Form2) handles them with SUBs named f_EventName, whose parameters must match the event’s, as for a class’s events; arguments without BYVAL go by reference to every handler in turn. The event comes from the form instance whose code raises it (Me), loaded or not, and reaches the variables that hold that instance. A variable declared As Form gets a form’s built-in events only, as in Visual Basic, not those its code declares. A form’s event may not take the name of an event every form has — Initialize, Load, QueryUnload, Unload, Terminate, Activate, Deactivate, Resize, Paint, Click, DblClick, GotFocus, LostFocus, the mouse and key events (MouseDown, KeyPress ...), DragDrop, DragOver, and DVX’s NewArgs, FullScreen, and design-mode events — because its WithEvents handlers name both kinds the same way: as in Visual Basic, that does not compile (Ambiguous name). Any other name is the form’s own, even one a control’s event has (Event Change, Event Timer: Sub f_Change handles it).
' code of form Picker
Public Event Chosen(ByVal item As String, Cancel As Boolean)
Private Sub OkButton_Click()
Dim stopIt As Boolean
RaiseEvent Chosen(List1.Text, stopIt)
If Not stopIt Then Unload Me
End Sub
' module
Public WithEvents pick As Picker
Sub ChooseOne()
Set pick = New Picker
pick.Show
End Sub
Sub pick_Chosen(ByVal item As String, Cancel As Boolean)
If item = "" Then Cancel = True
End Sub
Rules
-
WITHEVENTS goes with DIM, PUBLIC, or PRIVATE at the top level of a module, form, or class module (not inside a procedure), for a single variable declared as a class module’s name, a form (one of the program’s forms, or Form), or a control type (not Control). It cannot be an array and cannot use New: Set it to an object in code.
-
EVENT goes at the top level of a class module or a form’s code; RAISEEVENT in a procedure of that class module or form.
-
A WithEvents variable is visible to the procedures of its module or form, as every declared module variable is; in a class module it is a member variable of each object.
-
Handlers are SUBs named variable_EventName in the same module, form, or class module as the variable (a module’s in the same module file).
-
EVENT, RAISEEVENT, WITHEVENTS, and IMPLEMENTS are not reserved words: they only have their meaning where a name follows them in those places, so a program may still use them as its own names.
See also: Objects and Class Modules (Section 1.8).
1.8.14. Interfaces (Implements)
An interface is a set of properties and methods that several classes promise to provide, so that code can work with any of them through one variable type. In DVX BASIC, as in Visual Basic, the interface is an ordinary class module — its procedures are usually left empty — and a class that provides it says IMPLEMENTS:
' class module IShape
Public Function Area() As Double
End Function
Public Sub Scale(ByVal factor As Double)
End Sub
' class module Circle
Implements IShape
Private r As Double
Private Function IShape_Area() As Double
IShape_Area = 3.14159 * r * r
End Function
Private Sub IShape_Scale(ByVal factor As Double)
r = r * factor
End Sub
For every public member of the interface, the implementing class writes a procedure named Interface_Member of the same kind (Sub, Function, Property Get / Let / Set) with the same number of parameters, ending in a ParamArray exactly when the interface’s does; they are usually Private, so they are only reached through the interface. A call through the interface reaches the implementation directly (the compiler records which procedure implements each member), and an implementation’s BYVAL parameter gets a value even where the interface’s parameter is ByRef. A public variable of the interface is implemented as a Property Get and a Property Let (Property Set for an object variable). A class that leaves one out does not compile.
Code then uses the objects through a variable declared as the interface:
Dim s As IShape
Set s = New Circle
s.Scale 2
Print s.Area ' runs Circle's IShape_Area
Print TypeOf s Is IShape ' True
Print TypeName(s) ' Circle
Through a variable declared as the interface, a member always means the interface’s member, even when the class has a public member of the same name of its own. Through the class’s own type, As Object, or As Variant, the class’s own public members are used. SET into a variable of the interface type accepts an object of any class that Implements it (and of the interface class itself); TypeOf obj Is Interface is True for them. A class can implement several interfaces with one IMPLEMENTS line for each. An argument left out of a call through the interface takes the default the interface’s procedure declares, as in Visual Basic, even if the implementing procedure declares another. Friend procedures are not part of an interface.
See also: Objects and Class Modules (Section 1.8); Events (Section 1.8.13).
1.8.15. Collection Object
A Collection is a ready-made object that holds a list of items of any kind — numbers, text, objects — in order. Items can be looked up by position or by a text key, added anywhere in the list, and removed, and FOR EACH walks through them. The list grows as needed; there is no size to declare.
Dim fruit As New Collection
fruit.Add "Apple", "a"
fruit.Add "Cherry", "c"
fruit.Add "Banana", "b", "c" ' before the item with key "c"
Print fruit.Count ' 3
Print fruit(1) ' Apple
Print fruit("B") ' Banana (keys ignore case)
Dim f As Variant
For Each f In fruit
Print f ' Apple, Banana, Cherry
Next
fruit.Remove "a"
fruit.Remove 1 ' removes Banana, now the first item
Members
| Member | Description |
|---|---|
Add item [, key] [, before] [, after] |
Adds item at the end of the list, or before or after the item given by position or key. key, when given, is text that names the item. |
Remove indexOrKey |
Removes the item at that position (1 = first) or with that key. |
Item(indexOrKey) |
The item at that position or with that key. Item is the default member: c(2) is c.Item(2) and c("key") is c.Item("key"). |
Count |
The number of items. |
Positions start at 1 and change as items are added and removed. A key must be text, is compared without regard to upper and lower case, and must be unique in the Collection. Give either before or after, not both; leave out the arguments you do not use with commas (c.Add item, , 1 puts item first). Items are stored as they are: an object added to a Collection stays alive while the Collection holds it.
Make a Collection with DIM c AS NEW COLLECTION or SET c = NEW COLLECTION. Like any object, it is freed when the last reference to it goes.
Through a variable declared As Collection the members are checked when the program is compiled: another member name, the wrong number of arguments, using Add or Remove as a value, Count or Item as a statement, and assigning any of them are compile errors. Keyed lookups compare a hash of the key first, so finding an item by key stays fast in large Collections.
Errors
| Error | When |
|---|---|
5 |
A key that is not in the Collection (Item, Remove, before, or after), or Add given both before and after |
9 |
A position that is not in the Collection |
13 |
A key that is not text |
438 |
A member other than Add, Remove, Item, and Count, or assigning one, through As Object or As Variant |
450 |
The wrong number of arguments, through As Object or As Variant |
457 |
Add with a key that is already in use |
See also: Objects and Class Modules (Section 1.8); FOR EACH...NEXT (Section 1.4.4).
1.9. SQL Functions
DVX BASIC includes SQLite database support through the sql.bas include library. Add sql.bas to your project to gain access to these functions. All functions use database handles and result-set handles (Long integers) returned by SQLOpen and SQLQuery. Numeric parameters and results are Long, so row counts and integer column values keep their full 32-bit range.
SQLite is in the Databases part of DVX, which can be left out when DVX is installed. Without it the SQL functions do nothing: SQLOpen returns 0, and SQLError$ says that Databases are not installed. SysLibraryLoaded("dvxsql") (system.bas) tells beforehand.
1.9.1. Opening and Closing Databases
SQLOpen
Opens a SQLite database file and returns a database handle (> 0) or 0 on failure. The file is created if it does not exist. A file that cannot be changed (for example one marked read-only) still opens, but only for reading. When SQLOpen returns 0, SQLError$(0) tells you why.
db = SQLOpen(path$)
db = SQLOpen(App.Data & "\mydata.db")
1.9.2. Executing SQL
SQLExec
Executes a SQL statement that does not return data (INSERT, UPDATE, DELETE, CREATE TABLE, etc.). Returns True on success.
ok = SQLExec(db, sql$)
SQLExec db, "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)"
SQLExec db, "INSERT INTO users (name) VALUES ('Scott')"
ok = SQLExec(db, "DELETE FROM users WHERE id = 5")
Put text values in single quotes, as in the examples. Text in double quotes is read as a column name, so "Scott" in place of 'Scott' gives the error "no such column: Scott".
SQLEscape$
Returns text with every single quote doubled, the way SQL writes a quote inside a quoted value. Use it on text the user typed (or read from a file) before you put it between quotes in a statement: a name such as O’Brien would otherwise end the value early and break the statement.
SQLExec db, "INSERT INTO users (name) VALUES ('" & SQLEscape$(name$) & "')"
SQLExec runs every statement in sql$, one after another, before it returns.
Long Statements
A statement can take a while: one that changes many rows, CREATE INDEX on a big table, or the first SQLNext of a query that sorts or groups, which reads every row first. While a statement runs, DVX and the other programs keep going, and your program’s events run as they do during DoEvents. Ending the program (End, or closing its last form) stops the statement, and what it changed is undone.
An event that runs meanwhile cannot use the database the statement is running on: SQLExec, SQLQuery, and SQLNext return False or 0, and SQLError$ says "A statement is still running on this database". Its field functions return "" or 0. SQLFreeResult and SQLClose wait until the statement ends. Other databases can be used as always.
Code in a control file (a control written in BASIC) does not wait like this: its statements run to the end.
1.9.3. Querying Data
SQLQuery
Executes a SELECT query and returns a result-set cursor.
rs = SQLQuery(db, sql$)
rs = SQLQuery(db, "SELECT id, name FROM users ORDER BY name")
1.9.4. Reading Fields
SQLField$ / SQLFieldText$
Returns a field value as a string. Use SQLField$ to look up by column name; use SQLFieldText$ to look up by 0-based column index.
value$ = SQLField$(rs, columnName$)
value$ = SQLFieldText$(rs, columnIndex)
name$ = SQLField$(rs, "name")
first$ = SQLFieldText$(rs, 0)
1.9.6. Error Information
SQLError$
Returns the last error message for the database.
msg$ = SQLError$(db)
When a database file could not be opened, read, or written, the message ends with the reason in parentheses, for example "unable to open database file (No such file or directory)". If another program, or another handle in your own program, is changing the same database at that moment, the message is "database is locked": try again once the other change is finished, and free result sets with SQLFreeResult as soon as you are done with them, because an open result set stops other handles from saving changes.
1.9.7. Complete SQL Example
Dim db As Long
Dim rs As Long
db = SQLOpen(App.Data & "\contacts.db")
SQLExec db, "CREATE TABLE IF NOT EXISTS contacts (name TEXT, phone TEXT)"
SQLExec db, "INSERT INTO contacts VALUES ('Alice', '555-1234')"
rs = SQLQuery(db, "SELECT name, phone FROM contacts")
Do While SQLNext(rs)
Print SQLField$(rs, "name"); Tab(20); SQLField$(rs, "phone")
Loop
SQLFreeResult rs
SQLClose db
1.10. App Object
The App object tells a program about itself, as Visual Basic’s does: its folders, its name, its help file, whether another copy of it is running, and its version information.
| Property | Type | R/W | Description |
|---|---|---|---|
App.Path |
String |
R |
The folder the program is in |
App.User |
String |
R |
The program’s own folder in the user folder: its settings and every file it saves (databases, saved games, documents) |
App.Data |
String |
R |
The DATA folder in the program’s folder: the files the program comes with (read-only) |
App.Title |
String |
R/W |
The program’s name: its project’s Name to start with. Setting it renames the program where DVX shows it (Task Manager, its program screen’s window), and it is the title of a MsgBox or InputBox$ that gives none. |
App.EXEName |
String |
R |
The program file’s name without its extension (MYAPP for MYAPP.APP); run from the IDE, the project’s Name. |
App.HelpFile |
String |
R/W |
The help file F1 opens: the project’s Help File to start with. A name without a folder (or a path that does not start at a drive or a backslash) is in App.Path. Setting it changes what F1 opens from then on. |
App.PrevInstance |
Boolean |
R |
True when another copy of the program is running (a program whose project allows more than one copy at once). |
App.Major |
Integer |
R |
The first number of the project’s Version (2 for 2.10.7) |
App.Minor |
Integer |
R |
Its second number (10); 0 when it has none |
App.Revision |
Integer |
R |
Its third number (7); 0 when it has none |
App.CompanyName |
String |
R |
The project’s Publisher |
App.FileDescription |
String |
R |
The project’s Description |
App.LegalCopyright |
String |
R |
The project’s Copyright |
App.LegalTrademarks |
String |
R |
The project’s Trademarks |
App.ProductName |
String |
R |
The project’s Product, else its Name |
App.Comments |
String |
R |
The project’s Comments |
App.User is the place to write: it is kept apart from the program, so installing a new version never overwrites what is there, and backing up the user folder keeps it. Every copy of the program gets the same folder. It is APPS and the program’s folder in your user folder: USER\APPS\KPUNCH\NOTEPAD for APPS\KPUNCH\NOTEPAD\NOTEPAD.APP; for a program kept in the user folder, APPS and its path in there — a project in USER\PROJECTS\TODO, run from DVX BASIC, and the TODO.APP Make writes beside it share USER\APPS\PROJECTS\TODO. It is made the first time App.User is used. App.Data is for reading only: on a CD-ROM it cannot be written at all. Programs never write in DVX’s SHARED folder.
The version information comes from the project’s Project Properties (the Make page), saved in the project file’s [Project] section as Version, Publisher, Description, Copyright, Trademarks, Product, and Comments; it goes into the program when it is compiled. Only App.Title and App.HelpFile can be set: setting another member does not compile.
App alone is the App object itself, as in Visual Basic: it can be Set into an Object or Variant variable, or one declared As App (App’s type, which holds App only), passed for an Object parameter, compared with Is, and TypeName(App) is "App" (TypeOf o Is App is True for it). Its members are reached through the variable as through App (o.Title, With App ... .Path ... End With, CallByName); there a member App does not have raises error 438, setting one that can only be read error 383, and arguments error 450 (App has no methods). App is no form or control, and it has no default value: Print o or x = o of a variable holding App raises error 438.
settingsFile$ = App.User & "\settings.ini"
dbPath$ = App.User & "\myapp.db"
levelFile$ = App.Data & "\level1.dat"
Print "Running from: " & App.Path
Print App.ProductName; " version"; App.Major; "."; App.Minor
If App.PrevInstance Then MsgBox "Another copy is running."
App.Title = App.Title & " - " & docName$
Visual Basic’s App members that belong to Windows (hInstance, ThreadID, TaskVisible, StartMode, LogMode, LogPath, LogEvent, StartLogging, NonModalAllowed, OleRequestPending*, OleServerBusy*, RetainedProject, UnattendedApp) are not in DVX BASIC.
1.11. Debug Object
The Debug object helps while a program is being written, as Visual Basic’s does. Its two statements work only while the program runs in the IDE: in a program made with Make Executable (and in an installed control file) they do nothing and their arguments are not evaluated, as in a compiled Visual Basic program, so they can stay in the code.
| Statement | Description |
|---|---|
Debug.Print [items] |
Write items to the IDE’s Output window, with PRINT’s items: values, ; and , (the next 14-column zone), Spc(n), Tab(n), and Tab alone (the next zone); a ; or , at the end keeps the line open. It writes there also when the program has a screen of its own, where PRINT writes then. |
Debug.Assert condition |
When condition is False, pause the program at this statement, as a breakpoint would — also in a program started with Run (F5) —, so its variables can be looked at; Run, Debug, or a Step command goes on with the next statement. When it is True, nothing happens. |
Debug.Print "count ="; count, "total ="; total
Debug.Assert count >= 0
The Immediate window runs Debug.Print as it runs PRINT and ?. Debug is the Debug object only in these two statements: elsewhere it can be a name of the program’s own (a variable called Debug), and a program with a SUB or FUNCTION called Debug has no Debug statements.
1.12. Clipboard Object
The Clipboard object shares text with other programs and with the copy and paste of text boxes, as in Visual Basic. The DVX clipboard holds text only, so the format arguments accept vbCFText (1): any other format is never present and GetText returns "" for it.
| Method | Returns | Description |
|---|---|---|
Clipboard.Clear |
(none) |
Empty the clipboard. |
Clipboard.GetFormat(format) |
Boolean |
True when the clipboard holds data of that format (text for vbCFText). |
Clipboard.GetText([format]) |
String |
The clipboard text, or "" when it is empty. |
Clipboard.SetText text [, format] |
(none) |
Put text on the clipboard, replacing what was there. A format other than vbCFText is an error. |
Clipboard.SetText Text1.Text
If Clipboard.GetFormat(vbCFText) Then Text2.Text = Clipboard.GetText()
The Clipboard is an object like any other, as in Visual Basic: Set c = Clipboard, an argument for an Object parameter, TypeName(Clipboard) ("Clipboard"), and c Is Clipboard work, and its methods are reached through the variable. Its name is a type too (Dim c As Clipboard), which holds the Clipboard only. A control or form of your own named Clipboard takes the name’s place.
1.13. Printer Object
The Printer object draws pages on the printer chosen in the Control Panel, as in Visual Basic: text in any font at a size in points, lines, boxes, circles, dots, and pictures, anywhere on the page, page after page. It needs a printer model that prints pictures (the Control Panel’s Printer page); on a color printer the colors print as they are, on the others in shades of gray.
On a PostScript printer the page is drawn by the printer itself, as lines, curves, and letters rather than dots, so it prints as sharp as the printer can. Text is in the printer’s own Helvetica, Times, or Courier, whichever is nearest FontName: Courier for a fixed-pitch font or a name with Mono or Courier in it, Times for a name with Serif, Times, Roman, Tinos, or Ledger in it (but not Sans), and Helvetica for the rest. TextWidth and TextHeight measure the printer’s letters, so text lines up as it will print.
A page is 8 by 10 inches. Its coordinates are twips (1440 an inch) until ScaleMode or Scale changes them, as on Visual Basic’s Printer, so a program can place things in inches, centimeters, points, or its own units. Drawing goes to the page being made; NewPage prints it and starts the next, and EndDoc prints the last one and ends the document. The document starts when the first page is printed, at the printer and with the copies the program’s last PrintChoose (print.bas) chose, or else as the Control Panel has them; while it prints, the Printing window shows, with Cancel. A program that ends with a page drawn or a document started has EndDoc done for it. A program ended with End Task (in the Task Manager) prints nothing more: the page drawn is thrown away and the rest of the document is not sent, so ending it never waits for the printer or asks about it.
| Method | Description |
|---|---|
Printer.Print items |
Text at CurrentX / CurrentY in the font and ForeColor, as PRINT lays it out: ; joins, a comma goes to the next 14-character zone, TAB(n) and SPC(n) count characters of the font (its 0’s width), and a new line goes down a line of the font. CurrentX / CurrentY move past it. An array or a TYPE record raises error 13 (Type mismatch), which ON ERROR can trap. |
Printer.Line [(x1, y1)]-(x2, y2) [, color] [, B | BF] |
A line, a box, or a filled box, as on a PictureBox (STEP works too). |
Printer.Circle (x, y), r [, color [, start, end [, aspect]]] |
A circle, ellipse, or arc; filled in FillColor when FillStyle is not transparent. Circles are round on paper on every printer. |
Printer.PSet (x, y) [, color] |
One dot (DrawWidth across). |
Printer.PaintPicture pic, x, y [, w, h [, srcX, srcY, srcW, srcH]] |
A picture (a PictureBox, a file, or LoadPicture’s), stretched to w x h; without them, at its size on the screen (15 twips a pixel). |
Printer.NewPage |
Print the page (even a blank one) and start the next; Page goes up by 1. |
Printer.EndDoc |
Print the page drawn and end the document; Page goes back to 1. |
Printer.KillDoc |
Stop printing at once, as in Visual Basic: the page being drawn is thrown away and the document ends without waiting for the printer, even one that is busy or offline, and without asking about it. Nothing more is sent; what the printer has already taken stays printed. |
Printer.TextWidth(text), TextHeight(text) |
The size text takes in the font, in the Printer’s scale. |
Printer.Scale (x1, y1)-(x2, y2), ScaleX, ScaleY |
As on a PictureBox: a scale of your own, and lengths from one scale to another. |
| Property | Description |
|---|---|
CurrentX, CurrentY |
Where the next drawing starts. |
ForeColor, FillColor, FillStyle, DrawWidth, DrawStyle |
As on a PictureBox (black, transparent fills, a solid pen 1 dot wide to start). |
ScaleMode, ScaleLeft, ScaleTop, ScaleWidth, ScaleHeight |
The scale (vbTwips to start). |
FontName, FontSize, FontBold, FontItalic, FontUnderline, FontStrikethru |
The font of Print’s text; FontSize is in points (12 to start, in DejaVu Sans). Text prints crisp where the font has sizes made for printing (DejaVu Sans, Serif, and Sans Mono have them from 6 to 24 points at 300 dpi), and a little softer where a smaller size is enlarged. |
Copies |
How many times each page prints (1 to 99); as PrintChoose chose when it is not set. |
Page |
The page being drawn (1 first). Read only. |
Width, Height |
The page’s size in twips (11520 by 14400). Read only. |
TwipsPerPixelX, TwipsPerPixelY |
Twips in one of the printer’s dots. Read only. |
ColorMode |
vbPRCMColor on a color printer, else vbPRCMMonochrome. Read only. |
Orientation |
vbPRORPortrait: pages print upright only. |
DeviceName, Port |
The printer model and where it is connected, as the Control Panel names them. Read only. |
Sub mnuReport_Click ()
Printer.ScaleMode = vbInches
Printer.FontSize = 18
Printer.FontBold = True
Printer.CurrentX = 1
Printer.CurrentY = 1
Printer.Print "Sales by Region"
Printer.FontSize = 11
Printer.FontBold = False
Printer.Line (1, 1.5)-(7, 1.5)
Printer.FillStyle = 0
Printer.FillColor = vbBlue
Printer.Line (1, 2)-(1 + nNorth / 100, 2.4), vbBlue, B
Printer.CurrentX = 1: Printer.CurrentY = 2.5
Printer.Print "North"; Tab(20); nNorth
Printer.EndDoc
End Sub
A bad argument to a drawing method (an angle past 2 pi, a Scale on one line) raises error 5, and Copies outside 1 to 99, a FontSize of 0 or less or past 1000 points, and vbPRORLandscape raise error 380 (Invalid property value), as on a PictureBox: ON ERROR can trap them, and the property keeps its value.
The Printer has no Cls, Point, PAINT, or DRAW (Visual Basic’s Printer has none of them either), and no Printer.Font object: use FontName, FontSize, and the other Font properties. A raster operation given to PaintPicture is not used on paper. A control or form of your own named Printer takes the name’s place.
1.14. Screen Object
The Screen object is the DVX desktop, as in Visual Basic: its size, so a program can place its forms (for example in a corner of the screen), its color depth, the mouse pointer, and the arrangement of the windows on it.
| Property | Type | R/W | Description |
|---|---|---|---|
Screen.Width |
Long |
R |
Width of the desktop in pixels |
Screen.Height |
Long |
R |
Height of the desktop in pixels |
Screen.BitsPerPixel |
Long |
R |
Color depth of the display: 8, 15, 16, 24, or 32 bits per pixel |
Screen.MousePointer |
Integer |
R/W |
vbHourglass (11) for the busy pointer while a long job runs; another pointer (vbArrow, vbCrosshair, vbSizeNS, vbSizeWE, vbSizeNWSE, vbSizeNESW, vbNoDrop: see Mouse Constants) over every form of the program, whatever their controls' MousePointer; vbDefault (0) back to each control’s own |
Screen.ActiveControl |
Control |
R |
The control of the program that has the keyboard focus, Nothing when none has it (another program’s window has the focus) |
Screen.ActiveForm |
Form |
R |
The form of the program that has the focus (the active window), Nothing when none has it (another program’s window, or a dialog box such as a MsgBox, has the focus): Screen.ActiveForm.Caption |
Screen.DebugLayout |
Boolean |
R/W |
True draws a colored border around every layout container (VBox, HBox, Frame ...) in every window, to see how a form is laid out; False removes them |
The sizes are in pixels, the unit of a form’s Left, Top, Width, and Height in DVX (Visual Basic uses twips there).
Screen is an object like any other, as in Visual Basic, and so is Printer: Set o = Screen, an argument for an Object parameter, TypeName(Screen) ("Screen"), and o Is Screen work, and the properties and methods are reached through the variable (o.Width). Their names are types too, as in Visual Basic (Dim s As Screen, Sub Report(p As Printer)): a variable or parameter of the type holds that object only, and another object stored there raises error 13 (Type mismatch), or does not compile when the compiler can tell. Screen alone is the object; QBasic’s SCREEN function always has its arguments (SCREEN(row, col)). A control or form of your own named Screen or Printer takes the name’s place.
' Put the form at the right edge, 40 pixels from the top
Me.Left = Screen.Width - Me.Width - 40
Me.Top = 40
Set the hourglass before a long job and put the arrow back after it. The pointer is the whole desktop’s, so the program should not leave it busy; when the program ends, a busy pointer it set goes back to the arrow.
Screen.MousePointer = vbHourglass
CountWords
Screen.MousePointer = vbDefault
1.14.1. Arrange
Screen.Arrange arrangement puts every window on the desktop that is shown and not minimized (those of other programs too) in order, as the Window menu of a program does:
| Constant | Value | Arrangement |
|---|---|---|
vbCascade |
0 |
Overlapping, each one a little down and to the right of the one before |
vbTileHorizontal |
1 |
Stacked from top to bottom, each the full width of the screen |
vbTileVertical |
2 |
Side by side from left to right, each the full height of the screen |
vbTileGrid |
4 |
In rows and columns |
The values are those of Visual Basic’s MDIForm.Arrange (vbTileGrid is DVX’s own; 3, Visual Basic’s vbArrangeIcons, is not used).
Sub mnuCascade_Click ()
Screen.Arrange vbCascade
End Sub
Any other property or method raises error 438 (Object doesn’t support this property or method), a property that can only be read error 383 (Property is read-only), Arrange with another value error 5, and without one error 449: ON ERROR traps each. The QBasic statement SCREEN and function SCREEN(row, column) are unaffected: Screen followed by a dot is the object. A control or form of your own named Screen takes the name’s place.
1.15. INI Functions
DVX BASIC provides built-in functions for reading and writing standard INI configuration files (the same text format used by DVX system configuration).
1.15.1. IniRead
Reads a value from an INI file. Returns the default value if the file, section, or key is not found. All four arguments are required. Section and key names match without regard to case, and blanks around them are ignored ([ User ] is section User). If a name appears twice, the first one counts. Keys above the first section header belong to section "" (an empty section name). Lines starting with ; or # are comments.
value$ = IniRead(file$, section$, key$, default$)
name$ = IniRead(App.User & "\app.ini", "User", "Name", "Unknown")
fontSize = Val(IniRead(App.User & "\app.ini", "Display", "FontSize", "12"))
1.15.2. IniWrite
Writes a value to an INI file. Creates the file, section, or key if they do not exist. A new key goes after the last key of its section and a new section at the end of the file. Every other line — comments, blank lines, other keys, lines of any length — is kept exactly as it is. The changed key is written as key = value. Every line of the saved file ends in a carriage return and line feed (CR LF). The file is saved through a temporary file, so a failed write leaves the old file intact. If the file exists but cannot be read, or the new file cannot be written, IniWrite raises error 75 (Path/file access error) and leaves the file alone.
INIWRITE file$, section$, key$, value$
IniWrite App.User & "\app.ini", "User", "Name", "Scott"
IniWrite App.User & "\app.ini", "Display", "FontSize", Str$(fontSize)
1.16. Predefined Constants
The following constants are predefined by the compiler and available in all programs. No DIM or CONST declaration is required to use them.
1.16.1. MsgBox Button Style Flags
| Constant | Value | Description |
|---|---|---|
vbOKOnly |
0 |
OK button only (default) |
vbOKCancel |
1 |
OK and Cancel buttons |
vbYesNo |
2 |
Yes and No buttons |
vbYesNoCancel |
3 |
Yes, No, and Cancel buttons |
vbRetryCancel |
4 |
Retry and Cancel buttons |
1.16.2. MsgBox Icon Flags
Add an icon flag to the button style (with + or OR) to display an icon in the message box.
| Constant | Value | Description |
|---|---|---|
vbInformation |
&H10 |
Information icon (i) |
vbExclamation |
&H20 |
Warning icon (!) |
vbCritical |
&H30 |
Error/critical icon (X) |
vbQuestion |
&H40 |
Question icon (?) |
1.16.3. MsgBox Return Values
| Constant | Value | Description |
|---|---|---|
vbOK |
1 |
User clicked OK |
vbCancel |
2 |
User clicked Cancel |
vbYes |
3 |
User clicked Yes |
vbNo |
4 |
User clicked No |
vbRetry |
5 |
User clicked Retry |
1.16.5. Window State, Arrangement, and Mouse Pointer
A form’s WindowState and ZOrder, and Screen.Arrange (see Form and Screen Object); the MousePointer values are under Mouse Constants.
| Constant | Value | Description |
|---|---|---|
vbNormal |
0 |
WindowState: a normal window |
vbMinimized |
1 |
WindowState: shown only as an icon |
vbMaximized |
2 |
WindowState: filling the screen |
vbCascade |
0 |
Arrange: overlapping windows |
vbTileHorizontal |
1 |
Arrange: windows stacked top to bottom |
vbTileVertical |
2 |
Arrange: windows side by side |
vbTileGrid |
4 |
Arrange: windows in rows and columns |
vbBringToFront |
0 |
ZOrder: in front of the other windows (the default) |
vbSendToBack |
1 |
ZOrder: behind the other windows |
1.16.6. QueryUnload Constants
Why a form closes: the UnloadMode argument of its QueryUnload event (see Form Events in the Form topic).
| Constant | Value | Description |
|---|---|---|
vbFormControlMenu |
0 |
The user closed the form’s window: its close box, Alt+F4, or its system menu’s Close |
vbFormCode |
1 |
UNLOAD in the program’s code |
vbAppWindows |
2 |
DVX is exiting (Exit DVX asks every program to close) |
vbAppTaskManager |
3 |
Another program asked this one to close (ShellRunningClose), or DVX ended its screen saver |
vbFormMDIForm |
4 |
Never passed: DVX has no MDI forms |
vbFormOwner |
5 |
Never passed: DVX has no owned forms |
1.16.7. Data Control Validate Constants
The operation a Data control’s Validate event is called for: its Action argument (see the Data control’s Validate event). Setting Action to vbDataActionCancel cancels the operation; setting it to a Move or AddNew value turns a Move or AddNew into that one.
| Constant | Value | Description |
|---|---|---|
vbDataActionCancel |
0 |
Set by the handler: cancel the operation |
vbDataActionMoveFirst |
1 |
MoveFirst |
vbDataActionMovePrevious |
2 |
MovePrevious |
vbDataActionMoveNext |
3 |
MoveNext |
vbDataActionMoveLast |
4 |
MoveLast |
vbDataActionAddNew |
5 |
AddNew |
vbDataActionUpdate |
6 |
Update of a changed record |
vbDataActionDelete |
7 |
Delete |
vbDataActionFind |
8 |
Never passed: DVX’s Data control has no Find method |
vbDataActionBookmark |
9 |
Setting AbsolutePosition (or a DBGrid row click) |
vbDataActionClose |
10 |
Refresh: the records are read again |
vbDataActionUnload |
11 |
The form is unloading |
1.16.8. File Attribute Flags
Bit values used with GETATTR and SETATTR.
| Constant | Value | Description |
|---|---|---|
vbNormal |
0 |
Normal file (no attributes) |
vbReadOnly |
1 |
Read-only |
vbHidden |
2 |
Hidden |
vbSystem |
4 |
System file |
vbDirectory |
16 |
Entry is a directory |
vbArchive |
32 |
File has been modified since last backup |
1.16.9. Compare Constants
The compare argument of FILTER, INSTR, INSTRREV, REPLACE$, SPLIT, and STRCOMP.
| Constant | Value | Description |
|---|---|---|
vbUseCompareOption |
-1 |
Follow the OPTION COMPARE of the call’s file (the default) |
vbBinaryCompare |
0 |
Exact match |
vbTextCompare |
1 |
Ignore upper and lower case |
1.16.10. Day and Week Constants
The firstDay and firstWeek arguments of the date functions, and WEEKDAY results.
| Constant | Value | Description |
|---|---|---|
vbUseSystemDayOfWeek |
0 |
Weeks start on Sunday |
vbSunday |
1 |
Sunday |
vbMonday |
2 |
Monday |
vbTuesday |
3 |
Tuesday |
vbWednesday |
4 |
Wednesday |
vbThursday |
5 |
Thursday |
vbFriday |
6 |
Friday |
vbSaturday |
7 |
Saturday |
vbUseSystem |
0 |
Week 1 holds January 1 |
vbFirstJan1 |
1 |
Week 1 holds January 1 |
vbFirstFourDays |
2 |
Week 1 is the first with four days in the new year |
vbFirstFullWeek |
3 |
Week 1 is the first full week |
1.16.11. Format Constants
FORMATDATETIME’s namedFormat, and the leadingDigit, parens, and group arguments of FORMATNUMBER, FORMATCURRENCY, and FORMATPERCENT (see Format Function).
| Constant | Value | Description |
|---|---|---|
vbGeneralDate |
0 |
The date and the time (the date alone at midnight, the time alone on no date) |
vbLongDate |
1 |
The long date: Wednesday, January 5, 2000 |
vbShortDate |
2 |
The short date: 1/5/2000 |
vbLongTime |
3 |
The long time: 3:04:05 PM |
vbShortTime |
4 |
The short time, 24-hour: 15:04 |
vbUseDefault |
-2 |
The usual layout for the function |
vbTrue |
-1 |
Yes |
vbFalse |
0 |
No |
1.16.12. Drag and Drop Constants
The DragMode property, the Drag method, and the State argument of DragOver.
| Constant | Value | Description |
|---|---|---|
vbManual |
0 |
DragMode: the program starts drags with Drag |
vbAutomatic |
1 |
DragMode: pressing the control starts a drag |
vbBeginDrag |
1 |
Drag: start dragging (the default) |
vbEndDrag |
2 |
Drag: drop where the mouse is (Drag 0 cancels) |
vbEnter |
0 |
DragOver: the drag came onto the object |
vbLeave |
1 |
DragOver: the drag went off the object |
vbOver |
2 |
DragOver: the drag moved over the object |
1.16.13. PopupMenu Constants
The flags of the PopupMenu method, as Visual Basic’s (add an alignment and a button).
| Constant | Value | Description |
|---|---|---|
vbPopupMenuLeftAlign |
0 |
The menu’s left edge at x (the default) |
vbPopupMenuCenterAlign |
4 |
The menu’s middle at x |
vbPopupMenuRightAlign |
8 |
The menu’s right edge at x |
vbPopupMenuLeftButton |
0 |
Items chosen with the left button (the default) |
vbPopupMenuRightButton |
2 |
Items chosen with either button; DVX menus take either already |
1.16.14. Clipboard Constants
| Constant | Value | Description |
|---|---|---|
vbCFText |
1 |
Text, the format the DVX clipboard holds |
1.16.15. Mouse Constants
The Button argument of the MouseDown, MouseUp, and MouseMove events (several bits when several buttons are down), and the values of MousePointer (controls, forms, and Screen).
| Constant | Value | Description |
|---|---|---|
vbLeftButton |
1 |
The left button |
vbRightButton |
2 |
The right button |
vbMiddleButton |
4 |
The middle button |
vbDefault |
0 |
MousePointer: the control’s own pointer |
vbArrow |
1 |
MousePointer: the arrow |
vbCrosshair |
2 |
MousePointer: a cross, for placing things |
vbSizeNESW |
6 |
MousePointer: two-way arrow, top right to bottom left |
vbSizeNS |
7 |
MousePointer: two-way arrow, up and down |
vbSizeNWSE |
8 |
MousePointer: two-way arrow, top left to bottom right |
vbSizeWE |
9 |
MousePointer: two-way arrow, left and right |
vbHourglass |
11 |
MousePointer: busy |
vbNoDrop |
12 |
MousePointer: a circle with a line through it |
Visual Basic’s other pointers (vbIbeam, vbUpArrow, custom pointers) have no DVX shape; DVX has no MouseIcon.
1.16.16. Syntax Color Constants
The kinds of text a TextArea colors: the index of SetSyntaxColor and GetSyntaxColor, and the digits of the Colors argument of the Colorize event ("0" is vbSyntaxText ... "6" vbSyntaxType).
| Constant | Value | Description |
|---|---|---|
vbSyntaxText |
0 |
Ordinary text (ForeColor) |
vbSyntaxKeyword |
1 |
Keywords |
vbSyntaxString |
2 |
Strings |
vbSyntaxComment |
3 |
Comments |
vbSyntaxNumber |
4 |
Numbers |
vbSyntaxOperator |
5 |
Operators |
vbSyntaxType |
6 |
Type names |
1.16.17. CallByName Constants
| Constant | Value | Description |
|---|---|---|
vbMethod |
1 |
Call a method (or a function of a class) |
vbGet |
2 |
Read a property |
vbLet |
4 |
Assign a property a value |
vbSet |
8 |
Assign a property an object (Set) |
1.16.18. Key Code Constants
The KeyCode a KeyDown event gets, and the bits of its Shift argument (and of MouseDown’s, MouseUp’s, and MouseMove’s). The key codes are DVX’s, so compare KeyCode with the constants rather than with numbers from Visual Basic. The Shift bits are Visual Basic’s (1, 2, and 4), and Shift holds only them: the Num Lock, Caps Lock, and Scroll Lock keys are never in it. KeyDown comes before the control acts on the key; setting KeyCode to 0 cancels the key, as in Visual Basic. A character key gives its character’s code (Asc("a") with no Shift), and Ctrl with a letter gives 1 to 26 (Ctrl+A is 1, Ctrl+C 3, Ctrl+V 22, Ctrl+X 24).
| Constant | Value | Description |
|---|---|---|
vbKeyBack |
8 |
Backspace |
vbKeyTab |
9 |
Tab |
vbKeyReturn |
13 |
Enter |
vbKeyEscape |
27 |
Esc |
vbKeySpace |
32 |
Space bar |
vbKeyPageUp, vbKeyPageDown |
&H149, &H151 |
Page Up, Page Down |
vbKeyEnd, vbKeyHome |
&H14F, &H147 |
End, Home |
vbKeyLeft, vbKeyUp |
&H14B, &H148 |
Arrow keys |
vbKeyRight, vbKeyDown |
&H14D, &H150 |
Arrow keys |
vbKeyInsert, vbKeyDelete |
&H152, &H153 |
Ins, Del |
vbKeyF1 to vbKeyF10 |
&H13B to &H144 |
Function keys F1 to F10 |
vbKeyF11, vbKeyF12 |
&H185, &H186 |
Function keys F11 and F12 |
vbShiftMask |
1 |
Shift argument: a Shift key is down |
vbCtrlMask |
2 |
Shift argument: Ctrl is down |
vbAltMask |
4 |
Shift argument: Alt is down |
Sub List1_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyDelete Then
DeleteSelected
ElseIf KeyCode = 1 And (Shift And vbCtrlMask) <> 0 Then
SelectEverything ' Ctrl+A
End If
End Sub
1.16.19. Scale and Picture Constants
The scale units of ScaleMode and of the ScaleX / ScaleY methods, and the values of a Picture object’s Type (see Drawing on Forms and PictureBoxes, and LOADPICTURE).
| Constant | Value | Description |
|---|---|---|
vbUser |
0 |
The object’s own scale (Scale, ScaleWidth ...) |
vbTwips |
1 |
Twips (1440 an inch, 15 a pixel) |
vbPoints |
2 |
Points (72 an inch) |
vbPixels |
3 |
Pixels (the DVX default ScaleMode) |
vbCharacters |
4 |
Characters (120 twips across, 240 down) |
vbInches |
5 |
Inches |
vbMillimeters |
6 |
Millimeters |
vbCentimeters |
7 |
Centimeters |
vbHimetric |
8 |
Hundredths of a millimeter (ScaleX / ScaleY only; a Picture’s Width and Height) |
vbPicTypeNone |
0 |
Picture.Type of an empty picture |
vbPicTypeBitmap |
1 |
Picture.Type of a loaded picture |
1.16.20. Fill and Pen Constants
The values of FillStyle and DrawStyle on Forms, PictureBoxes, and the Printer (see Drawing on Forms and PictureBoxes).
| Constant | Value | Description |
|---|---|---|
vbFSSolid |
0 |
FillStyle: filled solid in FillColor |
vbFSTransparent |
1 |
FillStyle: not filled (the default) |
vbHorizontalLine |
2 |
FillStyle: horizontal lines |
vbVerticalLine |
3 |
FillStyle: vertical lines |
vbUpwardDiagonal |
4 |
FillStyle: lines rising to the right |
vbDownwardDiagonal |
5 |
FillStyle: lines falling to the right |
vbCross |
6 |
FillStyle: a cross hatch |
vbDiagonalCross |
7 |
FillStyle: a diagonal cross hatch |
vbSolid |
0 |
DrawStyle: a solid pen (the default) |
vbDash |
1 |
DrawStyle: dashes |
vbDot |
2 |
DrawStyle: dots |
vbDashDot |
3 |
DrawStyle: dash, dot |
vbDashDotDot |
4 |
DrawStyle: dash, dot, dot |
vbInvisible |
5 |
DrawStyle: no lines or outlines (fills still drawn) |
vbInsideSolid |
6 |
DrawStyle: solid |
1.16.21. Align Constants
The values of a PictureBox’s Align, the edge of its form it is docked to (see PictureBox).
| Constant | Value | Description |
|---|---|---|
vbAlignNone |
0 |
Not docked: among the form’s controls (the default) |
vbAlignTop |
1 |
Docked to the top, as wide as the form |
vbAlignBottom |
2 |
Docked to the bottom, as wide as the form |
vbAlignLeft |
3 |
Docked to the left, as tall as the form between those docked Top and Bottom |
vbAlignRight |
4 |
Docked to the right, as tall as the form between those docked Top and Bottom |
1.16.22. Alignment and MultiSelect Constants
The values of a Label’s Alignment and a RichEdit’s SelAlignment, in Visual Basic’s order, and of a ListBox’s MultiSelect and Style (see Label, RichEdit, and ListBox).
| Constant | Value | Description |
|---|---|---|
vbLeftJustify |
0 |
A Label’s text at its left (the default) |
vbRightJustify |
1 |
A Label’s text at its right |
vbCenter |
2 |
A Label’s text centered |
rtfLeft |
0 |
A RichEdit’s paragraphs at the left |
rtfRight |
1 |
A RichEdit’s paragraphs at the right |
rtfCenter |
2 |
A RichEdit’s paragraphs centered |
vbMultiSelectNone |
0 |
One item at a time (the default) |
vbMultiSelectSimple |
1 |
A click selects or deselects an item |
vbMultiSelectExtended |
2 |
Shift and Ctrl with a click or the arrow keys extend the selection |
vbListBoxStandard |
0 |
A ListBox of plain items (the default) |
vbListBoxCheckbox |
1 |
A ListBox with a check box before each item |
1.16.23. VarType Constants
The values VARTYPE returns (see Variants). For an array, VARTYPE adds vbArray to the type of its elements.
| Constant | Value | Kind of value |
|---|---|---|
vbEmpty |
0 |
Empty (nothing stored yet) |
vbNull |
1 |
Null |
vbInteger |
2 |
Integer |
vbLong |
3 |
Long |
vbSingle |
4 |
Single |
vbDouble |
5 |
Double |
vbCurrency |
6 |
Currency |
vbDate |
7 |
Date |
vbString |
8 |
String |
vbObject |
9 |
An object or Nothing |
vbError |
10 |
Error value (Visual Basic only; no DVX value has this type) |
vbBoolean |
11 |
Boolean |
vbVariant |
12 |
Variant (only in vbArray + vbVariant, an array of Variants) |
vbDataObject |
13 |
Data object (Visual Basic only; no DVX value has this type) |
vbByte |
17 |
Byte |
vbUserDefinedType |
36 |
A TYPE variable |
vbArray |
8192 |
Added to the element type for an array |
1.16.24. Error Constants
| Constant | Value | Description |
|---|---|---|
vbObjectError |
-2147221504 |
Base for your own error numbers, as in Visual Basic: a class module raises ERROR vbObjectError + n, and the handler recovers n with ERR - vbObjectError |
1.16.25. Color Constants
Colors in the form RGB makes (&HBBGGRR, see Color Functions), as in Visual Basic.
| Constant | Value | Color |
|---|---|---|
vbBlack |
&H0 |
Black |
vbRed |
&HFF |
Red |
vbGreen |
&HFF00 |
Green |
vbYellow |
&HFFFF |
Yellow |
vbBlue |
&HFF0000 |
Blue |
vbMagenta |
&HFF00FF |
Magenta |
vbCyan |
&HFFFF00 |
Cyan |
vbWhite |
&HFFFFFF |
White |
1.16.27. String Constants
Line ends and other control characters, as in Visual Basic. MsgBox, InputBox$, and the other dialog boxes start a new line at vbCrLf, vbLf, or vbCr alike. A TextArea’s lines end in vbLf; a text file’s, as PRINT # writes them, in vbCrLf.
| Constant | Value | Description |
|---|---|---|
vbCrLf |
CHR$(13) + CHR$(10) |
A carriage return and a line feed: the end of a line in a DOS text file |
vbNewLine |
CHR$(13) + CHR$(10) |
The same as vbCrLf |
vbCr |
CHR$(13) |
A carriage return |
vbLf |
CHR$(10) |
A line feed |
vbTab |
CHR$(9) |
A tab |
vbBack |
CHR$(8) |
A backspace |
vbFormFeed |
CHR$(12) |
A form feed (a new page, to a printer) |
vbVerticalTab |
CHR$(11) |
A vertical tab |
vbNullChar |
CHR$(0) |
A character with the code 0 |
vbNullString |
"" |
An empty string |
MsgBox "Saved." & vbCrLf & "The file is " & path
Print #1, name; vbTab; score
1.17. Include Libraries
DVX BASIC comes with a set of BASIC include files (.bas), in the INCLUDE folder beside the IDE (the SDK has them in include/basic). Each file is a small library of DECLARE LIBRARY wrappers around native DVX runtime functions. Add an include file to your project with File > Add Library, which copies it into the project’s folder (or list it in the .dbp’s [Modules] with another tool), and the declared functions become available to your code.
- commdlg.bas
-
File Open/Save dialogs (DlgFileOpenIn$ and DlgFileSaveIn$ start in a folder you name, and DlgFileSaveAs$ also suggests a file name, ready for Enter; an Open dialog takes only a file that exists, and DlgFileOpenOrCreate$ also takes a new name after asking whether to create it), the folder dialog (DlgFolder$, for a Browse button), input dialogs, choice dialogs, save-prompt dialogs, the color dialog, the font dialog (DlgFont), message boxes with your own buttons (DlgButtons)
- sql.bas
-
SQLite database access (SQLOpen, SQLQuery, SQLNext, SQLField$, etc.)
- comm.bas
-
Serial-port I/O (raw and packet) and optional encrypted links; port settings read back and changed, why a call failed, breaks, ring, and line errors (SerOpen, SerSet, SerLastError, CommOpen, CommOpenTcp, CommHandshakeStep, ...)
- conn.bas
-
Connections the way Terminal makes them: a serial port, a modem that dials, the secure link to the DVX host proxy, or Telnet, shown on a Terminal control, with capture, answerback, and file transfers (ConnCreate, ConnOpen, ConnPoll, ConnAttach, ConnSendFiles, ...)
- xfer.bas
-
File transfers with XMODEM, XMODEM-1K, YMODEM, and ZMODEM, on a serial port or a connection, with their progress and questions (XferSendFile, XferStatus, XferBytes, XferAnswer, ...)
- prefs.bas
-
Settings files (INI): load one, read and change its settings, list the keys of a section, save it; DVX’s own settings file, the screen mode it starts in, the names its choices are stored as and its default choices, and choices stored by names of your own (PrefsLoad, PrefsLoadFailed, PrefsGet$, PrefsSet, PrefsKeyName$, PrefsSaveAs, PrefsDvxIni$, PrefsVideoWidth, PrefsChoiceLabel$, PrefsChoiceDefault, PrefsGetChoiceFrom, ...)
- resource.bas
-
Read and write DVX resource blocks (icons, text, binary data) in bundled files
- help.bas
-
Compile help source files and see the compiler’s messages, and open DVX Help, at a topic if you like (HelpCompile, HelpCompileMessages$, HelpView, HelpViewTopic; HelpView "" opens the DVX user guide)
- hlpfile.bas
-
Read compiled help files yourself, for a help viewer of your own: topics, table of contents, keyword index, full-text search, and each topic’s headings, text, links, and pictures; show a topic in a HelpPane control (HlpOpen, HlpTocTitle$, HlpIndexKeyword$, HlpSearch, HlpLoadTopic, ...)
- net.bas
-
Network connections: TCP (TcpConnect, TcpListen, TcpSend, TcpRecv$, TcpPeer$, ...), UDP messages and name lookups, any bytes; the network settings and status (NetConfigLoad, NetConfigSet, NetConfigStore, NetRestart, NetStatus$, ...)
- print.bas
-
Printing: text with the page setup and pictures, with or without the Print dialog; a form; the Page Setup dialog; the printer and page settings; the printer ports (PrintModelLabel$, PrintSettingsStore, PrintPageSetting, PrintChoose, PrintForm, PrintPortStatus, ...)
- listhelp.bas
-
Lists and icon views you draw yourself (a UserControl, a PictureBox) that behave like ListBox and Program Manager: selection with Shift and Ctrl, the arrow keys in a list or a grid, Ctrl+A, Space, type-ahead, where a dragged item lands, and Program Manager’s icon view rules — its cells, the grid with a scroll bar, names on two lines, dragging and dropping (ListSelCreate, ListSelClick, ListSelNavigate, ListTypeAhead, ListIconMetric, ListIconLabel$, ...)
- security.bas
-
Security: random bytes for keys, key exchanges, ciphers, sealing, SHA-256 hashes, HMAC and public-key signatures, key making, and a safe compare (SecRandom$, SecX25519$, SecAeadLock$, SecEd25519Sign$, SecSha256$, SecHkdf$, ...)
- game.bas
-
Games: whether a key is being held down right now, forgetting held keys, frames FRAMEWAIT skipped, waiting for the screen’s retrace (GameKeyDown, GameKeyClear, FrameMissed, GameWaitRetrace)
- joystick.bas
-
Joysticks: how many there are, their names, where each stick points, and which buttons are pressed (JoyCount, JoyX, JoyY, JoyButton, ...); setting them up: calibration, dead zone, game port mode, keyboard joystick keys (JoySetCalibration, JoyCalibration, JoyRescan, JoyKeyIndex, JoySettingsStore, ...)
- sound.bas
-
Sound: play WAV and VOC files, tones and noise, set the volume (PlayWave, PlayTone, StopWave, SoundInfo$, ...); sounds loaded once and played with volume, pan, and pitch, sound made by the program as it goes, recording from a microphone or line input (RecordStart, RecordStop, RecordLevel, ...), the FM synthesizer chip, a wavetable card’s voices and memory (SoundLoad, SoundPlay, SoundSetPitch, SoundCreate, SoundStreamOpen, SoundStreamWrite, FmAlloc, FmWrite, WtAlloc, WtStart, ...); DVX’s own event sounds (SoundPlayEvent), master volume, sound driver, and MIDI settings (SoundEventFile$, SoundSetMasterVolume, SoundSettingsStore, ...)
- music.bas
-
Music: play MOD, S3M, XM, IT, MIDI, WAV, and VOC files, and play notes yourself (MusicLoad, MusicPlay, MusicStop, MusicNoteOn, MusicInfo$, ...); instruments from banks and SoundFonts, a sound card’s own (MusicSetBank, MusicPatchSet$, MusicRomBank$); raw bytes to the MIDI port (MidiAcquire, MidiPut, MidiRelease, MidiPortInfo$); what a MIDI keyboard plays, heard as it comes and recorded into MIDI files (MidiInOpen, MidiInMessage, MusicMidiSend, MidiRecordNew, MidiRecordSave, ...)
- fileops.bas
-
Files and folders: folder listings for a file list, paths and names, the file dialogs' filter rule, attributes and the time a file was changed, sizes, free space and disk sizes, drive kinds, whether a folder can be written, the folder for scratch files, making a folder path, and copying, moving, and deleting whole folders at once or as a job with progress, Cancel, and questions (FileOpsList, FileOpsListRows$, FileOpsFilterMatch, FileOpsSetModified, FileOpsDriveType, FileOpsIsWritable, FileOpsMakePath, FileOpsJobCreate, FileOpsJobRunFor, ...)
- system.bas
-
What Control Panel changes, at once for the whole desktop: the screen mode, the system colors and themes, the wallpaper, text smoothing, and the mouse (with DVX’s limits and defaults, MOUSE_* and SYS_VIDEO_DEFAULT_*), and storing them in DVX’s settings; the system font’s character pictures; the mouse pointer and the Shift, Ctrl, and Alt keys anywhere on the screen, moving the pointer, typing keys into the window in front, a picture of the whole screen, the memory, and whether a library is installed (SysSetVideoMode, SysSetColor, SysLoadTheme, SysSetWallpaper, SysSetTextSmoothing, SysSetMouse, SysColorsStore, SysFontGlyphRow, SysMouseX, SysSendKey, SysScreenshot, SysMemoryFreeKb, SysLibraryLoaded, ...)
- font.bas
-
Fonts: the font families DVX has, the sizes each comes in, whether one is fixed-pitch, and how wide text and how tall a line is in a font (FontFamilyCount, FontFamilyName$, FontFamilyFixed, FontSizeCount, FontSizeAt, FontNearestSize, FontTextWidth, FontLineHeight, FontAscent, FontRescan)
- richtext.bas
-
RTF without a control: an RTF document as plain text and plain text as RTF (RtfToText$, TextToRtf$); a RichEdit control reads and writes RTF itself (TextRTF, SelRTF, LoadFile, SaveFile)
- layout.bas
-
Control sizes in characters or in percent of the container instead of pixels (SizeChars, SizePercent)
- compiler.bas
-
The BASIC compiler: compile a project or files you give it, find compile errors in their files, list a program’s procedures and the language’s keywords, build an .app or a control file; put a project’s UserControls on a form designer’s toolbox; read source text as the compiler does (tokens, code or string or comment, renaming a control in code, WithEvents variables, class Events), F1 help topics; open, change, and save project files and UserControl headers (CompSourceFromProject, CompSourceAdd, CompCompile, CompError$, CompMapFile$, CompProcList$, CompBuildApp, CompDesignControls, CompTokens$, CompRenameInCode$, CompHelpTopic$, ProjOpen, ProjSave, ProjCtlSetHeader$, ...)
- debug.bas
-
Run a compiled program inside yours and debug it: breakpoints, stepping, its variables, expressions, Immediate-window lines, its PRINT output (RunCreate, RunStart, RunPoll, DbgSetBreakpoints, DbgStepOver, DbgLocals$, DbgEval$, DbgExec$, ...)
- designer.bas
-
Form designers: the control types, whether each holds other controls and can be placed, the names of new controls, default events, toolbox tooltips and icons, and each type’s properties (with their types and value names), methods, and events (with each event’s parameters); the names in .frm and class module text; .frm files as data to read, edit, and write, controls copied and pasted as text, and a loaded form written back as .frm text (CtlTypeCount, CtlTypeName$, CtlTypeFlags, CtlTypeNaturalSize$, CtlPropCount, CtlPropName$, CtlPropType, CtlEventList$, CtlEventParams$, CtlTypeEventParams$, FrmFormName$, FrmControlNames$, ClsClassName$, FrmOpen, FrmText$, FrmCtlAdd, FrmCtlText$, FrmCtlPaste, FrmMenuAdd, FormText$, ...)
- shell.bas
-
DVX itself, everything Program Manager and Task Manager do: start programs (DVX’s and DOS programs) and open documents, command lines (split into their parts) and the Run dialog, the installed programs and their names, file types, the running programs (find one, bring it to the front, ask it to close, or end it, and their priority), this program’s priority, keys that work in every program, Task Manager, system information, Exit DVX, the desktop and the program started after it, the DVX log; Program Manager’s program groups with their items, shortcut keys, and icons (ShellRun, ShellRunProgram, ShellRunDos, ShellProgramScan, ShellAssocCount, ShellRunningId, ShellRunningActivate, ShellRunningClose, ShellArg$, ShellSetPriority, HotkeyAdd, ShellExitDvx, ShellGroupsLoad, ShellItemGet$, ShellItemIcon$, ...)
- pkg.bas
-
Add-on packages: the packages installed in DVX and their details, files, and needs; reading .DPK files, installing, removing, making, and signing packages as jobs with progress, and planning what installing them takes; trusting a publisher’s key; and making keys (PkgOpen, PkgInstalledRows$, PkgOfferFileStart, PkgPlan, PkgInstallStart, PkgRunFor, PkgRemoveStart, PkgBuildStart, PkgSignStart, PkgKeygen, ...)
- json.bas
-
JSON: read a document (a web service’s reply, a settings file) and find values in it by path such as packages[3].version, and quote text for JSON of your own (JsonParse, JsonText$, JsonNumber, JsonCount, JsonKey$, JsonQuote$, ...)
- http.bas
-
Web requests: GET a page, a file, or a web service’s answer, or POST to one, over the network a little at a time with progress, to memory or to a file (resuming one left part-way), following redirects (HttpOpen, HttpStart, HttpRunFor, HttpStatus, HttpBody$, HttpSaveTo, ...)
- pkgnet.bas
-
A package server: what it offers, what it has that is newer than what is installed, and fetching packages with what they need, for pkg.bas to install (PkgNetOpen, PkgNetCatalogue, PkgNetUpdates, PkgNetFetch, PkgNetRunFor, PkgNetRows$, ...)
1.17.1. Using an Include Library
' With commdlg.bas added to the project
Dim path As String
path = DlgFileOpen$("Open a file", "Text Files (*.txt)|All Files (*.*)")
If path <> "" Then
Print "Selected: " & path
End If
1.17.2. When a Library Is Not Installed
Some libraries are optional parts of DVX (the network, printing, sound, joysticks ...). Calling a function of a library that is not on the computer raises run-time error 453 ("External function not found: " and the function’s name), which ON ERROR can trap — for example to show a message instead of a page of settings, as Control Panel does:
Dim status As String
On Error Resume Next
status = NetStatus$("message")
If Err.Number = 453 Then
lblNet.Caption = "The network is not installed."
Else
lblNet.Caption = status
End If
On Error GoTo 0
1.17.3. Message Boxes with Your Own Buttons
MsgBox offers fixed sets of buttons (OK, Yes and No, ...). With commdlg.bas in the project, DlgButtons(title, message, buttons, icon) shows a message box with the buttons you list, separated by |, with & before each button’s access key. It returns the index of the button chosen: 0 for the first, which Enter presses. Esc and closing the box choose the last button, so make the last one the choice that changes nothing. icon is vbQuestion, vbInformation, vbExclamation, vbCritical, or 0. Up to six buttons; -1 is returned when the list is empty or longer.
Select Case DlgButtons("Copy", "notes.txt already exists. Replace it?", _
"&Yes|&No|Yes to &All|&Cancel", vbQuestion)
Case 0
' replace this one
Case 2
' replace this and every other one
Case Else
' keep it (No), or stop (Cancel)
End Select
1.17.4. Color Dialog
With commdlg.bas in the project, DlgColor(title, defaultColor) shows the color dialog: a palette of basic colors, Red, Green, and Blue sliders with number boxes, and a preview. It starts at defaultColor and returns the color chosen, in the form RGB makes and ForeColor and BackColor use, or -1 when the user cancels.
Dim c As Long
c = DlgColor("Text Color", Label1.ForeColor)
If c <> -1 Then
Label1.ForeColor = c
End If
1.17.5. Font Dialog
With commdlg.bas in the project, DlgFont(title, family, size, style, flags) shows the font dialog: the font families, the styles and sizes each comes in, Underline and Strikeout boxes, and a sample. It starts at the font named by family, size (in pixels), and style, and returns True when the user chooses OK. DlgFontName$(), DlgFontSize(), and DlgFontStyle() then give the font chosen; after Cancel they give the font the dialog started at. style adds up FONT_BOLD, FONT_ITALIC, FONT_UNDERLINE, and FONT_STRIKE, the constants of font.bas (add it to the project too, or use 1, 2, 4, and 8). With flags DLG_FONT_FIXED the dialog lists only the fixed-pitch families, for text that must line up in columns; with 0 it lists them all. The dialog’s License button shows the chosen font’s notice and license. The answers fit a control’s or a form’s Font properties (see Fonts).
' With commdlg.bas and font.bas added to the project
Dim style As Long
If Label1.FontBold Then style = style + FONT_BOLD
If Label1.FontItalic Then style = style + FONT_ITALIC
If DlgFont("Label Font", Label1.FontName, Label1.FontSize, style, 0) Then
Label1.FontName = DlgFontName$()
Label1.FontSize = DlgFontSize()
Label1.FontBold = (DlgFontStyle() And FONT_BOLD) <> 0
Label1.FontItalic = (DlgFontStyle() And FONT_ITALIC) <> 0
Label1.FontUnderline = (DlgFontStyle() And FONT_UNDERLINE) <> 0
Label1.FontStrikethru = (DlgFontStyle() And FONT_STRIKE) <> 0
End If
1.17.6. Number Input Dialog
With commdlg.bas in the project, DlgIntInput(title, prompt, default, min, max) asks for a whole number with a spin box, and DlgIntInputStep(title, prompt, default, min, max, step) does the same with the arrows moving by step. Both return the number entered, or default when the user cancels; DlgInputCancelled() (True after a Cancel, False after OK) tells the two apart, as it does for DlgInputBox$.
n = DlgIntInputStep("Zoom", "Zoom in percent:", 100, 25, 400, 25)
If Not DlgInputCancelled() Then
SetZoom n
End If
1.17.7. Resources in Files
With resource.bas in the project, a program reads and writes the named resources DVX keeps at the end of program, widget, and library files: icons, text, and any bytes. ResOpen, ResCount, ResName$, ResType, and ResSize list them; ResGetText$ and ResAddText read and write text; ResAddFile and ResExtract copy a resource from or to a file; ResRemove takes one out. ResGetData$(file, name) gives every byte of a resource as a String (CHR$(0) included) — LoadPictureData(ResGetData$(file, name)) shows a picture resource — and ResAddData file, name, type, bytes adds or replaces a resource of any bytes (type RES_TYPE_BINARY, RES_TYPE_TEXT, RES_TYPE_ICON, or RES_TYPE_FONT, a .DFN font the program carries; see Fonts). RES_NAME_ICON ("icon32") and RES_NAME_WIDGET_ICON ("icon24") are the names DVX gives a program’s and a widget’s icon; a name is at most RES_NAME_MAX - 1 characters. A program reads the files and the string table it carries itself with LOADRESPICTURE, LOADRESDATA, and LOADRESSTRING, without resource.bas (see Program Resources).
Dim settings As String
settings = Chr$(1) + Chr$(0) + Chr$(255)
If ResAddData("mygame.app", "state", RES_TYPE_BINARY, settings) Then
Print Len(ResGetData$("mygame.app", "state")) ' 3
End If
|
Note
|
DVX BASIC does not have an $INCLUDE directive. Libraries are added to the project so that the compiler sees their DECLARE LIBRARY blocks. |
1.17.8. Encrypted Serial Links
With comm.bas in the project, CommOpen opens a packet link and CommHandshake sets up encryption. Give both ends the same passphrase to authenticate the connection. Without a passphrase the link is still encrypted and tamper-checked, but it cannot tell who is on the other end. CommHandshake returns False if the passphrases differ, if only one side gives one, or if the link fails.
Dim link As Long
link = CommOpen(1, 115200, 8, "N", 1, SER_HANDSHAKE_NONE)
If CommHandshake(link, "shared secret") Then
CommSend link, "hello", 0, True
Else
Print "Handshake failed"
End If
After the handshake, data that arrives unencrypted is ignored unless that channel is opened for it with CommSetPlain link, channel, True.
The same link runs over the network: with net.bas in the project too, CommOpenTcp(conn) opens it on a connection from TcpConnect or TcpAccept (both ends do), with every channel, the handshake, and encryption as on a COM port. The connection stays the program’s: close it with TcpClose after CommClose.
conn = TcpConnect("bbs.example.org", 2323)
link = CommOpenTcp(conn)
If CommHandshake(link, "shared secret") Then CommSend link, "hello", 5, True
CommHandshake waits until the key exchange is done (up to 30 seconds), and CommSend waits while the link has as much in flight as it can; the program’s events run while they wait, as they do in DoEvents. CommHandshakeStep(link, passphrase) does one step of it and returns at once, so a program can keep working: call it from a Timer until it returns something other than COMM_PENDING — COMM_OK when the link is ready, else a COMM_ERR_ code. CommLastError(link) gives the COMM_ code of the last CommHandshake, CommHandshakeStep, CommSend, CommSetPlain, or CommPoll, which tells a wrong passphrase (COMM_ERR_AUTH) from a line that does not answer (COMM_ERR_TIMEOUT). CommDropped(link) counts arriving packets thrown away because they were tampered with or came unencrypted where that is refused. Channels are numbered 0 to COMM_MAX_CHANNEL.
Sub Timer1_Timer ()
Select Case CommHandshakeStep(link, txtPass.Text)
Case COMM_PENDING
lblState.Caption = "Connecting..."
Case COMM_OK
Timer1.Enabled = False
lblState.Caption = "Connected"
Case COMM_ERR_AUTH
Timer1.Enabled = False
lblState.Caption = "Wrong passphrase"
Case Else
Timer1.Enabled = False
lblState.Caption = "The other side does not answer"
End Select
End Sub
1.17.9. Serial Port Settings and Errors
With comm.bas, SerOpen returns False when a port cannot be opened; SerLastError(com) then says why, as an SER_ERR_ constant (SER_ERR_NO_UART: there is no port there, SER_ERR_IRQ_NOT_FOUND, SER_ERR_INVALID_BAUD, ...), or SER_OK when the last SerOpen or SerSet worked.
| Function | Description |
|---|---|
SerSet(com, baud, dataBits, parity, stopBits, handshake) |
Change the settings of an open port (SerOpen’s arguments). True when done. |
SerGetBaud(com), SerGetDataBits(com), SerGetParity$(com), SerGetStopBits(com), SerGetHandshake(com) |
The settings of an open port; parity is "N", "E", "O", "M", or "S". When the port is not open the numbers are an SER_ERR_ code and the parity "". |
SerTxPending(com), SerFlushTx com |
Bytes written but not sent yet; throw them away. |
SerSetBreak com, state |
Send a break: True holds the line in the break state, False releases it (hold it a quarter to half a second). |
SerGetRi(com) |
True while the other end rings. |
SerLineErrors(com) |
Errors seen on received data, added up: SER_LINE_OVERRUN (data came faster than it was read), SER_LINE_PARITY, SER_LINE_FRAMING, SER_LINE_BREAK; 0 for none. |
1.17.10. Printing
With print.bas in the project, a program prints like the programs that come with DVX. PrintTextDialog shows the Print dialog (printer, copies, pages) and prints the text on pages laid out by the page setup: margins, a header, and a footer with the document name, date, and page number. PrintPageSetup shows the Page Setup dialog, which the user’s choices are saved from for every program. PrintPictureDialog prints a picture file scaled to the page, on printer models that print pictures (PrintCanPrintPictures says whether the chosen one does), in color on a color printer (PrintCanPrintColor says whether it is one) and in shades of gray on the others. PrintText and PrintPicture print without asking first. Each returns True when it printed.
Sub mnuPrint_Click ()
PrintTextDialog txtNotes.Text, "Notes"
End Sub
Sub mnuPageSetup_Click ()
PrintPageSetup
End Sub
For printer output a line at a time, see LPRINT and OPEN "LPT1:". To draw whole pages (text in any font and size, lines, boxes, circles, and pictures), use the Printer object.
A program that prints its own way has more:
| Function | Description |
|---|---|
PrintPageCount(text) |
How many pages text takes with the saved page setup and printer. |
PrintTextPages(text, title, firstPage, lastPage, copies) |
Print text without asking: those pages (0 and 0 for all), copies times. |
PrintPageCountSetup(text, lines, ..., footer) |
How many pages text takes with a page setup of the program’s own, given as for PrintPageSetupProblem$ (below), on the saved printer; 0 for a page setup that cannot be used. |
PrintTextSetup(text, title, lines, ..., footer) |
Print text without asking with a page setup of the program’s own (the user’s saved one stays as it is): on the printer, pages, and copies the program’s last PrintChoose chose, else on the saved printer, every page, once. A page setup that cannot be used is told to the user and nothing prints. |
PrintChoose(title, pageCount) |
Show the Print dialog only, with title as its title (the page range when pageCount is above 0). True when the user chose Print; then PrintChoiceDest, PrintChoiceFile$, PrintChoiceCopies, PrintChoiceFirst, and PrintChoiceLast say what was chosen (pages 0 and 0: all). |
PrintForm(formName) / PrintFormDialog(formName) |
Print what a loaded form shows, scaled to the page (a printer model that prints pictures); the second shows the Print dialog first. |
PrintPortPresent(port), PrintPortStatus(port) |
Whether a printer port exists (port 1 to 3 is LPT1 to LPT3, 4 to 7 a serial printer’s COM1 to COM4), and its state: PRINT_STATUS_ values added up (PRINT_STATUS_PAPER_OUT, PRINT_STATUS_SELECTED, PRINT_STATUS_NOT_BUSY, ...). |
PrintStatusProblem$(status, afterWrite, where) |
What is wrong with a printer in that state, in words ("" when nothing is), for printer where such as "LPT1". |
If PrintChoose("Report", 0) Then
If PrintDestIsFile(PrintChoiceDest()) Then
Open PrintFilePath$(PrintChoiceFile$()) For Output As #1
Else
Open PrintDestLabel$(PrintChoiceDest()) & ":" For Output As #1
End If
Print #1, "Report"
Close #1
End If
PrintDestLabel$ names the port chosen: LPT1 to LPT3, or COM1 to COM4 for a serial printer. Opened this way a serial port runs with the settings DOS gave it (its MODE command), not the Control Panel’s speed and handshake, which DVX’s own printing (PrintTextPages, PrintTextSetup) uses. A file chosen is named as the user typed it: PrintFilePath$ gives the file DVX’s printing would write (a name without a folder, such as the usual PRINTER.PRN, is in the user folder).
The page setup can be read and changed without the Page Setup dialog. Like the printer settings these take a handle from prefs.bas:
| Function | Description |
|---|---|
PrintPageSetting(prefs, field) |
A number of the page setup: "Lines" (lines per page, 0 = the printer’s usual length), "Columns", "MarginTop", "MarginBottom", "MarginLeft", "MarginRight", "TabWidth", or "Wrap" (True: long lines wrap at a space); -1 for an unknown field. |
PrintPageText$(prefs, field) |
"Header" or "Footer". In them &f is the document name, &p the page, &n the number of pages, &d the date, &t the time, && an ampersand; &l, &c, and &r put what follows left, centered, or right. |
PrintPageSetupProblem$(lines, columns, marginTop, marginBottom, marginLeft, marginRight, tabWidth, wrap, header, footer) |
"" when this page setup can be used, else why not. |
PrintPageSettingsStore(prefs, lines, columns, marginTop, marginBottom, marginLeft, marginRight, tabWidth, wrap, header, footer) |
Put a page setup into the settings (then PrefsSave). False for one PrintPageSetupProblem$ objects to. |
PrintPageLines(prefs, model) |
Lines per page the setup gives on printer model. |
The limits are CONSTs: PRINT_LINES_MIN to PRINT_LINES_MAX, PRINT_COLUMNS_MIN to PRINT_COLUMNS_MAX, PRINT_TAB_MAX, PRINT_COPIES_MAX, with the defaults PRINT_COLUMNS_DEFAULT, PRINT_MARGIN_TB_DEFAULT, PRINT_MARGIN_LR_DEFAULT, and PRINT_TAB_DEFAULT.
A program can also change the printer settings the way the Control Panel’s Printer page does. They are kept in DVX’s settings file, so these calls take a handle from prefs.bas (add prefs.bas to the project too). Printer models and destinations are numbered from 0.
| Function | Description |
|---|---|
PrintModelCount() / PrintModelLabel$(model) |
How many printer models there are, and the name of each. |
PrintModelProblem$(model) |
"" when DVX can print on the model, else why not, to show the user (its driver file is missing). |
PrintDestCount() / PrintDestLabel$(dest) |
How many places the printer can be connected to (LPT1 to LPT3, COM1 to COM4, a file), and the name of each. |
PrintDestIsFile(dest) |
True for the destination that prints into a file. |
PrintFilePath$(filePath) |
The file a printout into filePath goes to: a name without a folder, such as the usual PRINTER.PRN, is in the user folder; any other path as it is. |
PrintDestIsSerial(dest) |
True for a serial port (COM1 to COM4), which needs a speed and a handshake. |
PrintBaudRate(index) |
The serial speeds offered, from index 0 (0 past the last). |
PrintHandshakeCount() / PrintHandshakeLabel$(handshake) |
How many handshakes there are, and the name of each (None, XON / XOFF, Hardware (CTS), Hardware (DSR, Apple)). |
PrintSettingBaud(prefs), PrintSettingHandshake(prefs) |
A serial printer’s speed and handshake in the settings. |
PrintSerialStore(prefs, baud, handshake) |
Put a serial printer’s speed and handshake into the settings; False for a speed not offered. |
PrintSettingModel(prefs) |
The printer model in the settings. |
PrintSettingDest(prefs) |
Where the printer is connected. |
PrintSettingFile$(prefs) |
The file printed into when the destination is a file. |
PrintSettingsProblem$(dest, filePath) |
"" when this choice can be used, else why not (printing to a file needs its name). |
PrintSettingsStore(prefs, model, dest, filePath) |
Put the choice into the settings, leaving the others (the page setup too) as they are; then save with PrefsSave. |
Dim prefs As Long
Sub Form1_Load ()
Dim i As Long
prefs = PrefsLoad(PrefsDvxIni$())
For i = 0 To PrintModelCount() - 1
cboModel.AddItem PrintModelLabel$(i)
Next i
cboModel.ListIndex = PrintSettingModel(prefs)
End Sub
Sub cmdOK_Click ()
If PrintSettingsStore(prefs, cboModel.ListIndex, PrintSettingDest(prefs), _
PrintSettingFile$(prefs)) Then
PrefsSave prefs
End If
PrefsClose prefs
End Sub
1.17.11. Files and Folders
With fileops.bas in the project, a program can show and change what is on the disks. FileOpsList(folder, filter) reads a folder once — its folders and the files matching filter — and returns a listing (a number; FileOpsListFree frees it). FileOpsListRows$ gives the whole listing as name, size, type, and date columns, ready for a ListView’s SetRows, so even a folder of hundreds of files fills the list at once; FileOpsListSort re-sorts it by name, size, type, or date with folders first. FileOpsListName$, FileOpsListIsFolder, and FileOpsListSize read single entries, and FileOpsListFind finds one by name. FileOpsListFolders(listing) makes a new listing of just the folders in one, sorted by name, without reading the disk again (handy for a folder tree next to a file list).
Paths: FileOpsPathNormalize$ (the full path of an existing folder, or ""), FileOpsPathParent$, FileOpsPathJoin$, FileOpsPathSame, FileOpsPathIsRoot, FileOpsPathIsAbsolute (True for a path that is complete by itself, such as "C:\DOCS", False for one that counts from the current folder), FileOpsPathIsInside(path, folder) (True when path is folder itself or anywhere inside it: check it before copying or moving a folder, so it is never copied into itself), FileOpsPathSep$ (the character between folder names, "\" on DOS), FileOpsPathNative$ (a path written with that character, for showing it: "C:/DOCS/A.TXT" becomes "C:\DOCS\A.TXT"), FileOpsBaseName$, and FileOpsExtension$. Every one of them takes / and \ alike and gives back \. FileOpsFilterMatch(itemName, filter) tells whether a name matches a filter the way the file dialogs match it: wildcards * and ?, several patterns separated by ; such as "*.bmp;*.png", case not mattering.
Files: FileOpsMakeDir and FileOpsRename (FileOpsError$ says why one failed), FileOpsTempPath$ and FileOpsReplaceFile (save safely: write the new file to FileOpsTempPath$(path$), then FileOpsReplaceFile swaps it in; the old file comes back if that fails, and a read-only file is not replaced), FileOpsSaveText(path$, text$) (a whole text saved that way in one call, its line ends CR LF; 0, or the error number, see File Output Errors), FileOpsValidName(folder, itemName) (whether a name can be used for a new file or folder in folder, by the rules of its disk; FileOpsError$ says why not), FileOpsValidLongName and FileOpsValidShortName (the long-name or the 8.3 rules by themselves, whatever the disk takes), FileOpsShortPath$ (the short 8.3 form of an existing path, for an old program that cannot take long names or blanks), FileOpsMakePath (a folder and every missing folder above it, which MKDIR does not make), FileOpsIsFolder, FileOpsGetAttr, and FileOpsSetAttr (the FILEOPS_ATTR_ bits), FileOpsModified$ and FileOpsSetModified (when a file was last changed, read and set in the form "YYYY-MM-DD HH:MM"; FileOpsSetModified returns False for a date that does not exist), FileOpsTreeSize with FileOpsTreeBytes, FileOpsTreeFiles, and FileOpsTreeFolders (the size of a whole folder), and FileOpsFormatSize$.
Drives: FileOpsDriveList$ (the drive letters), FileOpsDriveType (FILEOPS_DRIVE_FIXED for a hard disk, FILEOPS_DRIVE_REMOVABLE for a floppy disk drive, FILEOPS_DRIVE_REMOTE for a network drive or a CD-ROM; asking never makes a drive spin up), FileOpsBootDrive$ (the drive the computer started from), FileOpsFreeBytes, FileOpsFreeKb, and FileOpsTotalBytes (the size of the disk; right for disks past 2 GB too), FileOpsLongNames(path) (True when the disk holding path takes long file names: up to 255 characters, with spaces and several dots; otherwise names are 8.3). FileOpsIsWritable(folder) is False where files cannot be made (a CD-ROM, a write-protected floppy), and FileOpsReadOnlySystem() is True when nothing can be saved: DVX runs from such a disk and there is no TEMP folder to keep the user folder in. FileOpsTempDir$() is the folder for scratch files ("" when there is none).
DVX’s folders: FileOpsUserDir$() is the user folder (USER in the DVX folder, or the folder DVXUSER names), where everything DVX and its programs save goes; FileOpsUserPath$(name) is a file or folder in it, for example FileOpsUserPath$("DOWNLOAD"); FileOpsUserInTemp() is True when DVX runs from a disk it cannot write to and keeps the user folder in the TEMP folder. A program’s own folder there is App.User. The fonts, sounds, themes, desktop pictures, MIDI instrument banks, and screen savers come in two folders each, DVX’s own (and add-on packages') in SHARED and the user’s in the user folder; the kinds are FILEOPS_KIND_FONTS, FILEOPS_KIND_SOUNDS, FILEOPS_KIND_THEMES, FILEOPS_KIND_WPAPER, FILEOPS_KIND_BANKS, and FILEOPS_KIND_SAVERS. An add-on’s files are in a folder of its vendor’s inside a kind’s folder and are named VENDOR\NAME (for example ACME\SPACE.THM). FileOpsKindDir$(kind, user) is DVX’s folder of a kind (user False) or the user’s (True); FileOpsKindBrowseDir$(kind) is the one a file dialog starts in (the user’s when it exists); FileOpsKindFind$(kind, fileName) finds a file by name, the user’s first ("" when there is none); FileOpsKindName$(kind, path) is the name alone of a file in one of the two folders, the way settings store it ("" for any other path); FileOpsKindList(kind) lists both folders as one, sorted by name, a user’s file hiding DVX’s of the same name (a list for FileOpsListCount, FileOpsListName$, and the rest; FileOpsListFree when done). Programs read DVX’s SHARED folder but never write in it.
FileOpsCopyTree, FileOpsMoveTree, and FileOpsDeleteTree do a whole folder in one call, as does FileOpsTreeSize. While one works, the rest of DVX goes on and so do the program’s own events, as with DoEvents (in a control’s code they wait until the call ends); if the program is ended meanwhile, the call stops and returns False. For a long copy, move, or delete with progress and questions, run the work as a job, a little at a time from a Timer: FileOpsJobCreate, then FileOpsJobAddSource for each file or folder, then FileOpsJobRunFor from the timer until it returns FILEOPS_STEP_DONE or FILEOPS_STEP_CANCELLED. When it returns FILEOPS_STEP_ASK (a file already exists, a file is read-only) or FILEOPS_STEP_ERROR, show FileOpsJobMessage$ and pass the user’s choice to FileOpsJobAnswer. FileOpsJobCurrent$, FileOpsJobFilesDone, FileOpsJobFilesTotal, FileOpsJobFoldersTotal, FileOpsJobPercent, FileOpsJobBytesDone, and FileOpsJobBytesTotal show the progress, and FileOpsJobCancel stops the job. A FILEOPS_MEASURE job only counts: the files (FileOpsJobFilesTotal), the folders inside what was added (FileOpsJobFoldersTotal), and the bytes (FileOpsJobBytesTotal), changing nothing and asking nothing; FileOpsJobUnread says how many folders could not be read. A Properties dialog counts a big folder this way without stopping the program. Files copied from a CD-ROM are read-only; FileOpsJobClearAttr job, FILEOPS_ATTR_READONLY before the job runs makes every copy changeable (FILEOPS_ATTR_EDITABLE clears all four attribute bits). Whatever a program leaves open is freed when it ends.
Dim job As Long
Sub cmdCopy_Click ()
job = FileOpsJobCreate(FILEOPS_COPY, "C:\BACKUP")
If FileOpsJobAddSource(job, "C:\DOCS") Then Timer1.Enabled = True
End Sub
Sub Timer1_Timer ()
Select Case FileOpsJobRunFor(job, 50)
Case FILEOPS_STEP_ASK
If MsgBox(FileOpsJobMessage$(job), vbYesNo + vbQuestion) = vbYes Then
FileOpsJobAnswer job, FILEOPS_ANSWER_YES
Else
FileOpsJobAnswer job, FILEOPS_ANSWER_NO
End If
Case FILEOPS_STEP_ERROR
FileOpsJobAnswer job, FILEOPS_ANSWER_SKIP
Case FILEOPS_STEP_DONE, FILEOPS_STEP_CANCELLED
Timer1.Enabled = False
FileOpsJobFree job
Case Else
ProgressBar1.Value = FileOpsJobPercent(job)
End Select
End Sub
1.17.12. Working with DVX
With shell.bas in the project, a program works with DVX the way Program Manager does — a whole desktop can be written in BASIC.
Starting programs. ShellRun program, args starts a program (args is what it gets as COMMAND$), runs a DOS program, or opens a document in the program set for its type; it returns True when it started (or the DOS program will run). ShellRunProgram(program, args, folder) does the same the way a Program Manager item does: file names in args, and a document named without a folder, are looked for in folder first ("" for none), and it returns the new program’s id (SHELL_RUN_DOS for a DOS program, 0 when it did not start; DVX has already said why). DOS programs are .EXE, .COM, and .BAT files (ShellIsDosProgram(path) says whether a file is one). ShellRunDos program, args, folder, pause runs one with DVX stepped aside: once your procedure has returned, DVX names the programs running besides the desktop, this one included, and asks them to close (each asks about unsaved work; No, or a program kept open, cancels the run); the screen then becomes the DOS screen until the program ends, and DVX comes back with the desktop. When DVX was started with DVX.COM, as Setup installs it, DVX leaves memory while the program runs and starts again after it, so the program gets all of DOS’s memory; ShellReturnedFromDos() is True in that new start, so a program run at start-up can skip what it shows only the first time. folder is where it runs ("" for its own folder); pause True shows "Press any key to return to DVX." when it ends. ShellRunDosWait(program, args, folder, pause) does the same and waits for it, as SHELL does: your program is not asked to close, its events run meanwhile (DVX stays in memory for this one), and the DOS program’s exit code (its ERRORLEVEL) comes back, -1 when it did not run. ShellMinimizeApp id runs that program minimized: its windows become icons, including the ones it opens while it starts. ShellRunCommand(commandLine) runs a whole command line (a program, in double quotes when its name has a blank, then its arguments) and returns the id too. ShellRunDialog$(history) shows DVX’s Run dialog offering history (earlier commands, newest first, one per line) and returns what the user chose, "" for Cancel. ShellOpenDocument path opens a document in the program set for its type in the Control Panel.
Installed programs. ShellProgramScan(folder, skipPath) finds every program in folder and its subfolders ("" for the APPS folder) and returns a list: ShellProgramCount(list) programs, ShellProgramPath$(list, index) each one’s path (index from 0), ShellProgramFree list when done (a list not freed is freed when the program ends). Give ShellAppPath$() as skipPath to leave this program out. ShellProgramName$(path) and ShellProgramDescription$(path) are the name and description a program shows, and ShellIsProgram(path) tells a program from a document. LOADPICTURE of a program gives its icon, so a PictureBox can show a grid of programs with PaintPicture. ShellProgramsFolder$() is the folder the installed programs are in (where ShellProgramScan("") looks), for example to start a Browse for a program there with DlgFileOpenIn$.
File types. ShellAssocProgram$(extension) tells which program opens files with that extension (with ",arguments" after it when it is given any), ShellAssocCommand$(document) just the program that opens a document. ShellAssocCount() file types are set; ShellAssocExt$(index) and ShellAssocValue$(index) read them (index from 0). ShellAssocSet(extension, program) sets one and ShellAssocRemove(extension) removes one, saved at once; ShellAssocNormalize$(extension) is the extension as stored (".txt" gives "TXT"; "" when it cannot be one).
Running programs. ShellRunningCount() says how many programs are running, and ShellRunningId(index) is the id of each one (index from 0; the same id ShellRunProgram returns). ShellAppId() is this program’s own id. ShellRunningName$(id) and ShellRunningPath$(id) are the name a running program shows and the path of its .app ("" when it is not running), and ShellRunningFind(program) is the id of a running copy of a program, 0 when it is not running. ShellRunningActivate id brings a program to the front the way Task Manager’s Switch To does (a minimized window is restored). ShellRunningClose id asks a program to close as if the user had closed its windows: it may ask to save its work and the user may cancel, and it is asked once your code has returned to DVX, so check from a Timer whether it is still running. ShellRunningKill id ends a program at once without asking it, the way Task Manager’s End Task does: whatever it had not saved is lost, so keep it for a program that does not respond. Ending the desktop (Program Manager) exits DVX, so the user is asked "Are you sure you want to exit DVX?" first, as Exit DVX asks. ShellAppIsHung(id) is True when a program has been busy for 5 seconds or longer ("Not responding" in Task Manager). A program cannot end itself with ShellRunningKill (END does that). ShellAppMemory(id) is how many bytes of memory a program is using. ShellMemoryRetained() is how many bytes the programs that have ended left in use (a program ended with End Task, or one that stopped with an error, cannot give all of its memory back; that memory is free again when DVX exits). ShellChangeCount() changes whenever a program starts or ends: check it from a Timer and update what you show when it is not the value you saw last. ShellTaskManager opens the Task Manager, ShellSystemInfo$() describes the computer as it is now (several lines, ending with where DVX’s log is, or its latest lines when DVX keeps the log in memory), and ShellExitDvx exits DVX: every program is asked to close, each asking about unsaved work, and a program that stays open stops the exit (ask the user first).
Sub cmdNotepad_Click ()
Dim id As Long
id = ShellRunningFind("APPS\KPUNCH\NOTEPAD\NOTEPAD.APP")
If id = 0 Then
ShellRun "APPS\KPUNCH\NOTEPAD\NOTEPAD.APP", ""
Else
ShellRunningActivate id
End If
End Sub
Sub FillTaskList ()
Dim i As Long, id As Long
lstTasks.Clear
For i = 0 To ShellRunningCount() - 1
id = ShellRunningId(i)
If ShellAppIsHung(id) Then
lstTasks.AddItem ShellRunningName$(id) & " (not responding)"
Else
lstTasks.AddItem ShellRunningName$(id)
End If
Next i
End Sub
Command lines. ShellCommandProgram$(commandLine) and ShellCommandArgs$(commandLine) split a command line the way ShellRunCommand does: the program (the first word, or the text in double quotes when it starts with one) and the arguments after it. ShellArgCount(commandLine) and ShellArg$(commandLine, index) split any command line into its words (index from 0) by DVX’s rule: words are separated by blanks, and a word with blanks in it is written in double quotes, which ShellArg$ leaves off ("" past the last word). ShellArgQuote$(text) writes one word that way: text in double quotes when it holds blanks, as it is otherwise, so a folder or file name with spaces in it reaches the program it is passed to whole (ShellRun "notepad.app", ShellArgQuote$(path$)). COMMAND$(n) gives this program’s own arguments the same way.
Keys for every program. HotkeyAdd(keyText) makes a key such as "Ctrl+Alt+E" work whichever program is in front and returns its id (0 when it is not a key, needs Ctrl or Alt, or another program uses it). The program asks for the keys pressed from a Timer: HotkeyNext() returns the id of the oldest one not asked for yet, 0 when there is none. HotkeyRemove id stops one; the rest stop when the program ends. HotkeyText$(keyText) writes a key the way DVX does ("ctrl+alt+e" gives "Ctrl+Alt+E"; "" when it is not a key), handy for checking what the user typed. HotkeyNames$() lists the named keys a key may be besides a letter, a digit, or F1 to F12, the way DVX writes them, for a message ("Backspace, Del, Down, End, Enter, Esc, Home, Ins, Left, PgDn, PgUp, Right, Space, Tab, and Up"). A few keys belong to DVX itself, whichever program is in front, and HotkeyAdd refuses them: Alt+Tab, Alt+F4, Ctrl+Esc, Ctrl+F12, and Alt+Space with any other modifier too, F1 and F10 alone, and Ctrl+Alt+Del. HotkeySystemUse$(keyText) says what DVX does with such a key ("closes the active window" for "Ctrl+Alt+F4"), "" for any other. ShellItemKeyValid(keyText) is Program Manager’s rule for an item’s shortcut: Ctrl together with Alt or Shift, so it never takes a key a program uses itself, and not one of DVX’s own keys ("" for no shortcut is valid too); ShellItemKeyError$(keyText) is the message Program Manager shows for a shortcut it refuses ("" when it is valid).
This program. ShellAppPath$ is this program’s own path (ShellRun ShellAppPath$(), "" starts another copy), and ShellInstanceCount says how many copies are running, for example to place each new window a little lower and to the right. ShellSetPriority(priority) gives this program more or less of the computer’s time while other programs run too: SHELL_PRIORITY_LOW, SHELL_PRIORITY_NORMAL (what every program starts with), SHELL_PRIORITY_HIGH, or any number between; ShellPriority() reads it. A program busy with long work leaves the others room at low priority. A program allows more than one copy when Project Properties has "Allow more than one copy to run at once" ticked. A program keeps its settings in App.User, as DVX’s own programs do; keep a desktop’s groups there with prefs.bas. ShellLog text writes a line to the DVX log. ShellSetDesktop program makes a program the desktop DVX starts with the next time ("" for Program Manager again); when the desktop ends, DVX ends. ShellSetWelcome program sets the program DVX starts after the desktop the next time it starts ("" for none).
Program groups. Program Manager keeps its groups in PROGMAN.INI; a desktop written in BASIC uses the same model and file format. ShellGroupsLoad(path) opens a groups file (a file not saved yet has the groups Main and Startup) and returns a handle, ShellGroupsSave(groups, path) writes it, and ShellGroupsFree frees it. An item whose shortcut key is no longer allowed (one DVX now keeps for itself, say) loses the key and keeps the rest; ShellGroupsKeyNotice$(groups) is then the message for the user, naming each such item, its key, and why ("" when nothing was dropped): show it once and save the groups, as Program Manager does. Groups and items are numbered from 0; group 0 is Installed Programs, which ShellGroupsScan(groups, skipPath) fills with every installed program and which is never saved. ShellGroupsChanged tells cheaply whether a program was installed or removed since. ShellGroupCount, ShellGroupName$, ShellGroupFind, ShellGroupAdd, ShellGroupRename, ShellGroupDelete, and ShellGroupNameValid manage the groups, and ShellGroupMove(groups, fromGroup, toGroup) moves one to another place in the list (Installed Programs always stays first); there is no limit on how many groups or items there are. ShellItemCount and ShellItemAdd(groups, group, name, program) list and add items; ShellItemGet$ and ShellItemSet read and change an item’s fields by name ("name", "program", "args", "folder", "icon", "key", "minimized", "col", "row", "description"); ShellItemDelete, ShellItemCopy (the copy has no shortcut key: a key starts one item only), ShellItemMove, ShellItemReorder, and ShellItemPlace rearrange them, ShellGroupArrange and ShellGroupPlaceUnplaced lay out an icon grid, and ShellItemMatches is Program Manager’s search. ShellGroupsGet and ShellGroupsSet read and set the options ("view": SHELL_VIEW_LARGE, SHELL_VIEW_SMALL, or SHELL_VIEW_LIST; "group", the group shown; "autoArrange", "minimizeOnRun", "restoreAlone"), and ShellGroupsHistory$ / ShellGroupsHistoryAdd keep the Run history (what ShellRunDialog$ takes). ShellItemIcon$(iconFile, program) is the file an item’s icon comes from — its icon file, else its program or picture, else the program that opens the document — ready for LOADPICTURE.
Dim groups As Long, main As Long, i As Long
Dim iconFile As String, progFile As String
groups = ShellGroupsLoad(App.User & "\groups.ini")
main = ShellGroupFind(groups, "Main")
i = ShellItemAdd(groups, main, "Notepad", "APPS\KPUNCH\NOTEPAD\NOTEPAD.APP")
If Not ShellItemSet(groups, main, i, "key", "Ctrl+Alt+N") Then
MsgBox "Not a shortcut."
End If
iconFile = ShellItemGet$(groups, main, i, "icon")
progFile = ShellItemGet$(groups, main, i, "program")
picIcon.Picture = LOADPICTURE(ShellItemIcon$(iconFile, progFile))
If Not ShellGroupsSave(groups, App.User & "\groups.ini") Then MsgBox "Not saved."
ShellGroupsFree groups
Sub Form1_Load ()
Dim copies As Long
copies = ShellInstanceCount()
Me.Left = 40 + (copies - 1) * 20
Me.Top = 30 + (copies - 1) * 20
End Sub
A desktop’s Timer keeps its running count current and starts the programs whose keys were pressed:
Sub Timer1_Timer ()
Dim id As Long
If ShellChangeCount() <> lastChange Then
lastChange = ShellChangeCount()
lblRunning.Caption = ShellRunningCount() & " programs running"
End If
id = HotkeyNext()
Do While id <> 0
StartItemWithKey id
id = HotkeyNext()
Loop
End Sub
1.17.13. Add-on Packages
With pkg.bas in the project, a program installs, removes, and makes add-on packages — the .DPK files Software installs — the way Software and Package Builder (both written in BASIC) do. PkgOpen() starts a session (a number; PkgClose ends it), and PkgError$(session) says why the last call that failed did. PkgOpenIn(root) starts one on another DVX folder (a copy being made ready on another disk, say): its installed packages and the keys its user folder trusts. Lists come back as rows for a ListView’s SetRows: cells separated by TAB, each row ending in a line feed.
What is installed. PkgInstalledRows$ lists every installed package (DVX itself is kpunch.dvx): id, name, version, kind, and summary. A package is named by its id, vendor.name (acme.chess). PkgField$(s, id, field) gives one detail (PKG_FIELD_NAME, PKG_FIELD_VERSION, PKG_FIELD_PUBLISHER, PKG_FIELD_SIGNER_NAME, ...); PkgFilesRows$, PkgDependsRows$, and PkgNeededBy$ its files (named from the DVX folder, such as "APPS\ACME\CHESS\CHESS.APP"), what it needs, and what needs it. PkgFileOwner$(s, fileName) is the other way: the id of the package that put a file there (its name from the DVX folder, such as "SHARED\FONTS\KPUNCH\ARIMO.DFN"; "" when none did).
Jobs. Reading package files, installing, removing, and making and signing packages each take a while (checking a signature alone takes a moment on a 486), so each is a job: a ...Start function starts it, and PkgRunFor(s, milliseconds) runs it a little at a time, returning PKG_RUN_BUSY until it is PKG_RUN_DONE or PKG_RUN_FAILED (PkgRunMessage$ says why); PkgRunPercent and PkgRunCurrent$ show how far it is. A session runs one job at a time.
Installing. PkgOfferFileStart(s, path) reads a package file and every package beside it (what it may need) as offers, numbered from 0; the one at path is 0, and the job fails when it cannot be read. PkgOfferField$ and PkgOfferFilesRows$ describe an offer before it is installed; PKG_FIELD_TRUST says whether DVX trusts who signed it. PkgPlan(s, "0") plans installing it with everything it needs, checked against this DVX and the packages installed (False, with PkgError$ saying why, when it cannot be installed); PkgPlanRows$ lists what will go in, PkgPlanBytes the disk space its files take, PkgPlanRoom the most free disk space installing needs at once (compare it with the disk’s free space), and PkgPlanRestart whether libraries or widgets are among them (they work from the next time DVX starts). PkgInstallStart(s) then starts installing.
Function RunJob(s As Long) As Long
Dim rc As Long
Do
rc = PkgRunFor(s, 60)
pbJob.Value = PkgRunPercent(s)
DoEvents
Loop While rc = PKG_RUN_BUSY
RunJob = rc
End Function
If PkgOfferFileStart(s, path) Then
If RunJob(s) = PKG_RUN_DONE And PkgPlan(s, "0") Then
If PkgInstallStart(s) Then
rc = RunJob(s)
End If
End If
End If
Removing. PkgDependents$(s, ids) lists the installed packages that need the ones going (they must go too), and PkgOrphans$(s, ids) those only they needed. PkgRemoveStart(s, ids, removeChanged) starts removing, run with PkgRunFor like an install; files changed since they were installed stay unless removeChanged, and PkgRunKept$ lists them; PkgRunUndeleted$ lists the files that could not be deleted (a program may be using one, or the disk is write-protected). An install lists them too, for the files an upgraded package’s old version had that the new one does not. PKG_FIELD_SETUP says whether Setup put an installed package there with DVX (no signature was checked then), and PKG_FIELD_SIGNED how a package is signed: "trusted", "untrusted" (by a key DVX does not trust, so not checked), "unfit" (by a key DVX trusts, but it does not fit), "no", or "setup"; for an installed package, as it was when it was installed.
Stopping. PkgRunCancel(s) stops a job after the package it is on: one still being unpacked is left as it was, and one whose files are already in is finished first, so keep calling PkgRunFor until it stops saying PKG_RUN_BUSY. When that was the job’s last package and it finished, nothing was left to stop: the job ends PKG_RUN_DONE. A package being made or signed stops at once, and nothing of it is left behind.
Trust. A publisher signs a package with a key so people can tell it came from them. PkgTrustKey(s, keyPath) trusts a publisher’s key file (.KEY) from then on. PkgKeysRows$(s) lists the keys DVX trusts (name, id, and "system" for DVX’s own or "user" for one trusted this way), and PkgUntrustKey(s, keyId) stops trusting one of the user’s.
Checking a package. PkgVerifyStart(s, path, keyPath) checks a package file without installing it, a job run with PkgRunFor: every file in it against the size and fingerprint its manifest lists, so a damaged or changed package is found. With keyPath (a .KEY file) the package must also be signed by that key, in it or beside it, or nothing starts.
Signing any data. PkgSignData$(s, bytes, secretPath) signs any bytes (a file read into a string, a message) with a secret key file, giving the signature as text; PkgCheckData(s, bytes, signature, keyPath) says whether a signature was made over those bytes by the key in keyPath, or with keyPath "" by a key DVX trusts.
Plain ZIP files. A session also lists, unpacks, and makes ordinary .ZIP files, as jobs run with PkgRunFor: PkgZipListStart(s, zipPath) reads one to its end, every file in it checked; PkgZipExtractStart(s, zipPath, folder) unpacks it into folder (a name that would leave folder stops it); PkgZipCreateStart(s, zipPath, files) makes one from rows of a name in it and the file it comes from (as PkgFolderRows$ gives them). PkgZipRows$(s) lists what the last of them read or packed: name, size, date, and "folder" for a folder.
From a package server. With pkgnet.bas in the project too, a program gets packages from a package server the way Software does. PkgNetOpen("") returns a handle on the server DVX’s settings name, with the account they give; PkgNetClose frees it. PkgNetServer$, PkgNetPort, PkgNetUser$, and PkgNetPassword$ read those settings (PkgNetUrl$ is the address they make), and PkgNetSaveSettings(server, port, user, password) changes them. A job is started with PkgNetCatalogue (every package the server offers), PkgNetUpdates (what it has that is newer than the packages installed, DVX itself among them), or PkgNetFetch(n, ids) (packages by id, with everything they need that is not installed), and run with PkgNetRunFor(n, milliseconds) until it is PKGNET_DONE or PKGNET_FAILED (PkgNetError$ says why); PkgNetPercent and PkgNetCurrent$ show how far a fetch is. PkgNetRows$ lists the answer (id, name, version, kind, summary, size, and the version installed, if any), and PkgNetField$ and PkgNetDependsRows$ describe one package in it (PKG_FIELD_SHA256 is its file’s fingerprint, PKG_FIELD_REPO_SIGNED whether the repository signed it). PkgNetOpenIn(server, root, downloadDir) works for another DVX folder and fetches into another folder. Each package fetched is checked against the size and fingerprint the server gives, and the server’s signature of it comes with it. What was fetched is in PkgNetDir$: PkgOfferServerStart(s, folder) reads every package there as the offers (a job), and PkgOfferIndex(s, id) gives the number of the one wanted, to plan and install as above. Read that way, each is from the package server, so PkgPlan refuses one that DVX’s own key did not sign, whatever the server says (PkgError$ says why). PkgNetClear removes them once they are installed; until then they stay, and a fetch of the same version checks them again rather than downloading them again. With an account (the settings', or PkgNetAccount(n, email, password) for another server), PkgNetUpload(n, path) publishes a package file for the server’s review, and PkgNetMine(n) asks what the account has sent: PkgNetMineRows$ lists it (id, name, version, state, and the review’s note); both sign in first. The account itself is made the same way, as jobs that need no account on the handle: PkgNetRegister(n, email, password) asks the server for an account, and the server mails the address a code; PkgNetVerify(n, email, code) gives that code, and the account is ready. For a forgotten password, PkgNetRecover(n, email) asks the server to mail a code, and PkgNetReset(n, email, code, password) gives it with the new password. A code is taken in capitals or small letters, with its hyphen or without. When such a job is PKGNET_DONE, PkgNetReply$(n) is what the server said ("Your account is ready."); when it is PKGNET_FAILED, PkgNetError$ gives the server’s reason as "The package server says: reason." (a wrong code, a password that is too short, too many tries). PkgNetUrlOf$(server, port) is the address a server’s name and port would make once saved ("" and 0 for DVX’s own server and the usual port), for PkgNetOpen on a server that is not in the settings yet.
n = PkgNetOpen("")
If PkgNetFetch(n, "acme.chess") Then
Do
rc = PkgNetRunFor(n, 60)
pbJob.Value = PkgNetPercent(n)
DoEvents
Loop While rc = PKGNET_BUSY
End If
If rc = PKGNET_DONE And PkgOfferServerStart(s, PkgNetDir$(n)) Then
rc = RunJob(s)
offer = PkgOfferIndex(s, "acme.chess")
' plan and install offer as above; once installed, PkgNetClear n
End If
Making packages. PkgBuildStart(s, template, files, out, secret) starts building a package, a job run with PkgRunFor like an install (PkgRunCurrent$ is the file it is on): template is a settings file with a [package] section (id, name, version, kind, and summary, publisher, author, license, homepage, and dvx as wanted) and a [depends] section (id = oldest version for each package it needs); files are rows of a name in the package (from the DVX folder, such as APPS\ACME\CHESS\CHESS.APP) and the file it is made from; secret is the secret key file (.SEC) to sign with, or "". PkgFolderRows$(s, folder, prefix) gives those rows for every file in a folder, and PkgKindFolder$(kind, id) the folder a package of that kind keeps its files in. PkgSignStart(s, path, secret, detached) signs a package already built: into it, a job run the same way, or beside it (NAME.SIG) when detached, done at once. PkgKeygen(s, name, base) makes a key pair (base.KEY to give out, base.SEC to keep private), and PkgKeyInfo$ reads a key file’s name and id. PkgIdValid and PkgVersionValid check an id and a version before building; PkgVersionCompare(a, b) says which of two versions is newer (-1, 0, or 1: "1.10.0" is newer than "1.9.2"); PkgKindName$ lists the kinds.
1.17.14. Web Requests and JSON
With http.bas in the project, a program asks web servers for pages, files, and web services' answers. HttpOpen(method, url) makes a request ("GET" to fetch, "POST" to send) and returns a handle; HttpClose frees it. Before starting it, HttpAddHeader adds a header, HttpSetBody gives a body to send with its type ("application/json", say), HttpSetBodyFile sends a file’s bytes instead (a piece at a time, so a file of any size), HttpSaveTo writes the answer’s body to a file instead of keeping it (with keepPart True, a file left part-way is finished rather than started again), and HttpSetTimeout sets how many seconds without progress mean the server is not answering (30 to start with). HttpStart starts it (False for an address that is not http://; there is no encryption), and HttpRunFor(h, milliseconds) runs it a little at a time, returning HTTP_BUSY until it is HTTP_DONE or HTTP_FAILED:
h = HttpOpen("GET", "http://example.com/news.txt")
IF HttpStart(h) THEN
DO
rc = HttpRunFor(h, 60)
lblProgress.Caption = CStr(HttpBytes(h)) & " bytes"
DoEvents
LOOP WHILE rc = HTTP_BUSY
END IF
IF rc = HTTP_DONE AND HttpStatus(h) = 200 THEN txtNews.Text = HttpBody$(h)
IF rc = HTTP_FAILED THEN MsgBox HttpError$(h)
HttpClose h
HTTP_DONE means the server answered: HttpStatus is how (200 OK, 404 not found, ...), HttpBody$ what it sent, HttpReplyHeader$ one of its headers, and HttpUrl$ where the answer came from when the server sent the request elsewhere (redirects are followed). HTTP_FAILED means no answer came, and HttpError$ says why. HttpBytes and HttpTotal (-1 until the server says) show progress.
With json.bas in the project, JsonParse(text) reads JSON — what most web services answer with — and returns a handle (0 when it is not JSON: JsonError$ says why and on which line); JsonFree frees it. The other functions find a value by its path from the top: member names and item numbers from 0, such as "packages[3].version". JsonType says what is there (JSON_STRING, JSON_NUMBER, JSON_ARRAY, ..., JSON_NONE for nothing), JsonText$ gives a string, JsonNumber a number, JsonBool True or False, JsonCount how many items an array or members an object has, and JsonKey$(h, path, i) the name of an object’s member i. JsonQuote$(text) puts text in quotes with its special characters escaped, for building JSON to send. Text comes and goes as DVX characters: an accented letter or a line-drawing character in a reply is the same character in JsonText$ ("?" stands for one DVX does not have), and JsonQuote$ writes such characters so that any web service reads them right:
h = JsonParse(HttpBody$(req))
FOR i = 0 TO JsonCount(h, "packages") - 1
lstPackages.AddItem JsonText$(h, "packages[" & CStr(i) & "].name")
NEXT i
JsonFree h
body = "{" & JsonQuote$("name") & ": " & JsonQuote$(txtName.Text) & "}"
1.17.15. Changing DVX’s Settings
With system.bas in the project, a program changes what Control Panel changes, at once for the whole desktop. Add prefs.bas too: the settings are saved through a prefs.bas handle.
Screen mode: SysVideoModeCount() says how many modes the display offers (numbered from 0), and SysVideoModeWidth, SysVideoModeHeight, and SysVideoModeBpp (bits per pixel) describe each. SysSetVideoMode(wide, high, bpp) changes the mode and keeps every window; it returns False when the mode could not be set (the old one stays), also while a program has the whole screen to itself. A mode the monitor cannot show leaves the user unable to answer, so do as Control Panel does: ask "Keep this mode?" and go back to the old mode by itself after some seconds. Screen.Width, Screen.Height, and Screen.BitsPerPixel tell the mode in use, and SYS_VIDEO_DEFAULT_WIDTH, SYS_VIDEO_DEFAULT_HEIGHT, and SYS_VIDEO_DEFAULT_BPP the mode DVX starts in when its settings name none. SysScreenshot(path) saves the whole screen as a picture file (BMP when path ends in .bmp, PNG otherwise) and returns True when it was written. SysPicturePatterns$() is the kinds of picture DVX reads as file name patterns separated by ";" (such as "*.bmp;*.png"), for a file dialog’s filter, DlgFileOpen$("Open Picture", "Pictures (" + SysPicturePatterns$() + ")|All Files (*.*)"), or FileOpsList, so a program offers exactly the pictures LOADPICTURE can read.
Colors: the system colors are numbered from 0 to SysColorCount() - 1. SysColorLabel$(id) is the text to show for one ("Desktop", "Window Face" ...), SysColorName$(id) the name it is stored as, and SysColorId(colorName) the id of a name (-1 for none) — to draw in the user’s colors, for example SysGetColor(SysColorId("desktop")). SysGetColor and SysSetColor read and set a color as an RGB() value; each SysSetColor redraws the whole screen. SysResetColors goes back to DVX’s own colors. SysLoadTheme(path) and SysSaveTheme(path) read and write a theme file (.THM; DVX’s own are in SHARED\THEMES, the user’s in the THEMES folder of the user folder, FileOpsKindDir$(FILEOPS_KIND_THEMES, True)); both return True when they worked.
Wallpaper: SysSetWallpaper(path) shows a BMP, JPG, PNG, or GIF image behind the desktop ("" for none) and returns False when the image could not be loaded (the old one stays). SysSetWallpaperMode mode says how it fills the screen, a choice of PREFS_CHOICE_WALLPAPER (Stretch, Tile, or Center; see Settings Files). SysWallpaper$() and SysWallpaperMode() tell what is in use.
Screen saver: SysSetScreenSaver fileName, minutes chooses the screen saver — a program in the SAVERS folders, named as FileOpsKindList(FILEOPS_KIND_SAVERS) lists it, or "" for none — and the minutes with no key or mouse input before it starts (SCREEN_SAVER_WAIT_MIN to SCREEN_SAVER_WAIT_MAX; DVX’s default is SCREEN_SAVER_WAIT_DEFAULT). SysScreenSaver$() and SysScreenSaverWait() tell what is in use, SysScreenSaverStart() starts it now as Control Panel’s Test does (False when none is chosen or one is running), and SysScreenSaverRunning() is True while one runs. SysIdleSeconds() is how long it has been since the last key or mouse input anywhere on the screen.
Text: SysSetTextSmoothing True smooths the edges of text and SysSetTextSmoothing False stops it; SysTextSmoothing() tells which the user chose. Text is smoothed only when the screen shows more than 256 colors, and only in the fonts and sizes that come smoothed. Every window is drawn again when it changes.
Mouse: SysSetMouse wheelDir, dblClickMs, accel, mickeys, wheelStep applies a whole mouse setup at once: the scroll wheel’s direction (1 or -1, the values of PREFS_CHOICE_WHEEL), the double-click time in milliseconds, the acceleration (a value of PREFS_CHOICE_ACCEL), how far the mouse moves for 8 pixels of pointer movement (8 is normal, higher is slower), and the lines scrolled per wheel notch (1 to 10). An accel or mickeys of 0 leaves that one as it is. SysMouseWheelDir, SysMouseDoubleClick, SysMouseAccel, SysMouseMickeys, and SysMouseWheelStep read the setup in effect. MOUSE_WHEEL_STEP_MIN and MOUSE_WHEEL_STEP_MAX are the limits of the wheel step, and MOUSE_WHEEL_STEP_DEFAULT, MOUSE_DBLCLICK_DEFAULT_MS, and MOUSE_SPEED_DEFAULT are DVX’s defaults (what a Default button puts back).
The pointer and the keyboard: SysMouseX() and SysMouseY() are where the mouse pointer is on the screen, and SysMouseButtons() the buttons held (vbLeftButton, vbRightButton, and vbMiddleButton bits) — also while the pointer is over another program’s window, where your MouseMove events do not see it. SysSetMousePos x, y moves the pointer (it is kept on the screen). SysShiftState() is the Shift, Ctrl, and Alt keys held now (vbShiftMask, vbCtrlMask, and vbAltMask bits). SysSendKey(keyCode, shift) types a key into the window that has the focus as if the user pressed it, like SendKeys in other BASICs: keyCode as a KeyDown event gets it — a character code such as ASC("a") or 13 for Enter, or a vbKey constant such as vbKeyF1 — and shift the vbShiftMask, vbCtrlMask, and vbAltMask bits held with it (SysSendKey ASC("s"), vbCtrlMask is Ctrl+S). The keys arrive in order, one at a time, once your code has returned to DVX; up to 64 can wait, and SysSendKey returns False when that many are waiting. A program cannot press the mouse buttons: to "click" a control, call its event procedure or set its value.
Memory: SysMemoryTotalKb() is the computer’s memory in KB and SysMemoryFreeKb() how much of it is free (-1 when it cannot be told).
Libraries: some parts of DVX are optional (Setup’s "What to install" page; Software lists each as one package), and so are their libraries: Networking has dvxnet, http, and pkgnet (net.bas, http.bas, pkgnet.bas), Databases has dvxsql (sql.bas), and Communications has conn and xfer (conn.bas, xfer.bas). SysLibraryLoaded(libName) is True when the library a DECLARE LIBRARY line names (any case) is installed (DVX loads a library when it is first needed, so asking loads it). A program that can do without such a library asks first and leaves out what needs it: calling a function of a library that is not there stops the program with "External function not found". Software, for one, keeps its package server pages off without pkgnet.
If SysLibraryLoaded("pkgnet") Then
handle = PkgNetOpen("")
Else
lblStatus.Caption = "The package server needs DVX's Networking part."
End If
System font: SysFontWidth() and SysFontHeight() are the size of every character of the system font in pixels, and SysFontFirstChar() to SysFontFirstChar() + SysFontCharCount() - 1 the character codes it has. SysFontGlyphRow(code, row) is one row of a character’s picture: a bit per pixel, &H80 the leftmost — for drawing text dot by dot, enlarged or in a font editor of your own.
Saving: SysColorsStore, SysWallpaperStore, SysScreenSaverStore, SysFontsStore, and SysMouseStore write the colors, the wallpaper, the screen saver, text smoothing, and the mouse setup into a prefs.bas handle, in the sections DVX reads when it starts; PrefsSetVideoMode does the same for a screen mode. Store them in PrefsLoad(PrefsDvxIni$()) and save it, and DVX starts with them next time. SysColorsLoad, SysWallpaperLoad, SysScreenSaverLoad, SysFontsLoad, and SysMouseLoad apply what a handle holds. A PrefsCreate handle filled with the Store calls is a snapshot in memory: load it again to undo every change, the way Cancel works in Control Panel.
Dim snap As Long
Dim oldW As Long, oldH As Long, oldBpp As Long
Sub Form1_Load ()
snap = PrefsCreate()
SysColorsStore snap
SysWallpaperStore snap
SysFontsStore snap
SysMouseStore snap
oldW = Screen.Width
oldH = Screen.Height
oldBpp = Screen.BitsPerPixel
End Sub
Sub cmdOK_Click ()
Dim ini As Long
ini = PrefsLoad(PrefsDvxIni$())
SysColorsStore ini
SysWallpaperStore ini
SysFontsStore ini
SysMouseStore ini
PrefsSetVideoMode ini, Screen.Width, Screen.Height, Screen.BitsPerPixel
If Not PrefsSave(ini) Then MsgBox "The settings could not be saved."
PrefsClose ini
Unload Me
End Sub
Sub cmdCancel_Click ()
SysColorsLoad snap
SysWallpaperLoad snap
SysFontsLoad snap
SysMouseLoad snap
If Screen.Width <> oldW Or Screen.Height <> oldH Or _
Screen.BitsPerPixel <> oldBpp Then
SysSetVideoMode oldW, oldH, oldBpp
End If
Unload Me
End Sub
1.17.16. Fonts
Besides the System font (the 8x16 font DVX draws everything with unless told otherwise), DVX comes with font families in its FONTS folder: families for text (sans-serif, serif, and fixed-pitch), display and handwriting families for headings, and pixel fonts. Which of them a computer has depends on how DVX was installed: Setup puts in none, the base set (DejaVu Sans, Sans Mono, and Serif), or all of them. Text in a family that is not installed is drawn in the System font, so a program that cares can look for the family first (FontFamilyCount and FontFamilyName$). With font.bas in the project a program can list them and measure text in them.
A family comes in up to four styles — regular, bold, italic, and bold italic — and in the pixel sizes it was made at. A font is always drawn at one of those sizes, never scaled: asking for another size gives the nearest one (FontNearestSize says which), and asking for a style a family has no face for makes it from the nearest face, bold by thickening and italic by slanting. Name a font by its family, size, and style on every call; a family name DVX does not have means the System font. Style is 0 for regular or FONT_BOLD + FONT_ITALIC; FONT_UNDERLINE and FONT_STRIKE are lines drawn with the text.
' With font.bas added to the project: every family and its sizes
Dim i As Long
Dim j As Long
Dim sizes As String
For i = 0 To FontFamilyCount() - 1
sizes = ""
For j = 0 To FontSizeCount(FontFamilyName$(i), 0) - 1
sizes = sizes & " " & Str$(FontSizeAt(FontFamilyName$(i), 0, j))
Next j
Print FontFamilyName$(i); ":"; sizes
Next i
' How wide a heading is in 24-pixel bold DejaVu Sans
Print FontTextWidth("DejaVu Sans", 24, FONT_BOLD, "Chapter One")
FontFamilyFixed tells a fixed-pitch family (every character as wide as every other, for columns and code) from a proportional one. FontLineHeight is the height of one line of text and FontAscent the distance from the top of a line to the baseline the letters sit on. FontRescan reads the FONTS folder again after fonts were added or removed. FontLicence$(family, size, style) gives the notice and license that go with a font: where it came from, its copyright notices, and its license text (empty for the System font).
A program can carry fonts of its own, so its text looks the same whatever fonts were installed. List the .DFN files in the project’s Fonts (Project > Properties in the IDE): Make builds them into the program, and they are its fonts whenever it runs, from the IDE too. FontAddFile(path), FontAddData(label, bytes), and FontAddResources(file) add more while it runs. A program’s fonts are its own — other programs never see them — and they go when it ends. Where a font it carries is of a family that is installed too, its sizes and styles come first and the installed family fills in the rest: a program that carries DejaVu Sans Bold at 36 pixels draws that size from its own font and every other size and style of DejaVu Sans from the FONTS folder. Fonts are made from TrueType, Type 1, and bitmap fonts with the SDK’s mkfont, or copied from the FONTS folder; each .DFN carries its own license.
' With font.bas added to the project: a title in a font the program carries
If FontAddFile(App.Path + "\TITLE.DFN") Then
lblTitle.FontName = "DejaVu Sans"
lblTitle.FontSize = 36
lblTitle.FontBold = True
End If
Every control and every form can have a font of its own, set with the properties FontName, FontSize (in pixels), FontBold, FontItalic, FontUnderline, and FontStrikethru, as in Visual Basic; they need no include file. A control that is given no font uses the font of the control it is in (a Frame, for example), else its form’s, so setting a form’s font changes every control on it that has none. Reading one of the properties gives the font the object draws with: a FontSize the family does not come in reads back as the nearest size it has, and a FontName DVX does not have reads back as "System". Setting one changes only that part of the font, keeping the size the font has: where a family’s styles come in different sizes (a font the program carries in bold only, say), set FontBold and FontItalic before FontSize, so the size is picked from the style’s own sizes. Controls that edit text in columns (TextBox, TextArea, ComboBox, SpinButton, and Terminal) take only fixed-pitch families and show the System font in place of a proportional one. Print, TextWidth, TextHeight, PrintAccel, and TextWidthAccel on forms and picture boxes use the object’s font. In the form designer, the Font row of the Properties window sets the six properties at once, and they are saved in the .frm file; DlgFont (see Font Dialog) lets the user choose a font while the program runs.
Sub Form1_Load ()
Me.FontName = "DejaVu Sans" ' every control without a font of its own
Me.FontSize = 14
lblTitle.FontSize = 24 ' the title larger, in DejaVu Sans too
lblTitle.FontBold = True
txtNotes.FontName = "DejaVu Sans Mono"
End Sub
Two controls mix fonts in one control. A RichLabel shows text built by calls — SetFont, SetStyle, and SetColor choose how the text added next looks, AddText adds it — in paragraphs aligned left, centered, or right. A RichEdit is a text box the user writes such text in, like a small word processor: the Sel properties (SelBold, SelFontName, SelColor, SelAlignment, ...) read and change the selection’s look, TextRTF holds the whole text with its looks as RTF, and LoadFile and SaveFile read and write files. richtext.bas turns RTF into plain text and back without a control. See the controls' own pages for their properties.
Sub cmdBold_Click ()
RichEdit1.SelBold = Not RichEdit1.SelBold
End Sub
1.17.17. Held Keys for Games
With game.bas in the project, GameKeyDown(keyCode) tells whether a key is being held down right now, so a game can move something for as long as a key is held instead of waiting for key presses. It returns True only while one of the program’s own windows is active. Name the key with one of the GAMEKEY_ constants (the arrow keys, Shift, Ctrl, Alt, Space, Enter, Esc, and a few letters) or with its PC keyboard scan code (add &H80 for the gray keys between the typing keys and the number pad). A Timer polls it:
Sub Timer1_Timer ()
If GameKeyDown(GAMEKEY_LEFT) Then shipX = shipX - 2
If GameKeyDown(GAMEKEY_RIGHT) Then shipX = shipX + 2
End Sub
GameKeyClear forgets the keys held now, so each reads as up until it is pressed again (after a pause screen, say); like GameKeyDown it only works while one of the program’s windows is active. FrameMissed() counts the frames FRAMEWAIT skipped because the program was too slow to draw them in time, since it began waiting at its present rate (0 before the first FRAMEWAIT), so a game can draw less when it falls behind. GameWaitRetrace waits until the screen starts drawing its next picture from the top; a full-screen game that draws right after it does not tear.
Do
MoveEverything
If FrameMissed() > lastMissed Then
lastMissed = FrameMissed()
detail = detail - 1
End If
DrawEverything
FRAMEWAIT 60
Loop Until quitting
1.17.18. Joysticks
With joystick.bas in the project, a program reads joysticks and game pads. JoyCount() says how many there are; they are numbered from 1, and so are their axes, buttons, and hats. JoyX(joy) and JoyY(joy) say where the stick points, from -32768 (all the way left or up) to 32767 (all the way right or down), 0 in the middle; JoyAxis(joy, axis) reads any axis (3 and 4 are a throttle or rudder). JoyButton(joy, button) is True while the button is held down, and also once after a quick press that happened since the program last asked about that button, so a Timer never misses a shot. JoyHat(joy, hat) gives the direction a hat switch is pushed in degrees (0 is up, 90 right) or JOY_HAT_CENTERED. JoyName$(joy), JoyAxes(joy), and JoyButtons(joy) describe the joystick.
Sub Timer1_Timer ()
If JoyCount() = 0 Then Exit Sub
shipX = shipX + JoyX(1) \ 8192
If JoyButton(1, 1) Then FireShot
End Sub
A program can also hear of every change instead of reading the joystick: JoyWatch joy, True starts keeping that joystick’s changes (False stops), and JoyEvent() gives the next one since it was last asked, each once and in order (the last 64 are kept): JOY_EVENT_AXIS (an axis moved), JOY_EVENT_BUTTON_DOWN, JOY_EVENT_BUTTON_UP, JOY_EVENT_HAT, or JOY_EVENT_NONE when nothing has changed. JoyEventJoy() and JoyEventIndex() say which joystick and which axis, button, or hat, and JoyEventValue() an axis’s new position or a hat’s direction. A button pressed and let go between two Timer ticks still gives both.
Sub Form1_Load ()
ok = JoyWatch(1, True)
End Sub
Sub Timer1_Timer ()
Dim kind As Long
kind = JoyEvent()
Do While kind <> JOY_EVENT_NONE
If kind = JOY_EVENT_BUTTON_DOWN And JoyEventIndex() = 1 Then FireShot
If kind = JOY_EVENT_AXIS And JoyEventIndex() = 1 Then
shipSpeed = JoyEventValue() \ 8192
End If
kind = JoyEvent()
Loop
End Sub
When no joystick is connected the keyboard stands in for one (the arrow keys, with Left Ctrl, Space, Left Shift, and Z as buttons), and it only answers while one of the program’s windows is active. Joysticks are calibrated, and the keyboard joystick’s keys chosen, on the Control Panel’s Game Controllers tab. QBasic’s STICK and STRIG work too, without joystick.bas.
joystick.bas can also set joysticks up, as the Control Panel does. JoyHats(joy) counts the hats, JoyAxisPresent(joy, axis) is True when an axis answers, JoyConnected(joy) is False once a joystick stops answering, and JoyCanCalibrate(joy) is True for one with analog axes. For calibrating, JoyRawAxis(joy, axis) gives an axis’s raw reading and JoyRawButtons(joy) the buttons held (1 for button 1, 2 for button 2, 4 for button 3, ... added up); JoySetCalibration(joy, axis, minV, centerV, maxV) takes the readings at one end, the middle, and the other end, and JoyClearCalibration(joy, axis) lets the axis find its own range again. JoyDeadZone(joy) and JoySetDeadZone(joy, percent) are the dead zone round the middle (0 to 50 percent). JoyChoiceCount, JoyChoiceLabel$, JoyChoice, and JoySetChoice list and change the game port’s mode (JOY_CHOICE_GAMEPORT) and when the keyboard joystick stands in (JOY_CHOICE_FALLBACK); JoyKeyCount and JoyKeyName$(index) list the keys the keyboard joystick can use, and JoyKbdSlot(slot) and JoySetKbdSlot(slot, keyIndex) its keys for up, down, left, right, and buttons 1 to 4 (slots 0 to 7). These lists are numbered from 0, so they fill a DropDown in order. JoyKeyIndex(keyName) gives a key’s number by its name (-1 when unknown), JoyKeyCode(index) its raw key code, which GameKeyDown in game.bas takes, and JoyKeyNameOf$(rawCode) the name of a raw key code. JoyIsKeyboard(joy) is True for the keyboard standing in for a joystick, and JoyCalibration(joy, axis, part) reads back an axis’s calibration: part JOY_CAL_MIN, JOY_CAL_CENTER, or JOY_CAL_MAX of the readings set with JoySetCalibration, or of the range the axis found by itself (0 for a joystick that cannot be calibrated). JoySetting$(key, default) and JoySetSetting key, value reach any other joystick setting; JOY_KEY_POLL_HZ is the key of how often joysticks are read, JOY_POLL_HZ_MIN to JOY_POLL_HZ_MAX times a second (JOY_POLL_HZ_DEFAULT normally), and dead zones go up to JOY_DEADZONE_MAX percent (JOY_DEADZONE_DEFAULT normally). After a new game port mode, JoyRescan() looks for joysticks again; it returns the new count, or -1 while another program is using a joystick. Every change applies at once; JoySettingsStore handle puts them all into a settings handle from prefs.bas for the program to save, and JoySettingsLoad handle takes them back from one, to undo.
Sub cmdCenter_Click ()
' The stick rests in the middle: remember the readings
centerX = JoyRawAxis(1, 1)
End Sub
Sub cmdFinish_Click ()
If Not JoySetCalibration(1, 1, lowX, centerX, highX) Then
MsgBox "Move the stick all the way to each side."
End If
End Sub
1.17.19. Sound
With sound.bas in the project, a program plays sound files and tones through whatever sound hardware the computer has: a Sound Blaster, the PC speaker (tones only, unless sampled sound on the speaker is switched on), or nothing at all, in which case the program works the same but is silent. Several programs can play at once, and everything a program plays stops when it ends.
PlayWave(fileName) plays a WAV or VOC file once and PlayWaveLoop(fileName) over and over; PlayTone(frequency, milliseconds, volume) plays a tone of frequency hertz (20 to 20000) and PlayNoise(frequency, milliseconds, volume) noise, which sounds brighter the higher the frequency; a length of 0 plays until stopped. Each returns a voice number, or SOUND_FAILED (0) when the sound could not be played, and then SoundError$() says why. StopWave(voice) stops one sound, StopAllSounds() all of the program’s sounds, and SoundPlaying(voice) is True while a sound is still playing. SoundVolume(volume) sets the volume of everything the program plays. Volumes are percent (0 to 100). SoundInfo$() describes the sound device, like "Sound Blaster 16 (DSP 4.05) at 220h, 22050 Hz, 16-bit stereo".
Dim boom As Long
Sub cmdFire_Click ()
boom = PlayWave("BOOM.WAV")
If boom = SOUND_FAILED Then
lblStatus.Caption = SoundError$()
End If
End Sub
WAV files must be uncompressed (8 or 16 bits, mono or stereo); VOC files may be 8- or 16-bit. QBasic’s BEEP, SOUND, and PLAY work too, without sound.bas.
PlayTriangle(frequency, milliseconds, volume) plays a triangle tone, softer than PlayTone’s square tone. SoundGetVolume() gives the volume of everything the program plays. SoundCaps(field) tells what the sound device can do, by name in any case: "dac" (it plays recorded sound), "synth" (it has a music synthesizer), "tone" (it plays tones on a tone generator), "running", and "record" (it records sound) are True or False; "voices" (how many sounds play at once), "rate" (hertz), "bits", "channels", and "recordsources" (the inputs it records from) are numbers. SoundDriver$() is the short name of the sound driver playing ("sb", "speaker", ...; "" when none is), and SoundStats(field) what the mixer has done since the device started: "renders" (blocks of sound made), "frames" (samples made), "underruns" (stream samples that were due but not yet written), "clipped" (samples too loud), "dropped" (sounds dropped because too many played at once), and "playing" (voices playing now). SoundPlayEvent eventIdx, wait plays one of DVX’s own event sounds (SOUND_EVENT_DEFAULT, SOUND_EVENT_ERROR, SOUND_EVENT_WARNING, ...), the one the settings choose; with wait True it returns once the sound has played (DVX and the program’s events go on meanwhile, as in DoEvents; in a control file’s code, and once the program is ending, it does not wait).
A sound played often is best loaded once. SoundLoad(fileName) loads a WAV or VOC file and returns a sound number, or 0 (SoundError$() says why); it reads and decodes the whole file before it returns, so for a long recording (a minute or more) use MusicLoad and MusicPlay (music.bas), which play a WAV or VOC file as they read it; SoundCreate(data, rate, bits, channels) makes a sound from raw sound data in a string: 8-bit samples (0 to 255, 128 is silence) or 16-bit ones (two bytes each, the low byte first), mono or stereo (left, right, left, ...), rate times a second (SOUND_RATE_MIN to SOUND_RATE_MAX). SoundLoadData(bytes) loads one from the bytes of a WAV or VOC file held in a string, such as ResGetData$ (resource.bas) or HttpBody$ (http.bas) gives. SoundPlay(sound, volume, pan, loopIt) plays it on a new voice and returns the voice number; pan goes from SOUND_PAN_LEFT (-100) through SOUND_PAN_CENTER (0) to SOUND_PAN_RIGHT (100). SoundLength(sound) is its length in milliseconds, SoundRate(sound), SoundBits(sound), and SoundChannels(sound) how it was recorded, and SoundFree sound stops its voices and forgets it. While a voice plays, SoundSetVolume voice, volume, SoundSetPan voice, pan, and SoundSetPitch voice, percent change it (pitch is a percent of the recorded speed: SOUND_PITCH_NORMAL is 100, 200 is an octave higher, from SOUND_PITCH_MIN 25 to SOUND_PITCH_MAX 400), and SoundSetFrequency voice, hertz changes a tone’s frequency. SoundPause voice holds a sound’s voice where it is, silent, and SoundResume voice goes on from there (a tone cannot be paused). A program’s sounds are freed when it ends.
To hear of every sound ending, call SoundEnded() from a Timer: it gives the next of the program’s voices that ended since it was last asked (each once, in the order they ended; the last 64 are kept), or 0 when none has, and SoundEndReason() says why that one ended: SOUND_END_FINISHED (it played to its end), SOUND_END_STOPPED (StopWave, StopAllSounds, or its sound was freed), or SOUND_END_DROPPED (too many sounds played at once and it was the quietest).
Sub Timer1_Timer ()
Dim v As Long
v = SoundEnded()
Do While v <> 0
If v = engine And SoundEndReason() = SOUND_END_FINISHED Then
engine = SoundPlay(idle, 60, 0, True)
End If
v = SoundEnded()
Loop
End Sub
Dim laser As Long
Sub Form1_Load ()
laser = SoundLoad("LASER.WAV")
End Sub
Sub Fire (x As Integer)
Dim v As Long
v = SoundPlay(laser, 80, (x - 160) * 100 \ 160, False)
SoundSetPitch v, 90 + Int(Rnd * 20)
End Sub
A program can also make its sound as it goes, for speech or music of its own. SoundStreamOpen(rate, bits, channels, bufferMs) opens a stream that starts playing at once (silence until data arrives) and holds bufferMs milliseconds of sound (0 for the usual SOUND_STREAM_MS_DEFAULT; SOUND_STREAM_MS_MIN to SOUND_STREAM_MS_MAX). SoundStreamWrite(stream, data) adds raw sound data in the stream’s format and returns how many bytes it took; keep the rest and write it again later. SoundStreamSpace(stream) is the room left and SoundStreamQueued(stream) what is waiting to play, both in samples (a stereo sample counts once). SoundStreamVoice(stream) is the stream’s voice, for SoundSetVolume, SoundSetPan, SoundSetPitch, SoundPause, and SoundResume. SoundStreamFlush stream drops what is waiting to play, so what is written next is heard at once (to jump to another place in what you play), and SoundStreamClose stream stops it. A Timer keeps a stream fed:
Sub Timer1_Timer ()
Dim taken As Long
taken = SoundStreamWrite(stream, pending)
pending = Mid$(pending, taken + 1)
If Len(pending) = 0 Then pending = MakeMoreSound()
End Sub
A melody of tones — a game’s tune or a sound effect — plays without a gap or a stumble in a note queue. NotesOpen(wave, volume) opens one in a waveform (SOUND_WAVE_SQUARE, SOUND_WAVE_TRIANGLE, or SOUND_WAVE_NOISE) and returns its number, or 0. NotesAdd(queue, hertz, milliseconds) adds a tone (0 hertz for a rest; fractions count) and returns True, or False when 256 are already waiting; each lasts exactly as long as asked, as long as the next is added before the one playing ends. NotesSetTone(queue, wave, volume) changes the waveform and volume (percent of the queue’s) of the tones added from then on, so they change in time with the tune. NotesQueued(queue) is how many tones and rests have not finished (0 once it has gone quiet) and NotesSpace(queue) how many more fit; NotesVoice(queue) is its voice, for SoundSetVolume and SoundSetPan. NotesClear queue silences it and forgets what it holds, and NotesClose queue closes it. PLAY’s V and @ commands give PLAY tunes a volume and a waveform too.
q = NotesOpen(SOUND_WAVE_TRIANGLE, 80)
For f = 200 To 800 Step 50
ok = NotesAdd(q, f, 15) ' a rising sweep, 15 ms a step
Next f
A program can record sound from the sound card’s microphone, line, or CD input into a WAV file, or into memory. SoundCaps("record") says whether the card can, and SoundCaps("recordsources") which inputs it has (the bit 2 ^ RECORD_MIC, RECORD_LINE, or RECORD_CD set for each). RecordStart(fileName, rate, bits, channels, inputSource) starts recording (0 for 22,050 Hz, 16-bit, mono) and returns True, or False with SoundError$ saying why; the card records at its nearest, which RecordRate(), RecordBits(), and RecordChannels() tell. While it records, RecordLength() is how long the recording is (milliseconds) and RecordLevel() the loudest sound since it was last asked (percent: a level meter); RecordLost() counts samples dropped because DVX was too busy. RecordStop() ends it and returns True when the file was all written; Recording() is True in between. RecordCancel() ends it and throws it away instead: nothing of it is written (True; False when the program has no recording). RecordPause() pauses the recording and RecordResume() goes on with it: while it is paused nothing is recorded (the card stays taken, so nothing plays meanwhile), and after it the recording goes on from where it paused, with nothing between, RecordLength() leaving the paused time out. Both return True, or False when the program has no recording (SoundError$ says why); pausing a paused recording, or resuming one not paused, does nothing, and Recording() is True while it is paused. A file of that name already on the disk is replaced only when RecordStop ends the recording: a recording that cannot start, cannot all be written (the disk filled up), or is thrown away leaves it as it was. With a file name of "", RecordStart records into memory instead: RecordRead$(maxBytes) takes up to maxBytes of what was recorded and not yet taken, as raw sound data in the recording’s format (as SoundCreate and SoundStreamWrite take it), and RecordQueued() is how many bytes are waiting. Take them often, from a Timer: about two seconds are kept, and what does not fit is lost (RecordLost()). A program can show the sound as it comes, change it, or send it over the network. Most sound cards record or play, not both, so nothing plays while a program records, and one program records at a time. A program’s recording ends when the program does, complete as RecordStop leaves it. Running a DOS command (SHELL) ends it the same way, and Recording() is then False, but the recording stays the program’s until RecordStop (True when its file was all written), RecordCancel (False, and SoundError$ says the recording had already ended: the file it completed stays), or the next RecordStart.
If RecordStart("NOTE.WAV", 0, 0, 0, RECORD_MIC) Then
' ... a Timer shows RecordLength() and RecordLevel()
ok = RecordPause() ' nothing is recorded while it asks
If MsgBox("Keep the recording?", vbYesNo + vbQuestion) = vbYes Then
ok = RecordStop() ' NOTE.WAV is the new recording
Else
ok = RecordCancel() ' NOTE.WAV stays as it was
End If
End If
On a computer with an FM synthesizer chip (AdLib and most Sound Blasters), a program can play instruments of its own. FmInfo$(field) describes the chip: "description" (like "OPL3 FM synthesizer at 388h", "" when there is none), "voices", "free" (voices no program has), "stereo", and "owned" (one program has the whole chip). FmAlloc() takes one of its two-operator voices (0 when none is free), FmWrite(voice, register, value) sets one of the voice’s registers (the FM_ constants: FM_MOD_CHAR, FM_CAR_LEVEL, FM_FNUM_LOW, FM_KEY_BLOCK with FM_KEY_ON, ...; True when it worked), and FmFree voice gives it back. A player of chip music files can take the whole chip with FmRawAcquire() (False while another program has it), set any register with FmRawWrite(register, value) (bank * FM_BANK_REGS + register; the second bank only on an OPL3) and give it back with FmRawRelease. A frequency number for FM_FNUM_LOW and FM_KEY_BLOCK is hertz * 2 ^ 20 / (FM_CHIP_HZ * 2 ^ block).
On a wavetable sound card (a Gravis UltraSound, a Sound Blaster AWE32 or AWE64), a program can play recorded sounds on the card’s own voices from the card’s memory. WtInfo$(field) describes the card: "description" ("" when there is none), "voices", "free" (voices no program has), "memory", "freememory" (the largest free block), "freetotal" (all free, in blocks maybe apart; bytes), "level" (how many centibels louder a voice at full volume is than the loudest recorded sound the card plays: 0 when it is the same or not known), and what the card does itself ("envelopes", "lfos", "filter", "effects", "8bit", "rom"; True or False as text). WtMemAlloc(bytes, bits) takes memory for samples of 8 or 16 bits (its address, -1 when there is no room), WtUpload(address, pcm, bits) copies 16-bit mono samples there (a binary string, two bytes a sample; True when it worked), and WtMemFree address gives it back. WtAlloc() takes a voice (0 when none is free); WtStart(voice, address, startFrame, endFrame, loopStart, loopEnd, loopMode, bits, pitch, attenuation, pan) plays a sample on it from startFrame (0: its first; loopMode 0 plays once, 1 loops, 3 loops until WtRelease; pitch in cents, 0 for 44,100 samples a second and 1200 an octave higher; attenuation in centibels, 0 loudest and 60 half as loud; pan -100 to 100); on a card with a General MIDI sample ROM (WtInfo$("rom")) the address may be WT_ADDR_ROM plus the bytes from the ROM’s start. WtSetPitch, WtSetAttenuation, and WtSetPan change a playing voice, WtStop silences it, WtActive(voice) is True while it sounds, and WtFree voice gives it back. WtShape(voice, field, value) shapes the voice’s notes as a SoundFont instrument does, one value by name, where the card can (WtInfo$ "envelopes", "lfos", "filter", "effects"): the volume envelope ("voldelay", "volattack", "volhold", "voldecay", "volsustain", "volrelease"), the modulation envelope ("moddelay" to "modrelease", "modenvpitch", "modenvfilter"), the modulation and vibrato LFOs ("modlfodelay", "modlfofreq", "modlfopitch", "modlfofilter", "modlfovolume", "viblfodelay", "viblfofreq", "viblfopitch"), the filter ("filterfc", "filterq"), and the effects ("reverb", "chorus"), in the units sound.bas lists. A value is kept for the voice’s next WtStart; the filter, the effects, and the LFO depths also change a note that is sounding. Everything a program took is given back when it ends.
sound.bas also changes DVX’s own sound settings, as the Control Panel’s Sounds page does. DVX plays a sound for each of SoundEventCount() events, numbered from 0: SoundEventLabel$(eventIdx) names one ("Start DVX", "Error", ...) and SoundEventKey$(eventIdx) gives its key in DVX.INI. With a settings handle from prefs.bas (PrefsLoad(PrefsDvxIni$())), SoundEventFile$(handle, eventIdx) is the event’s sound file ("" for none) and SoundSetEventFile handle, eventIdx, fileName changes it; after the program saves the file, SoundEventsReload makes DVX play the new sounds. SoundTestFile(fileName) plays a file the way DVX plays its event sounds (0 when it cannot, and SoundError$() says why), and SoundFolder$() is the folder of DVX’s own sounds. SoundMasterVolume() and SoundSetMasterVolume percent are the volume of all sound from every program. SoundDriverCount() reads the list of sound drivers and SoundDriverName$(index) names each; SoundDriverAuto$() is the setting that means "find the best one". SoundMidiCount() and SoundMidiLabel$(index) list where MIDI music can play, SoundMidiInCount() and SoundMidiInLabel$(index) where MIDI input can come from, and SoundModulesCount() and SoundModulesLabel$(index) where music modules can play. SoundSettingDriver$(handle), SoundSettingMidi(handle), SoundSettingModules(handle), and SoundSettingVolume(handle) read the sound driver, MIDI choice, modules choice, and master volume from the settings, and SoundSettingsStore handle, driver, midi, modules, volume stores them (a new driver or MIDI choice takes effect when DVX next starts, a modules choice with the next music); SoundSettingMidiIn(handle) and SoundSettingMidiInStore handle, midiIn read and store the MIDI input choice (it takes effect when DVX next starts). SoundSettingSpeakerPcm(handle) and SoundSettingSpeakerPcmStore handle, onOff read and store whether the PC speaker plays recorded sound (True), which takes a lot of the computer’s time, or only tones (False). After saving the settings, SoundOutputRefresh makes the sound output start again with them as soon as nothing is playing, so a change such as the digital PC speaker is heard with the next sound.
Dim ini As Long
Dim i As Long
ini = PrefsLoad(PrefsDvxIni$())
For i = 0 To SoundEventCount() - 1
lstEvents.AddItem SoundEventLabel$(i) & ": " & SoundEventFile$(ini, i)
Next i
1.17.20. Music
With music.bas in the project, a program plays music files: tracker modules (MOD, S3M, XM, and IT files, made of recorded instrument sounds) wherever the computer can play sampled sound (on a Gravis UltraSound’s or Sound Blaster AWE’s own voices, which takes the computer little time), MIDI files (.MID, types 0, 1, and 2) on the computer’s music synthesizer, or on a built-in synthesizer that sounds much the same when there is none, and WAV and VOC sound files wherever the computer can play sampled sound (a long WAV recording is read from the disk as it plays, so it needs no memory). Several programs can play music at once, and everything a program plays stops when it ends.
MusicLoad(fileName) loads a music file and returns its music number, or MUSIC_FAILED (0) when it could not be loaded; MusicError$() then says why. MusicLoadData(bytes) does the same with the bytes of a music or sound file held in a string (from ResGetData$ or HttpBody$, say). MusicPlay(music, loopIt) plays it from where it is (the start after loading or stopping); with loopIt True it starts over at the end until it is stopped. MusicStop(music) stops and goes back to the start, MusicPause(music) and MusicResume(music) pause and go on, and MusicPlaying(music) is True while it plays. MusicEnded(music) is True once after the music played to its end (not when it was stopped) since MusicPlay started it: a Timer that asks it can start the next tune on time. MusicVolume(music, volume) sets its volume in percent (0 to 100). MusicPosition(music) and MusicLength(music) give the place and the length in milliseconds, and MusicSeek(music, milliseconds) goes to a place (a module goes to the start of the part that holds it). MusicFree(music) stops a music and forgets it.
MusicLoadMacro(macro) makes a music from a music macro string, the kind PLAY takes, with its notes on the General MIDI instruments its I commands name (the piano before any I): the tune can then be played in the background, paused, stopped, and made quieter like any music. MIDI music plays on the instruments chosen in Control Panel; MusicSetBank music, bank plays one music on another instrument bank, named as in the banks folders ("" is DVX’s standard bank), before the music first plays (MusicError$ says when the bank is missing or damaged). A SoundFont (.SF2 or .SBK) gives the recorded instruments for a wavetable card or the built-in SoundFont synthesizer, as can a Gravis UltraSound’s own patches: MusicPatchSet$() names them (their ULTRASND.INI, "" when there are none), and MusicRomBank$() names the instruments built into a Sound Blaster AWE card ("" when Creative’s software is not installed).
tune = MusicLoadMacro("T150 I41 O4 L8 CEG>C4")
MusicSetBank tune, "DMXOPL.OP2"
MusicPlay tune, False
Dim tune As Long
Sub Form1_Load ()
tune = MusicLoad("THEME.MOD")
If tune = MUSIC_FAILED Then
lblStatus.Caption = MusicError$()
Else
MusicPlay tune, True
End If
End Sub
A program can also play notes itself, like a keyboard. MusicMidiOpen() returns a live music that is already playing. MusicNoteOn(music, channel, note, velocity) starts a note and MusicNoteOff(music, channel, note) ends it; MusicProgram(music, channel, program) chooses a channel’s instrument, MusicControl(music, channel, controller, value) sets a controller (7 volume, 10 pan, 11 expression, 64 the sustain pedal, 123 all notes off), and MusicPitchBend(music, channel, bend) bends the channel’s notes (-8192 to 8191, two semitones either way at the ends). Channels are 1 to 16, and channel 10 (MUSIC_DRUMS) plays drums, one per note. Notes, velocities, instruments, and controller values are 0 to 127; middle C is note 60, and instruments are numbered as in General MIDI (0 piano, 24 guitar, 40 violin, 56 trumpet, 73 flute). The same calls work on a MIDI file that is playing.
Dim keys As Long
Sub Form1_Load ()
keys = MusicMidiOpen()
MusicProgram keys, 1, 73
End Sub
Sub cmdC_Click ()
MusicNoteOn keys, 1, 60, 100
tmrNoteOff.Enabled = True
End Sub
Sub tmrNoteOff_Timer ()
MusicNoteOff keys, 1, 60
tmrNoteOff.Enabled = False
End Sub
MusicGetVolume(music) gives a music’s volume in percent. MusicInfo$(music, field) tells about it, by name in any case: "title" (a module’s own title, or the name a MIDI file gives itself; "" for a sound file), "output" (where it plays, for people), "kind" ("module", "midi", "live", or "sound"), "where" ("stream", "mpu401", "fm", "software", "wave", or "softwave"; "wave" is a wavetable card’s voices, for a module too; "" before it first plays), and "paused" and "looping" (True or False as text; VAL gives the value).
A program that sends MIDI itself (system exclusive messages, a sequencer of its own) can have the MIDI port, one program at a time, when the settings send MIDI music to the MIDI port. MidiPortInfo$(field) describes it: "description" ("" when there is none), "present", "owned" (a program has it), "input" (it brings MIDI in), and "inputowned" (a program reads what comes in). MidiAcquire() takes the port (False when another program has it or there is none), MidiPut(byteValue) sends one byte (False when the port could not take it yet: send it again), and MidiRelease gives the port back.
When the settings take MIDI input from the MIDI port (Control Panel, Sounds, MIDI in), a program can read what a MIDI keyboard or another instrument plays. MidiInOpen() starts reading (False when there is no MIDI input or another program reads it; SoundError$() says which) and MidiInClose stops; a program’s reading stops when it ends. MidiInMessage() gives the next message that came, or MIDI_NONE (-1) when none waits. A message is packed into one number: the status is midiMsg AND 255 (its kind, midiMsg AND MIDI_KIND_MASK, is MIDI_NOTE_ON, MIDI_NOTE_OFF, MIDI_CONTROL, MIDI_PROGRAM, MIDI_PITCH_BEND, MIDI_KEY_PRESSURE, or MIDI_CHANNEL_PRESSURE, and its channel, numbered as MusicNoteOn numbers them, is (midiMsg AND MIDI_CHANNEL_MASK) + 1), the first data byte (the note) is (midiMsg \ 256) AND 255, and the second (the velocity) (midiMsg \ 65536) AND 255. A note on with a velocity of 0 is a note off too. MidiInTime() is when the message MidiInMessage gave last came and MidiInClock() the time now, both in milliseconds since MidiInOpen; MidiInLost() counts bytes lost because the program read too late. MusicMidiSend music, midiMsg plays a message as it came on a live music (MIDI thru), so what is played is heard.
A MIDI recording keeps messages with their times and saves them as a MIDI file that MusicLoad plays. MidiRecordNew() returns a recording number (0 when there is no room; MusicError$() says why), MidiRecordAdd recording, milliseconds, midiMsg adds a message (MidiInTime() is the time to give, when the recording started with MidiInOpen), MidiRecordCount(recording) and MidiRecordLength(recording) tell how many messages it has and when the last came, MidiRecordSave(recording, fileName) writes the file (False when it could not be written; MusicError$() says why, and a file of that name already on the disk stays as it was; a note still held at the end is let go), and MidiRecordFree recording frees it (freed without MidiRecordSave, a recording writes nothing: that is how a take the user does not keep is thrown away). MidiRecordPause recording, milliseconds pauses a recording and MidiRecordResume recording, milliseconds goes on with it (MidiInClock() is the time to give): what comes in between is not kept, what comes later is moved earlier by the time paused, so the recording goes on with no gap, and the notes held when it pauses are let go there (a sustain pedal down is let up). MidiRecordTime(recording, milliseconds) is how long the recording has been going at that time, the time paused left out (a clock to show while recording). A program’s recordings are freed when it ends. The Sound Recorder records a MIDI keyboard this way:
Dim take As Long
Dim keys As Long
Sub cmdRecord_Click ()
If MidiInOpen() Then
take = MidiRecordNew()
keys = MusicMidiOpen()
tmrTake.Enabled = True
End If
End Sub
Sub tmrTake_Timer ()
Dim midiMsg As Long
midiMsg = MidiInMessage()
Do While midiMsg <> MIDI_NONE
MusicMidiSend keys, midiMsg
MidiRecordAdd take, MidiInTime(), midiMsg
midiMsg = MidiInMessage()
Loop
End Sub
Sub cmdStop_Click ()
tmrTake.Enabled = False
MidiInClose
MusicFree keys
If Not MidiRecordSave(take, "SONG.MID") Then
Print "Not saved: " & MusicError$()
End If
MidiRecordFree take
End Sub
1.17.21. Network Connections
With net.bas in the project, a program talks to other computers over the network set up in the Control Panel. TcpConnect returns a handle (0 when it failed; NetError$ says why), TcpSend sends text, and TcpRecv$ returns whatever has arrived without waiting, so a Timer keeps the program responsive:
Dim conn As Long
Sub Form1_Load ()
conn = TcpConnect("bbs.example.org", 23)
If conn = 0 Then
Print "Could not connect: " & NetError$()
End If
End Sub
Sub Timer1_Timer ()
If TcpPending(conn) > 0 Then Print TcpRecv$(conn)
If TcpConnected(conn) = 0 Then Timer1.Enabled = False
End Sub
| Function | Description |
|---|---|
HostLookup$(hostName) |
The address of a name, such as "192.0.2.10", or "" when it is not found. Waits for the answer; other programs keep running. |
HostLookupStart(hostName) |
The same without waiting: a lookup handle (0 when too many are under way). |
HostLookupPoll(lookup) |
NET_BUSY while the lookup goes on, NET_DONE once found, NET_FAILED (NetError$ says why). |
HostLookupResult$(lookup) |
The address found, once HostLookupPoll says NET_DONE. |
HostLookupClose lookup |
Free a lookup handle (or give the lookup up). |
HostName$(address) |
The name of an address; the address itself when no name is known for it. |
NetAddress$() |
This computer’s address ("" while it has none). |
NetError$() |
Why the last call failed, in plain words. |
TcpConnect(host, port) |
Connect; a handle, or 0. Waits up to 20 seconds; other programs keep running. |
TcpConnectStart(host, port) |
The same without waiting: the connection’s handle at once (0 when it cannot start). |
TcpConnectPoll(handle) |
NET_BUSY while the host is looked up and the connection made, NET_DONE once it is (the handle then works as TcpConnect’s), NET_FAILED (close it). |
TcpListen(port) |
Wait for connections on port; a listening handle, or 0. |
TcpAccept(handle) |
A connection that arrived on a listening handle, or 0 when none is waiting. |
TcpSend(handle, bytes) |
Send text or any other bytes; the bytes sent, or -1. Waits while the connection’s buffer is full. |
TcpSendSome(handle, bytes) |
Send what the connection takes now, never waiting: the bytes taken from the start (0 while it is full), or -1. |
TcpPending(handle) |
Bytes waiting to be read (-1 for a bad handle). |
TcpRecv$(handle) |
What has arrived (up to 4096 bytes), or "". |
TcpPeek$(handle) |
What has arrived (up to 4096 bytes), left waiting for the next TcpRecv$: look for a line’s end or a message’s length first. |
TcpConnected(handle) |
1 while the connection is open, 0 once the other side closed it. |
TcpShutdown(handle) |
Tell the other side nothing more will be sent; what it sends can still be read. |
TcpPeer$(handle) |
"address:port" of the other side ("" when not connected). |
TcpLocalPort(handle) |
The port a handle uses on this computer (the one TcpListen(0) picked). |
TcpSetNoDelay(handle, enable) |
True: send small pieces at once instead of gathering them (typing, games). |
TcpSetKeepAlive(handle, enable) |
True: check now and then that the other side of an idle connection is still there. |
TcpClose handle |
Close a connection or a listening handle. |
UdpOpen(port) |
A UDP handle on port (0 = any free port), or 0. |
UdpSend(handle, host, port, text) |
Send one message; the bytes sent, or -1. "255.255.255.255" reaches every computer nearby. |
UdpRecv$(handle) |
The next message that arrived, or "". |
UdpFrom$() |
"address:port" of the sender of the last UdpRecv$ message. |
UdpClose handle |
Close a UDP handle. |
The strings sent and received may hold any bytes, CHR$(0) too, so binary protocols work as well as text. Every connection a program opens is closed for it when the program ends.
HostLookup$, TcpConnect, and TcpSend wait until they are done. Other programs keep running meanwhile, but yours does not: its windows do not answer, and the first lookup after DVX starts can also wait for the network to get its settings (DHCP). To stay responsive, start the lookup or connection and check on it from a Timer:
Dim conn As Long
Sub cmdConnect_Click ()
conn = TcpConnectStart("bbs.example.org", 23)
Timer1.Enabled = conn <> 0
End Sub
Sub Timer1_Timer ()
Select Case TcpConnectPoll(conn)
Case NET_DONE
Timer1.Enabled = False
lblStatus.Caption = "Connected"
Case NET_FAILED
Timer1.Enabled = False
lblStatus.Caption = "Could not connect: " & NetError$()
TcpClose conn
End Select
End Sub
A program can also edit the network settings the way the Control Panel’s Network page does, and show the network’s state. The settings are kept in DVX’s settings file, so NetConfigLoad and NetConfigStore take a handle from prefs.bas (add prefs.bas to the project too). NetConfigLoad gives a settings handle (0 when none is free); read and change its fields by name, check them, store them, and restart the network only when they changed:
Dim prefs As Long
Dim cfg As Long
Sub Form1_Load ()
prefs = PrefsLoad(PrefsDvxIni$())
cfg = NetConfigLoad(prefs)
txtName.Text = NetConfigGet$(cfg, "hostname")
lblState.Caption = NetStatus$("message")
End Sub
Sub cmdOK_Click ()
NetConfigSet cfg, "hostname", txtName.Text
If NetConfigProblem$(cfg) <> "" Then
MsgBox NetConfigProblem$(cfg)
Exit Sub
End If
NetConfigStore cfg, prefs
PrefsSave prefs
If NetConfigChanged(cfg) Then NetRestart
NetConfigFree cfg
PrefsClose prefs
End Sub
| Function | Description |
|---|---|
NetConfigLoad(prefs) |
A settings handle holding the network settings of prefs (0 for the usual settings), or 0 when none is free. |
NetConfigGet$(cfg, field) |
One setting as text: "dhcp" ("-1" when the address comes from the network automatically, "0" when it is fixed), "address", "netmask", "gateway", "dns1", "dns2", "hostname", "vector" (the packet driver’s interrupt, 0 = find it). |
NetConfigSet(cfg, field, value) |
Change one setting (same names; "dhcp" and "vector" take numbers). True when the field exists. |
NetConfigProblem$(cfg) |
"" when the settings can be used, else why not in plain words. |
NetConfigChanged(cfg) |
True when the settings differ from what NetConfigLoad read. |
NetConfigStore(cfg, prefs) |
Put the settings into prefs (then save it with PrefsSave). True when done. |
NetConfigFree cfg |
Free the settings handle. |
NetVectorCount() / NetVector(index) |
The packet driver interrupts to choose from: index 0 is 0 (find it), then each one the settings accept. |
NetRestart() |
Stop the network and start it with the saved settings. True when it is running. |
NetStop |
Stop the network (every program’s connections are closed) until NetRestart. |
NetState() |
The network’s state as a number: NET_STATE_STOPPED, NET_STATE_NO_DRIVER (no network card driver found), NET_STATE_CONFIGURING (waiting for an address from the network), or NET_STATE_UP. |
NetStatus$(field) |
The network’s state as text: "message" (in plain words), "up" and "link" ("-1" / "0"), "dhcp", "address", "netmask", "gateway", "dns1", "dns2", "hostname", "driver" (the network card’s driver), "mac" (its hardware address), "vector", "sockets", "rxpackets", "rxbytes", "rxdropped", "txpackets", "txbytes". "" for an unknown field. |
Settings handles a program leaves open are freed for it when it ends.
CommRecvEncrypted(handle, channel) tells whether the data the last CommRecv$ on that channel returned can be trusted. It returns True when every byte of it arrived encrypted and authenticated, and also when that CommRecv$ returned nothing or CommRecv$ has not been called on the channel yet. It returns False when any byte arrived unencrypted, which can only happen before CommHandshake or on a channel opened with CommSetPlain, and for an invalid handle or a channel outside 0-127.
Dim msg As String
msg = CommRecv$(link, 1)
If msg <> "" And Not CommRecvEncrypted(link, 1) Then
Print "Unencrypted: " & msg
End If
1.17.22. Connections and Terminals
With conn.bas in the project, a program talks to another computer the way the Terminal program does, whatever is in between: a serial port, a modem (it sends its setup command, dials, dials again when the line is busy, and notices when the carrier is lost), the secure link to the DVX host proxy (encrypted, and authenticated with a passphrase), or Telnet over the network. ConnCreate makes a connection (a number); ConnSetSerial, ConnSetModem, ConnSetHost, and ConnSetPassphrase set it up, and ConnOpen(conn, type) starts it. Opening only starts: dialing and the key exchange go on while the program runs, so call ConnPoll often from a Timer. ConnState says where it is (CONN_CLOSED, CONN_OPENING, CONN_OPEN) and ConnStatus$ what is happening or why it ended; ConnStatusSerial changes whenever ConnStatus$ does.
ConnAttach conn, "Term1" puts what arrives on the Terminal control Term1 (ConnPoll moves it there) and sends what is typed in it. The control is found as its name written alone is (see How Names Are Found): called from a form’s code, that form’s Term1; from a module’s, the one loaded form’s that has one, error 1001 (Ambiguous control name) when several forms have one. ConnPoll then also appends what arrives to a capture file (ConnCapture), answers the other side’s ENQ with an answerback (ConnSetAnswerback), and notices a ZMODEM sender starting a download: ConnZmodemRequest is True once, and the program answers with ConnReceiveFiles in the same Timer event. ConnSetEcho shows what is typed on the Terminal too. Without a Terminal, read with ConnRead$ and send with ConnWrite (any bytes, CHR$(0) too). ConnOpen returns CONN_OK or a CONN_ERR_ code; ConnErrorText$ puts the code in words. ConnSetXferWindow conn, bytes limits how much a ZMODEM sender may send before it waits for an answer (0 = no limit, up to XFER_WINDOW_MAX; -1, the default, picks by the line). ConnSendBreak holds a serial line in the break state for a moment; ConnClose hangs up and ConnFree forgets the connection.
Dim conn As Long
Dim download As Long
Sub Form1_Load ()
conn = ConnCreate()
ConnSetSerial conn, 2, 115200, 8, "N", 1, CONN_FLOW_RTSCTS
ConnAttach conn, "Term1"
ConnOpen conn, CONN_SERIAL
End Sub
Sub Timer1_Timer ()
ConnPoll conn
If ConnZmodemRequest(conn) Then
download = ConnReceiveFiles(conn, XFER_ZMODEM, "DOWNLOAD", _
XFER_EXIST_RENAME, False)
End If
End Sub
1.17.23. File Transfers
With xfer.bas in the project, a program sends and receives files with XMODEM, XMODEM-1K, YMODEM, or ZMODEM. A transfer is a number: XferSendFile and XferReceive start one on a serial port opened with SerOpen (comm.bas), and ConnSendFiles and ConnReceiveFiles start one on a connection (conn.bas). XferSendFiles and XferReceiveFiles (a serial port) and the Conn ones take the options Terminal has: a batch of files (one path per line), escaping every control character, asking the receiver to continue interrupted files, and what to do with a file that is already there. On a serial port XferPoll moves the transfer along; on a connection ConnPoll does. XferStatus tells where it is (XFER_RUNNING until it ends with XFER_DONE, XFER_FAILED, or XFER_CANCELLED), and XferBytes, XferSize, XferFile$, XferFileIndex, XferFileCount, XferBatchBytes, XferBatchSize, XferResumedAt, and XferErrors show its progress; XferMessage$ says how it ended. A receive with XFER_EXIST_ASK stops in XFER_ASKING when a file already exists: XferAskSize, XferAskRemoteSize (the size the sender offers, -1 when it did not say), and XferCanResume describe it, and XferAnswer continues with an XFER_EXIST_ choice. XferCancel stops a transfer and XferClose frees it.
XferCrc16(bytes) and XferCrc32(bytes) give the check values the protocols use (CRC-16 as XMODEM computes it, 0 to 65535; the CRC-32 of ZMODEM and ZIP files as a Long, negative when its top bit is set) for any bytes. XferSafeName$(name, folder) gives the name a receive into folder stores a sender’s file name as: no folder or device name; a long name, its case kept, where folder’s disk takes long names (a character a name cannot hold becomes _), else an 8.3 name of characters every disk accepts.
1.17.24. Lists You Draw Yourself
With listhelp.bas in the project, a list or icon view a program draws itself — in a UserControl or a PictureBox — follows the same rules as ListBox and ListView. ListSelCreate(multi, count) makes a selection for count items (several at a time when multi is True) and returns a handle; it remembers which items are selected and which one is current (the one the keyboard moves). Items are numbered from 0. Give it the clicks and keys, and ask it what to draw:
| Function | Description |
|---|---|
ListSelClick sel, index, shift |
A click on an item, with the MouseDown event’s Shift: alone it selects only that item, with Ctrl it turns the item on or off, with Shift it selects the items from the last click up to it. |
ListSelKey(sel, keyCode, shift) |
Ctrl+A selects every item (returns LISTSEL_KEY_ALL), Space turns the current item on or off (LISTSEL_KEY_TOGGLE); LISTSEL_KEY_NONE for other keys. |
ListSelNavigate(sel, keyCode, shift, columns, pageRows) |
The arrow keys, Home, End, PgUp, and PgDn, in a list (columns 1) or a grid with columns items per row, pageRows rows a page; with Shift they select from the last click. The new current item, or -1 when nothing moved. |
ListSelMove sel, index, shift |
Make an item current as the keyboard does (after type-ahead). |
ListSelCursor(sel), ListSelSetCursor sel, index |
The current item (-1: none); make one item current and the only one selected. |
ListSelIsSelected(sel, index), ListSelSelectedCount(sel) |
Whether an item is selected; how many are. |
ListSelSetItem sel, index, selected; ListSelSetAll sel, selected |
Select or clear one item, or all. |
ListSelInsert sel, index; ListSelRemove sel, index |
An item was added or removed: the others keep their selection. |
ListSelReorder sel, fromIndex, dest |
An item was dragged to dest: its selection goes with it. |
ListReorderDest(fromIndex, toSlot, count) |
Where an item dragged from fromIndex lands when dropped in front of slot toSlot (count: after the last item); -1 when the drop changes nothing. |
ListSelReset sel, count; ListSelCount(sel); ListSelFree sel |
The list now holds count new items; how many it holds; free the handle. |
ListNavigateIndex(keyCode, current, count, pageSize), ListGridNavigate(keyCode, current, count, columns, pageRows) |
The same keys without a selection handle. |
ListSelTypeAhead(sel, ch, items) |
Type-ahead as ListBox does it: the item the key ch takes the list to from its current item. Keys typed less than a second apart make up the text looked for ("ma" finds the first item starting with "ma"); the same letter again goes on to the next item with it. Any case; items holds the texts separated by CHR$(10). -1 when none matches. |
ListTypeAhead(ch, items, current) |
One key alone: the next item after current whose text starts with the letter ch, any case (going round to the first); items holds the texts separated by CHR$(10). -1 when none does. |
ListTypeAheadMatch(ch, text) |
True when text starts with the letter ch. |
Sub UserControl_KeyDown (KeyCode As Integer, Shift As Integer)
If ListSelKey(sel, KeyCode, Shift) <> LISTSEL_KEY_NONE Then UserControl.Refresh
If ListSelNavigate(sel, KeyCode, Shift, columns, rowsShown) >= 0 Then
UserControl.Refresh
End If
End Sub
Sub UserControl_KeyPress (KeyAscii As Integer)
Dim i As Long
i = ListSelTypeAhead(sel, Chr$(KeyAscii), itemTexts)
If i >= 0 Then
ListSelMove sel, i, 0
UserControl.Refresh
End If
End Sub
Selections a program leaves open are freed when it ends.
An icon view drawn with listhelp.bas looks and behaves like Program Manager’s: the same cells for large icons, small icons, and the list, the same frame and scroll bar, a large icon’s name on two lines, and the same rules for the keys, dragging, and dropping. The grid functions take the view mode (LISTICON_VIEW_LARGE, LISTICON_VIEW_SMALL, or LISTICON_VIEW_LIST), the size of a character (TextWidth("W") and TextHeight("W")), the size of the whole view, how many items it shows, and rowsTaken: LISTICON_BY_ORDER when the items fill the grid in order, else how many rows items placed in cells of their own take. Draw the view’s frame with DrawBevel (LISTICON_FRAME wide; with the face -1 after the items, so a row cut off at the bottom stops at the frame) and its scroll bar with DrawScrollBar as a control’s bar (its control argument True); the grid leaves room for it.
- ListIconMetric(mode, metric, cw, ch, w, h, count, rowsTaken)
-
One value of the grid: a cell’s size (LISTICON_CELL_W, LISTICON_CELL_H), where its picture goes and how big it is (LISTICON_PICTURE_X, LISTICON_PICTURE_Y, LISTICON_PICTURE_SIZE), where its name goes and how many characters it shows (LISTICON_TEXT_X, LISTICON_TEXT_Y, LISTICON_NAME_CHARS; a large icon’s two lines are each centered in the cell), the list’s detail column (LISTICON_DETAIL_X, 0 in the other views); the inside of the frame less the scroll bar (LISTICON_INNER_X, LISTICON_INNER_Y, LISTICON_INNER_W, LISTICON_INNER_H), the columns, the rows shown whole and in all (LISTICON_COLUMNS, LISTICON_ROWS_SHOWN, LISTICON_ROWS), the largest top row (LISTICON_TOP_ROW_MAX), True when the scroll bar is needed (LISTICON_SCROLLBAR), where the text of an empty view goes (LISTICON_EMPTY_X, LISTICON_EMPTY_Y), the frame’s width (LISTICON_FRAME), and the rows a wheel notch scrolls (LISTICON_WHEEL_ROWS).
- ListIconCellAt(mode, cw, ch, w, h, count, rowsTaken, topRow, x, y)
-
The cell under x, y with the view scrolled to topRow, numbered row * columns + column; -1 outside the grid.
- ListIconLabel$(name, maxChars, lineNo)
-
Line 1 or 2 of a large icon’s name, maxChars characters a line (LISTICON_NAME_CHARS): the first line ends at the last blank that fits, else it is cut; the second is the rest, cut. "" for a line the name does not need.
- ListIconNavigate(keyCode, current, cells, columns, pageRows)
-
The item the arrow keys, Home, End, PgUp, or PgDn move to when the items stand in cells of their own, gaps allowed: cells holds each item’s column and row, all separated by commas ("0,0,2,0,1,1"). -1 for another key or when no item is that way.
- ListIconScrollPress(mode, cw, ch, w, h, count, rowsTaken, topRow, x, y)
-
A left press on the scroll bar: the top row after it (an arrow moves a row, the trough a page, the thumb nothing); -1 when x, y is not on the scroll bar.
- ListIconScrollGrab(mode, cw, ch, w, h, count, rowsTaken, topRow, x, y)
-
How far below the top of the thumb a press is; -1 when it is not on the thumb.
- ListIconScrollDrag(mode, cw, ch, w, h, count, rowsTaken, grab, y)
-
The top row with the thumb, held grab pixels below its top, dragged to y. While the button is down the control gets the mouse even outside it.
- ListIconDragStarted(dx, dy)
-
True when a press has moved far enough to start a drag.
- ListIconDragScroll(mode, cw, ch, w, h, count, rowsTaken, topRow, y)
-
While an item is dragged: the top row after the view scrolls a row because the mouse is above or below the grid.
- ListIconDropCell(mode, cw, ch, w, h, count, rowsTaken, topRow, x, y)
-
The cell a dragged item would be dropped on (above or below the grid: the nearest row); -1 for none.
- ListIconDropDest(fromIndex, cell, count)
-
Items in order: the place an item dragged from fromIndex takes when dropped on a cell — that cell’s, the last place for a cell past the end; -1 when the drop changes nothing.
Sub UserControl_Paint ()
Dim cw As Long, ch As Long, frameWidth As Long, nameChars As Long
cw = UserControl.TextWidth("W")
ch = UserControl.TextHeight("W")
frameWidth = ListIconMetric(LISTICON_VIEW_LARGE, LISTICON_FRAME, cw, ch, _
UserControl.Width, UserControl.Height, _
itemCount, LISTICON_BY_ORDER)
UserControl.DrawBevel 0, 0, UserControl.Width, UserControl.Height, _
True, vbWhite, frameWidth
' ... each item in its cell, its name in two lines:
nameChars = ListIconMetric(LISTICON_VIEW_LARGE, LISTICON_NAME_CHARS, _
cw, ch, UserControl.Width, UserControl.Height, _
itemCount, LISTICON_BY_ORDER)
UserControl.Print ListIconLabel$(itemName, nameChars, 1);
End Sub
1.17.25. Security
With security.bas in the project, a program has the building blocks of DVX’s encrypted serial link for its own protocols and files. All of them take and give strings that may hold any bytes, CHR$(0) too.
| Function | Description |
|---|---|
SecRandom$(count) |
count random bytes, good for keys and salts (RND is not). SecAddEntropy bytes stirs something unpredictable (key timings, mouse positions) into the generator. |
SecX25519PublicKey$(secretKey) |
The public key to send the other side, for a secret key of SEC_X25519_KEY_SIZE random bytes (SecRandom$). |
SecX25519$(secretKey, otherPublicKey) |
The secret both sides now share, which nobody listening can work out ("" for a key the other side should not have sent). About a sixth of a second on a slow computer. Make keys from it with SecHkdf$. |
SecX25519Start(secretKey, otherPublicKey) |
The same without the wait: SecX25519Step(h) then does a ninth of the work a call, returning SEC_X25519_PENDING until it is done (SEC_OK); SecX25519End$(h) gives the secret (with otherPublicKey "", the public key) and frees the handle. |
SecAeadLock$(key, nonce, extra, bytes) |
bytes sealed: encrypted with a SEC_AEAD_KEY_SIZE-byte key and a SEC_AEAD_NONCE_SIZE-byte nonce, followed by a tag that proves them, and extra (sent in the clear), unchanged. Use a new nonce for every message: SecRandom$(SEC_AEAD_NONCE_SIZE) is safe. |
SecAeadUnlock$(key, nonce, extra, sealed) |
What SecAeadLock$ sealed, or "" when anything was changed (or the key, nonce, or extra differs). |
SecEd25519KeyPair$(seed) |
A signing key made from seed, which SecRandom$ makes (SEC_ED25519_SEED_SIZE bytes); keep it private. SecEd25519PublicKey$(key) is the key to give out. |
SecEd25519Sign$(key, bytes) |
The signature of bytes; SecEd25519Check(signature, publicKey, bytes) is True only for exactly those bytes signed with that key. |
SecDhCreate() |
The older key exchange (Diffie-Hellman), with fresh keys (a few seconds on a slow computer); a handle, or 0. |
SecDhCreateStart() |
The same without the wait: SecDhStep(dh) then computes the keys a slice at a time, returning SEC_DH_PENDING until they are ready (SEC_OK). |
SecDhPublicKey$(dh) |
This side’s public key (SEC_DH_KEY_SIZE bytes), to send to the other side. |
SecDhComputeSecret(dh, otherPublicKey) |
Combine with the other side’s public key: SEC_OK, or SEC_ERR_PARAM for a key that is not acceptable. |
SecDhComputeStart(dh, otherPublicKey) |
The same a slice at a time: SEC_DH_PENDING (or SEC_ERR_PARAM at once), then SecDhStep as above. |
SecDhSecret$(dh) |
The secret both sides now share, which nobody listening can work out. Make keys from it with SecHkdf$; never use it as a key itself. SecDhFree dh frees the handle. |
SecCipherCreate(key) |
The older cipher (XTEA), with a SEC_XTEA_KEY_SIZE-byte key; 0 for a key of another length. It does not show tampering: add SecHmac$, or seal instead. |
SecCipherCrypt$(cipher, bytes) |
Encrypt — or decrypt, the same call — bytes. SecCipherSetCounter cipher, n sets the position in the key stream; the same key and position must never encrypt two different messages. SecCipherFree cipher frees it. |
SecSha256$(bytes) |
The SHA-256 hash (SEC_SHA256_SIZE bytes). For data in pieces: SecSha256Open, SecSha256Add h, piece, then SecSha256End$(h), which also frees the handle. |
SecHmac$(key, bytes) |
The HMAC-SHA256 signature of bytes with key; SecHmacOpen(key), SecHmacAdd, and SecHmacEnd$ for pieces. |
SecHkdf$(salt, secret, info, length) |
length bytes (up to SEC_HKDF_MAX_OUT) of keys made from secret; a different info gives different keys. |
SecEqual(a, b) |
True when a and b hold the same bytes, compared in the same time wherever they differ (for signature checks). |
' Both sides: make keys, swap public keys (here over a TCP connection),
' and agree a sealing key
Dim mine As String, theirs As String, key As String, nonce As String
mine = SecRandom$(SEC_X25519_KEY_SIZE)
TcpSend conn, SecX25519PublicKey$(mine)
' ... receive the other side's public key into theirs ...
key = SecHkdf$("", SecX25519$(mine, theirs), "chat", SEC_AEAD_KEY_SIZE)
' Send a message: the nonce, then the sealed bytes
nonce = SecRandom$(SEC_AEAD_NONCE_SIZE)
TcpSend conn, nonce & SecAeadLock$(key, nonce, "", "Hello")
Handles a program leaves open are freed, and their keys wiped, when it ends.
1.17.26. Settings Files
With prefs.bas in the project, a program keeps its settings in an INI file the way DVX’s own programs do. PrefsLoad(path) reads the file once (a file that is not there reads as empty); PrefsGet$, PrefsGetInt, and PrefsGetBool read a key of a section (each with the value to use when it is missing), and PrefsSet, PrefsSetInt, PrefsSetBool, and PrefsRemove change it in memory. PrefsSave writes it back, keeping comments and every line it did not change. To write a whole new file — dropping sections that are no longer wanted — fill a PrefsCreate handle and save it with PrefsSaveAs: the old file is replaced only once the new one is completely written. PrefsLoadFailed(handle) is True when the file PrefsLoad was given is there but could not be read (damaged, or on a disk that failed): the handle then holds none of its settings, and PrefsSave refuses to replace the file, so the settings in it are not lost. A program that writes the file anew with PrefsSaveAs should check PrefsLoadFailed first and leave such a file alone. PrefsClose frees a handle. IniRead and IniWrite (built in) do one value at a time and read or write the whole file each time; prefs.bas is the faster choice for many settings.
A password is better kept with PrefsSetSecret handle, section, key, value and read back with PrefsGetSecret$(handle, section, key) ("" when it is missing). The file then holds a "*" and a row of letters and digits that change each time it is saved, not the password itself, so it cannot be read over someone’s shoulder. This scrambles the password; it does not lock it away: anyone who knows how DVX scrambles it can unscramble it, so treat the file with the same care as the password. A value typed into the file by hand, without the "*", is read as it is.
Dim ini As Long
ini = PrefsLoad(App.User & "\MYAPP.INI")
userName = PrefsGet$(ini, "User", "Name", "Unknown")
PrefsSetInt ini, "Window", "Left", Me.Left
If Not PrefsSave(ini) Then MsgBox "The settings could not be saved."
PrefsClose ini
PrefsDvxIni$() is the path of DVX’s own settings file, DVX.INI, which Control Panel changes; other libraries (system.bas, joystick.bas, net.bas, print.bas, and sound.bas) read and store their part of it through a prefs.bas handle. PrefsSetVideoMode handle, wide, high, bpp stores the screen mode DVX starts in, and PrefsVideoWidth(handle), PrefsVideoHeight(handle), and PrefsVideoBpp(handle) read it (DVX’s own start-up mode, SYS_VIDEO_DEFAULT_* in system.bas, for a value that is not there). PrefsKeyName$(handle, section, index) is the name of key number index of a section (from 0, in the order of the file; "" past the last key), to go through every key of a section.
A settings window that saves onto a file other programs also change should save only what its user changed. PrefsApplyChanges handle, before, after makes in handle the changes that turn before into after: each key after has that before lacks or holds with another value is set, each key before has that after lacks is removed, and every other key of handle is left as it is. Store the window’s settings into a PrefsCreate handle when it opens and into another on OK, then PrefsLoad the file afresh, apply, and save: what another program or a hand edit changed in the file while the window was open stays. A before of 0 counts as empty.
Some settings are stored by name, from a fixed list of choices: the mouse acceleration (PREFS_CHOICE_ACCEL), the wallpaper mode (PREFS_CHOICE_WALLPAPER), and the scroll wheel direction (PREFS_CHOICE_WHEEL). For each list, PrefsChoiceCount(table) says how many choices it has (numbered from 0), PrefsChoiceLabel$(table, i) is the text to show, PrefsChoiceName$(table, i) the name stored in the file, and PrefsChoiceValue(table, i) the value it stands for (what SysSetMouse takes). PrefsChoiceIndex(table, choiceName) and PrefsChoiceIndexOfValue(table, value) find a choice (-1 when there is none), and PrefsGetChoice(handle, section, key, table) reads one from a file, giving DVX’s default choice when the key is missing or unknown. PrefsChoiceDefault(table) is that default choice, what a Defaults button selects. For a list of your own, PrefsGetChoiceFrom(handle, section, key, choiceNames, defaultName) does the same with the names separated by "|" ("large|small|list" stores choice 1 as "small"), giving defaultName’s choice for a missing or unknown key.
For i = 0 To PrefsChoiceCount(PREFS_CHOICE_ACCEL) - 1
cboAccel.AddItem PrefsChoiceLabel$(PREFS_CHOICE_ACCEL, i)
Next i
cboAccel.ListIndex = PrefsChoiceIndexOfValue(PREFS_CHOICE_ACCEL, SysMouseAccel())
1.17.27. Help Files
With help.bas in the project, HelpCompile(source, output) compiles a help source file (.dhs) into a help file (.hlp), True when it worked; its .image pictures are looked for in the source’s folder. HelpCompileMessages$() gives the compiler’s errors and warnings, one per line, each with the file and line ("error: NOTES.DHS:1: directive .h1 outside of a topic"). While a big file compiles, the rest of DVX and the program’s own events go on, as with DoEvents: one compile runs at a time, so a second HelpCompile meanwhile returns False at once, and the compile stops if the program ends. HelpView file opens a help file in DVX Help (a file named without a folder is looked for beside the program; "" opens the DVX user guide). HelpViewTopic file, topicId opens it at a topic, the way F1 does. A DVX Help that is already open shows the file in its window instead of a second copy starting.
With hlpfile.bas, a program reads help files itself — everything a help viewer needs. HlpOpen(path) opens a help file and returns a handle (0 when it is not one); HlpClose closes it (a program’s open files are closed when it ends). Topics are numbered from 0: HlpTopicCount, HlpTopicTitle$ and HlpTopicId$ (the name links and HelpTopic use), HlpFindTopic(handle, topicId) (-1 when there is none), and HlpStartTopic(handle, topicId), the topic to show first (topicId when the file has it, else the file’s own start page). HlpTocCount, HlpTocTitle$, HlpTocDepth, HlpTocTopic, and HlpTocExpanded give the table of contents in order — a depth of 0 is the top level, a topic of -1 a heading that only groups others — ready to fill a TreeView. HlpIndexCount, HlpIndexKeyword$, and HlpIndexTopic give the keyword index (sorted), for a list or DlgChoice. HlpSearch(handle, words) searches the titles, text, and keywords as DVX Help does and returns how many topics have every word; HlpSearchTopic(handle, n) gives them.
To show a topic, put a HelpPane control on the form and call HelpPane1.ShowTopic handle, topic: headings, paragraphs, lists, notes, code, tables, pictures, and links look as they do in DVX Help, and the text wraps to the control’s width. A click on a link, or Enter on one reached with Tab, fires the HelpPane’s LinkClick event with the ID of the topic the link names; the program decides what to do, usually show that topic and remember it for a Back button. A program that draws topics itself reads them with HlpLoadTopic(handle, topic) and HlpRecordType, HlpRecordFlags, HlpRecordText$, and HlpRecordLink$ (the HLP_REC_ constants), saves a picture for LOADPICTURE with HlpRecordImageSave, and wraps text with HlpWrap$.
Dim hlp As Long
Dim history(63) As Long, histPos As Long
Sub Form1_Load ()
hlp = HlpOpen(App.Path + "\MYAPP.HLP")
For i = 0 To HlpTocCount(hlp) - 1
If HlpTocDepth(hlp, i) = 0 Then
Toc.AddItem HlpTocTitle$(hlp, i)
Else
Toc.AddChildItem lastTop, HlpTocTitle$(hlp, i)
End If
If HlpTocDepth(hlp, i) = 0 Then lastTop = Toc.ItemCount() - 1
Toc.SetItemTag Toc.ItemCount() - 1, Str$(HlpTocTopic(hlp, i))
Next i
GoTopic HlpStartTopic(hlp, "")
End Sub
Sub GoTopic (ByVal topic As Long)
histPos = histPos + 1
history(histPos) = topic
HelpPane1.ShowTopic hlp, topic
Me.Caption = HlpTopicTitle$(hlp, topic) + " - My Help"
End Sub
Sub HelpPane1_LinkClick (Topic As String)
GoTopic HlpFindTopic(hlp, Topic)
End Sub
Sub Toc_Change ()
If Val(Toc.GetItemTag(Toc.ListIndex)) >= 0 Then
GoTopic Val(Toc.GetItemTag(Toc.ListIndex))
End If
End Sub
A help viewer written in BASIC can also take the place of DVX’s own: installed as APPS\KPUNCH\DVXHELP\DVXHELP.APP with a NewArgs event procedure, it is handed "helpfile topic" when F1 is pressed while it is open (see New Arguments in the Form topic).
1.17.28. Sizes in Characters
Control sizes (Width, Height, MinWidth, MinHeight, MaxWidth, MaxHeight) and a container’s Padding and Spacing are pixels. With layout.bas in the project, SizeChars(n) is a size of n characters of the control’s font (the system font unless the control or its container has a font of its own) and SizePercent(n) one of n percent (0 to 100); give them to one of those properties and the layout works out the pixels each time it arranges the form, so a box for an address keeps room for its characters whatever its font. Reading the property back gives the pixels it stands for at that moment.
A percentage in a size property is of the inside of the control’s container (its width for Width, MinWidth, and MaxWidth, its height for the others); in Padding and Spacing it is of the container’s own width. A percentage never makes a form bigger: it counts as nothing when the form is fitted to its controls, and it takes only the room the container has to spare — so a control with MinWidth = SizePercent(50) is half as wide as its row when the row has room, and no wider than leaves the other controls their own widths. Percentages inside percentages multiply, and resizing the form works them out again.
txtAddress.MinWidth = SizeChars(16)
lstFiles.MaxHeight = SizePercent(50)
picPreview.MinWidth = SizePercent(40)
fraOptions.Padding = SizePercent(5)
The same sizes go in a .frm file and the IDE’s Properties window as text: MinWidth = 50% is SizePercent(50), MinWidth = 20ch is SizeChars(20), and a plain number is pixels, as before (see Sizes in a .frm in the controls overview). A UserControl’s natural size takes them too: its header’s Width and Height in the .ctl file as text, and UserControl.MinWidth and MinHeight in its code as SizePercent and SizeChars (see UserControls: Your Own Controls).
1.17.29. Compiling and Debugging Programs
With compiler.bas in the project, a program compiles BASIC programs — what a development tool written in BASIC needs. A source set holds the files of one program: CompSourceFromProject(src, dbpPath) reads a whole project (.dbp) from disk, or CompSourceAdd(src, path, text, kind) adds files one at a time, in the order a project compiles: modules, then class modules, then UserControls, then forms (COMP_KIND_AUTO tells them apart by the file name; a form’s whole .frm text is added, and the code after its layout is compiled; a UserControl’s whole .ctl text, its header and its code). CompCompile(src, optionExplicit, validate) gives a compiled module, or 0 with CompError$() saying what is wrong and CompErrorFile$() / CompErrorFileLine() where. With validate True, Label1.Captoin and other misspelled control members, and controls of an unknown type, are found while compiling instead of when the line runs (the set’s own UserControls are known types).
Line numbers of compiled programs (errors, breakpoints, the line a program is paused on) count through all the files of the source set. CompMapFile$(src, line) and CompMapLine(src, line) give the file and the line in it; CompConcatLine(src, path, fileLine) goes the other way. CompSourceFiles$ lists the files in compile order. CompBuildApp(module, src, outPath, release) builds an .app the way the IDE’s Make Executable does, with the project’s name, icon, and help file, its forms, and its UserControls. For a control project (its Type setting is "Control") it builds a control file instead (outPath NAME.wgt), the way the IDE’s Make Control does: the project’s UserControls with their toolbox pictures and names, there for every program once the file is copied into DVX’s WIDGETS folder (DVX loads it when it starts). CompProcList$(text) lists the SUB, FUNCTION, and PROPERTY blocks of source text with their first and last lines (also for code that does not compile yet), CompIsIdent checks a name, and CompKeyword$ lists the language’s keywords, CompKeywordClass the kind of each (COMP_KW_OTHER, COMP_KW_TYPE, or COMP_KW_LITERAL), and CompKeywordReserved whether a program may also use it as a name of its own.
Project files: ProjOpen(dbpPath) opens a project file (.dbp) and ProjNew(name, folder) starts a new one; ProjSave writes it and ProjClose frees it. ProjFileCount, ProjFile$ (the name as the project lists it), ProjFilePath$ (the full path), ProjFileKind (COMP_KIND_MODULE, COMP_KIND_FORM, COMP_KIND_CLASS, or COMP_KIND_CONTROL), and ProjFileFind list its files; ProjAddFile, ProjRemoveFile, and ProjRenameFile (on disk and in the project together, saved at once) change the list. ProjGet$ and ProjSet read and set its settings by their names in the file: Name, Type ("Control" for a control project, empty for a program), Author, Publisher, Version, Copyright, Description, Icon, HelpFile, CommandArgs, StartupForm, OptionExplicit, and MultiInstance (the last two "true" or "false"). This is the project model the DVX BASIC IDE uses.
A UserControl’s header (the Begin UserControl block at the top of its .ctl file) is read and changed the way the IDE’s Properties window does it, the rest of the text left as it is: ProjCtlKeys$() lists the keys in the window’s order with the kind of value each takes (Name, Width, Height, CanGetFocus, BackColor, ToolboxIcon, Description, DefaultEvent; the kinds Name, Size, Boolean, Color, and Text, a Size being pixels, a percentage such as 50%, or characters such as 20ch), ProjCtlHeader$(text, key) reads one (its default when the header leaves it out), ProjCtlSetHeader$(text, key, value) gives the text with one set (an empty value removes it; Name renames the control), and ProjCtlNew$(name) the text of a new UserControl, as File > New UserControl makes it.
With debug.bas too, a program runs a compiled module as a child program inside itself: RunCreate(module, src, appDir, args) prepares it, RunStart(run, startupForm, breakOnStart) loads its forms, and RunPoll(run, ms), called from a Timer, runs it for at most ms milliseconds at a time and returns what it is doing: RUN_RUNNING, RUN_EVENTS (waiting for events on its forms), RUN_PAUSED, RUN_ENDED, or RUN_ERROR (RunError$ and RunErrorLine tell why and where). RunOutput$ collects what it PRINTs; INPUT asks with an input box. RunStop ends it and RunFree forgets it.
DbgSetBreakpoints run, "12, 40" sets breakpoints (line numbers of the source set). While the program is paused, DbgLine and DbgProc$ say where (a SUB or FUNCTION of a form’s code as Form1.Refill, since two forms may each have one of the name), DbgLocals$ and DbgCallStack$ give the variables and the calls as rows for a ListView’s SetRows, DbgEval$(run, expr) shows a variable or expression as the IDE’s Watch window does, DbgExec$(run, line) runs an Immediate-window line (x = 5 changes a variable, anything else is printed), and DbgSetVar changes a variable; DbgStepInto, DbgStepOver, DbgStepOut, DbgRunToLine, and DbgContinue go on, DbgPause stops it at the next line. The program’s form captions show [break] while it is paused.
A program paused in its module-level code waits until you step or continue it. One paused inside one of its event handlers — or in its forms' Load code, which runs inside RunStart — waits right there while your Timer and menus keep working; RunPoll called meanwhile returns at once, and RunStart returns only after such a pause.
' compiler.bas and debug.bas in the project; tmrRun is a Timer
Dim src As Long, mdl As Long, kid As Long
Sub StartDebugging
src = CompSourceCreate()
If Not CompSourceFromProject(src, "C:\PROJ\HELLO.DBP") Then
MsgBox CompError$()
Exit Sub
End If
mdl = CompCompile(src, True, True)
If mdl = 0 Then
MsgBox CompErrorFile$() & " line" & Str$(CompErrorFileLine()) & _
": " & CompError$()
Exit Sub
End If
kid = RunCreate(mdl, src, "", "")
DbgSetBreakpoints kid, Str$(CompConcatLine(src, "C:\PROJ\MAIN.BAS", 12))
If RunStart(kid, "", False) Then tmrRun.Enabled = True
End Sub
Sub tmrRun_Timer
Select Case RunPoll(kid, 40)
Case RUN_PAUSED
lstLocals.SetRows DbgLocals$(kid)
lblWhere.Caption = CompMapFile$(src, DbgLine(kid)) & ":" & _
Str$(CompMapLine(src, DbgLine(kid)))
Case RUN_ENDED, RUN_ERROR
tmrRun.Enabled = False
txtOutput.Text = txtOutput.Text & RunOutput$(kid) & RunError$(kid)
End Select
End Sub
1.17.30. Form Designers and Code Editors
A form designer or a code editor written in BASIC uses the same pieces as the DVX BASIC IDE. designer.bas describes the control types, which CtlTypeName$(0 to CtlTypeCount - 1) gives in alphabetical order: the toolbox lists the types CtlTypeFlags marks CTL_FLAG_DESIGNABLE (with CtlTypeTooltip$ and the icon CtlTypeIconFile writes), CTL_FLAG_NOVISUAL marks a type with nothing to see while the program runs (a Timer), which a designer shows in a tray of its own, new controls are named CtlTypeNamePrefix$ plus a number, a new control of a UserControl type starts at the natural size of its header, CtlTypeNaturalSize$(typeName, "Width") and CtlTypeNaturalSize$(typeName, "Height") — text such as 120, 50%, or 20ch, which FrmCtlSet takes for its MinWidth and MinHeight and ProjCtlSetHeader$ for the header ("" for DVX’s own types, which have none) —, and the properties window lists CtlPropName$ for 0 to CtlPropCount - 1 with CtlPropType (CTL_PROP_STRING ... CTL_PROP_ENUM, plus CTL_PROP_READONLY) and CtlPropEnum$ for an enumerated property’s choices. "Form" and "Menu" stand for the form itself and a menu item. The event list is CtlEventList$, and CtlEventParams$ writes an event procedure’s parameter list; CtlTypeEventParams$(typeName, eventName) does it for one type, whose events may have parameters of their own (a UserControl’s events), and "UserControl" stands for the object in a UserControl’s own code (UserControl_MouseDown has Button, Shift, X, and Y). For a project’s files, FrmFormName$ and FrmControlNames$ read a .frm file’s form and control names (the Object list), FrmCode$ its code, and ClsClassName$ a class module’s name.
The form being designed is a real form: CreateControl and RemoveControl add and remove controls, CallByName reads and sets a property by its name, Me.Controls lists the controls, Container (Set ctl.Container = Frame1) and MoveBefore move them, and LoadFormText shows a .frm file. Its DesignMode (see the Form control) stops the controls from working and reports the mouse and keys in DesignMouse and DesignKey, with the selection handles drawn for DesignSelection.
A project’s own UserControls go on the toolbox too, as in the IDE. Compile the project — its forms may be left out — and give the module and the source set to CompDesignControls(module, src, appDir) from compiler.bas: the UserControls are then control types of this program alone, listed by CtlTypeName$ with their Description as the tooltip and their ToolboxIcon as the icon, with their properties, methods, and events, and known to CreateControl and LoadFormText. On the forms they run their code — not the project’s module-level code — with UserControl.UserMode False on a form in DesignMode; App.Path is appDir, or the project’s folder for "". When a control’s code calls UserControl.PropertyChanged, the form raises DesignPropertyChanged (CtrlName, PropertyName), so the properties window can read them again. Call CompDesignControls again after a UserControl changed (the ones before are let go first) and CompDesignRelease when the project closes; the end of the program lets them go too. The module stays in use while they are there, even after CompModuleFree, and must be one this program compiled.
' compiler.bas and designer.bas in the project; Canvas is the form
' being designed
Sub LoadProjectControls(dbpPath As String)
Dim src As Long
Dim mdl As Long
Dim made As Long
src = CompSourceCreate()
If CompSourceFromProject(src, dbpPath) Then mdl = CompCompile(src, True, False)
If mdl = 0 Then
MsgBox CompError$()
Else
made = CompDesignControls(mdl, src, "")
If CompError$() <> "" Then MsgBox CompError$()
CompModuleFree mdl
End If
CompSourceFree src
End Sub
Sub Canvas_DesignPropertyChanged(CtrlName As String, PropertyName As String)
If CtrlName = Canvas.DesignSelection Then RefreshPropertyList
End Sub
A .frm file can also be worked on as data, the way the DVX BASIC IDE does it, without showing it. FrmOpen(text$), FrmOpenFile(path$), or FrmNew(name$) gives a handle to a form model (0 when the text is not a form); FrmText$ writes it back as .frm text in the form the IDE saves and FrmSave writes it to a file; FrmFree frees it (a program’s open handles are freed when it ends). FrmGet$ and FrmSet read and change the form’s properties (Caption, Width, AutoSize, Layout, Icon, Tag ...; Name renames the form), FrmGetCode$ and FrmSetCode its code. The controls are numbered from 0 in file order, each one followed by the controls inside it: FrmCtlCount, FrmCtlFind, FrmCtlName$, FrmCtlType$, FrmCtlIndex (its control array index, -1 when it is not in an array), and FrmCtlParent (the container, -1 for the form) describe them; FrmCtlGet$ and FrmCtlSet read and set any property as text (Name renames the control alone, as Visual Basic does — an element of a control array leaves it, keeping its Index, and the other elements keep the name — and the controls inside it follow; Index makes it an array member — "" none, 0 to 32767 one no other control of its name has; a control whose name others share keeps one, and gets none while one of them has none — and FrmCtlIndexError$ says why one is refused, "" when it is not; an OptionButton set to True clears the others in its container), FrmCtlJoin renames a control the name of other controls of its type, an element of their control array (a lone control of that name becomes element 0, it takes the next Index; an element of another array leaves that one), as the Visual Basic designer does on such a rename, FrmCtlRemoveProp takes a set one out, and FrmCtlPropCount / FrmCtlPropName$ list the ones that were set. FrmCtlAdd adds a control (its name "" gives the next free one, Command1, Label2 ...) as the last control of a container (-1: the form), FrmCtlRemove removes one with what is inside it, FrmCtlMove puts one before another of the same container, and FrmCtlReparent into another container. FrmCtlText$ gives a control with what is inside it as .frm text, what a designer puts on the Clipboard to copy it, and FrmCtlPaste puts such text into a container: a name that is already taken is replaced by a free one. The menu items are numbered from 0 in menu order with a Level (0 for a menu on the menu bar or a popup menu, 1 for its items, 2 and more for submenus): FrmMenuCount, FrmMenuGet$ / FrmMenuSet (Name, Index — -1 for an item in no menu control array —, Caption, Shortcut, ShortcutText, Checked, RadioCheck, Enabled, Visible, Tag, Level; Name refuses a name in use, but an item with an Index joins the menu control array of its name when no element has that Index), FrmMenuAdd, FrmMenuRemove (with the items under it), FrmMenuMove (past the previous or next item of its level), and FrmMenuIndent (one level in or out, with the items under it). Only what was set is written: a property a control has by default is left out of the file.
FormText$(formName$) writes a loaded form as it is now as .frm text — one shown with LoadFormText, made with CreateForm and CreateControl, or one of the program’s own: its properties, its controls in their containers with each property that differs from a new control of that type, and its menus (a form loaded this way has no code). A designer that keeps its form live saves it with FormText$, and FrmOpen(FormText$(...)) reads it as a model.
compiler.bas reads source text as the compiler does, for a code editor: CompTokens$(source) lists its tokens (line, column, length, kind, and text, the kind one of Keyword, Identifier, String, Number, Date, Symbol, Comment, and Error); CompInCode(source, position) tells whether a character is code rather than inside a string or a comment; CompRenameInCode$(source, oldName, newName, codeOnly) renames a form, control, or menu item where code refers to it (Command1.Caption, Command1_Click), leaving strings and comments alone with codeOnly; CompWithEvents$ lists the WithEvents variables a file declares and CompClassEvents$ the Events of a class module or a form’s code, for the Object and Event lists; CompHelpTopic$(word) and CompHelpCtrlTopic$(typeName) are the help topics F1 opens (HelpViewTopic on dvxbasic.hlp beside the IDE).
A code editor is a TextArea: SetSyntaxMode "bas" colors BASIC as the IDE does (SetSyntaxColor changes the colors), SetLineMarker marks breakpoints and the current line, GutterClick reports clicks on the line numbers, SelStart / SelLength / SelText and Cut, Copy, Paste, SelectAll, and Undo give the Edit menu, FindNext / ReplaceSelection / ReplaceAll find and replace, and LineCount / GetLine / CursorLine / CursorCol read the text (see TextArea).
' designer.bas in the project: put a copy of the first control of a
' .frm file into a Frame of the same form and save it
Sub CopyIntoFrame(path As String)
Dim h As Long
Dim box As Long
h = FrmOpenFile(path)
If h = 0 Then Exit Sub
box = FrmCtlAdd(h, "Frame", "", -1)
If FrmCtlSet(h, box, "Caption", "Copies") And _
FrmCtlPaste(h, FrmCtlText$(h, 0), box) >= 0 Then
If Not FrmSave(h, path) Then MsgBox "Could not save " & path
End If
FrmFree h
End Sub
' designer.bas in the project: fill a properties list for a control
Sub ShowProperties(ctl As Object, typeName As String)
Dim i As Integer
Dim v As String
lstProps.Clear
For i = 0 To CtlPropCount(typeName) - 1
If (CtlPropType(typeName, i) And CTL_PROP_TYPEMASK) <> CTL_PROP_OBJECT Then
v = CallByName(ctl, CtlPropName$(typeName, i), vbGet)
lstProps.AddItem CtlPropName$(typeName, i) & " = " & v
End If
Next
End Sub
See also: DECLARE LIBRARY (Section 1.4.2).
Chapter 2. Forms and Controls
2.1. Form
The Form is the top-level container representing a DVX window. It is declared in the .frm file with Begin Form FormName. All controls are children of the form’s content box, which uses either VBox (default) or HBox layout.
2.1.1. Form Properties
- Name
-
Type: String; Default: "Form1". The form’s name, used for event dispatch and Load statement.
- Caption
-
Type: String; Default: (same as Name). Window title bar text.
- Width
-
Type: Integer; Default: 400. Window width in pixels. In the .frm file it is ignored when AutoSize is True. A value below 0 raises error 380 (Invalid property value), as in Visual Basic; one smaller than the window’s frame fits in becomes the smallest it does, as when the user drags it.
- Height
-
Type: Integer; Default: 300. Window height in pixels. In the .frm file it is ignored when AutoSize is True. Below 0 raises error 380, as Width does.
- Left
-
Type: Integer; Default: 0. Initial X position. Used when Centered is False.
- Top
-
Type: Integer; Default: 0. Initial Y position. Used when Centered is False.
- Layout
-
Type: String; Default: "VBox". Content box layout: "VBox" (vertical) or "HBox" (horizontal).
- AutoSize
-
Type: Boolean; Default: False. When True, the window shrink-wraps to fit its content.
- Resizable
-
Type: Boolean; Default: True. Whether the user can resize (and maximize) the window at runtime. True unless the .frm says Resizable = False, as Visual Basic’s forms have a sizable border unless told otherwise: set it False for a dialog box or a layout that should keep its size.
- Centered
-
Type: Boolean; Default: True. When True, the window is centered on screen; an AutoSize form at the size it has when it is first shown, after its Load. When False, Left/Top are used.
- Visible
-
Type: Boolean; Default: False. True shows the form and False hides it, exactly like Show and Hide (the first show fires Activate).
- Enabled
-
Type: Boolean; Default: True. False makes the form take none of the user’s input, as in Visual Basic: no click, key, or mouse event reaches it or its controls (which are drawn disabled), and its window cannot be moved, sized, closed, or brought forward by the user (its title bar, borders, close box, menus, Alt+F4, and Alt+Tab do nothing for it). It still paints, its timers still run, and code can move, show, hide, and unload it. The control that had the focus loses it (LostFocus) and gets it back (GotFocus) when Enabled is set True again; a form that was the active one stays active, taking no keys. Reading it gives the form’s own setting, also in design mode, where the form takes input anyway (see Designing Forms). The .frm says Enabled = False only.
- ContextMenu
-
Type: String; Default: "". Name of a popup menu shown when the form is right-clicked.
- HelpTopic
-
Type: String; Default: "". Help topic opened by F1 while the form is active and the focused control has no HelpTopic of its own. Empty opens the project’s help file at its default page.
- Padding
-
Type: Integer; Default: 4. Space in pixels between the window’s edges and the controls (the content box’s Padding); 0 is none. Also a percentage of the form’s width (SizePercent in code, "10%" in the .frm and the Properties window) or characters (SizeChars, "2ch").
- Spacing
-
Type: Integer; Default: 4. Space in pixels between one control and the next (the content box’s Spacing); 0 is none.
- WindowState
-
Type: Integer; Default: 0. vbNormal (0), vbMinimized (1, shown only as an icon at the bottom of the screen), or vbMaximized (2, filling the screen). Set on a hidden form (or in the .frm file), it takes effect when the form is shown; reading it then gives the state the form will have.
- Controls
-
Type: Collection; Default: (none). The form’s controls (read-only), in the order they were made, then its menus and menu items in menu order (the .frm’s; a loaded element of a menu control array after the array’s last one), as in Visual Basic: Me.Controls.Count, Me.Controls(0) (the first, as in Visual Basic: the index counts from 0 to Count - 1), Me.Controls("Text1"), For Each c In Me.Controls. Elements of a control array or menu control array are in it too but have no name key. A menu is of type Menu (TypeOf c Is Menu, TypeName(c) = "Menu") and has no Left, Container, or the other control properties (error 438): a loop that reads them skips menus with If Not TypeOf c Is Menu Then. Each use without an index makes a new Collection, which counts from 1 as every Collection does (Set c = Me.Controls: c(1) is the first); changing it does not change the form.
- DesignMode
-
Type: Boolean; Default: False. True puts the form in design mode, for a form designer: see Designing Forms below. Not in .frm files.
- Icon
-
Type: Picture; Default: (DVX’s). The picture shown for the window while it is minimized: a picture file name (BMP, PNG, JPEG, or GIF) or a picture from LOADPICTURE or LOADPICTUREDATA (Set works too); "" puts DVX’s back. Reading it gives a Picture object. Also in the .frm file. A file that is not a picture is an error.
- Tag
-
Type: String; Default: "". Any text the program wants to keep with the form, as for controls.
- MousePointer
-
Type: Integer; Default: 0. The mouse pointer over the form where its controls have none (see MousePointer under Common Properties).
- BackColor
-
Type: Long; Default: (the theme’s). The form’s background, as in Visual Basic: the whole form behind its controls, which the controls with no face of their own (a Label, a CheckBox, an OptionButton, a Frame’s title, a Slider, an Image’s empty part, an HBox or VBox) show too, and what the form’s drawing starts in and Cls clears to. It reads the theme’s window content color until it is set; setting it clears what was drawn on the form. 0 is black. Also in the .frm file.
- FontName
-
Type: String; Default: "System". The form’s font: the font of every control on it that has none of its own, and of the form’s Print and TextWidth. FontSize, FontBold, FontItalic, FontUnderline, and FontStrikethru go with it, as for controls (see Fonts under Common Properties). Also in the .frm file.
- ActiveControl
-
Type: Control; Default: (none). The control of the form that has the keyboard focus (read-only), Nothing when none of them has it: Me.ActiveControl.SelText for an Edit menu’s Copy. Screen.ActiveControl is the focused control of the whole program. Not in .frm files.
- DesignSelection
-
Type: String; Default: "". The name of the control (Text1, or Text1(2) in a control array) whose selection handles are drawn while the form is in design mode; "" for none. Not in .frm files.
- MaxWidth
-
Type: Integer; Default: 0. The widest the user can make the window, by dragging or maximizing; 0 is the screen’s width. A window wider than a new MaxWidth shrinks to it. Also in the .frm file.
- MaxHeight
-
Type: Integer; Default: 0. The tallest the window can be made, as MaxWidth; 0 is the screen’s height.
- GameInput
-
Type: Boolean; Default: False. True for a game: while the form has the keyboard, every key goes to it — none to F1 (help), F10 or Alt (the menu bar), menu shortcuts, or DVX’s shortcut keys. Only Alt+Tab, Ctrl+Esc, and Alt+F4 still reach DVX. Also in the .frm file.
- FullScreen
-
Type: Boolean; Default: False. True gives the form the whole screen: a video mode as large as the form’s inside (its controls and drawing, without the title bar), the form shown on it at the largest whole multiple of its size that fits, centered on black, kept up to date as it changes. The mouse works on it as in the window, and every key goes to it as with GameInput. A hidden form is shown first. When the user switches to another program (Alt+Tab, Ctrl+Esc), or the program shows a message box or another form, the desktop comes back; the form gets the whole screen again with the focus. Reads False when no video mode could be set (the form stays in its window). False gives the desktop back. Run time only; see the FullScreen event.
Maximizing a window, or restoring a maximized one, changes its size, so Resize fires. Minimizing does not change the size and fires no Resize. A minimized window keeps its maximized state: set WindowState = vbMaximized to bring it back filling the screen, vbNormal to bring it back at its normal size.
frmTerminal.Show
frmTerminal.WindowState = vbMinimized ' starts as an icon
2.1.2. Form Events
- Initialize
-
Parameters: (none). Fires when a form instance is made: the first use of the form’s name (even Set f = Form1, which does not load it; the startup form’s as the program starts), New, or LoadFormText. It comes before the form’s Load, with the form’s variables as the form will load with them.
- Load
-
Parameters: (none). Fires after the form and all controls are created. This is the default event.
- Unload
-
Parameters: Cancel As Integer. Fires when the form is being closed or unloaded, after QueryUnload. Set Cancel = 1 to keep the form loaded, as in Visual Basic. A handler without the parameter (Sub Form1_Unload) runs too.
- QueryUnload
-
Parameters: Cancel As Integer, UnloadMode As Integer. Fires before Unload. Set Cancel = 1 to abort the close. UnloadMode says why the form closes: vbFormControlMenu (0) the user closed its window (its close box, Alt+F4, or the system menu’s Close), vbFormCode (1) Unload in the program’s code, vbAppWindows (2) DVX is exiting, vbAppTaskManager (3) another program asked this one to close (ShellRunningClose) or DVX ended its screen saver. DVX has no MDI forms or owned forms, so vbFormMDIForm (4) and vbFormOwner (5) never come. A handler that takes Cancel alone (Sub Form1_QueryUnload(Cancel As Integer)) runs too, as one without parameters does. End Task in Task Manager ends a program without running its code, so no QueryUnload comes then.
- Terminate
-
Parameters: (none). Fires when a form instance is gone: it is not loaded and nothing refers to it any more, as in Visual Basic. It runs as soon as the last reference goes, before the code goes on: Set Form1 = Nothing after its Unload when no variable still holds it, Set f = Nothing or another value for the last variable holding a copy New made, the end of the procedure whose local variable held it, or the Unload of a copy nothing else refers to; a copy LoadFormText made as its Unload frees it. It also fires for every instance left as the program ends normally (not with END). Never while the form is loaded; the handler still has the form’s variables.
- Resize
-
Parameters: (none). Fires when the window changes size: resized by the user, maximized, or restored (by the user or WindowState).
- Activate
-
Parameters: (none). Fires when the window gains focus.
- Deactivate
-
Parameters: (none). Fires when the window loses focus.
- Click
-
Parameters: (none). Fires when the form itself is clicked: a mouse button pressed and released on the form’s background, not on one of its controls (they get their own events), its title bar, menu bar, or border. In Visual Basic’s order: MouseDown at the press, then MouseUp and Click at the release, Click only when the release is over the form’s background.
- DblClick
-
Parameters: (none). Fires when the form’s background is double-clicked: MouseDown, MouseUp, Click, DblClick, MouseUp, as in Visual Basic.
- MouseDown
-
Parameters: Button As Integer, Shift As Integer, X As Single, Y As Single. Fires when a mouse button is pressed on the form’s background. Button is vbLeftButton, vbRightButton, or vbMiddleButton; Shift holds the vbShiftMask, vbCtrlMask, and vbAltMask bits of the keys held; X and Y are where, in the form’s scale (its ScaleMode, pixels by default, or the scale Scale set).
- MouseUp
-
Parameters: Button As Integer, Shift As Integer, X As Single, Y As Single. Fires when a button pressed on the form’s background is released, wherever the mouse is.
- MouseMove
-
Parameters: Button As Integer, Shift As Integer, X As Single, Y As Single. Fires when the mouse moves over the form’s background; Button holds the buttons down.
- Paint
-
Parameters: (none). Fires when the form is shown or resized and on Refresh, unless AutoRedraw is True (see Drawing on Forms and PictureBoxes).
- DragDrop
-
Parameters: Source As Control, X As Single, Y As Single. Fires when a dragged control is dropped on an empty part of the form. X and Y are where, in the form’s scale, as for MouseDown.
- DragOver
-
Parameters: Source As Control, X As Single, Y As Single, State As Integer. Fires while a dragged control moves over an empty part of the form. State is vbEnter, vbLeave, or vbOver.
- NewArgs
-
Parameters: (none). Fires when the running program is handed new arguments: COMMAND$ has changed (see New Arguments below).
- FullScreen
-
Parameters: State As Integer. With FullScreen True: dvxFullScreenActive (1) when the form has the whole screen (draw anything that must look new then), dvxFullScreenSuspended (2) when the desktop came back while another window has the focus, dvxFullScreenEnded (0) when the form’s video mode could not be set again (FullScreen is False now).
- DesignMouse
-
Parameters: Action As Integer, Button As Integer, X As Integer, Y As Integer, CtrlName As String, Handle As Integer. In design mode: the mouse was pressed, moved, released, or double-clicked in the form. See Designing Forms below.
- DesignKey
-
Parameters: KeyCode As Integer, Shift As Integer. In design mode: a key was pressed in the form (KeyCode and Shift as in KeyDown).
- DesignPropertyChanged
-
Parameters: CtrlName As String, PropertyName As String. In design mode: the code of a UserControl on the form called PropertyChanged. See Designing Forms below.
See Drag and Drop under Common Properties, Events, and Methods. While a control is dragged over a form with no DragDrop event procedure, the mouse pointer shows the "no drop" sign.
A variable declared WithEvents As the form’s type (Dim WithEvents f As Form2), or As Form, gets the events of the form instance it holds too, after the form’s own handlers (Sub f_Load, Sub f_QueryUnload(Cancel As Integer, UnloadMode As Integer)); a Cancel either handler sets keeps the form loaded. Initialize and Terminate reach only the form’s own handlers. A form’s code can also declare events of its own (Public Event) and raise them (RaiseEvent), which a variable declared WithEvents As that form handles. See Events of a Form and A Form’s Own Events under Events in the Language Reference.
2.1.3. New Arguments
A program with a NewArgs event procedure on any of its forms can be handed new arguments while it runs, instead of DVX starting another copy of it. COMMAND$ (and COMMAND$(1), COMMAND$(2), ...) then give the new arguments, and NewArgs fires on every loaded form that has the procedure (a form not loaded yet gets nothing: forms load when the program first refers to them). When the arguments arrive while one of the program’s event procedures is still running — for example while it shows a message box or a dialog, or a form with vbModal — they are held, and NewArgs fires once that procedure has finished; if several arrive meanwhile, only the last is given.
DVX hands new arguments to the help viewer: F1 and the Help menus of programs (and HelpView in BASIC) send "helpfile topic" to the program installed as APPS\KPUNCH\DVXHELP\DVXHELP.APP when it is already running. A help viewer written in BASIC and installed there gets them in NewArgs. Starting a program that is already running — from Program Manager, the Run dialog, a document opened in it, or ShellRun — gives it the new arguments when it allows only one copy and has a NewArgs procedure: its window comes to the front and NewArgs fires. Without a NewArgs procedure DVX says it is already running; a program that allows more than one copy (Project Properties) starts another copy instead.
Sub Form1_NewArgs ()
' F1 in another program while this help viewer is open
If COMMAND$(1) <> openFile Then OpenHelpFile COMMAND$(1)
GoTopic HlpStartTopic(hlp, COMMAND$(2))
End Sub
2.1.4. Form Methods
| Statement | Description |
|---|---|
Load FormName |
Load the form (creates the window and controls, fires Load event). |
Load f |
Load the form a Form variable, an Object, or Me refers to (a copy New made too), firing its Load event, without showing it; nothing for a loaded form. |
Unload FormName |
Unload the form (fires Unload, destroys window); Unload f and Unload Me unload the form they refer to. |
Load Ctrl(n) |
Add element n to the form’s control array or menu control array Ctrl: a copy of its lowest element as the form file made it, hidden (see Control Arrays). |
Unload Ctrl(n) |
Remove element n, one Load added, from the array. |
FormName.Show |
Make the form visible. |
FormName.Show 1 |
Show as a modal dialog (vbModal): the statement returns when the form is hidden or unloaded, so the code after it can read what the user chose. |
FormName.Hide |
Hide the form without unloading it. |
FormName.FitWidth |
Make the window just wide enough for its controls, keeping its height (AutoSize fits both). |
FormName.FitHeight |
Make the window just tall enough for its controls, keeping its width. |
FormName.Move left [, top [, width [, height]]] |
Move the window and change its size at once, as Visual Basic’s Move: Left and Top as those properties set them, then Width and Height in one resize (one Resize event). An argument left out keeps what the form has; Left is needed (error 449 without it), and a Width or Height below 0 raises error 380. |
FormName.ZOrder [position] |
vbBringToFront (0, the default) puts the window in front of the others with the focus, vbSendToBack (1) behind them (the focus going to the window now on top), as in Visual Basic. A hidden form’s window stays where it is. |
FormName.SaveScreenshot file$ |
Save a picture of what the window shows inside its frame to a file: BMP when the name ends in .bmp, PNG otherwise. An error when the form has no window or the file cannot be written. |
In the form’s own code its properties and methods need no Me, as in Visual Basic: Caption = "Ready", Hide, Show vbModal, Refresh, and PopupMenu mnuEdit are the form’s own (see How Names Are Found in the language reference for what comes first). PRINT stays the PRINT statement there: Me.Print prints on the form.
2.1.5. Several Copies of a Form
A form can be open more than once, the way a program opens a second document window. New FormName makes another copy of the form: its own window, controls, menus, and form-level variables, built from the same .frm. As in Visual Basic, the copy loads (its Load event runs) at its first use — f.Show, f.Caption, or one of its controls — and starts hidden like any loaded form, so call Show. Keep the copy in a variable declared As the form’s name (or As Form, As Object):
Dim f As Form1 ' a Form1 copy, or the form itself
Set f = New Form1 ' a new copy
f.Caption = "Second window"
f.Text1.Text = "Hello" ' this copy's Text1
f.Show
Dim g As New Form1 ' declares and makes a copy at once
A variable declared As the form’s name holds only that form or a copy of it, as in Visual Basic, and knows the form’s members: f.Count, f.Refill, f.Text1, and the properties and methods every form has (f.Caption, f.Show, f.Controls(0)) are looked up when the program is compiled — in the IDE and by the command-line compiler alike — so a misspelled name, or one of the form’s Private variables or procedures, is reported then, as for Form1.Count and Form1.Xyzzy. A control CreateControl adds while the program runs is no member the compiler knows: use the reference CreateControl gives, or Form1.Controls("name"). Storing another form in it (Set f = Form2, Set f = New Form2) does not compile when the compiler knows what is stored; a value it cannot know until the program runs (from a variable As Object or As Form) raises error 13 (Type mismatch) there when it is not a Form1. The same holds for a parameter declared As Form1, a FUNCTION’s result As Form1, and a Private or Public variable As Form1 of a form’s or a class’s code. Through a variable As Object or As Form, members are found by their names when the program runs: that variable can hold any form, and f.Show then shows whichever form it holds (and runs the Show of a class’s object, which has its own).
The code of the form serves every copy. In it, Me, the controls named on their own (Text1), and the form-level variables are those of the copy whose event is running, so each window keeps its own state. Unload f closes that copy only. The copy keeps its variables, and its next use (f.Show) loads that same copy again, with its Load event, as in Visual Basic. So does Me after Unload Me in the form’s own code: Unload Me then Me.Show in one handler closes the window and loads the form again. A copy’s variables are freed once it is not loaded and nothing refers to it any more, after its Terminate event; its Initialize event runs as New makes it.
The form’s name (Form1.Caption, Form1.Show, Load Form1) is Visual Basic’s predeclared form variable: it means the program’s own form of that name, unless SET gives it another one. Using the name when that form is not loaded (it was never used, or it was unloaded) loads it, with its Load event. Taking the form as an object does not load it, as in Visual Basic: Set f = Form1, TypeName(Form1), Form1 given for an object parameter (CreateControl’s too), and f Is Form1 make a reference to the form, which loads (with its Load event) at the first use of one of its properties, methods, or controls through it (f.Caption, f.Text1, f.Show). The reference keeps meaning the form: f Is Me in the form’s code is True, and after Unload Form1 a use of f loads the form again. Set Form1 = f, with a copy of Form1, makes the name mean that copy from then on, and Set Form1 = New Form1 a fresh copy. Set Form1 = Nothing lets go of the form the name held: a variable that still refers to it keeps it, with its variables, and one that is loaded stays loaded; the name’s next use makes a new Form1, with new variables, as in Visual Basic. CreateForm with the name of one of the program’s forms gives that form too (loaded, with its Load event, when it is not), and a form LoadFormText makes with such a name is a copy of its own.
The form’s variables are the program’s form’s whether it is loaded or not. They are made before any of the form’s code runs, as in Visual Basic: a fixed array sized, a TYPE variable given its record, a STRING * n filled with spaces, an object variable Nothing (a WithEvents one ready for its events), a Variant Empty, any other variable its type’s zero (VarType of a Long is vbLong before it is first set), so the form’s code outside procedures may use them before their DIM lines, and a DIM there does nothing when it runs. A procedure of Form1’s code that runs while Form1 is not loaded — one SetEvent made the handler of a control on another form, for example — has Form1’s variables, made then with their starting values, and Form1 has them when it loads. Unloading the form keeps them, as in Visual Basic: its next load runs its Load event with them as they were (their starting values are not set again), so a form can remember what it showed. Set Form1 = Nothing lets them go with the form: they are freed once nothing refers to it and it is not loaded, and the name’s next use starts them again. A copy New made has its own variables, kept while it is unloaded and freed once nothing refers to it.
A form’s SUBs and FUNCTIONs (those not declared PRIVATE) are its methods, as in Visual Basic: Form2.Refill, x = Form2.Twice(3), x = Form2.Total (a FUNCTION without arguments, read without parentheses), and the same through a variable (f.Refill), including Property Get and Property Let procedures (Form2.Title = "x"). Through a variable declared As Object (or As Form, or As the form’s name) the arguments go as they do to a class’s procedures (see Using Objects in the language reference): each is converted to its parameter’s type, a variable given for a parameter without BYVAL gets what the procedure stores in it, an OPTIONAL one left out takes its default, and arguments can be given by name (f.Refill count:=3). A SUB or FUNCTION of Form2’s code called by its name alone from elsewhere (Refill) runs for Form2 the same way. Each runs for that form: with its form-level variables, Me as that form, and its controls named alone. Calling one does not load the form, so a Property Let the program sets before Show is there for the form’s Load, Visual Basic’s way to hand a form its data.
Each form’s procedures are its own: two forms can each have a Refill (and a Command1_Click), and in a form’s code Refill means its own. By its name alone, from a module or another form, a procedure is found when only one form has a Public one of that name; when several have, the compiler asks for the form’s name (Form2.Refill). A PRIVATE SUB or FUNCTION belongs to its form’s code: other code cannot call it, by name or as Form2.Refill.
Controls are found the same way. In a form’s code a control named alone (Text1) is that form’s own, as in Visual Basic — for each copy of the form its own copy’s — whatever code called the procedure; a control CreateControl made while the program runs, which the .frm does not declare, is looked for on the form first and then as below. Code outside the forms (a module, a class) can name a control alone too, which Visual Basic cannot: it is the control of the one loaded form that has a control of that name, and when several loaded forms have one (two forms with a Text1, or two copies of one form) using the name raises error 1001 (Ambiguous control name) rather than picking one; write the form’s name there (Form2.Text1, f.Text1). A control named through a form is that form’s own only.
A variable the form’s code declares PUBLIC at the form’s level is a property of the form, as in Visual Basic: Form2.Count = 5, n = Form2.Count, Form2.Names(2) for an element of a Public array, the same through a variable (f.Count), and Me.Count in the form’s own code. It is the variable of that form’s instance, which the form’s code uses too: using it does not load the form, and the form has it when it loads. A value stored in it, or in an element of a Public array, is converted to its type, through the form’s name or any variable (an Integer Count set to 2.7 holds 3; a STRING * n variable keeps its length, cut or padded with spaces). The statements that write a variable — INPUT, LINE INPUT, READ, GET #, SWAP, LSET, RSET, and MID$ assignment — take it too (Read Form2.Count, LSet Form2.Code = "AB"), as they take any variable, and REDIM, REDIM PRESERVE, and ERASE take a Public array (ReDim Form2.Names(n), Erase Form2.Names). A Public variable declared As a class takes only an object of that class, or Nothing (error 13 otherwise, as for any variable of the class). It is a variable all the same: given for a parameter without BYVAL, Form2.Count (Form2.Names(2), f.Count, Me.Count) is the variable itself, which the procedure changes as it would any variable (see SUB...END SUB in the language reference). The form keeps that variable if it loads or unloads while the call runs, and a copy New made stays while a call has one of its variables. The fields of a Public TYPE variable are reached through the form as a variable’s are: Form2.Pos.X = 5, n = Form2.Pts(2).Y, With Form2.Pos, Form2.Pos = rec, and Bump Form2.Pos.X passes the field itself. Through a variable As the form’s name they are the form’s own; through one As Object that works when every form and class of the program with a Public member of that name declares it a variable of the same TYPE (see Using Objects in the language reference). The form’s other form-level variables (DIM, DIM SHARED, PRIVATE) are its own: other code and Me cannot use them, and the compiler says so. In the same way a form’s code sees a module’s PUBLIC variables, not the variables a module declares with DIM SHARED, DIM, or PRIVATE, which are that module’s own (see Variable Scope and SHARED in the language reference). An OPTION COMPARE in the form’s code holds in its code alone: its event procedures compare text as it says, whatever code runs them. Give them names other than those of the properties every form has (Caption, Width ...): with a DIM Width in Form2’s code, Form2.Width is that error rather than the form’s width. A Public variable or procedure named like such a property is used in place of it.
' In Form2's code
Public Count As Integer
Public Pos As PointType ' a TYPE of the program's
Private Sub Refill
Count = 0
End Sub
' Elsewhere
Form2.Count = Form2.Count + 1 ' Form2 is not loaded for this
Form2.Pos.X = 10 ' a field of its Public TYPE variable
Bump Form2.Count ' Bump(n As Integer) changes Form2.Count
Form2.Show ' its Load sees Count and Pos as they are
2.1.6. Designing Forms
A form designer written in BASIC shows the form being designed as a real form and turns on its design mode. While DesignMode is True, the controls on the form take no mouse clicks or keys and fire no events (Timers too are quiet); the form instead tells the designer what the user does (a form whose Enabled is False takes this input too, so a form that starts disabled can be designed):
-
DesignMouse (Action, Button, X, Y, CtrlName, Handle): Action is DSGN_MOUSE_DOWN (1, a button was pressed), DSGN_MOUSE_MOVE (2), DSGN_MOUSE_UP (3), or DSGN_MOUSE_DBLCLICK (4, a double click: open the code, say). Button is the button pressed or released (1 left, 2 right, 4 middle; for a move, the buttons held). X and Y are where, in the form. CtrlName is the control there — the innermost one when containers hold others — or "" for the form itself. Handle is the selection handle of the selected control under the mouse: DSGN_HANDLE_E (3, the right edge: drag to change the width), DSGN_HANDLE_SE (4, the corner), or DSGN_HANDLE_S (5, the bottom edge), or DSGN_HANDLE_NONE (-1).
-
DesignKey (KeyCode, Shift): a key, for Delete, the arrow keys, and so on.
-
DesignPropertyChanged (CtrlName, PropertyName): the code of a UserControl on the form — one of the project’s own, put on the designer’s toolbox with CompDesignControls (compiler.bas) — called UserControl.PropertyChanged PropertyName: read its properties again. Such controls run their code on the form with UserControl.UserMode False.
DesignSelection names the selected control; the form draws its eight selection handles over the controls (the three that resize in black) and shows the resize mouse pointers over them. The constants are in designer.bas, which also lists the control types, their properties, and events (see Include Libraries in the language reference). Together with CreateControl, RemoveControl, CallByName, Controls, Container, MoveBefore, LoadFormText, and the .frm model of designer.bas (FrmOpen, FrmText$, FrmCtlText$ / FrmCtlPaste to copy and paste controls, FormText$ to write the live form as .frm text), a designer has what the DVX BASIC IDE’s own designer uses.
Sub Canvas_DesignMouse(Action As Integer, Button As Integer, _
X As Integer, Y As Integer, _
CtrlName As String, Handle As Integer)
If Action = DSGN_MOUSE_DOWN Then
If Handle <> DSGN_HANDLE_NONE Then
resizing = True ' drag the selected control's size
Else
Canvas.DesignSelection = CtrlName
ShowProperties CtrlName
End If
ElseIf Action = DSGN_MOUSE_UP Then
resizing = False
End If
End Sub
2.1.7. Drawing
Forms have Visual Basic’s drawing methods and properties (Cls, PSet, Line, Circle, Point, Print, PaintPicture, DrawFocusRect, DrawBevel, DrawButtonFace, DrawArrow, DrawScrollBar, DrawScrollArrow, ScrollBarClick, ScrollBarsNeeded, PrintAccel, Scale, CurrentX, CurrentY, ForeColor, BackColor, DrawWidth, DrawStyle, FillColor, FillStyle, FontScale, AutoRedraw, ScaleMode, ScaleLeft, ScaleTop, ScaleWidth, ScaleHeight): see Drawing on Forms and PictureBoxes. In the form’s own code they need no Me, as in Visual Basic: Cls, Line (0, 0)-(99, 99), Circle (50, 50), 20, PSet (1, 1), Scale (0, 0)-(100, 100), Point(x, y), and BackColor = vbBlue are the form’s own. Print is the exception: PRINT alone stays the PRINT statement (the Output window), so write Me.Print to print on the form.
2.1.8. Example
Sub Form1_Load ()
Form1.Caption = "Hello World"
Print "Form loaded!"
End Sub
Sub Form1_QueryUnload (Cancel As Integer, UnloadMode As Integer)
If UnloadMode = vbFormControlMenu Then
If MsgBox("Really quit?", 4) <> 6 Then
Cancel = 1
End If
End If
End Sub
Sub Form1_Resize ()
Print "Window resized"
End Sub
See also: Drawing on Forms and PictureBoxes (Section 2.3); FRM File Format (Section 2.7).
2.2. Common Properties, Events, and Methods
Every control in DVX BASIC inherits a set of common properties, events, and methods. These are handled by the form runtime before dispatching to widget-specific interface descriptors.
2.2.1. Common Properties
- Name
-
Type: String; R/W: R. The control’s name (e.g. "Command1"). Read-only at runtime.
- Index
-
Type: Integer; R/W: R. The control’s index in its control array (see Control Arrays). Set in the .frm file only; reading it on a control in no array raises error 343 (Object not an array), as in Visual Basic.
- Left
-
Type: Integer; R/W: R/W. X position in pixels relative to the parent container.
- Top
-
Type: Integer; R/W: R/W. Y position in pixels relative to the parent container.
- Width
-
Type: Integer; R/W: R/W. Current width in pixels. Setting this changes the minimum width constraint. A value below 0 raises error 380 (Invalid property value), as in Visual Basic, and the size stays.
- Height
-
Type: Integer; R/W: R/W. Current height in pixels. Setting this changes the minimum height constraint. A value below 0 raises error 380.
- MinWidth
-
Type: Integer; R/W: R/W. Minimum width for layout. Setting it works like setting Width; reading it returns the minimum that was set.
- MinHeight
-
Type: Integer; R/W: R/W. Minimum height for layout. Setting it works like setting Height; reading it returns the minimum that was set.
- MaxWidth
-
Type: Integer; R/W: R/W. Maximum width cap (0 = no limit, stretch to fill). It wins over MinWidth and over the width the control’s contents ask for.
- MaxHeight
-
Type: Integer; R/W: R/W. Maximum height cap (0 = no limit, stretch to fill). It wins over MinHeight and over the height the control’s contents ask for. MinWidth, MinHeight, MaxWidth, and MaxHeight raise error 380 for a value below 0, as Width and Height do. Each of them (and a container’s Padding and Spacing) also takes a percentage of the container or a number of characters: SizePercent(n) and SizeChars(n) in code, "50%" and "20ch" in the .frm file and the Properties window (see Sizes in a .frm below).
- Weight
-
Type: Integer; R/W: R/W. Layout weight. 0 = fixed size, >0 = share extra space proportionally. A TextBox or ComboBox (one line high) takes no share of a column’s extra height, only of a row’s extra width.
- Visible
-
Type: Boolean; R/W: R/W. Whether the control is visible.
- Enabled
-
Type: Boolean; R/W: R/W. Whether the control accepts user input. Disabling a container (Frame, VBox, HBox...) also blocks mouse and keyboard input to every control inside it, and those controls are drawn disabled (grayed); enabling it draws them normally again, unless one is disabled itself. Their own Enabled stays True. This differs from Visual Basic 6, where controls in a disabled Frame keep their normal look; DVX follows Windows Forms.
- BackColor
-
Type: Long; R/W: R/W. Background color as a 24-bit RGB value packed in a Long (use the RGB function to construct; 0 is black). Until it is set the control has its usual color, and BackColor reads that color, as in Visual Basic: for a control with no face of its own (Label, CheckBox, OptionButton, Slider, Image, and a Frame’s, HBox’s, or VBox’s inside) the color of what it sits on — its container’s BackColor, else the form’s (see the Form topic). A Frame, HBox, or VBox given one fills its inside with it, and so do the controls in it that have no face of their own.
- ForeColor
-
Type: Long; R/W: R/W. Foreground (text) color as a 24-bit RGB value packed in a Long (use the RGB function to construct; 0 is black). Until it is set it reads the theme’s text color.
- FontName
-
Type: String; R/W: R/W. The family of the font the control draws its text in, such as "DejaVu Sans" ("System" is DVX’s own 8 x 16 font). A family DVX does not have gives the System font. See Fonts below.
- FontSize
-
Type: Integer; R/W: R/W. The size of the font in pixels. A size the family does not come in becomes the nearest one it has; one below 1 raises error 380, as in Visual Basic.
- FontBold
-
Type: Boolean; R/W: R/W. True for the bold style of the font.
- FontItalic
-
Type: Boolean; R/W: R/W. True for the italic style of the font.
- FontUnderline
-
Type: Boolean; R/W: R/W. True to underline the text.
- FontStrikethru
-
Type: Boolean; R/W: R/W. True to draw a line through the text.
- TabIndex
-
Type: Integer; R/W: R. Accepted for VB compatibility but ignored. DVX has no tab order.
- ToolTipText
-
Type: String; R/W: R/W. Tooltip text shown after the mouse hovers over the control. Empty string or unset = no tooltip.
- HelpTopic
-
Type: String; R/W: R/W. Help topic opened by F1 while the control has the focus. Empty = the form’s HelpTopic. F1 uses the project’s help file.
- DragMode
-
Type: Integer; R/W: R/W. vbManual (0, the default): the program starts a drag with the Drag method. vbAutomatic (1): pressing the left mouse button on the control starts a drag. See Drag and Drop below.
- DragIcon
-
Type: Picture; R/W: R/W. Picture shown under the mouse while the control is dragged: a picture file name (BMP, PNG, JPEG, or GIF) or a Picture object from LOADPICTURE or LOADPICTUREDATA (Set works too). Reading it gives a Picture object, which stands for the file name where a value is needed. Empty = a dotted outline the size of the control.
- Parent
-
Type: Form; R/W: R. The form the control is on (Text1.Parent.Caption).
- Tag
-
Type: String; R/W: R/W. Any text the program wants to keep with the control (DVX does nothing with it), as in Visual Basic. Also in the .frm file.
- MousePointer
-
Type: Integer; R/W: R/W. The mouse pointer shown over the control (and the controls inside it that have none of their own): vbDefault (0, the control’s own pointer), vbArrow (1), vbCrosshair (2), vbSizeNESW (6), vbSizeNS (7), vbSizeNWSE (8), vbSizeWE (9), vbHourglass (11), or vbNoDrop (12). A form’s MousePointer is used where no control has one, and Screen.MousePointer over every form of the program. Change it in MouseMove to show different pointers over parts of a control. Also in the .frm file; another value is an error.
- Container
-
Type: Object; R/W: R/W. The container control the control is in (a Frame, VBox, TabPage ...), or its form. Set Text1.Container = Frame1 moves the control into Frame1, after the controls there; Set Text1.Container = Me moves it onto the form itself. The new container must be a container control on the same form, not the control itself or one inside it.
Size properties (Width, Height, and the Min/Max sizes) are limited to 0..32767.
Text given to a property that takes a number or a Boolean is converted as Visual Basic converts it, the same rules as CDBL and CBOOL (see Numbers in Text in the Language Reference): Text1.Width = "120" and Text1.Width = "1,200" set a number, Check1.Value = "True" and Text1.Visible = "0" a Boolean ("True" or "False" in any letter case, or a number). Text that is neither, an empty string included, raises error 13 (Type mismatch) and the property keeps its value; so does such text given to a method’s numeric or Boolean argument (List1.RemoveItem "first"). Convert text you are not sure of first: Text1.Width = VAL(widthText$) takes 0 for text with no number. A property that takes one of its names (a Label’s Alignment) takes the name or a number, the number’s text too.
2.2.2. Indexed Properties
A property with an index, as in Visual Basic, is read with the index in parentheses and set with an assignment: a ListBox’s, ComboBox’s, or DropDown’s List(i) (the text of item i) and ItemData(i) (a number the program keeps with item i), and a ListBox’s or ListView’s Selected(i) (whether item i is selected). An index there is no item for raises error 381 (Invalid property array index), as reading ItemData(List1.ListIndex) does with nothing selected, and one used without its index error 450. A UserControl’s property with arguments (Property Get Item(i) and Property Let Item(i, v) in its code) is used the same way: Gauge1.Item(2) = "two" runs its Property Let, and Gauge1.Item(2) its Property Get; more or fewer arguments than its procedures take raise error 450 or 449.
List1.AddItem "Widget"
List1.ItemData(List1.NewIndex) = 1042 ' the part number of the item just added
List1.List(0) = "Widget (blue)" ' a new text; its ItemData stays
partNo = List1.ItemData(List1.ListIndex)
List1.Selected(0) = True ' adds item 0 to a MultiSelect selection
2.2.3. Fonts
The six Font properties are one font. A control that has not been given one draws in the font of the control it is in (a Frame, for example), or else in its form’s; the properties read the font the control draws with. Setting one of them gives the control a font of its own with that one part changed, keeping the others: Label1.FontBold = True makes the label’s text bold in whatever family and size it had. Controls that edit text in columns (TextBox, TextArea, ComboBox, SpinButton, and Terminal) take only fixed-pitch families, such as "DejaVu Sans Mono", and show the System font in place of any other. The fonts DVX has, and the sizes each comes in, are listed by font.bas; DlgFont in commdlg.bas lets the user choose one. In the form designer the Font row of the Properties window sets all six, and they are saved in the .frm file.
2.2.4. Default Properties
As in Visual Basic, a control’s name used where a value is needed means its default property: Text1 = "hi" sets Text1.Text, Print Label1 prints Label1.Caption, and If Check1 Then reads Check1.Value. So does a control given without SET — to a Variant or any other variable, another control’s property, or an object’s member: v = Text1 stores Text1’s text, Label1.Caption = Text1 and Text2 = Text1 copy it, and with o holding Text2 (Set o = Text2), o = Text1 does too. Where an object is expected — SET, Is, an object parameter, Collection.Add, TypeOf — the name still means the control itself (Set v = Text1 keeps the control in v).
A control’s type is an object type, as in Visual Basic: a variable or parameter declared As TextBox, As Label, As ListBox (any of the types a .frm names its controls by, a UserControl of the program’s too) holds a control of that type, As Control any control or menu item: Dim t As TextBox, Set t = Text1, t.Text = "hi", Sub Clear(ByVal box As TextBox). Another control there raises error 13 (Type mismatch), and the members are found by name when the program runs, as for As Control. See Control Types in the language reference.
| Control | Default property |
|---|---|
TextBox, TextArea, ComboBox, DropDown, ListBox, DBGrid |
Text |
Label, Frame, Data |
Caption |
CheckBox, OptionButton, CommandButton |
Value |
HScrollBar, SpinButton, ProgressBar |
Value |
Image, ImageButton, PictureBox |
Picture |
Timer |
Enabled |
Other controls, forms, and menu items have no default property: using one as a value, or giving one without SET where a value is stored, raises error 438 (Object doesn’t support this property or method), as in Visual Basic. An object of one of the program’s classes given to a control’s property or method has its default value too, also when that is a Property Get or a Function (Text1.Text = acct sets acct’s default value; List1.AddItem acct adds it).
2.2.5. Errors in Code That Uses Controls
As in Visual Basic, a mistake in code that uses a control, a form, a menu, the Printer, the Screen, or the Clipboard raises an error ON ERROR can trap, its details (the control, the property, what was wrong) in Err.Description; one no handler traps ends the program with the BASIC Runtime Error box. A property or method the object does not have raises error 438 (Object doesn’t support this property or method); a property that can only be read error 383 (Property is read-only), Name, Index, and a form’s Layout, which only the .frm sets, error 382 (Property cannot be set at run time); a value the property cannot take error 380 (Invalid property value), as Visual Basic’s controls refuse it, and the property keeps its value — a Width or Height below 0 (of a control or a form; Left and Top may be below 0), a ListIndex below -1 or past the list, a ListBox’s, ComboBox’s, or DropDown’s TopIndex outside the list, a Value outside Min to Max (a scroll bar, a SpinButton, a ProgressBar), a SelStart, SelLength, MaxLength, or Interval below 0, a TabStrip’s TabIndex past its tabs, a number a named property (an Alignment, a MultiSelect) has no name for, a DragMode other than 0 or 1 —, Null error 94, an array error 13, and text that is not a number given to a numeric or Boolean property error 13 (Type mismatch); an index there is no item for given to an indexed property (ItemData(i), List(i) = text) or to a method that reads or changes that item (a TreeView’s GetItemText or SetItemText, a ListView’s GetCell or IsItemSelected, or a TabStrip’s SetActive) error 381 (Invalid property array index); a bad argument to a method error 5 (Illegal function call), such as an index past the list given to AddItem or RemoveItem, one left out error 449, too many error 450 (a method that takes its arguments as they come, such as a SpinButton’s SetRealRange or a UserControl’s own, too); and a control that RemoveControl removed, or one of a form that is gone, used through a reference to it error 364 (Object was unloaded). The Language Reference lists every error number. What is wrong in a .frm file itself (a control type DVX does not have, a value its property cannot take) is reported as the form loads, and ends the program.
2.2.6. Common Events
These events are wired on every control, whether it is loaded from a .frm file or created at runtime with CreateControl (whose handlers SetEvent names). A variable declared WithEvents As the control’s type that holds it gets every event of the control too, after the control’s own handler (Dim WithEvents t As TextBox, Sub t_Change: see Events in the Language Reference).
- Click
-
Parameters: (none). Fires when the control is clicked: in Visual Basic’s order, MouseDown at the press, then MouseUp and Click at the release, Click only when the button is released over the control (pressed on a Label and released elsewhere, the Label gets its MouseUp and no Click). On a ListBox, ListView, TreeView, ComboBox, or DropDown it is the user’s pick of an item, as in Visual Basic, after Change when the pick changed the selection (a ComboBox’s pick raises no Change): a click on an item, even the one already selected (between MouseDown and MouseUp), a selection moved with the keys (not on a TreeView, whose Click is the mouse’s), or an item chosen from a ComboBox’s or DropDown’s list with the mouse or the keys. A click below the last item of a ListView or TreeView raises Click alone; a click on a scroll bar, a ListView’s column header, a ComboBox’s text or arrow, or the closed box of a DropDown raises no Click there. It also fires, after Change, when the program’s code changes a CheckBox’s Value, sets an OptionButton’s Value to True (it was not selected), changes the selected item of a ListBox, DropDown, or ListView (its ListIndex, or a ListBox’s Text), or changes a TabStrip’s tab (TabIndex), and alone when it changes a ComboBox’s ListIndex; and setting a CommandButton’s Value to True clicks the button (Click fires every time, except while the button or its container is disabled or hidden), as in Visual Basic.
- DblClick
-
Parameters: (none). Fires when the control is double-clicked (not on its scroll bars or a list’s column headers, as in Visual Basic), at the second press: MouseDown, MouseUp, Click, DblClick, MouseUp, as in Visual Basic (the second press raises no MouseDown, except on a CommandButton, CheckBox, OptionButton, or list).
- Change
-
Parameters: (none). Fires when the control’s value or text changes: by the user, or when the program’s code changes it, as in Visual Basic: a TextBox’s, TextArea’s, ComboBox’s, or RichEdit’s Text (also through its default property, Text1 = "x"), a RichEdit’s TextRTF, a CheckBox’s or OptionButton’s Value, an HScrollBar’s or SpinButton’s Value (or RealValue), a Label’s Caption, a PictureBox’s Picture, the selected item of a ListBox, DropDown, or ListView (its ListIndex, or a ListBox’s Text), or a TabStrip’s tab (TabIndex). A ComboBox’s pick from its list, by the user or by setting its ListIndex, raises Click and no Change, as in Visual Basic. Setting the value it already has fires nothing, and so does what a form’s .frm sets as the form loads. A program that changes a value in an event of its own (a timer that moves a slider, say) and does not want its Change to act on that keeps a flag, as a Visual Basic program does: set it before the change, and have Change do nothing while it is set.
- GotFocus
-
Parameters: (none). Fires when the control receives keyboard focus.
- LostFocus
-
Parameters: (none). Fires when the control loses keyboard focus.
- KeyPress
-
Parameters: KeyAscii As Integer. Fires when a key that is a character is pressed, after KeyDown and before the control acts on the key: a printable key, Enter (13), Backspace (8), Esc (27), a Ctrl+letter (Ctrl+A to Ctrl+Z are 1 to 26), and Tab (9) when no other control on the form can take the focus, as in Visual Basic. KeyAscii is the ASCII code; set it to another code to change the character the control gets, or to 0 to cancel the key.
- KeyDown
-
Parameters: KeyCode As Integer, Shift As Integer. Fires when any key is pressed down, before KeyPress and before the control acts on the key. KeyCode is the key (vbKeyDelete, vbKeyReturn, ... or a character’s code; Ctrl+A to Ctrl+Z are 1 to 26); Shift holds vbShiftMask, vbCtrlMask, and vbAltMask bits (see Key Code Constants in the language reference). Set KeyCode to 0 to cancel the key: no KeyPress follows, and the control does nothing with it.
- KeyUp
-
Parameters: KeyCode As Integer, Shift As Integer. Fires when a key is released.
- MouseDown
-
Parameters: Button As Integer, Shift As Integer, X As Single, Y As Single. Fires when a mouse button is pressed over the control — not on its scroll bars or a list’s column headers, as in Visual Basic. Button is vbLeftButton, vbRightButton, or vbMiddleButton; Shift holds the vbShiftMask, vbCtrlMask, and vbAltMask bits of the keys held; X and Y are where (see Mouse Coordinates below).
- MouseUp
-
Parameters: Button As Integer, Shift As Integer, X As Single, Y As Single. Fires when a mouse button is released (not for a press on its scroll bars or column headers): the left button’s release goes to the control it was pressed on, wherever the mouse is, as in Visual Basic, before its Click.
- MouseMove
-
Parameters: Button As Integer, Shift As Integer, X As Single, Y As Single. Fires when the mouse moves over the control (Button: the buttons held); none while a button pressed on a scroll bar or a column header is held.
- Scroll
-
Parameters: Delta As Integer. Fires when the control is scrolled (mouse wheel or scrollbar).
- DragDrop
-
Parameters: Source As Control, X As Single, Y As Single. Fires when a dragged control is dropped on this control. Source is the dragged control; X and Y are where, as a mouse event’s (see Mouse Coordinates below).
- DragOver
-
Parameters: Source As Control, X As Single, Y As Single, State As Integer. Fires while a dragged control moves over this control. State is vbEnter (0) when it comes onto the control, vbOver (2) as it moves across, vbLeave (1) when it goes off.
As in Visual Basic, a key gives KeyDown, then KeyPress (for a key that is a character), and only then does the control act on it: a TextBox types the character, a CheckBox is toggled, a list moves its selection. So the handlers still see the control as it was before the key, and they can change the key or cancel it: KeyCode and KeyAscii are passed by reference, and the control gets what the handler leaves in them. 0 cancels the key. A handler that declares the parameter ByVal (Sub Text1_KeyPress(ByVal KeyAscii As Integer)) gets the value only: what it leaves there is not passed back, as in Visual Basic, and the same goes for any event’s parameters, such as a ByVal Cancel in QueryUnload. A program that is busy running code gets the keys for controls whose KeyDown or KeyPress it handles when it is done (or at DoEvents), as a Visual Basic program does; keys for other controls are acted on at once.
Sub Text1_KeyPress(KeyAscii As Integer)
' Capitals only, and no spaces
If KeyAscii = vbKeySpace Then KeyAscii = 0
KeyAscii = Asc(UCase$(Chr$(KeyAscii)))
End Sub
Mouse Coordinates
MouseDown, MouseUp, MouseMove, DragDrop, and DragOver give X and Y as Visual Basic does, Singles in the units of the scale that applies: a form or a PictureBox in its own scale (its ScaleMode, or the scale Scale set, ScaleLeft and ScaleTop included), any other control in the units of its container’s ScaleMode, the nearest PictureBox it sits in or else its form, measured from the control’s own top-left corner. In DVX’s default scale, pixels, they are whole pixels. A UserControl’s own MouseDown, MouseUp, and MouseMove are in its UserControl’s scale. Shift is the Shift, Ctrl, and Alt keys held when the event happened (vbShiftMask 1, vbCtrlMask 2, vbAltMask 4, added up).
Sub Picture1_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
' Draw while the left button is down; with Shift, in red
If Button And vbLeftButton Then
If Shift And vbShiftMask Then Picture1.ForeColor = vbRed
Picture1.PSet (X, Y)
End If
End Sub
2.2.7. Common Methods
| Method | Parameters | Description |
|---|---|---|
SetFocus |
(none) |
Gives keyboard focus to this control. |
Refresh |
(none) |
Forces the control to repaint. |
Drag |
[Action] |
Starts or ends dragging this control: vbBeginDrag (1, the default) starts, vbEndDrag (2) drops it where the mouse is, 0 cancels the drag without a drop. |
MoveBefore |
[Control] |
Moves the control just before another control (into that control’s container when it is in another one), or with none to the end of its own container. The layout places controls in this order, and Controls lists them in it. |
ScrollToControl |
Control |
Of a ScrollPane: scrolls so that a control inside it (the control, or its name as a string) is in view, also one that cannot take the focus (a Label). On another control, or with a control that is not inside it, it is an error. |
2.2.8. Drag and Drop
Any control can be dragged onto another control or onto a form, as in Visual Basic. While a control is dragged, a dotted outline of it (or its DragIcon picture) follows the mouse, and the controls and forms it passes over get DragOver events. Releasing the mouse button drops it: the control or form under the mouse gets a DragDrop event, with the dragged control as Source. Pressing Esc cancels the drag.
The mouse pointer shows where a drop can land: over a control or form that has a DragDrop event procedure it is the usual arrow; over one without, and outside the program’s forms, it is the "no drop" sign (a circle with a line through it). The outline or DragIcon picture still follows the mouse either way.
With DragMode set to vbAutomatic, pressing the left mouse button on the control starts the drag, and the control gets no Click, MouseDown, or MouseUp from the left button. With DragMode vbManual, start the drag yourself, usually in MouseDown. A drag started while the mouse button is up ends at the next click. During a drag no mouse events other than DragOver and DragDrop are raised.
Drop targets only react: nothing is moved or copied for you. Use Source in DragDrop to decide what to do, for example read its Name or Caption, or check what kind of control it is with TypeOf Source Is TextBox (see Operators).
Note that vbCancel is the MsgBox Cancel value (2), which as a Drag action means vbEndDrag; cancel a drag with Drag 0.
DragIcon takes a file name or a picture loaded with LOADPICTURE or LOADPICTUREDATA: Set Label1.DragIcon = LoadPicture("drag.bmp"). A missing file or one that is not a picture raises its error at LOADPICTURE; a file name that cannot be read when the drag starts shows the outline instead.
' Label1 has DragMode = 1 (vbAutomatic) in the form designer.
Sub List1_DragOver(Source As Control, X As Single, Y As Single, State As Integer)
If State = vbEnter Then Label2.Caption = "Drop to add " & Source.Caption
End Sub
Sub List1_DragDrop(Source As Control, X As Single, Y As Single)
List1.AddItem Source.Caption
End Sub
' DragMode vbManual: the button starts its own drag, left button only.
Sub Command1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
If Button = 1 Then Command1.Drag vbBeginDrag
End Sub
See also: Form (Section 2.1); Data Binding (Section 2.4); FRM File Format (Section 2.7).
2.3. Drawing on Forms and PictureBoxes
Forms and PictureBoxes have Visual Basic’s drawing methods. They draw with the same code as the QBasic graphics statements (see Console and Graphics in the language reference), in pixels unless ScaleMode or Scale says otherwise, with colors as Visual Basic RGB values, &HBBGGRR (RGB(255, 0, 0) or &HFF is red). A PictureBox draws on its picture. A form draws on its background, behind its controls, as in Visual Basic: the drawing covers the whole inside of the window, follows its size as it changes (keeping what was drawn; the part the window grew by is BackColor), and starts in the form’s BackColor. The controls show over it and keep their places (drawing adds no scroll bars), and a press on the drawing is the form’s own (its MouseDown’s X and Y are where PSet would put the point).
Drawings stay until they are drawn over or cleared. In a form’s own code the form’s drawing methods and properties need no object, as in Visual Basic: Cls, Line, Circle, PSet, Scale, Point, TextWidth, ScaleWidth, and the rest are the form’s own (Line and Me.Line are the same there). Print without an object is the exception: it stays the PRINT statement, so write Me.Print to print on the form. In a module’s code Line, Circle, PSet, and Cls without an object are the QBasic graphics statements (they draw on the program’s screen).
Through a variable As Object (or As Form for a form, As Control or As PictureBox for a PictureBox) the drawing methods work on whatever form, PictureBox, or Printer it holds: o.Line (0, 0)-(10, 10), o.Circle (5, 5), 3, o.PSet Step(1, 1), and o.Print "Hi"; are their drawing statements, as in Visual Basic. A class can have Public procedures of these names too; on an object of a class the statement is a call of the class’s own procedure, with comma-separated arguments (o.Line 1, 2, 3). Through As Object the way the arguments are written tells which is meant: after Line, Circle, PSet, or Scale, arguments that start with Step or with a point in parentheses (for Line also -(x, y)), or no arguments at all, are the drawing statement; any other arguments are a call of the object’s own method (write Call o.Line((a + b), c) for a call whose first argument is in parentheses). Print through As Object is always the drawing statement. A drawing statement that reaches an object of a class calls its procedure of that name with the values the statement packs (a class without one raises error 438), so give such an object comma-separated arguments.
2.3.1. Drawing Methods
| Method | Description |
|---|---|
Cls |
Clears the drawing to BackColor; CurrentX and CurrentY go to 0. |
PSet [Step](x, y) [, color] |
Draws a point (DrawWidth wide). |
Line [[Step](x1, y1)]-[Step](x2, y2) [, color] [, B | BF] |
Draws a line, a box (B), or a filled box (BF). A box without F is filled with FillColor when FillStyle is 0. |
Circle [Step](x, y), radius [, color [, start [, end [, aspect]]]] |
Draws a circle, ellipse, or arc, filled with FillColor when FillStyle is 0 (full circles). |
DrawFocusRect x, y, width, height [, color] |
Draws the dotted rectangle DVX shows around the control that has the keyboard focus (every other pixel of its edge), for things a program draws itself, such as the focused link of a help topic. A negative width or height counts from the other edge. |
Point(x, y) |
The color of a pixel, -1 outside the picture. With fewer than 16 million colors on the screen it is the color the screen shows: black, white, and full colors such as RGB(255, 0, 0) read back exactly, others may differ slightly. |
Print items |
Writes text at CurrentX, CurrentY in ForeColor, in the object’s font FontScale times as large, with PRINT’s separators (; and ,), SPC, and TAB (counted in the font’s character width); ends by moving to the next line unless the last item is followed by ; or ,. An array or a TYPE record raises error 13 (Type mismatch), which ON ERROR can trap, as PRINT’s does. |
PaintPicture picture, x, y [, width, height [, srcX, srcY, srcWidth, srcHeight [, opcode]]] |
Copies a picture, stretched to width x height: an image file (BMP, PNG, JPEG, or GIF), a picture from LOADPICTURE, or a PictureBox given by its name as a string or by a Control variable. opcode combines each pixel with the one already there (see Raster Operations). |
Scale [(x1, y1)-(x2, y2)] |
Gives the drawing coordinates of its own: (x1, y1) is the top-left corner and (x2, y2) the bottom-right one (y2 below y1 makes y go up). Scale alone goes back to pixels. |
ScaleX(width [, fromScale [, toScale]]) |
A width in fromScale converted to toScale (see Scales). |
ScaleY(height [, fromScale [, toScale]]) |
A height in fromScale converted to toScale. |
TextWidth(text) |
Width of the text in the object’s font, in the scale’s units, at the FontScale size. |
TextHeight(text) |
Height of a line of text in the object’s font, in the scale’s units, at the FontScale size. |
2.3.2. Drawing the DVX Look
These methods draw the parts DVX’s own controls are made of, in the colors of the current theme, for controls a program draws itself (a PictureBox that acts as a list or a toolbar). Coordinates and lengths are in the scale’s units; colors are RGB values.
- DrawBevel x, y, width, height [, sunken [, face [, border]]]
-
A raised box like a window or button edge, or with sunken True a sunken one like a text box’s. face is the fill color (the theme’s face color when left out; -1 leaves the inside as it is, to frame what is already drawn); border is the edge width in pixels (2).
- DrawButtonFace x, y, width, height [, pressed [, face]]
-
A button face, up or with pressed True pushed down.
- DrawArrow x, y, size, direction [, color]
-
A solid triangle centered on x, y, size pixel rows tall, pointing dvxArrowUp (0), dvxArrowDown (1), dvxArrowLeft (2), or dvxArrowRight (3), in ForeColor unless a color is given.
- DrawScrollBar x, y, length, position, visible, total [, horizontal [, control]]
-
A scroll bar with its arrows and its thumb, for a list of total rows of which visible are shown from row position, with its top-left corner at x, y. It stands upright (16 pixels wide, length tall, arrows at the top and bottom) unless horizontal is True: then it lies across (length wide, 16 pixels tall, arrows at the left and right ends). With control True it is the narrower bar of a control such as ListBox (14 pixels).
- DrawScrollArrow x, y, size, direction
-
One arrow button of a scroll bar, as at the ends of DrawScrollBar’s bars: a square button size wide and tall (size in the scale’s horizontal units) with its top-left corner at x, y and an arrow pointing dvxArrowUp, dvxArrowDown, dvxArrowLeft, or dvxArrowRight, in the theme’s scroll bar colors.
- ScrollBarClick(length, offset, position, visible, total [, horizontal [, control]])
-
The new position after a click on a scroll bar DrawScrollBar drew with the same length, rows, direction, and kind: offset is how far the click is from the top of the bar, or from its left end when horizontal is True. The arrows move one row, the trough a page, the thumb leaves it as it is. Needs no drawing. As on every scroll bar, holding the left button down on an arrow or the trough of a bar DrawScrollBar drew repeats the MouseDown event: once after a fifth of a second, then twenty times a second, each time once the program has drawn the bar again (in MouseDown, or in Paint after Refresh), while the pointer stays on the object, until the button is let go or, in the trough, the thumb reaches the pointer.
- ScrollBarsNeeded(contentWidth, contentHeight, areaWidth, areaHeight)
-
Which scroll bars content that big needs in an area that big, as DVX’s controls decide it: vbSBNone (0), vbHorizontal (1), vbVertical (2), or vbBoth (3). A vertical bar narrows the area and may make a horizontal one needed, and the other way round. The sizes are in the object’s scale. Needs no drawing.
- PrintAccel text [, enabled]
-
Prints a caption in the object’s font at CurrentX, CurrentY with the letter after & underlined (&& prints one &); enabled False gives the grayed, embossed look of a disabled control. CurrentX moves past the text.
- TextWidthAccel(text)
-
Width of a caption without its & signs in the object’s font, in the scale’s units.
- AccelKey(text)
-
The access key of a caption in lower case ("f" for "&File"), "" when it has none.
Sub Picture1_Paint()
Picture1.DrawBevel 0, 0, Picture1.ScaleWidth, Picture1.ScaleHeight, True, vbWhite
Picture1.DrawButtonFace 4, 4, 60, 20, pressed
Picture1.CurrentX = 10: Picture1.CurrentY = 8
Picture1.PrintAccel "&Go", Picture1.Enabled
Picture1.DrawScrollBar Picture1.ScaleWidth - 18, 2, _
Picture1.ScaleHeight - 22, topRow, 8, 40
Picture1.DrawScrollBar 2, Picture1.ScaleHeight - 18, _
Picture1.ScaleWidth - 22, leftCol, 10, 60, True
End Sub
Sub Picture1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
' A click on the bar along the bottom scrolls sideways
If Y >= Picture1.ScaleHeight - 18 And X < Picture1.ScaleWidth - 20 Then
leftCol = Picture1.ScrollBarClick(Picture1.ScaleWidth - 22, X - 2, _
leftCol, 10, 60, True)
Picture1.Refresh
End If
End Sub
Without a color, drawing uses ForeColor. Step makes a point relative to CurrentX, CurrentY, which every drawing method leaves at its last point. Coordinates, radii, CurrentX and CurrentY, and PaintPicture’s rectangles are in the scale’s units (a radius in its horizontal units); DrawWidth is always in pixels. An argument out of range — a color, an angle past 2 pi, a Scale whose two corners are on one line — raises error 5 (Illegal function call), PaintPicture without a picture, x, and y error 449 (Argument not optional) and with something that is no picture error 481 (Invalid picture), on a form, a PictureBox, and the Printer alike: ON ERROR traps each, as in Visual Basic, and Err.Description says what was wrong.
2.3.3. Raster Operations
PaintPicture’s opcode says how each copied pixel is combined with the pixel already there (the destination) and with the FillColor (the pattern), as in Visual Basic. Leaving it out copies the picture (vbSrcCopy).
| Constant | Value | Result |
|---|---|---|
vbSrcCopy |
&HCC0020 |
The picture |
vbSrcPaint |
&HEE0086 |
Picture OR destination |
vbSrcAnd |
&H8800C6 |
Picture AND destination |
vbSrcInvert |
&H660046 |
Picture XOR destination |
vbSrcErase |
&H440328 |
Picture AND NOT destination |
vbNotSrcCopy |
&H330008 |
NOT picture |
vbNotSrcErase |
&H1100A6 |
NOT (picture OR destination) |
vbMergeCopy |
&HC000CA |
Picture AND pattern |
vbMergePaint |
&HBB0226 |
NOT picture OR destination |
vbPatCopy |
&HF00021 |
The pattern |
vbPatPaint |
&HFB0A09 |
Pattern OR NOT picture OR destination |
vbPatInvert |
&H5A0049 |
Pattern XOR destination |
vbDstInvert |
&H550009 |
NOT destination |
vbGrayCopy |
&H1000000 |
The picture grayed, as DVX shows a disabled picture (DVX only) |
vbTransparentCopy |
&H2000000 |
Every pixel of the picture but the key color: a color given after the opcode, else the color of the picture’s top-left pixel (DVX only) |
vbGrayCopy and vbTransparentCopy copy the picture at its own size (width and height are not used): Picture1.PaintPicture "ship.bmp", x, y, 32, 32, 0, 0, 32, 32, vbTransparentCopy, vbMagenta draws a sprite. A picture file (or a LOADPICTURE picture) drawn again and again, a sprite in a game loop say, is read from the disk only the first time while the program runs and the file does not change (about a megabyte of pictures is kept that way).
Any of the 256 raster operations of Windows can be given by its number; the bits work on the pixel values, so with fewer than 32 bits a pixel the results follow the display’s color format.
' XOR the picture in, and out again
Picture1.PaintPicture Picture2, 0, 0, 32, 32, 0, 0, 32, 32, vbSrcInvert
Picture1.PaintPicture Picture2, 0, 0, 32, 32, 0, 0, 32, 32, vbSrcInvert
2.3.4. Scales
ScaleMode picks the units: 0 user (set by Scale or the Scale properties), 1 twips (1440 an inch, 15 a pixel), 2 points (72 an inch), 3 pixels, 4 characters (120 twips across, 240 down), 5 inches, 6 millimeters, 7 centimeters. Unlike Visual Basic, whose default is twips, DVX starts every form and PictureBox in pixels (ScaleMode 3), and Scale without arguments goes back to pixels. Setting ScaleLeft, ScaleTop, ScaleWidth, or ScaleHeight makes a user scale from the current one; ScaleWidth and ScaleHeight may not be 0, and ScaleMode must be 0 to 7 (error 380 otherwise). With a user scale the units stay fixed to the picture’s edges when it is resized; other scale modes keep their unit size.
The constants vbUser (0), vbTwips (1), vbPoints (2), vbPixels (3), vbCharacters (4), vbInches (5), vbMillimeters (6), and vbCentimeters (7) name the scale modes. The units assume a standard display of 96 pixels an inch (15 twips a pixel), whatever the screen really is, so an inch is always 96 pixels.
ScaleX and ScaleY convert a width or a height from one scale to another, as in Visual Basic: fromScale is the scale the value is in, vbHimetric (8, hundredths of a millimeter, the unit of a Picture’s Width and Height) when it is left out; toScale the scale wanted, the object’s ScaleMode when left out. vbUser means the object’s current scale. Visual Basic’s vbContainerPosition and vbContainerSize are not available; any other scale number raises error 5, which ON ERROR can trap.
Picture1.Scale (0, 100)-(100, 0) ' 0..100 across, y going up
Picture1.Line (0, 0)-(100, 100), RGB(255, 0, 0)
Picture1.ScaleMode = 7 ' centimeters
Picture1.Circle (2, 2), 1
Dim pic As Object
Set pic = LoadPicture("logo.bmp")
w = Me.ScaleX(pic.Width, vbHimetric, vbPixels) ' the picture's width in pixels
2.3.5. AutoRedraw and the Paint Event
A form or PictureBox fires its Paint event when it is shown, when the form is resized, when a PictureBox changes size (its Width or Height set to a new value, or its Resize method) while its form is showing, and when the program calls its Refresh method, so a program can draw everything in Paint as in Visual Basic. A PictureBox also fires its Resize event, before that Paint, whenever its drawing takes another size: its Width or Height set, its Resize method, or a Picture or Load of another size, as in Visual Basic (what its .frm sets as the form loads fires none). Unlike Visual Basic, DVX keeps what was drawn even with AutoRedraw False (the default), so drawing outside Paint also stays on the screen, and what a form drew under a control stays there too: a control that repaints shows over it, and one hidden or moved away uncovers it, with no Paint. With AutoRedraw = True, Paint does not fire. A program that sets AutoRedraw = False itself gets Visual Basic’s behavior exactly: the drawing is cleared to BackColor before each Paint.
Sub Picture1_Paint ()
Picture1.Circle (50, 50), 40, RGB(0, 128, 0)
End Sub
2.3.6. Drawing Properties
| Property | Type | Default | Description |
|---|---|---|---|
ForeColor |
Long |
&H000000 |
Color of drawing and printing. |
BackColor |
Long |
&HFFFFFF |
Color Cls clears to. Setting it clears the drawing to the new color. A form’s is the form’s background, the theme’s window content color by default (see the Form topic). |
CurrentX |
Single |
0 |
Where the next drawing or printing starts. |
CurrentY |
Single |
0 |
|
DrawWidth |
Integer |
1 |
Pen width in pixels; below 1 raises error 380 (Invalid property value), as in Visual Basic. |
DrawStyle |
Integer |
0 |
The pen’s lines and outlines: 0 solid, 1 dashes, 2 dots, 3 dash-dot, 4 dash-dot-dot (a pen 1 pixel wide only; a wider one draws solid), 5 none at all (fills are still drawn), 6 solid. Other values raise error 380 (Invalid property value), which ON ERROR can trap; the property keeps its value. The constants vbSolid to vbInsideSolid name them. |
FillStyle |
Integer |
1 |
How boxes (B) and circles are filled with FillColor: 0 solid, 1 (the default) not at all, 2 horizontal lines, 3 vertical lines, 4 upward diagonals, 5 downward diagonals, 6 a cross hatch, 7 a diagonal cross hatch (the lines 8 pixels apart, the gaps left as they are). Other values raise error 380. BF fills solid in the line’s color. The constants vbFSSolid to vbDiagonalCross name them. |
FillColor |
Long |
&H000000 |
Color boxes and circles are filled with. |
FontScale |
Integer |
1 |
How many times as large Print writes its text (1 to 8): each dot of the font becomes a FontScale x FontScale block, for titles and banners. TextWidth and TextHeight follow it; PrintAccel does not. |
AutoRedraw |
Boolean |
False |
True: no Paint events (see above). |
ScaleMode |
Integer |
3 |
Units of the coordinates (see Scales). |
ScaleLeft |
Single |
0 |
Coordinate of the left edge. |
ScaleTop |
Single |
0 |
Coordinate of the top edge. |
ScaleWidth |
Single |
(size) |
Width of the drawing in the scale’s units (a form’s inside, before it has drawn too). |
ScaleHeight |
Single |
(size) |
Height of the drawing in the scale’s units. |
2.3.7. Example
Sub Command1_Click ()
Picture1.Resize 200, 150
Picture1.BackColor = RGB(255, 255, 255)
Picture1.DrawWidth = 2
Picture1.Line (10, 10)-(190, 140), RGB(0, 0, 255), B
Picture1.FillStyle = 0
Picture1.FillColor = RGB(255, 255, 0)
Picture1.Circle (100, 75), 40, RGB(255, 0, 0)
Picture1.CurrentX = 70
Picture1.CurrentY = 120
Picture1.Print "Hello!"
End Sub
See also: PictureBox (Section 3.18); Form (Section 2.1).
2.4. Data Binding
DVX BASIC provides VB3-style data binding through three properties that can be set on most controls:
| Property | Set On | Description |
|---|---|---|
DataSource |
Any control |
Name of the Data control to bind to (e.g. "Data1"). |
DataField |
Any control |
Column name from the Data control’s recordset to display. |
2.4.1. How It Works
-
Place a Data control on the form and set its DatabaseName and RecordSource properties.
-
Place one or more display/edit controls (TextBox, Label, etc.) and set their DataSource to the Data control’s name and DataField to a column name.
-
When the form loads, the Data control auto-refreshes: it opens the database, runs the query, and navigates to the first record.
-
Bound controls are updated automatically each time the Data control repositions (the Reposition event fires, and the runtime pushes the current record’s field values into all bound controls).
-
What the user types into a bound control (and text the program sets in it) goes into the current record in the Data control’s record cache at once, so moving to another record (the Data control’s arrows, a DBGrid row, a Move method) saves the edit first. Text the Data control itself puts there is not an edit.
-
When a bound control loses focus (LostFocus), Update is called automatically to save the record to the database.
2.4.2. Master-Detail Binding
For hierarchical data (e.g. orders and order items), use two Data controls:
-
A master Data control bound to the parent table.
-
A detail Data control with its MasterSource set to the master’s name, MasterField set to the key column in the master, and DetailField set to the foreign key column in the detail table.
When the master record changes, the detail Data control automatically re-queries using the master’s current value for filtering. All controls bound to the detail are refreshed.
2.4.3. DBGrid Binding
Set the DBGrid’s DataSource to a Data control name. The grid auto-populates columns from the query results and refreshes whenever the Data control refreshes.
2.4.4. Example
VERSION DVX 1.00
Begin Form frmData
Caption = "Data Binding Example"
AutoSize = False
Width = 400
Height = 280
Begin Data Data1
DatabaseName = "myapp.db"
RecordSource = "customers"
End
Begin Label lblName
Caption = "Name:"
End
Begin TextBox txtName
DataSource = "Data1"
DataField = "name"
End
Begin Label lblEmail
Caption = "Email:"
End
Begin TextBox txtEmail
DataSource = "Data1"
DataField = "email"
End
End
Sub Data1_Reposition ()
Print "Current record changed"
End Sub
Sub Data1_Validate (Action As Integer, Save As Integer)
If Save And txtName.Text = "" Then
MsgBox "Name cannot be empty!"
Action = vbDataActionCancel
End If
End Sub
See also: Data (Section 3.4); DBGrid (Section 3.5).
2.5. Menu System
Menus are defined in the .frm file using Begin Menu blocks. Each menu item has a name, caption, and nesting level. Menu items fire Click events dispatched as MenuName_Click.
2.5.1. FRM Syntax
Begin Form Form1
Caption = "Menu Demo"
Begin Menu mnuFile
Caption = "&File"
Begin Menu mnuOpen
Caption = "&Open"
End
Begin Menu mnuSave
Caption = "&Save"
End
Begin Menu mnuSep1
Caption = "-"
End
Begin Menu mnuExit
Caption = "E&xit"
End
End
Begin Menu mnuEdit
Caption = "&Edit"
Begin Menu mnuCopy
Caption = "&Copy"
End
Begin Menu mnuPaste
Caption = "&Paste"
End
End
End
2.5.2. Menu Item Properties
In the .frm file a menu item takes these keys:
| Key | Type | Description |
|---|---|---|
Caption |
String |
The text displayed. Use & for accelerator key. Set to "-" for a separator. |
Index |
Integer |
The item’s index in a menu control array: items next to each other in one menu (or menus next to each other on the menu bar) that share a Name, each with an Index of its own (0 to 32767), as in Visual Basic. |
Checked |
Boolean |
Whether the menu item shows a checkmark. An item with a Checked line (True or False) is a check item: choosing it turns its checkmark on or off before its Click event runs, so the handler reads the new state. |
RadioCheck |
Boolean |
Show the check as a radio dot instead of a checkmark. Radio items next to each other form a group: choosing one checks it and clears the others. |
Shortcut |
String |
A key that runs the item from anywhere in the form, shown at the right of the item: "F2", "Ctrl+X", "Alt+Enter", "Shift+Del" (Ctrl, Alt, and Shift, then a letter, digit, F1 to F12, or Backspace, Del, Down, End, Enter, Esc, Home, Ins, Left, PgDn, PgUp, Right, Space, Tab, Up). |
ShortcutText |
String |
Key text shown at the right of the item without making a shortcut, for keys a control handles itself (for example "Del" on a Delete item whose list deletes on Del in its KeyDown handler, so a text box keeps its own Del). Shown instead of the Shortcut’s text when both are set. |
Enabled |
Boolean |
Whether the menu item is enabled (default True). |
Visible |
Boolean |
On a top-level menu, False keeps it off the menu bar: it is a popup menu (for PopupMenu and ContextMenu) until code sets Visible = True, as in Visual Basic. On an item, separator, or submenu inside a menu, False hides it until code sets Visible = True. |
Tag |
String |
Any text the program wants to keep with the menu, as for controls. |
A Shortcut key works while the form’s window has the focus, before the focused control sees the key, so give one only to keys no control there needs (F-keys, Ctrl, or Alt combinations). F1 always opens the help and never reaches a shortcut. An unknown Shortcut stops the program with an error when the form loads.
Begin Menu mnuRename
Caption = "&Rename..."
Shortcut = "F2"
End
Begin Menu mnuDelete
Caption = "&Delete"
ShortcutText = "Del"
End
At run time code can use only these properties of a menu (a menu of the menu bar, a popup menu, a submenu, an item, or a separator):
| Property | Type | R/W | Description |
|---|---|---|---|
Name |
String |
R |
The menu’s name. |
Index |
Integer |
R |
Its index in its menu control array; error 343 (Object not an array) for one in none. |
Caption |
String |
R/W |
The text, with & before its access key. Setting it keeps an item’s key text (Shortcut or ShortcutText), and reading it gives the text without it. As in Visual Basic, "-" makes an item a separator line and other text makes a separator an item again; a separator’s Caption reads "-". On a menu of the menu bar the new title is shown at once, and Alt and its new access key open it. |
Checked |
Boolean |
R/W |
Whether the item shows a checkmark. Setting it on an item that has neither Checked nor RadioCheck in the .frm makes it a check item (as in VB, any item can be checked). A menu of the menu bar or a popup menu reads False and has none to set. |
Enabled |
Boolean |
R/W |
Whether it is enabled. A menu of the menu bar set to False is grayed: it does not open, by the mouse or by the keyboard (Alt and its access key, F10, Left, and Right pass over it). |
Visible |
Boolean |
R/W |
Whether it is shown. A hidden item, separator, or submenu (with everything in it) is out of its menu and keeps its caption, checkmark, and place: shown again, it returns where it was. A menu of the menu bar set to False leaves the bar (it is then a popup menu PopupMenu can still show); when the last one goes the menu bar goes too, and the window keeps its size, so the form’s inside grows (its Resize runs) — and shrinks again when one is shown. |
Shortcut |
String |
R/W |
The key that runs the item ("Ctrl+K", written as in the .frm file, "" for none). Setting it changes the key and the key text shown in the item; "" removes both. An unknown key is an error. A menu of the menu bar or a popup menu reads "" and has none to set. |
Tag |
String |
R/W |
Any text the program keeps with the menu (the .frm’s Tag to start with; "" for an element LOAD made). |
A menu is of type Menu (TypeName(mnuFile) is "Menu", TypeOf c Is Menu is True), and its form’s Controls collection lists it after the form’s other controls (see Controls in the Form topic). A property of the controls a menu does not have (Left, Width, Container ...) raises error 438.
RadioCheck and ShortcutText are design-time only: using them on a menu in code is a compile error in the IDE and error 438 (Object doesn’t support this property or method) otherwise; setting Name or Index raises error 382 (Property cannot be set at run time), and a Shortcut DVX has no key for, or Checked or Shortcut set on a menu of the menu bar or a popup menu, error 380 (Invalid property value).
2.5.3. Menu Control Arrays
As in Visual Basic, menu items next to each other in one menu can share a Name, each with its own Index: a menu control array. Menus next to each other on the menu bar can too. In code an element is the name with its index (mnuZoom(1).Checked = True), and all of them run one Click procedure, which gets the element’s Index. LOAD name(index) adds an element while the program runs, a copy of the array’s lowest element as the .frm made it (its caption, check mark, and Enabled there; not its Shortcut) right after the array’s last element, hidden until its Visible is set to True; UNLOAD name(index) removes one LOAD made. An element LOAD adds to an array of menu-bar menus is a menu of the bar with no items: clicking it (or Alt and its access key) runs its Click, and nothing drops down. LOAD of an element that is there raises error 360 (Object already loaded), UNLOAD of one that is not error 340, UNLOAD of one the .frm made error 362 (Can’t unload controls created at design time); see Control Arrays in the Language Reference.
Begin Menu mnuFile
Caption = "&File"
Begin Menu mnuOpen
Caption = "&Open..."
End
Begin Menu mnuRecent
Caption = "-"
Index = 0
Visible = False
End
Begin Menu mnuExit
Caption = "E&xit"
End
End
A recent-files list: the separator mnuRecent(0) stays hidden until there is a file, and each file gets an element after it, made an item by its Caption:
Dim recentCount As Integer
Sub ShowRecent(files() As String, count As Integer)
Dim i As Integer
For i = 1 To recentCount
Unload mnuRecent(i)
Next
mnuRecent(0).Visible = count > 0
For i = 1 To count
Load mnuRecent(i)
mnuRecent(i).Caption = "&" & i & " " & files(i)
mnuRecent(i).Visible = True
Next
recentCount = count
End Sub
Sub mnuRecent_Click(Index As Integer)
MsgBox "Open file " & Index
End Sub
2.5.4. Menus at Run Time
These methods work on any control of a form, or on the form itself (Me.AddMenuItem ...). They name menus by their .frm names: a top-level menu (of the menu bar, or hidden there: a popup menu), a submenu, or a popup menu made with CreateMenu. PopupMenu also takes the menu itself, as Visual Basic’s does (Me.PopupMenu mnuEdit).
| Method | Parameters | Description |
|---|---|---|
PopupMenu |
menu [, flags [, x [, y]]] |
Shows the menu (a menu, or its name) as a popup at the mouse, or at x, y in the control (a coordinate left out is the mouse’s), as Visual Basic’s: flags vbPopupMenuCenterAlign or vbPopupMenuRightAlign put the menu’s middle or right edge at x (vbPopupMenuLeftAlign, the default, its left edge); vbPopupMenuLeftButton and vbPopupMenuRightButton change nothing (either button chooses). The menu’s Click runs first. |
CreateMenu |
menu$ |
Makes an empty popup menu of that name (nothing happens if one exists). |
AddMenu |
menu$, caption$ |
Adds a menu at the end of the form’s menu bar, which appears with the first one (so a form made with CreateForm can have a menu bar). Add items to it by its name. The window keeps its size; the controls get the height the bar takes. |
RemoveMenu |
menu$ |
Removes a top-level menu of the form (of the menu bar, or a popup menu of the .frm) with all its items; with the last one the bar goes too. Not for popup menus CreateMenu made (DestroyMenu) or items (RemoveMenuItem). |
AddMenuItem |
menu$, item$, caption$ [, shortcut$] |
Adds an item at the end of the menu. Choosing it runs the Sub item_Click, and item.Caption, .Checked, .Enabled, .Visible, and .Shortcut work as for .frm items. shortcut$ gives it a key, as Shortcut in the .frm file. |
AddMenuRadioItem |
menu$, item$, caption$ [, checked] |
Adds a radio item: radio items next to each other form a group, and choosing one checks it and clears the others. |
AddMenuSeparator |
menu$ [, separator$] |
Adds a separator line at the end of the menu. With a name it can be hidden and removed like an item. |
AddSubMenu |
menu$, submenu$, caption$ |
Adds a submenu at the end of the menu; add items to it by its name. |
RemoveMenuItem |
item$ |
Removes an item or named separator (shown or hidden) from its menu. An unknown name does nothing, and so do a menu control array’s (UNLOAD removes its elements) and a top-level menu’s (RemoveMenu removes it). A submenu, shown or hidden, cannot be removed. |
DestroyMenu |
menu$ |
Frees a popup menu made with CreateMenu, or a top-level menu of the .frm (as RemoveMenu), and every item in it. |
An item AddMenuItem makes needs its own Click procedure (Sub mnuRecent1_Click and so on); a list of items that grows and shrinks, such as recent files, is simpler as a menu control array (above), whose elements share one.
A menu that is open while the program changes it — items added, removed, hidden, or shown again (Load and Unload of elements too), the menu removed or destroyed, or its form unloaded, from a Timer or from the Click of a submenu opening from it — closes first, with the submenus open from it. A menu put on the menu bar or taken off it before an open one leaves that one open; a title made longer or shorter moves the others at once, so a click right after it finds the titles where they are now.
2.5.5. Nesting
Menu items are nested by placing Begin Menu blocks inside other Begin Menu blocks:
-
Level 0: top-level menu bar headers (e.g. "File", "Edit").
-
Level 1: items within a top-level menu.
-
Level 2+: submenu items.
A level-0 menu that contains children becomes a top-level menu header. A non-level-0 menu that contains children becomes a submenu.
2.5.6. Event Dispatch
Choosing a menu item (not a header, separator, or submenu) fires MenuName_Click, whether it is on the menu bar or in a popup menu; an element of a menu control array fires MenuName_Click(Index As Integer) with its index. As in Visual Basic, a menu’s own Click fires when it is about to open — a menu of the menu bar clicked or opened from the keyboard, a submenu opening, a menu PopupMenu shows — so its code can set what is in it first (an Edit menu’s Paste enabled only when there is something to paste); a menu of the menu bar with no items opens none, so its Click is all it does.
Sub mnuOpen_Click ()
MsgBox "Open was clicked"
End Sub
Sub mnuExit_Click ()
Unload Form1
End Sub
Sub mnuEdit_Click ()
' The Edit menu is opening: Paste only with text to paste
mnuPaste.Enabled = Clipboard.GetText() <> ""
End Sub
Menus a program changes while it runs, as in Visual Basic:
mnuFile.Caption = "&Archivo" ' a new title (Alt+A opens it)
mnuEdit.Enabled = False ' grayed on the menu bar
mnuDebug.Visible = False ' off the menu bar
Me.PopupMenu mnuPop ' a hidden menu of the .frm as a popup menu
See also: Form (Section 2.1); FRM File Format (Section 2.7).
2.6. Control Arrays
DVX BASIC supports VB-style control arrays. Multiple controls can share the same name, differentiated by an Index property. When an event fires on a control array element, the element’s index is passed as the first parameter.
2.6.1. Defining Control Arrays in FRM
Begin CommandButton Command1
Caption = "Button A"
Index = 0
End
Begin CommandButton Command1
Caption = "Button B"
Index = 1
End
Begin CommandButton Command1
Caption = "Button C"
Index = 2
End
2.6.2. Event Handler Convention
When a control has an Index property (>= 0), the event handler receives Index As Integer as the first parameter, before any event-specific parameters.
Sub Command1_Click (Index As Integer)
Select Case Index
Case 0
MsgBox "Button A clicked"
Case 1
MsgBox "Button B clicked"
Case 2
MsgBox "Button C clicked"
End Select
End Sub
2.6.3. Accessing Array Elements in Code
Use the indexed form ControlName(Index) to access a specific element:
Command1(0).Caption = "New Text"
Command1(1).Enabled = False
|
Note
|
An index there is no element for (Btn(5) with no Btn(5)) raises error 340 (Control array element doesn’t exist), as in Visual Basic. Control array elements share the same event handler Sub. The runtime prepends the Index argument automatically. If you define parameters on the Sub, Index comes first, followed by the event’s own parameters (e.g. KeyPress would be Sub Ctrl1_KeyPress (Index As Integer, KeyAscii As Integer)). An element’s Index property reads its index. |
2.6.4. The Control Array Object
As in Visual Basic, the array’s name alone (Command1, with no index) is the whole array, an object with these members:
| Member | Description |
|---|---|
Count |
How many elements the array has. |
LBound |
The lowest Index of its elements. |
UBound |
The highest Index of its elements. |
Item(Index) |
The element of that Index (its default member: Command1.Item(2) is Command1(2)); an Index it has no element for raises error 340. |
FOR EACH goes through its elements in Index order, and the object can be kept in a variable As Object (Set arr = Command1, then arr(2) or arr.Count). It follows Load and Unload. TypeName gives Object. Any other member raises error 438, and Count, LBound, and UBound cannot be set (error 383).
Dim i As Integer
Dim c As Control
For i = Command1.LBound To Command1.UBound
Command1(i).Enabled = True
Next i
For Each c In Command1
c.Caption = "Button " & c.Index
Next c
2.6.5. Adding and Removing Elements
As in Visual Basic, Load adds an element to a control array while the program runs, and Unload removes one Load added. The new element is a copy of the array’s lowest element as the .frm made it — its text, size, colors, font, Tag, and the control’s own properties at design time (what the program changed since is not copied) — placed after the array’s last element in that element’s container, and it starts hidden:
Load Command1(3)
Command1(3).Caption = "Button D"
Command1(3).Visible = True
...
Unload Command1(3)
Load of an element that is there raises error 360 (Object already loaded), Unload of one that is not error 340, Unload of one the .frm made error 362 (Can’t unload controls created at design time), an index on a control that is in no array error 343 (Object not an array), and Load or Unload of a control named alone (Unload Command2) error 361 (Can’t load or unload this object). Menu items make arrays the same way (see Menu Control Arrays under Menu System).
See also: Common Properties, Events, and Methods (Section 2.2).
2.7. FRM File Format
The .frm file is a text file that describes a form’s layout, controls, menus, and code. It follows a format compatible with VB3 .frm files, with DVX-specific extensions.
2.7.1. Structure
VERSION DVX 1.00
Begin Form FormName
form-level properties...
Begin Menu mnuFile
Caption = "&File"
Begin Menu mnuOpen
Caption = "&Open"
End
End
Begin TypeName ControlName
property = value
...
End
Begin Frame Frame1
Caption = "Group"
Begin TypeName ChildName
...
End
End
End
BASIC code follows...
Sub FormName_Load ()
...
End Sub
2.7.2. Rules
-
The VERSION line is optional. VERSION DVX 1.00 marks a native DVX form. VB forms with version <= 2.0 are accepted for import.
-
The form block begins with Begin Form Name and ends with End.
-
Controls are nested with Begin TypeName Name / End.
-
Container controls (Frame, VBox, HBox, Toolbar, TabStrip, ScrollPane, Splitter, WrapBox) can have child controls nested inside them.
-
Properties are assigned as Key = Value. String values are optionally quoted.
-
A Key = Value line belongs to the innermost block that is still open, also when it comes after the blocks nested inside it. DVX writes a block’s properties before the blocks inside it.
-
Everything after the form’s closing End is BASIC source code.
-
Comments in the form section use ' (single quote).
-
Blank lines are ignored in the form section.
2.7.3. Common FRM Properties
| Property | Applies To | Description |
|---|---|---|
Caption |
Form, controls |
Display text or window title. |
Text |
TextBox, ComboBox |
Initial text content. |
MinWidth / Width |
Controls |
Minimum width. Both names are accepted. |
MinHeight / Height |
Controls |
Minimum height. Both names are accepted. |
MaxWidth |
Controls |
Maximum width (0 = no cap). |
MaxHeight |
Controls |
Maximum height (0 = no cap). |
Padding / Spacing |
Form, containers |
Space inside the edge / between the controls. |
Weight |
Controls |
Layout weight for flexible sizing. |
Left |
Form, controls |
X position (used by Form when Centered=False; informational for controls). |
Top |
Form, controls |
Y position. |
Index |
Controls |
Control array index (-1 or absent = not in array). |
Visible |
Controls |
Initial visibility. |
Enabled |
Controls |
Initial enabled state. |
Layout |
Form |
"VBox" or "HBox". |
AutoSize |
Form |
Auto-fit window to content. |
Resizable |
Form |
Allow runtime resizing (True when not given). |
Centered |
Form |
Center window on screen. |
DatabaseName |
Data |
SQLite database file path. |
RecordSource |
Data |
Table name or SQL query. |
DataSource |
Bound controls |
Name of the Data control. |
DataField |
Bound controls |
Column name in the recordset. |
2.7.4. Sizes in a .frm
A size property — a control’s MinWidth (Width), MinHeight (Height), MaxWidth, and MaxHeight, and a form’s or container’s Padding and Spacing — holds pixels as a plain number, a percentage of the container with % after it, or a number of characters of the control’s font (the system font unless it or its container has a font of its own) with ch after it, both in the .frm file and in the IDE’s Properties window. They are what SizePercent and SizeChars (layout.bas) give in code, and they follow the same rules: a percentage counts for nothing when the form is fitted to its controls and takes only the room the container has to spare. A plain number is pixels, as in every .frm before, and a value the form could not take (12px, 50 %, a percentage above 100) is refused by the Properties window. Dragging a control’s resize handle in the designer keeps the kind of size it has: a percentage stays a percentage of the container, and characters stay characters. A UserControl’s header Width and Height (its natural size, in its .ctl file) take the same text (see UserControls: Your Own Controls).
Begin Frame fraOptions
MinWidth = 50%
MaxHeight = 200
Padding = 5%
Begin TextBox txtName
MinWidth = 20ch
End
End
See also: Form (Section 2.1); Common Properties, Events, and Methods (Section 2.2); Menu System (Section 2.5); Control Arrays (Section 2.6).
2.8. UserControls: Your Own Controls
A UserControl is a control you write in DVX BASIC. Once written, it is used exactly like the controls DVX comes with: you put it on a form in the designer (or in a .frm file with Begin), set its properties, call its methods, and write handlers for its events. Programs written in C can create and use it too.
A UserControl lives in a .ctl file. In the IDE, File > New UserControl makes one (see UserControls in the IDE). The file starts with a header that describes the control, then holds the control’s code. The code is a class: every control on a form is one object of the class, with its own copies of the class’s variables.
VERSION DVX 1.00
Begin UserControl Gauge
Width = 120
Height = 30
CanGetFocus = True
BackColor = &H00FFFFFF&
ToolboxIcon = "gauge.bmp"
Description = "A gauge"
DefaultEvent = "Changed"
End
Option Explicit
Public Event Changed(ByVal Level As Integer)
Private mLevel As Integer
Public Property Get Level() As Integer
Level = mLevel
End Property
Public Property Let Level(ByVal Value As Integer)
mLevel = Value
RaiseEvent Changed(mLevel)
UserControl.Refresh
End Property
Private Sub UserControl_Paint()
UserControl.Cls
UserControl.Line (0, 0)-(mLevel * UserControl.Width \ 100, _
UserControl.Height - 1), RGB(0, 128, 0), BF
End Sub
A form uses it like any control:
Begin Form Form1
Begin Gauge Gauge1
Level = 40
End
End
Sub Gauge1_Changed (ByVal Level As Integer)
lblLevel.Caption = Str$(Level)
End Sub
2.8.1. The Header
The header is a Begin UserControl block: the control’s name (the type name forms use) and its settings, one on each line, with nothing after the value (a ' comment there becomes part of it). Every setting is optional. In the IDE, the Properties window shows and changes them while the .ctl file is the active file; the Code Editor shows the code that follows the header, not the header.
- Width, Height
-
The natural size: the smallest size the form’s layout gives it (64 x 64 pixels when not given). It is written as a size is in a .frm file (see Sizes in a .frm under FRM File Format): pixels (120), a percentage of the container the control is placed in (50%), or characters of its font (20ch). A percentage follows the rules of a control’s MinWidth = 50%: it counts for nothing when the form is fitted to its controls, and it takes only the room the container has to spare; a MinWidth the form gives the control counts too, the larger of the two winning. The code changes the natural size with UserControl.MinWidth and MinHeight.
- CanGetFocus
-
True (the default): a click or Tab gives it the keyboard focus. False: it never has the focus and gets no keys.
- BackColor
-
The color Cls clears it to (white when not given).
- ToolboxIcon
-
A 24 x 24 picture file in the project folder, shown in the designer’s toolbox (a plain control picture when not given).
- Description
-
The toolbox tooltip (its name when not given).
- DefaultEvent
-
The event the designer opens when the control is double-clicked.
2.8.2. Properties, Methods, and Events
The control’s public members are what programs use:
-
Public Property Get / Let (or Set) pairs and Public variables are its properties. A property with only Property Get is read-only, with only Property Let write-only. A property whose type is Integer, Long, or Byte is a whole number, Boolean is True / False, Single and Double (and Currency) are numbers, String, Date, and Variant are text; a property of an object type, an array, or a TYPE cannot be a property of a control. A property with arguments (Public Property Get Item(i As Integer) As String and Public Property Let Item(i As Integer, v As String)) is an indexed one, as a ListBox’s ItemData(i): the program reads it as Gauge1.Item(2) and sets it as Gauge1.Item(2) = "two"; it has no row in the Properties window.
-
A property declared As an ENUM is a choice of its members, as a built-in control’s Alignment is: the designer’s Properties window shows the member’s name and a double-click steps to the next member, the form file stores the name (Look = Circle), and code sets it with a member, its number, or its name as text (Shape1.Look = Circle, Shape1.Look = 1, Shape1.Look = "Circle"). This needs the members numbered 0, 1, 2, and so on, each number once, as an ENUM numbers them when no values are given; an ENUM with other values (Small = 10) makes a whole-number property.
-
Public Subs and Functions are its methods. They take any arguments; a Function’s value is the method’s result. A call with fewer arguments than the procedure needs (its Optional ones may be left out) raises error 449 where the program made it, more than it has error 450, as for any control’s method; the control’s code does not run.
-
An error a property procedure or a method does not handle goes back to the program’s statement that used it, as in Visual Basic: Gauge1.Level = 5, x = Gauge1.Item(1), or Gauge1.Reset raises the error there, where ON ERROR can trap it, with the same Err.Number and Err.Description, and Err.Source the project’s and the control’s name (MyApp.Gauge: for a control in an installed control file, its control project’s name), or the source the control’s Err.Raise gave. Untrapped there, it ends the program as any error does. To report a problem to the program, Err.Raise a number of your own in the property procedure or method (vbObjectError + 513 and up, as Visual Basic suggests: Err.Raise vbObjectError + 513, "Gauge", "Level must be 0 to 100").
-
Public Events are its events. RaiseEvent sends one to the program that has the control: its handler CtrlName_EventName runs with the arguments, and a ByRef parameter the handler changes (a number, a Boolean, or a String) comes back changed.
Names that every control already has (Name, Left, Top, Width, Height, MinWidth, MinHeight, MaxWidth, MaxHeight, Weight, Visible, Enabled, ReadOnly, BackColor, ForeColor, Caption, Text, ToolTipText, ContextMenu, HelpTopic, DataSource, DataField, Tag, MousePointer ...) belong to the form: a control’s own property of such a name is not used. Give your properties other names (Title instead of Caption, Value or Level instead of Text).
A property’s default is the value it has after UserControl_Initialize ran. The form’s .frm sets only the properties the designer user changed, through your Property Let, after Initialize.
The control’s name is a control type, as in Visual Basic: Dim g As Gauge (or a parameter ByVal g As Gauge) holds one of the forms' Gauge controls — Set g = Gauge1, then g.Level = 3 — another control there raises error 13, and TypeOf obj Is Gauge tells such a control. Its members are found by name when the program runs. New makes no Gauge (it does not compile): a control is made by placing it on a form, or with Load or CreateControl.
2.8.3. The UserControl Object
Inside the control’s code, UserControl is the control itself: the surface it draws on and the side the program sees.
- Width, Height
-
Its current size in pixels (read-only; the form’s layout decides it).
- MinWidth, MinHeight
-
Its natural size: the form lays it out again when you change them. They take pixels, or SizePercent(n) and SizeChars(n) (layout.bas), the header’s 50% and 20ch; they read back in pixels, a percentage as it works out in the container now. Pixels below 0 raise error 380 (Invalid property value).
- Enabled
-
False while the control, or a container it is in, is disabled (read-only).
- HasFocus
-
True while it has the keyboard focus (read-only).
- CanGetFocus
-
The header’s CanGetFocus (read-only).
- UserMode
-
False while it sits in a form designer (the IDE’s, or a form with Form.DesignMode = True), True in a running program. In the designer the code draws it, but the user’s clicks and keys go to the designer.
- Name
-
The name the program gave the control ("" when a C program gave none).
- Ambient
-
Its container’s suggestions, as Visual Basic’s AmbientProperties (read-only): Ambient.UserMode (UserMode’s), Ambient.DisplayName (the control’s name), and Ambient.BackColor and Ambient.ForeColor — the colors around it: those of the nearest container with colors of its own (a Frame’s, a PictureBox’s), else its form’s when the program set them or drew on the form, else the color scheme’s window colors (an HBox or VBox has none of its own); the control’s own for a control of an installed control file or one a C program made. Any other member raises error 438.
- Extender
-
The control as its form has it: Extender.Name, Extender.Tag, Extender.Left, Extender.Visible, Extender.Parent, Extender.Container, and what else every control has there. Nothing for a control of an installed control file (its code is shared by every program) or one a C program made.
- SetFocus
-
Gives it the keyboard focus.
- Refresh
-
Runs UserControl_Paint now and shows the result.
- Invalidate
-
Asks for UserControl_Paint at the next chance, once however often it is called before then: change many things (add a hundred items) and the control is drawn once.
- PropertyChanged name
-
Tells a designer that a property changed, so its property sheet shows the new value.
- CanPropertyChange(name)
-
True: as in Visual Basic, a property may change (no property of a DVX control is bound to data).
- Cls, Line, PSet, Circle, Print, Point, PaintPicture, DrawFocusRect, TextWidth, TextHeight, Scale, ScaleX, ScaleY
-
Drawing, as on a PictureBox.
- DrawBevel, DrawButtonFace, DrawArrow, DrawScrollBar, DrawScrollArrow, ScrollBarClick, ScrollBarsNeeded, PrintAccel, TextWidthAccel, AccelKey
-
Drawing in DVX’s own look (bevels, button faces, arrows, upright and horizontal scroll bars and their arrow buttons, captions with an underlined access key), as on a PictureBox.
- CurrentX, CurrentY, ForeColor, BackColor, FillColor, FillStyle, FontScale, DrawWidth, DrawStyle, AutoRedraw, ScaleMode, ScaleLeft, ScaleTop, ScaleWidth, ScaleHeight
-
Drawing properties, as on a PictureBox.
The drawing members work exactly as on a PictureBox (see Drawing on Forms and PictureBoxes). In the control’s code the UserControl object’s members need no UserControl in front, as in Visual Basic and as a form’s members need no Me in its code: Width, MinWidth = 40, Cls, Line (0, 0)-(Width - 1, 9), Circle, PSet, Point(x, y), TextWidth(s), ScaleWidth, BackColor = vbRed, Refresh, Invalidate, PropertyChanged "Level", Ambient.UserMode, and Extender.Name are the control’s own, and so are Me.Width and Me.Refresh (Me is the control: a name its class has no member of is the UserControl object’s). As in a form’s code, the procedure’s own names (a local Height) and the class’s own declarations (its variables, constants, and procedures: a SUB Refresh of its own) come first, then the UserControl object’s members, then the module’s names and the built-in functions (see How Names Are Found in the language reference); with an argument list only a method is the control’s (Left(s, 2) is the built-in function), and a property cannot be a FOR counter or what INPUT reads into. PRINT stays the PRINT statement there: UserControl.Print prints on the control. UserControl.Width and the rest keep working, and another class module’s code has none of these names.
The drawing stays until you draw again. UserControl_Paint runs when the control first appears, after its size changed, when you call Refresh, and after you call Invalidate; draw everything there and call UserControl.Invalidate (or UserControl.Refresh, to see the result at once) whenever what it shows changes.
2.8.4. The Control’s Events
The program runs these procedures of the control’s code when they exist. Each is a Private Sub with exactly these parameters:
| Procedure | When |
|---|---|
UserControl_Initialize () |
The control was made (before the form’s property values are set). |
UserControl_Terminate () |
The control is going away (its form unloads). It cannot draw any more. |
UserControl_Resize () |
Its size changed (and once when it first appears). |
UserControl_Paint () |
It must be drawn (after Resize, after Refresh). |
UserControl_Click () |
The left button was pressed and let go over it (after MouseUp). |
UserControl_DblClick () |
A second quick left press, which raises no MouseDown: MouseDown, MouseUp, Click, DblClick, MouseUp, as in Visual Basic. A control that acts on a press of its own (a scroll bar it draws) acts on this one too, at the first press’s place. |
UserControl_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single) |
A button went down over it. |
UserControl_MouseMove (Button As Integer, Shift As Integer, X As Single, Y As Single) |
The mouse moved over it (Button 0), or with the left button held after a press on it, anywhere. |
UserControl_MouseUp (Button As Integer, Shift As Integer, X As Single, Y As Single) |
A button went up. |
UserControl_MouseWheel (Delta As Integer) |
The wheel turned over it (Delta is positive downwards). |
UserControl_KeyDown (KeyCode As Integer, Shift As Integer) |
A key went down while it has the focus. |
UserControl_KeyPress (KeyAscii As Integer) |
A character key was typed. |
UserControl_KeyUp (KeyCode As Integer, Shift As Integer) |
A key went up. |
UserControl_GotFocus () |
It got the keyboard focus. |
UserControl_LostFocus () |
It lost the keyboard focus. |
Button is vbLeftButton, vbRightButton, or vbMiddleButton (in MouseMove, the buttons held). Shift holds vbShiftMask, vbCtrlMask, and vbAltMask. X and Y are in the UserControl’s own scale (its ScaleMode, pixels unless the code sets another, or the scale Scale set), from its top-left corner. The compiler reports a handler with other parameters.
These events are the control’s own: the program does not see them. The program sees only the events the control raises. To let a program react to clicks, raise your own Click (Public Event Click, then RaiseEvent Click in UserControl_Click); an event named Click, DblClick, Change, KeyPress, KeyDown, KeyUp, MouseDown, MouseUp, MouseMove, or Scroll reaches the program’s CtrlName_Click (and so on) handler as for any control. Give those events Visual Basic’s parameters: Button, Shift, X, Y for MouseDown, MouseUp, and MouseMove; KeyCode, Shift for KeyDown and KeyUp; KeyAscii for KeyPress; Delta for Scroll. GotFocus and LostFocus reach the program by themselves.
2.8.5. Using Controls in a Program
In the IDE, File > New UserControl (or File > Add File with a .ctl file) adds a control to the open project; while the project is open the control is in the Toolbox, ready to be placed on the project’s forms. In the project file, the .ctl file is listed in the [Controls] section of the project’s .dbp:
[Controls]
File0 = gauge.ctl
Count = 1
When the program starts, its controls are registered before any form is loaded, so its forms can use them; they go away when the program ends. They belong to the program: other programs (and other copies of the same program) can have controls of the same name, and each program uses its own. The control’s code runs in the program, with the program’s rules, and DoEvents works as anywhere. An error its property procedures and methods do not handle goes to the statement that called them (see Properties, Methods, and Events); one in its own event procedures (UserControl_Paint, UserControl_Click, and the others), which no statement of the program called, ends the program, as in Visual Basic.
2.8.6. Installing a Control for Every Program
A control project holds only controls (no forms): its .dbp says
[Project]
Name = GAUGE
Type = Control
[Controls]
File0 = gauge.ctl
Count = 1
Building it — in the IDE, File > Make Control (set the project’s Type to Control in File > Project Properties first); or with the BASIC compiler, bascomp gauge.dbp (on DVX, SYSTEM\BASCOMP.EXE) — makes gauge.wgt, a control file. Copied into DVX’s WIDGETS folder (in a folder of its own, like the controls DVX comes with), it is loaded when DVX starts: every program can use its controls, the designer’s toolbox shows them with their ToolboxIcon and Description, and C programs create them by name. A control project may hold several controls and the modules they need; its help file goes beside the control file as for any widget.
A program may declare a variable, a parameter, or a FUNCTION As an installed control’s type (Dim g As Gauge, WithEvents too, whose handlers hear the control’s events: see Events) when one of its forms has a control of that type, or, compiled in the IDE, whenever the control is installed; an object stored there must be such a control (error 13 otherwise).
All the programs using an installed control file share one copy of its code and its module variables: module-level code of the control project runs once, when the first of its controls is made. A control’s own variables (its class members) are separate for each control. Because the code is shared:
-
DoEvents does nothing in an installed control’s code, and its code never lets another program run in between.
-
While its code runs for one program, another program that needs it (to paint or for an event) is turned away: the control keeps its old picture and the event is dropped (DVX.LOG notes it once).
-
An error a property procedure or method does not handle goes to the program’s statement that called it, as for a program’s own control. One in the control’s event procedures, or in its module-level code, is shown, and the control carries on; it does not end the program that was using it.
2.8.7. Limits
-
A control cannot hold other controls (its UserControl object has no Controls collection); it draws what it shows on its UserControl surface.
-
Properties are numbers, Booleans, text, and ENUM choices; a property of an ENUM whose members are not numbered 0, 1, 2 ... is a whole number in the Properties window.
-
CanGetFocus is fixed by the header (read-only in code).
-
UserControl_Terminate cannot draw: the surface is already gone.
-
A program cannot have a control of the same name as one installed in WIDGETS (the program stops with "Control cannot be registered").
Chapter 3. Control Reference
3.1. CheckBox
A toggle control with a label. The checked state is exposed as a Boolean. Supports accelerator keys (put '&' before a character in the Caption). Press Space to toggle it when it has the focus (Enter presses the form’s Default button instead, as in Visual Basic). As in Windows, a mouse click toggles the box when the button is released over it: the box shows pressed while the button is held, and moving off it before the release cancels the click.
3.1.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Caption |
String |
The text displayed next to the checkbox. |
Value |
Boolean |
True if checked, False if unchecked. Setting it to the other value fires Change and Click, as in Visual Basic (not the Value the .frm gives as the form loads). |
No type-specific methods.
3.1.2. Click and Change
| Event | Description |
|---|---|
Click |
The box was checked or cleared, with the mouse (at the release, after MouseDown and MouseUp), with Space, or with its access key, or the program’s code changed Value (as in Visual Basic). From the keyboard, KeyDown and KeyPress for the key come first, and setting KeyCode or KeyAscii to 0 there leaves the box as it is. |
Change |
The same, just before Click. DVX’s own: Visual Basic’s CheckBox has only Click. |
Setting Value to the value it already has fires neither.
Default Event: Click
3.1.3. Example
Begin CheckBox Check1
Caption = "Enable feature"
End
Sub Check1_Click ()
If Check1.Value Then
Label1.Caption = "Feature ON"
Else
Label1.Caption = "Feature OFF"
End If
End Sub
See also: Common Properties, Events, and Methods (Section 2.2).
3.2. ComboBox
VB Equivalent: ComboBox — DVX Widget: combobox (editable text field + drop-down list, default maxLen 256) | Name Prefix: Combo
A combination of a single-line text input and a drop-down list. The user can either type a value or pick one from the list. Selecting a list item copies its text into the edit field. Supports the same AddItem / RemoveItem / Clear / SetItems / List methods as ListBox.
Its font must be fixed-pitch, every character the same width; the designer’s Font dialog offers only those families for it. Given a proportional font it draws in the system font instead.
3.2.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Text |
String |
The text in the editable field. Setting it fires Change when the text is different, as in Visual Basic. |
ListIndex |
Integer |
Index of the currently selected list item (-1 = user typed something not in the list). Setting it to another item puts that item’s text in the field and fires Click, as in Visual Basic (not Change); a value below -1 or past the last item raises error 380 (Invalid property value). |
MaxLength |
Integer |
Most characters the edit field holds (0 = the default, 256). Longer text is cut when it is set; a value below 0 raises error 380. |
List(i) |
String |
The text of list item i; setting it (Combo1.List(0) = "New text") changes the item, keeping its ItemData. See ListBox. |
ItemData(i) |
Long |
A number the program keeps with list item i, as a ListBox’s. An index there is no item for raises error 381. |
NewIndex |
Integer |
The index of the item added last by AddItem (read-only); -1 after a RemoveItem, Clear, or SetItems. See ListBox. |
Sorted |
Boolean |
True keeps the list in order (case ignored), as in Visual Basic: AddItem puts an item in its place (NewIndex says where), AddItem with an index puts it there, and setting it True sorts the items, the selection on its item. See ListBox. |
TopIndex |
Integer |
The item shown at the top of the drop-down list, as in Visual Basic: setting it scrolls that item to the top, as far as the list scrolls (near the end the last item stays at the bottom; TopIndex reads where it went), and the list opens there, scrolled on only as far as it takes to show the selected item. The selection stays. An index past the list (or below 0) raises error 380. See ListBox. |
3.2.2. Type-Specific Methods
| Method | Description |
|---|---|
AddItem text$ [, index%] |
Append an item to the drop-down list or, with index%, put it before item index% (0 to ListCount), as in Visual Basic: the selection stays on its item and the text is kept. An index past the list raises error 5. |
Clear |
Remove all items. |
List(index%) |
Return the text of the item at the given index. |
ListCount() |
Return the number of items in the list. |
RemoveItem index% |
Remove the item at the given index. The selection stays on the same item; removing the selected item leaves no selection (the text is kept). An index there is no item for raises error 5. |
SetItems items$ |
Replace all the items at once from a "|"-separated list ("Red|Green|Blue"; every "|" separates two items, "" empties the list). Nothing is selected afterwards. The text is kept. |
3.2.3. Type-Specific Events
| Event | Parameters | Description |
|---|---|---|
DropDown |
(none) |
The list is about to open (a click on the arrow, F4, Alt+Down, Alt+Up, or the control’s access key), as in Visual Basic. The handler can fill or change the list before it shows. |
Click fires when the user picks an item from the list, as in Visual Basic, after the item’s text goes into the field: a click on an item of the open list, each move of Up, Down, or a typed letter while the list is open, and Up or Down while it is closed. A pick never raises Change: as in Visual Basic, Change is for the text the user types or edits in the field. A click on the field or the arrow raises no Click. The mouse wheel over the closed box steps the selection one item a notch (a pick each, with Click); over the open list it scrolls the list without moving the selection.
Default Event: Change (as in Visual Basic: double-clicking a ComboBox in the designer opens its Change handler)
3.2.4. Example
Begin ComboBox Combo1
End
Sub Form1_Load ()
Combo1.AddItem "Small"
Combo1.AddItem "Medium"
Combo1.AddItem "Large"
End Sub
' An item picked from the list
Sub Combo1_Click ()
Label1.Caption = "Selected: " & Combo1.Text
End Sub
' Text typed in the field
Sub Combo1_Change ()
Label1.Caption = "Typed: " & Combo1.Text
End Sub
See also: Common Properties, Events, and Methods (Section 2.2).
3.3. CommandButton
A push button that triggers an action when clicked. The Caption may include a '&' before a character to mark an accelerator key (e.g. "&OK" underlines 'O', and Alt+O activates the button).
3.3.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Caption |
String |
The text displayed on the button. Use '&' for an accelerator key. |
Default |
Boolean |
True: Enter presses this button, wherever the focus is on its form, unless the focused control uses Enter itself: another button (Enter presses it instead), an open drop-down list (Enter takes its choice), or a TextArea (Enter starts a new line). The focused control then gets no KeyDown or KeyPress for the Enter, as in Visual Basic. |
Cancel |
Boolean |
True: Escape presses this button, wherever the focus is on its form. |
Value |
Boolean |
True while the button is held down. Setting it to True in code clicks the button: its Click event runs (every time it is set), as in Visual Basic; Command1 = True does the same, Value being the default property. A button that is disabled (Enabled = False) or hidden (Visible = False), or is in a disabled or hidden Frame or other container, is not clicked: setting Value does nothing, as it cannot be clicked by the mouse or the keys either. |
Default and Cancel make a form work like a dialog box: give the OK button Default = True and the Cancel button Cancel = True. If several buttons on a form have the property, the first one (in the order they were made) that is visible and enabled is pressed.
No type-specific methods or events.
Default Event: Click
3.3.2. Example
Begin Form Form1
Caption = "Button Demo"
Begin CommandButton Command1
Caption = "&Click Me!"
End
End
Sub Command1_Click ()
MsgBox "Button was clicked!"
End Sub
See also: Common Properties, Events, and Methods (Section 2.2).
3.4. Data
A data access control that connects to a SQLite database and provides record navigation. Other controls bind to a Data control via their DataSource and DataField properties. The Data control cache is populated by calling Refresh. Move operations and Refresh auto-save the current row if dirty; a move is refused while the save fails, and Refresh discards an edit that cannot be saved. Updates find the record by the key value it was loaded with, so the key column itself can be edited; a key stored as a number in a column without a declared type, or a missing (NULL) key, is still found as long as it identifies exactly one record. Writing a field back with the value it already has is not an edit (Validate’s Save stays False). While a Validate handler runs, MoveFirst, MoveLast, MoveNext, MovePrevious, AddNew, Refresh, and Update on the same Data control are ignored (they would save, and validate, the same record again); Delete is allowed. A RecordSource whose first word is SELECT, WITH, or VALUES is a query; anything else is the name of a table. A query is read-only (AddNew, Update, and Delete fail, and LastError says why), and edits made to its records are dropped when the current record changes.
A new record (AddNew) is saved with the columns that are not empty: an empty one is left to the database, which gives it its default value, so an id INTEGER PRIMARY KEY column left empty gets the next number by itself. The record is then read back, so it shows the id (and defaults) the database gave it.
A Data control with a DetailField shows the records that belong to the master’s current record, and none while the master has no current record (an empty table, or its MasterField empty).
Validate works as in Visual Basic. It fires before every operation that leaves the current record (a Move, setting AbsolutePosition, AddNew, Refresh, Delete, and the form unloading) and before Update writes a changed record, with two arguments: Action, the operation (a vbDataAction constant, below), and Save, True when the record was changed. In the handler, set Action to vbDataActionCancel to cancel the operation (the record and its changes stay as they are), set Save to False to drop the changes and let the operation go on, or set Action to another Move or to vbDataActionAddNew to do that instead of a Move or an AddNew. When nothing was changed, the record is not written; when it was and Save stays True, it is written before the operation (a move whose write fails does not happen, and LastError says why).
| Constant | Value | The operation |
|---|---|---|
vbDataActionCancel |
0 |
(set by the handler) cancel the operation |
vbDataActionMoveFirst |
1 |
MoveFirst |
vbDataActionMovePrevious |
2 |
MovePrevious |
vbDataActionMoveNext |
3 |
MoveNext |
vbDataActionMoveLast |
4 |
MoveLast |
vbDataActionAddNew |
5 |
AddNew |
vbDataActionUpdate |
6 |
Update (only when the record was changed) |
vbDataActionDelete |
7 |
Delete (the record and its changes go together: Save does not matter) |
vbDataActionFind |
8 |
never (DVX’s Data control has no Find method) |
vbDataActionBookmark |
9 |
setting AbsolutePosition (a DBGrid row click too) |
vbDataActionClose |
10 |
Refresh (the records are read again: changes not written are dropped, and canceling does not stop it) |
vbDataActionUnload |
11 |
the form unloads (canceling drops the changes: the form still unloads) |
Sub Data1_Validate(Action As Integer, Save As Integer)
If Save Then
If MsgBox("Save the changes?", vbYesNo) = vbNo Then Save = False
End If
End Sub
A Validate handler written with Cancel alone (Sub Data1_Validate(Cancel As Integer), the shape DVX’s had before) still runs, for every operation: setting Cancel to 1 is setting Action to vbDataActionCancel.
When the form unloads, after its QueryUnload and Unload events (when neither cancels), the Data control saves an edit not saved yet, as in Visual Basic: Validate fires first with vbDataActionUnload, and canceling there, or setting Save to False, drops the edit (the form still unloads). A save that fails drops the edit too. LastError cannot be read then, since the control goes with its form: a program that must know calls Update in QueryUnload, reads LastError, and sets Cancel there to keep the form open. An edit is dropped without Validate when the program ends with END (its forms go without their Unload events, as in Visual Basic) and when DVX ends it (End Task, an error that stops it).
When something fails (the database cannot be opened, the table does not exist, a record breaks a rule of the table such as two records with the same key, a query cannot be changed, Validate canceled the operation) nothing is raised: the operation just does not happen, and LastError says why. Every operation clears LastError first, so read it right after the one you want to check; it is "" when that one worked.
Data1.Update
If Data1.LastError <> "" Then MsgBox "Not saved: " & Data1.LastError
A big record set is read a part at a time: Refresh reads the first 64 records, and the rest arrive while your program and DVX go on, so RecordCount grows until every record is in. MoveLast, AddNew, Update, and Delete read the rest first, and MoveNext and AbsolutePosition read as far as they need. Until every record is in, other programs (and SQLExec) cannot change that database: their changes fail with "database is locked".
EOF and BOF work as in Visual Basic, so a loop like this reads every record once:
Data1.Refresh
Do Until Data1.EOF
total = total + Val(Data1.GetField("amount"))
Data1.MoveNext
Loop
3.4.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
DatabaseName |
String |
Path to the SQLite database file. |
RecordSource |
String |
Table name, or a query for the recordset (its first word SELECT, WITH, or VALUES; read-only). |
KeyColumn |
String |
Primary key column name (used for UPDATE/DELETE operations); empty, or a name the table does not have, means the first column. |
Caption |
String |
Text displayed on the navigator bar. |
BOF |
Boolean |
True after MovePrevious at the first record (which stays the current record), or when there are no records; moving onto a record clears it (read-only). |
EOF |
Boolean |
True after MoveNext at the last record (which stays the current record), or when there are no records; moving onto a record clears it (read-only). |
MasterSource |
String |
Name of a master Data control (for master-detail binding). |
MasterField |
String |
Column in the master recordset to read for the filter value. |
DetailField |
String |
Column in this recordset that matches the master field. Set, the control shows only the records whose DetailField is the master’s value (none while the master has no current record). |
RecordCount |
Long |
The number of records read so far: all of them once the rest has arrived, or after MoveLast (read-only). |
FieldCount |
Integer |
The number of columns (read-only). |
AbsolutePosition |
Long |
The current record, 0 for the first (-1 when there are none). Setting it moves there (saving pending changes first, as the Move methods do) and fires Reposition; a value out of range does nothing. |
LastError |
String |
Why the last operation (Refresh, a Move, SetField, Update, AddNew, Delete) failed, "" when it worked (read-only). |
3.4.2. Type-Specific Methods
| Method | Parameters | Description |
|---|---|---|
MoveFirst |
(none) |
Navigate to the first record. |
MoveLast |
(none) |
Navigate to the last record (every record is read first). |
MoveNext |
(none) |
Navigate to the next record. |
MovePrevious |
(none) |
Navigate to the previous record. |
AddNew |
(none) |
Append a blank record and move to it. |
Delete |
(none) |
Delete the current record. |
Refresh |
(none) |
Re-query the database and reload records. |
Update |
(none) |
Write pending changes to the database. |
GetField |
col$ |
The current record’s value of a column, as text, without a bound control ("" for an unknown column). |
SetField |
col$, value$ |
Change a column of the current record; written to the database by Update (or when the record changes). |
FieldName |
index% |
The name of a column, 0 for the first ("" past the last). |
GetCell |
row&, col% |
The text of any cell (both from 0) without moving the current record ("" outside). |
3.4.3. Type-Specific Events
| Event | Parameters | Description |
|---|---|---|
Reposition |
(none) |
Fires after the current record changes. Default event. |
Validate |
Action As Integer, Save As Integer |
Fires before an operation leaves the current record, and before Update writes a changed one: Action is the operation (vbDataAction constants), Save True when the record was changed. Set Action = vbDataActionCancel to cancel, Save = False to drop the changes (see above). |
Default Event: Reposition
3.4.4. Example
Begin Data Data1
DatabaseName = "books.db"
RecordSource = "titles"
KeyColumn = "id"
End
Begin TextBox Text1
DataSource = "Data1"
DataField = "title"
End
Sub Form1_Load ()
Data1.Refresh
End Sub
See also: Common Properties, Events, and Methods (Section 2.2); Data Binding (Section 2.4).
3.5. DBGrid
A data-bound grid that displays records from a Data control in a tabular format. Columns auto-populate from the query results. Bind the grid using the DataSource property. Click a column header to sort (numbers by their value, 2 before 10, ahead of the entries that are not numbers, which sort as text with upper and lower case alike); drag a column border to resize. The highlighted row is always the bound Data control’s current record: selecting a row moves the Data control’s cursor, and navigating the Data control moves the highlight. Re-binding keeps the sort order and column settings, and a column width set by dragging a border is kept. A column’s automatic width fits its header and its first 200 records; text wider than its column is clipped. Records that arrive later (a Data control reads a big record set a part at a time) appear as they come, in the grid’s sort order. The mouse wheel scrolls the rows without changing the current record.
3.5.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
DataSource |
String |
Name of the Data control that supplies records. |
GridLines |
Boolean |
Show or hide grid lines between cells (default: True). |
SelectedRow |
Integer |
Index of the current record’s row (-1 = no records). Setting it moves the Data control’s cursor; negative values are ignored. |
Text |
String |
The current record’s first visible column ("" with no record), read-only. It is the grid’s default property, so Print DBGrid1 prints it. For another field, read the Data control’s recordset or the field’s bound control. |
3.5.2. Type-Specific Methods
| Method | Parameters | Description |
|---|---|---|
Refresh |
(none) |
Reload and redraw the grid from the Data control. |
SetColumnHeader |
Field As String, Header As String |
Set the displayed header text for a column. |
SetColumnVisible |
Field As String, Visible As Boolean |
Show or hide a column by field name. |
SetColumnWidth |
Field As String, Width As Integer |
Set the pixel width of a column by field name. |
3.5.3. Type-Specific Events
| Event | Parameters | Description |
|---|---|---|
Click |
(none) |
Fires for every click on the rows or the empty space below them, after MouseUp at the release over the grid (the press moves the current record; not on a column header or a scroll bar, as in Visual Basic), and when the arrow, Page Up, Page Down, Home, or End keys move to another record. |
DblClick |
(none) |
Fires for a double-click on the rows or the empty space below them (not on a column header, a column border, or a scroll bar), and for Enter. Default event. |
A click on a column header, a column border, or a scroll bar raises no MouseDown or MouseUp either, as in Visual Basic.
Default Event: DblClick
3.5.4. Example
Begin Data Data1
DatabaseName = "books.db"
RecordSource = "titles"
End
Begin DBGrid DBGrid1
DataSource = "Data1"
GridLines = True
End
Sub Form1_Load ()
Data1.Refresh
End Sub
Sub DBGrid1_DblClick ()
MsgBox "Opening row " & Str$(Data1.BOF)
End Sub
See also: Common Properties, Events, and Methods (Section 2.2); Data (Section 3.4); Data Binding (Section 2.4).
3.6. DropDown
DVX Extension — DVX Widget: dropdown (non-editable drop-down list; Visual Basic’s ComboBox with Style 2, Dropdown List)
A read-only drop-down list. Unlike ComboBox, the user cannot type free text; they can only select from the provided items. Supports AddItem / RemoveItem / Clear / SetItems / List. Use the Up and Down keys, or type an item’s first letter, to change the choice. F4, Alt+Down, or Alt+Up opens the list (Space types a letter and Enter is left to the form’s default button, as in Windows); in the open list, the arrow keys and typed letters move the highlight, and Enter, Space, F4, Alt+Down, or Alt+Up takes the highlighted item and closes the list. Esc closes the list without changing the choice.
3.6.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
ListIndex |
Integer |
Index of the currently selected item (-1 = none). Setting it to another item fires Change and then Click, as a pick does; a value below -1 or past the last item raises error 380 (Invalid property value). |
List(i) |
String |
The text of item i; setting it (DropDown1.List(0) = "New text") changes the item, keeping its ItemData. See ListBox. |
ItemData(i) |
Long |
A number the program keeps with item i, as a ListBox’s. An index there is no item for raises error 381. |
NewIndex |
Integer |
The index of the item added last by AddItem (read-only); -1 after a RemoveItem, Clear, or SetItems. See ListBox. |
Sorted |
Boolean |
True keeps the list in order (case ignored), as Visual Basic’s: AddItem puts an item in its place (NewIndex says where), AddItem with an index puts it there, and setting it True sorts the items, the selection on its item. See ListBox. |
TopIndex |
Integer |
The item shown at the top of the drop-down list, as in Visual Basic: setting it scrolls that item to the top, as far as the list scrolls (near the end the last item stays at the bottom; TopIndex reads where it went), and the list opens there, scrolled on only as far as it takes to show the selected item. The selection stays. An index past the list (or below 0) raises error 380. See ListBox. |
3.6.2. Type-Specific Methods
| Method | Description |
|---|---|
AddItem text$ [, index%] |
Append an item to the drop-down list or, with index%, put it before item index% (0 to ListCount), as in Visual Basic: the selection stays on its item. An index past the list raises error 5. |
Clear |
Remove all items. |
List(index%) |
Return the text of the item at the given index. |
ListCount() |
Return the number of items in the list. |
RemoveItem index% |
Remove the item at the given index. The selection stays on the same item; removing the selected item leaves no selection. An index there is no item for raises error 5. |
SetItems items$ |
Replace all the items at once from a "|"-separated list ("Red|Green|Blue"; every "|" separates two items, "" empties the list). Nothing is selected afterwards. |
3.6.3. Type-Specific Events
| Event | Parameters | Description |
|---|---|---|
DropDown |
(none) |
The list is about to open (a click on the box, F4, Alt+Down, Alt+Up, or the control’s access key), as a Visual Basic ComboBox’s. The handler can fill or change the list before it shows. |
Click fires when the user picks an item, as for a Visual Basic drop-down list ComboBox: a click on an item of the open list, the highlighted item taken with Enter, Space, F4, Alt+Down, or Alt+Up as the list closes (also the item chosen already, as a click on it), and Up, Down, or a typed letter while the list is closed. Change fires just before it, only when the pick changed the choice (a DropDown’s Change is DVX’s own). The click that opens the list raises DropDown, not Click. The mouse wheel over the closed box steps the choice one item a notch (a pick each, with Change and Click); over the open list it scrolls the list without moving the choice.
Default Event: Click
3.6.4. Example
Begin DropDown DropDown1
End
Sub Form1_Load ()
DropDown1.AddItem "Small"
DropDown1.AddItem "Medium"
DropDown1.AddItem "Large"
DropDown1.ListIndex = 1
End Sub
Sub DropDown1_Click ()
Label1.Caption = "Picked: " & DropDown1.List(DropDown1.ListIndex)
End Sub
See also: Common Properties, Events, and Methods (Section 2.2).
3.7. Frame
A container with a titled border. Child controls are placed inside the frame using VBox layout. In the .frm file, nest Begin/End blocks inside the Frame block.
3.7.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Caption |
String |
The title displayed in the frame border. |
| Property | Type | Description |
|---|---|---|
Alignment |
Enum |
Where the children sit along the frame from top to bottom when they do not fill it: Left (the top, the default), Center, or Right (the bottom). |
Padding |
Integer |
Space in pixels between the border and the children: 4 unless set; 0 is none. SizePercent (layout.bas) makes it a percentage of the frame’s width. |
Spacing |
Integer |
Space in pixels between one child and the next: none unless set. SizePercent (layout.bas) makes it a percentage of the frame’s width. |
No type-specific methods or events.
Setting Enabled = False on a Frame disables every control inside it for mouse and keyboard input.
Container: Yes
Default Event: Click
3.7.2. Example
Begin Frame Frame1
Caption = "Options"
Begin CheckBox Check1
Caption = "Option A"
End
Begin CheckBox Check2
Caption = "Option B"
End
End
See also: Common Properties, Events, and Methods (Section 2.2).
3.8. HBox
A container that arranges its children horizontally, left to right. No visible border. Use Weight on children to distribute extra space proportionally.
3.8.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Alignment |
Enum |
Where the children sit along the row when they do not fill it: Left (the left, the default), Center, or Right (the right). |
Padding |
Integer |
Space in pixels between the edge of the box and the children: 4 unless set; 0 is none. SizePercent (layout.bas) makes it a percentage of the box’s width. |
Spacing |
Integer |
Space in pixels between one child and the next: 4 unless set; 0 is none. SizePercent (layout.bas) makes it a percentage of the box’s width. |
Alignment = Right puts a row of buttons at the right, as dialog boxes have them.
No type-specific methods or events.
Container: Yes
Default Event: Click
3.8.2. Example
Begin HBox ButtonRow
Spacing = 4
Begin CommandButton Command1
Caption = "OK"
End
Begin CommandButton Command2
Caption = "Cancel"
End
End
See also: Common Properties, Events, and Methods (Section 2.2); VBox (Section 3.34).
3.9. HelpPane
Shows one topic of a help file the way DVX Help does: headings, paragraphs, and lists wrapped to the control’s width, notes, code, tables, pictures, rules, and links, with a scroll bar when the topic is longer than the control. Open the help file with hlpfile.bas (HlpOpen) and give its handle to ShowTopic. With a TreeView for the table of contents and a few buttons, a HelpPane makes a complete help viewer (see Help Files under Include Libraries).
A link is followed with a click, or with Enter or Space after Tab has moved to it: the HelpPane fires LinkClick with the ID of the topic the link names and remembers it in LinkTopic. It does not change topic by itself — the LinkClick event procedure usually shows the topic and adds it to its Back list. Everything a topic shows is copied when it is shown, so closing the help file afterwards does not change what the HelpPane shows.
3.9.1. Type-Specific Properties
| Property | Type | R/W | Description |
|---|---|---|---|
Topic |
Integer |
R |
The topic shown (numbered from 0, as hlpfile.bas numbers them); -1 when nothing is shown. |
LinkTopic |
String |
R |
The topic ID of the last link followed ("" before any). |
3.9.2. Type-Specific Methods
| Method | Description |
|---|---|
ShowTopic hlpFile&, topic& |
Show a topic of an open help file (an HlpOpen handle) from the top. A topic that is not in the file, or a closed handle, shows nothing. |
Clear |
Show nothing. |
3.9.3. Type-Specific Events
| Event | Parameters | Description |
|---|---|---|
LinkClick |
Topic As String |
A link was followed (clicked, or Enter or Space on it). Topic is the ID of the topic it names; HlpFindTopic gives its number. |
Default Event: LinkClick
3.9.4. Example
' hlpfile.bas in the project
Dim hlp As Long
Sub Form1_Load ()
hlp = HlpOpen(App.Path + "\MYAPP.HLP")
HelpPane1.ShowTopic hlp, HlpStartTopic(hlp, "")
End Sub
Sub HelpPane1_LinkClick (Topic As String)
HelpPane1.ShowTopic hlp, HlpFindTopic(hlp, Topic)
Me.Caption = HlpTopicTitle$(hlp, HelpPane1.Topic)
End Sub
Sub Form1_Unload ()
HlpClose hlp
End Sub
See also: Common Properties, Events, and Methods (Section 2.2).
3.10. HScrollBar
A horizontal slider/scrollbar control. The value ranges between Min and Max (default 0 to 100). Arrow keys move the value by 1, Page Up/Page Down by a tenth of the range, Home/End to the limits. The Change event fires only when the value actually changes: when the user moves it, or when the program’s code sets Value to another value (as in Visual Basic).
3.10.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Value |
Integer |
The current slider position, Min to Max. A value outside that range raises error 380 (Invalid property value) and the slider stays where it was, as in Visual Basic; set Min and Max first. |
Min |
Integer |
Lowest value (default 0). Setting Min above Max raises Max to match; a Value outside the new range moves to its nearer end. |
Max |
Integer |
Highest value (default 100). Setting Max below Min lowers Min to match; a Value outside the new range moves to its nearer end. |
Default Event: Change
3.10.2. Example
Begin HScrollBar HScroll1
MinWidth = 200
End
Sub HScroll1_Change ()
Label1.Caption = "Value: " & Str$(HScroll1.Value)
End Sub
See also: Common Properties, Events, and Methods (Section 2.2).
3.11. Image
A static image display control. Loads bitmap images from file. Set the Picture property at design-time (in the .frm file) or at runtime to load a file.
3.11.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Picture |
Picture |
Path to an image file to load (or a Picture object from LOADPICTURE or LOADPICTUREDATA); a program, widget, or library file gives its icon. Reads back as a Picture object for the picture shown, which stands for the file name ("" for a picture from bytes) where a value is needed. Setting it to "" clears the image. A file that cannot be loaded leaves the image and Picture unchanged. A disabled Image is drawn grayed (its transparent color stays transparent). |
Stretch |
Boolean |
When True, an image larger than the control is scaled down to fit, keeping its proportions; a smaller image stays at natural size. When False, the image is shown at natural size. |
ImageWidth |
Integer |
Width of the loaded image in pixels (read-only). |
ImageHeight |
Integer |
Height of the loaded image in pixels (read-only). |
MaskColor |
Long |
The transparent color (an RGB value): with UseMaskColor True, pixels of this color are not drawn, so the form shows through. |
UseMaskColor |
Boolean |
True leaves out the pixels of MaskColor (default False). |
3.11.2. Type-Specific Methods
| Method | Description |
|---|---|
SetPictureData(bytes$ [, name$]) |
Show the picture held in bytes$ (the bytes of a BMP, PNG, JPEG, or GIF file, such as HttpBody$ or ResGetData$ gives), as Picture = LoadPictureData(bytes$) does but without keeping a Picture object, so it suits showing many pictures in turn. Picture then reads name$ ("" without it). Returns True, or False (the picture unchanged) when the bytes are not a picture. |
No type-specific events.
Default Event: Click
3.11.3. Example
Begin Image Image1
Picture = "assets/logo.bmp"
Stretch = True
End
Sub Image1_Click ()
MsgBox "Size: " & Str$(Image1.ImageWidth) & "x" & Str$(Image1.ImageHeight)
End Sub
See also: Common Properties, Events, and Methods (Section 2.2).
3.12. ImageButton
A button that displays an image instead of text. Has the same press/release behavior as CommandButton, but shows a bitmap. Typically used inside a Toolbar.
3.12.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Picture |
Picture |
Path to an image file to load (or a Picture object from LOADPICTURE or LOADPICTUREDATA); a program, widget, or library file gives its icon. Reads back as a Picture object for the picture shown, which stands for the file name ("" for a picture from bytes) where a value is needed. Setting it to "" clears the image. A file that cannot be loaded leaves the image and Picture unchanged. |
ImageWidth |
Integer |
Width of the loaded image in pixels (read-only). |
ImageHeight |
Integer |
Height of the loaded image in pixels (read-only). |
MaskColor |
Long |
The transparent color (an RGB value): with UseMaskColor True, the picture’s pixels of this color show the button face, so an icon need not be square. |
Stretch |
Boolean |
When True, a picture larger than the button is scaled down to fit inside its frame, keeping its proportions, and the button can be any size; a smaller picture stays at natural size. When False (the default) the button is as large as its picture. |
UseMaskColor |
Boolean |
True leaves out the pixels of MaskColor (default False). |
A disabled ImageButton is drawn grayed (its transparent color stays transparent).
3.12.2. Type-Specific Methods
| Method | Description |
|---|---|
SetPictureData(bytes$ [, name$]) |
Show the picture held in bytes$ (the bytes of a BMP, PNG, JPEG, or GIF file, such as HttpBody$ or ResGetData$ gives), as Picture = LoadPictureData(bytes$) does but without keeping a Picture object, so it suits showing many pictures in turn. Picture then reads name$ ("" without it). Returns True, or False (the picture unchanged) when the bytes are not a picture. |
No type-specific events.
Default Event: Click
3.12.3. Example
Begin Toolbar Toolbar1
Begin ImageButton ImageButton1
Picture = "icons/save.bmp"
End
Begin ImageButton ImageButton2
Picture = "icons/open.bmp"
End
End
Sub ImageButton1_Click ()
MsgBox "Save clicked"
End Sub
See also: Common Properties, Events, and Methods (Section 2.2).
3.13. Label
A static text label. Supports left, center, and right alignment. Put '&' before a character in the Caption to define an accelerator that moves focus to the next focusable control.
3.13.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Caption |
String |
The text displayed by the label. Setting it to other text fires Change, as in Visual Basic. |
Alignment |
Enum |
Text alignment, by name or by Visual Basic’s number: Left (vbLeftJustify, 0; the default), Right (vbRightJustify, 1), or Center (vbCenter, 2). Another number raises error 380 (Invalid property value). |
WordWrap |
Boolean |
True: the Caption wraps onto as many lines as it needs at the label’s Width, and the label is as tall as its lines, so a long caption never makes the form wider. False (the default): one line, as wide as the Caption. A label with WordWrap and no Width stays one line. |
DataSource |
String |
Name of a Data control for data binding: the label shows a field of its current record. |
DataField |
String |
Column name for data binding. |
No type-specific methods or events.
Default Event: Click
3.13.2. Example
Begin Label Label1
Caption = "Hello, World!"
Alignment = "Center"
End
See also: Common Properties, Events, and Methods (Section 2.2).
3.14. Line
A visual separator line, horizontal or vertical. A Line placed in a horizontal container (HBox, Toolbar) starts vertical; anywhere else it starts horizontal. Set Vertical to turn it the other way, for example a vertical Line between two side-by-side groups inside a VBox.
3.14.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Vertical |
Boolean |
True for a vertical line, False for a horizontal one. |
No type-specific events or methods.
See also: Common Properties, Events, and Methods (Section 2.2).
3.15. ListBox
A scrollable list of selectable items. Items are managed via methods (AddItem, RemoveItem, Clear). Supports single and multi-select modes (MultiSelect), a check box before each item (Style), a sorted list (Sorted), drag-to-reorder, and keyboard navigation with type-ahead search. When the box is narrower than its longest item (its width limited by MaxWidth or by the form), a horizontal scroll bar appears; it and the Left and Right keys scroll the items sideways a character at a time.
3.15.1. Type-Specific Properties
- ListIndex
-
Type: Integer. Index of the currently selected item (-1 = no selection). Setting it to another item fires Change and then Click, as in Visual Basic; a value below -1 or past the last item raises error 380 (Invalid property value) and the selection stays.
- Text
-
Type: String. The selected item ("" with none); the default property, so Print List1 prints it. Setting it selects the first item that is that text (case ignored), with Change and Click as for ListIndex; with none, the selection stays as it is.
- List(i)
-
Type: String. The text of item i (0 to ListCount - 1), as in Visual Basic. Reading an index there is no item for gives ""; setting one (List1.List(0) = "New text") changes the item’s text and keeps its selection and ItemData, and an index there is no item for raises error 381.
- ItemData(i)
-
Type: Long. A number the program keeps with item i (0 until it is set), as in Visual Basic: it moves with its item when items are added or removed before it, or the item is dragged. An index there is no item for raises error 381 (Invalid property array index), as ItemData(ListIndex) does with nothing selected.
- NewIndex
-
Type: Integer. The index of the item added last by AddItem (read-only), as in Visual Basic; -1 when an item was removed since, after Clear or SetItems, or when none was added. List1.ItemData(List1.NewIndex) = n gives the new item its number. In a sorted list it is where the item went.
- Selected(i)
-
Type: Boolean. Whether item i is selected, read and set, as in Visual Basic. In a list with MultiSelect, setting it selects or deselects item i alone; in a Checkbox list (Style) it is the item’s check mark, and setting it checks or unchecks item i, with ItemCheck when the mark changes; in any other, True selects item i (ListIndex) and False deselects it when it is the selected one. A change of the item’s selection fires Change and then Click, as for ListIndex. An index there is no item for raises error 381.
- Sorted
-
Type: Boolean. True keeps the items in order (case ignored), as in Visual Basic: AddItem without an index puts an item in its place (after the items that sort the same) and NewIndex says where; AddItem with an index puts it at that index, as Visual Basic does, even if that is out of order; SetItems loads the items in order. Setting it True sorts the items the list holds, each keeping its ItemData and selection. (In Visual Basic it is set in the form designer only; DVX also takes it from code.)
- TopIndex
-
Type: Integer. The item shown at the top, as in Visual Basic: setting it scrolls that item to the top, as far as the list scrolls (near the end the last item stays at the bottom; TopIndex reads where it went), the selection unchanged. An index past the list (or below 0) raises error 380.
- MultiSelect
-
Type: Enum. None (vbMultiSelectNone, 0), Simple (vbMultiSelectSimple, 1), or Extended (vbMultiSelectExtended, 2), as in Visual Basic. Simple: a click or Space selects or deselects an item. Extended: a click selects the item alone, Ctrl+click selects or deselects it, Shift+click and Shift+arrow select a range, and Space toggles the current item. Changing it starts the selection again from the current item. A Checkbox list (Style) keeps it for when it is Standard again. Another number raises error 380.
- Style
-
Type: Enum. Standard (vbListBoxStandard, 0) or Checkbox (vbListBoxCheckbox, 1), as in Visual Basic. Checkbox puts a check box before each item: its check mark is the item’s selection (Selected(i)), and ListIndex is the current item, one at a time whatever MultiSelect says. A click on an item’s box, or on the current item, checks or unchecks it, as Space does; a click on another item’s text makes it the current item. Setting Style unchecks every item (Standard goes back to MultiSelect’s selection). Another number raises error 380.
3.15.2. Type-Specific Methods
| Method | Parameters | Description |
|---|---|---|
AddItem |
Text As String [, Index As Integer] |
Add an item to the end of the list or, with Index, before item Index (0 to ListCount; ListCount adds it at the end), as in Visual Basic: the items from Index on move down, the selected item stays selected (ListIndex goes up by one), and the new item is NewIndex. An Index past the list raises error 5. |
Clear |
(none) |
Remove all items from the list. |
ClearSelection |
(none) |
Deselect all items (in a Checkbox list, uncheck them). |
IsItemSelected |
Index As Integer |
Returns True if the item at Index is selected (Selected(Index) as a method). An index there is no item for raises error 381. |
List |
Index As Integer |
Return the text of the item at the given index (List is also an indexed property: see above). |
ListCount |
(none) |
Return the number of items in the list. |
RemoveItem |
Index As Integer |
Remove the item at the given index. Items after it keep their selection; removing the selected item leaves no selection. NewIndex is -1 afterwards; an index there is no item for raises error 5. |
SelectAll |
(none) |
Select all items (multi-select mode; in a Checkbox list, check them all). |
SetItemSelected |
Index As Integer, Selected As Boolean |
Select or deselect a specific item (in a Checkbox list, check or uncheck it), as Selected(Index) = Selected does, but without an event. An index there is no item for raises error 381. |
SetItems |
Items As String |
Bulk-load items from a pipe-delimited string (e.g. "Red|Green|Blue"). Replaces existing items. Every "|" separates two items ("a|" is "a" and an empty item); "" empties the list. |
SetMultiSelect |
Multi As Boolean |
Enable or disable multi-select mode (True is MultiSelect Extended). |
SetReorderable |
Reorderable As Boolean |
Enable or disable drag-to-reorder. |
Click fires when the user picks an item, as in Visual Basic: a click on an item, even the one already selected (after MouseDown, before MouseUp), or a selection moved with the arrow keys, Home, End, Page Up, Page Down, a typed letter, or (multi-select) Space. Change fires just before it, only when the pick changed the selection (a ListBox’s Change is DVX’s own). A click on a scroll bar or below the last item raises no Click, and the second click of a double-click raises DblClick instead (after Change, when that click picked another item); a double-click on a scroll bar raises no DblClick, and a click there no MouseDown or MouseUp, as in Visual Basic.
The mouse wheel scrolls the list without moving the selection, as in Visual Basic: it raises Scroll, not Change or Click.
3.15.3. Type-Specific Events
| Event | Parameters | Description |
|---|---|---|
ItemCheck |
Item As Integer |
A Checkbox list’s item was checked or unchecked, as in Visual Basic: by a click or Space (after Change, before Click), or by the program’s Selected(Item) = value (not by SetItemSelected). Selected(Item) is the new mark. |
Default Event: Click
3.15.4. Example
Sub Form1_Load ()
List1.AddItem "Apple"
List1.AddItem "Banana"
List1.AddItem "Cherry"
End Sub
Sub List1_Click ()
Dim idx As Integer
idx = List1.ListIndex
If idx >= 0 Then
Label1.Caption = "Selected: " & List1.List(idx)
End If
End Sub
' "Avocado" goes before "Banana", with its own number
Sub Command1_Click ()
List1.AddItem "Avocado", 1
List1.ItemData(List1.NewIndex) = 42
End Sub
' The items the user selected in a list with MultiSelect, or the
' items checked in a list with Style Checkbox
Sub Command2_Click ()
Dim i As Integer
For i = 0 To List1.ListCount - 1
If List1.Selected(i) Then Print List1.List(i)
Next i
End Sub
' A Checkbox list says what was checked as it happens
Sub List1_ItemCheck (Item As Integer)
If List1.Selected(Item) Then
Label1.Caption = List1.List(Item) & " is checked"
Else
Label1.Caption = List1.List(Item) & " is unchecked"
End If
End Sub
See also: Common Properties, Events, and Methods (Section 2.2); ComboBox (Section 3.2); DropDown (Section 3.6).
3.16. ListView
A multi-column list with column headers. Supports sorting, multi-select, and drag-to-reorder. A column sorts numerically when both entries are numbers (2 before 10, -1.5 before 0), and the numbers come before the entries that are not; the others sort as text with upper and lower case alike. Equal entries keep their order.
3.16.1. Type-Specific Properties
| Property | Type | R/W | Description |
|---|---|---|---|
ListIndex |
Integer |
R/W |
Index of the currently selected row (-1 = none). Setting it to another row fires Change and then Click, as a ListBox’s does; a value below -1 or past the last row raises error 380 (Invalid property value). |
MultiSelect |
Boolean |
R/W |
True lets the user select several rows (Shift and Ctrl with a click), as Visual Basic’s ListView’s MultiSelect; the same as SetMultiSelect. |
Selected(i) |
Boolean |
R/W |
Whether data row i is selected, as a ListBox’s Selected(i): set, it selects or deselects row i alone with MultiSelect, else True selects it (ListIndex) and False deselects it when it is the selected one; a change fires Change and then Click. A row there is not raises error 381. |
SortColumn |
Integer |
R/W |
The column the list is sorted by, -1 when it is unsorted: what SetSort or the user’s last click on a column header chose. Setting it sorts by that column in the current SortOrder (ascending when the list was unsorted); -1 unsorts the list, and a column the list does not have raises error 380. |
SortOrder |
Integer |
R/W |
The order of the sort: 0 = none, 1 = ascending, 2 = descending (a click on the same header again reverses it). Setting it re-sorts the SortColumn in that order; 0 unsorts the list, an unsorted list stays unsorted, and another number raises error 380. |
3.16.2. Type-Specific Methods
| Method | Description |
|---|---|
AddItem text$ [, index%] |
Add a row (sets first column text) after the last or, with index%, before data row index% (0 to ListCount), as Visual Basic’s ListItems.Add with an index: the rows from index% on move down and keep their selection, and a sorted list shows the new row in its place. An index past the list raises error 5. |
Clear |
Remove all rows. |
ClearSelection |
Deselect all rows. |
GetCell$(row%, col%) |
Returns the text of a cell. |
IsItemSelected(index%) |
Returns True if the row is selected. |
ListCount() |
Returns the number of rows (the same as RowCount; also read as the ListCount property). |
RemoveItem index% |
Remove a row by index. Rows after it keep their selection; removing the selected row leaves no selection. An index there is no row for raises error 5. |
RowCount() |
Returns the number of rows. |
SelectAll |
Select all rows. |
SelectedRows$() |
Returns the numbers of the selected rows (as IsItemSelected numbers them) separated by spaces, "" when none: one call instead of IsItemSelected for every row of a long list. |
SetCell row%, col%, text$ |
Set the text of a cell. |
SetColumns spec$ |
Define columns. Pipe-delimited "Name,Width,Align|Name,Width": the width in characters (missing or 0 = as wide as the contents), then Left (the default), Center, or Right for the column’s text. |
SetItemSelected index%, selected |
Select or deselect a row. |
SetMultiSelect multi |
Enable or disable multi-select. |
SetReorderable reorderable |
Enable or disable row reordering. |
SetRows text$ |
Replace all the rows at once: one row per line (separated by CHR$(10)), cells separated by CHR$(9) (Tab); missing cells are blank and extra ones are dropped. Much faster than AddItem and SetCell for long lists. The selection is cleared and the cursor goes to the first row. |
SetSort col%, dir% |
Sort by column. dir: 0=none, 1=ascending, 2=descending. An invalid column or direction clears the sort. Has no effect while reordering is enabled. |
GetCell, SetCell, IsItemSelected, and SetItemSelected raise error 381 (Invalid property array index) for a row there is none for (and GetCell and SetCell for a column the list does not have), as Selected(i) does; Visual Basic’s ListView gives its ListItems collection’s error, Index out of bounds, there. SetItemSelected is Selected(i) = selected as a method: in a list without MultiSelect, True makes the row the selected one, and it fires no event.
3.16.3. Type-Specific Events
| Event | Parameters | Description |
|---|---|---|
ColumnClick |
Column As Integer |
A column header was clicked (Column 0 is the first). The list has already sorted itself by that column (the same column again reverses), with or without a handler; a program that orders the rows itself calls SetSort -1, 0 in the handler (or SetSort for another order) and fills the list in its own order. |
ItemClick |
Item As Integer |
The user picked a row (Item is its number, as ListIndex numbers it): a click on a row, even the one already selected, or a selection moved with the keys. Visual Basic passes the ListItem itself; DVX passes its number. |
When the user picks a row, the events come in Visual Basic’s order: MouseDown, then Change (only when the pick changed the selection; a ListView’s Change is DVX’s own), ItemClick, Click, and MouseUp. A row picked with the arrow keys, Home, End, Page Up, Page Down, a typed letter, or (multi-select) Space raises Change, ItemClick, and Click the same way. A click in the empty space below the last row raises Click alone, as in Visual Basic; a click on a column header raises ColumnClick only, and one on a scroll bar raises nothing. The second click of a double-click raises DblClick instead (after Change, when that click picked another row), on a row or in the empty space below the rows; a double-click on a column header, a header border, or a scroll bar raises no DblClick (and no click there raises MouseDown or MouseUp), as in Visual Basic. Enter raises DblClick too: check ListIndex in the handler when only a row should count.
The mouse wheel scrolls the list without moving the selection, as in Visual Basic: it raises Scroll, not Change or Click.
Default Event: Click
3.16.4. Example
ListView1.SetColumns "Name,20|Size,10|Type,15"
ListView1.AddItem "readme.txt"
ListView1.SetCell 0, 1, "1024"
ListView1.SetCell 0, 2, "Text"
ListView1.SetSort 0, 1
' Many rows at once; the size column right-aligned
ListView2.SetColumns "Name,14|Size,10,Right"
ListView2.SetRows "a.txt" & Chr$(9) & "120" & Chr$(10) & "b.txt" & Chr$(9) & "4,096"
See also: Common Properties, Events, and Methods (Section 2.2).
3.17. OptionButton
A radio button for mutually exclusive choices. OptionButtons placed in the same container form a group: selecting one clears the others. The Value property is True for the selected button. As in Windows, a mouse click selects the button when the mouse button is released over it: it shows pressed while the button is held, and moving off it before the release cancels the click. With the keyboard, the arrow keys move to the next or previous button of the group and select it, and Space or the button’s access key selects the button that has the focus (Enter presses the form’s Default button instead).
3.17.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Caption |
String |
The text displayed next to the radio button. |
Value |
Boolean |
True when this button is selected. Setting it to True selects this button and clears the others in its container, and when the button was not selected fires its Change and Click, as in Visual Basic (the buttons it clears get nothing); setting it to False deselects it and fires nothing. The Value the .frm gives as the form loads fires nothing. |
OptionIndex |
Integer |
The index of this button among the OptionButtons of its container (read-only). |
3.17.2. Type-Specific Methods
| Method | Parameters | Description |
|---|---|---|
GetSelected |
(none) |
Returns the index (as OptionIndex counts) of the selected OptionButton of this button’s container, or -1 when none is: one call instead of reading every button’s Value. |
SetSelected |
Index As Integer |
Select the OptionButton at the given index within this button’s container; -1 selects none. It fires no event (set that button’s Value to True for its Click). An index there is no OptionButton for raises error 381 (Invalid property array index). |
3.17.3. Click and Change
| Event | Description |
|---|---|
Click |
The button became selected: the user selected it with the mouse (at the release, after MouseDown and MouseUp), with the arrow keys, Space, or its access key, or the program’s code set its Value to True, as in Visual Basic. Clicking the button that is already selected fires nothing. From the keyboard, KeyDown and KeyPress for the key come first, and setting KeyCode or KeyAscii to 0 there cancels the key. |
Change |
The same, just before Click. DVX’s own: Visual Basic’s OptionButton has only Click. |
Default Event: Click
See also: Common Properties, Events, and Methods (Section 2.2).
3.18. PictureBox
A drawing surface (canvas). Supports drawing lines, rectangles, circles, text, and individual pixels. Can load BMP, PNG, JPEG, and GIF images and save BMP or PNG images. The default canvas size is 64x64 pixels.
Colors are Visual Basic RGB values, &HBBGGRR, as RGB() makes them (RGB(255, 0, 0) or &HFF is red).
3.18.1. Type-Specific Properties
- Align
-
Type: Enum. Docks the PictureBox to an edge of its form, as in Visual Basic: 0 - None (the default; it stands among the form’s controls), 1 - Top, 2 - Bottom, 3 - Left, 4 - Right (the constants vbAlignNone, vbAlignTop, vbAlignBottom, vbAlignLeft, and vbAlignRight). One docked Top or Bottom is as wide as the form and keeps its height; one docked Left or Right is as tall as the space between the Top and Bottom ones and keeps its width. Its drawing takes that size and follows the form as it is resized, keeping what was drawn on it (white where it grew), with a Resize event each time. Several docked to the same edge stand side by side in the order of the form’s controls. Only a PictureBox standing directly on the form docks; one inside a Frame or another container stays where it is. Setting Align to None puts it back among the form’s controls. Another number raises error 380 (Invalid property value).
- BorderStyle
-
Type: Enum. 0 - None: no frame, the control is exactly the size of the drawing. 1 - FixedSingle (the default): a sunken frame 2 pixels wide around the drawing. Mouse coordinates and drawing positions start inside the frame either way. Another number raises error 380.
- ImageHeight
-
Type: Integer. Height of the drawing in pixels (read-only). After Load it is the loaded image’s height.
- ImageWidth
-
Type: Integer. Width of the drawing in pixels (read-only). After Load it is the loaded image’s width.
- Picture
-
Type: String. The picture file the canvas shows ("" when it shows none). Setting it to a file name, or to LoadPicture(path$), loads that file as Load does; LoadPictureData(bytes$) shows a picture from bytes; setting it to "" (or LoadPicture("")) clears the canvas to white. Clear and Resize wipe the picture, so Picture becomes "". The default property: Picture1 = "logo.bmp" loads it. Setting it to another picture fires Change, as in Visual Basic.
Load and Save return 0 on success and -1 on failure (missing or unreadable file, unsupported format, path that cannot be written). Call them as functions to check the result, or as statements to ignore it. A failed Load leaves the drawing unchanged.
3.18.2. Type-Specific Methods
| Method | Description |
|---|---|
Clear color% |
Fill the entire canvas with the specified color. |
DrawLine x0%, y0%, x1%, y1%, color% |
Draw a line between two points. |
DrawRect x%, y%, w%, h%, color% |
Draw a rectangle outline. |
DrawText x%, y%, text$ |
Draw text at the given position. |
FillCircle cx%, cy%, radius%, color% |
Draw a filled circle. |
FillRect x%, y%, w%, h%, color% |
Draw a filled rectangle. |
GetPixel(x%, y%) |
Returns the color at a pixel. With fewer than 16 million colors on the screen it is the color the screen shows: black, white, and full colors such as RGB(255, 0, 0) read back exactly, others may differ slightly. |
Load(path$) |
Load a BMP, PNG, JPEG, or GIF image; the canvas takes the image’s size. Returns 0 on success, -1 on failure. |
Resize w%, h% |
Resize the canvas to new dimensions. The drawing is cleared to white. |
Save(path$) |
Save the canvas: BMP when path$ ends in .bmp, PNG otherwise. Returns 0 on success, -1 on failure. |
SetPenColor color% |
Set the drawing color for subsequent operations. |
SetPenSize size% |
Set the pen size in pixels (1 to 255; larger values use 255): the round dot DrawLine draws at each point of a line is size pixels across and down. |
SetPictureData(bytes$ [, name$]) |
Show the picture held in bytes$ (the bytes of a BMP, PNG, JPEG, or GIF file, such as HttpBody$ or ResGetData$ gives) as Load shows a file, without keeping a Picture object as Picture = LoadPictureData(bytes$) does. Picture then reads name$ ("" without it). Returns True, or False (the drawing unchanged) when the bytes are not a picture. |
SetPixel x%, y%, color% |
Set the color of a single pixel. |
3.18.3. Type-Specific Events
- Resize
-
Parameters: (none). The drawing took another size, as Visual Basic’s PictureBox Resize: once as the PictureBox is made (before its form’s Load, or when CreateControl makes it), then each time its Width or Height is set (also in the form’s Load), the Resize method runs, a Picture or Load of another size arrives, Align docks it, or the form resized a docked one. It fires before the Paint a Width, Height, or Resize change brings. A size the drawing already has fires none, and a PictureBox the form’s layout stretches without Align keeps its drawing’s size, so that fires none either.
Default Event: Click
3.18.4. Example
Picture1.Resize 200, 150
Picture1.Clear &HFFFFFF
Picture1.SetPenSize 2
Picture1.DrawRect 10, 10, 180, 130, &H000000
Picture1.FillCircle 100, 75, 40, RGB(255, 0, 0)
Picture1.DrawText 60, 130, "Hello!"
If Picture1.Save("output.bmp") <> 0 Then
MsgBox "Could not save output.bmp"
End If
A PictureBox also has Visual Basic’s drawing methods and properties (Cls, PSet, Line, Circle, Point, Print, PaintPicture, DrawFocusRect, DrawBevel, DrawButtonFace, DrawArrow, DrawScrollBar, DrawScrollArrow, ScrollBarClick, ScrollBarsNeeded, PrintAccel, Scale, CurrentX, CurrentY, ForeColor, BackColor, DrawWidth, FillColor, FillStyle, FontScale, AutoRedraw, ScaleMode, ScaleLeft, ScaleTop, ScaleWidth, ScaleHeight) and a Paint event: see Drawing on Forms and PictureBoxes.
3.19. ProgressBar
A progress indicator bar, lying flat (the default) or standing upright.
3.19.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Value |
Integer |
Current progress value (0-100). A value outside 0 to 100 raises error 380 (Invalid property value), as a Visual Basic ProgressBar’s outside its Min to Max (0 to 100 by default) does. |
Vertical |
Boolean |
True: the bar stands upright and fills from the bottom up. False (the default): it lies flat and fills from left to right. Can be set in the designer or at run time. |
No type-specific events or methods. No default event.
See also: Common Properties, Events, and Methods (Section 2.2).
3.20. RichEdit
A text box for text in many fonts, sizes, and colors, bold, italic, underlined, or struck through, in paragraphs aligned left, centered, or right — a small word processor’s page. The user types, selects, and edits as in any text box; a program reads and changes the selection’s look with the Sel properties, and the whole text, with its looks, as RTF (Rich Text Format, the format word processors save), so it can be saved to a file and loaded again.
Text starts in the control’s own font (FontName, FontSize, and the other Font properties, or the form’s) and in its ForeColor; text left in them follows the control when they change. The Sel properties read the first character of the selection; setting one changes the selection, or with nothing selected, the text typed next. SelStart counts characters from 0, and the break between two paragraphs is one character.
3.20.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
TextRTF |
String |
The whole text with its fonts, styles, colors, and alignment, as RTF. Setting it replaces the text (plain text is taken as it is), and fires Change when the text or its formatting is different. |
SelRTF |
String |
The selection as RTF. Setting it replaces the selection. |
SelStart |
Integer |
Where the selection starts (the caret when nothing is selected). Past the end of the text it is the end; below 0 it raises error 380 (Invalid property value), as in Visual Basic. |
SelLength |
Integer |
How many characters are selected (as many as there are past SelStart); below 0 it raises error 380. |
SelText |
String |
The selection’s text. Setting it replaces the selection with plain text. |
SelBold |
Boolean |
Bold. |
SelItalic |
Boolean |
Italic. |
SelUnderline |
Boolean |
Underlined. |
SelStrikethru |
Boolean |
Struck through. |
SelColor |
Long |
The color, as RGB() makes it; -1 for the control’s ForeColor. |
SelFontName |
String |
The font family ("" for the control’s own). |
SelFontSize |
Integer |
The size in pixels (the nearest one the family comes in); below 1 it raises error 380. |
SelAlignment |
Enum |
The alignment of the selection’s paragraphs in Visual Basic’s numbers: Left (rtfLeft, 0), Right (rtfRight, 1), or Center (rtfCenter, 2); the name as text works too. Another number raises error 380. |
CanUndo |
Boolean |
An edit can be undone (read-only). |
CanRedo |
Boolean |
An undone edit can be done again (read-only). |
Text (a common property) is the plain text, a line per paragraph; setting it replaces everything with plain text, and fires Change when the text is different. ReadOnly lets the user select and copy but not change the text.
3.20.2. Type-Specific Methods
| Method | Description |
|---|---|
Undo |
Undo the last edit (typing a run of characters is one edit). Up to 100 edits are kept. |
Redo |
Do an undone edit again. |
Cut, Copy, Paste |
The clipboard. Text copied from a RichEdit pastes back into a RichEdit with its looks; text from elsewhere takes the look of the text typed next. |
SelectAll |
Select all the text. |
Find(text[, matchCase]) |
Select the next place text is, from the selection on and around past the end; returns where it starts, or -1. Any case unless matchCase is True. |
LoadFile(path) |
Load a file: RTF when it is RTF, else plain text. Returns 0, or -1 when it cannot be read. |
SaveFile(path) |
Save the text: as RTF when path ends in .rtf, else as plain text. Returns 0, or -1 when it cannot be written. |
3.20.3. Type-Specific Events
| Event | Parameters | Description |
|---|---|---|
SelChange |
(none) |
The selection or the caret moved. |
Change fires after every edit. Default Event: Change
3.20.4. Keys
| Key | Action |
|---|---|
Ctrl+B, Ctrl+I, Ctrl+U |
Bold, italic, or underline on or off. |
Ctrl+L, Ctrl+E, Ctrl+R |
Align the paragraph left, centered, or right. |
Ctrl+Z, Ctrl+Y |
Undo, Redo. |
Ctrl+X, Ctrl+C, Ctrl+V |
Cut, Copy, Paste. |
Ctrl+A |
Select all. |
Ctrl+Left, Ctrl+Right |
A word back or on. |
Ctrl+Home, Ctrl+End |
The start or the end of the text. |
Shift with a moving key |
Extend the selection. |
A double click selects a word, a triple click the paragraph.
3.20.5. Example
Sub Form_Load ()
RichEdit1.Text = "Dear friend,"
RichEdit1.SelStart = 0
RichEdit1.SelLength = 4
RichEdit1.SelBold = True
RichEdit1.SelColor = RGB(0, 0, 160)
End Sub
Sub cmdItalic_Click ()
RichEdit1.SelItalic = Not RichEdit1.SelItalic
End Sub
Sub cmdSave_Click ()
If RichEdit1.SaveFile("LETTER.RTF") <> 0 Then
MsgBox "The letter could not be saved."
End If
End Sub
See also: Common Properties, Events, and Methods (Section 2.2).
3.21. RichLabel
Text that mixes fonts, sizes, bold and italic, underlining, and colors, in paragraphs that are each aligned left, centered, or right. Build the text with calls: SetFont, SetStyle, and SetColor choose how the text you add next looks; AddText adds it; AddLineBreak starts a new line; and AddParagraph starts a new paragraph. Clear empties the control so you can build it again.
Text starts in the control’s own font (FontName, FontSize, and the other Font properties, or the form’s). Set Width to have the text wrap at that width; otherwise each paragraph stays on one line and the control is as wide as its longest line.
3.21.1. Methods
| Method | Description |
|---|---|
Clear |
Remove all the text. The font, style, and color go back to the control’s own. |
SetFont family, size |
The font family (for example "DejaVu Serif") and size in pixels of the text added next. "" and 0 go back to the control’s own font and size. |
SetStyle style |
FONT_BOLD, FONT_ITALIC, FONT_UNDERLINE, and FONT_STRIKE added together (from font.bas; FONT_REGULAR for none) for the text added next. |
SetColor color |
The color of the text added next, as RGB() makes it; -1 for the control’s ForeColor. |
AddText text |
Add text in the font, style, and color chosen. |
AddLineBreak |
Start a new line in the same paragraph. |
AddParagraph alignment |
Start a new paragraph: 0 left, 1 centered, 2 right (as a Label’s Alignment). |
Changing the font, style, or color affects only the text added afterwards. A line is as tall as the largest font on it.
No type-specific properties or events.
Default Event: Click
3.21.2. Example
Sub Form_Load ()
RichLabel1.Clear
RichLabel1.SetFont "DejaVu Serif", 18
RichLabel1.SetStyle FONT_BOLD
RichLabel1.AddText "Welcome"
RichLabel1.AddParagraph 0
RichLabel1.SetFont "", 0
RichLabel1.SetStyle 0
RichLabel1.AddText "Text in "
RichLabel1.SetColor RGB(160, 0, 0)
RichLabel1.AddText "red"
RichLabel1.SetColor -1
RichLabel1.AddText " and "
RichLabel1.SetStyle FONT_ITALIC + FONT_UNDERLINE
RichLabel1.AddText "italic underlined"
RichLabel1.SetStyle 0
RichLabel1.AddText " words."
End Sub
See also: Common Properties, Events, and Methods (Section 2.2).
3.22. ScrollPane
A scrollable container. Place child controls inside and the ScrollPane automatically provides scrollbars when the content exceeds the visible area. Clicking on content that does not respond to the mouse (a Label, an Image, or empty space) gives the ScrollPane the focus, so the arrow and page keys scroll it.
3.22.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
NoBorder |
Boolean |
When True, suppresses the border around the scroll pane. |
Padding |
Integer |
Space in pixels between the edge and the controls inside (0, the default, is none). SizePercent (layout.bas) makes it a percentage of the pane’s width. |
Spacing |
Integer |
Space in pixels between the controls inside, which are stacked top to bottom (0, the default, is none). SizePercent (layout.bas) makes it a percentage of the pane’s width. |
ScrollTop |
Integer |
How far the content is scrolled down, in pixels (run time). Values past the end stop at the end. |
ScrollLeft |
Integer |
How far the content is scrolled to the right, in pixels (run time). Values past the end stop at the end. |
3.22.2. Type-Specific Methods
| Method | Description |
|---|---|
ScrollToTop |
Scroll back to the top-left corner of the content. |
ScrollToControl ctrl |
Scroll so that a control inside the pane (the control, or its name) is in view, also one that cannot take the focus. |
3.22.3. Events
| Event | Description |
|---|---|
Change |
The user scrolled the content (the scrollbars, dragging a scroll box, the arrow, page, Home, and End keys); read ScrollTop and ScrollLeft for the new position. Setting ScrollTop or ScrollLeft, or ScrollToTop, does not fire it. |
3.22.4. Scrolling a Picture Bigger Than the Window
A ScrollPane with NoBorder = True filling a form, holding a PictureBox larger than the window, gives the form scrollbars of its own: the user scrolls the picture, Change says where it is, and ScrollTop / ScrollLeft move it from code. To draw only the part in view (for a picture too large to keep whole), keep the PictureBox the size of the view, and draw from Change with ScrollTop and ScrollLeft as the offset.
Sub Form1_Load ()
picBig.Resize 1200, 900
picBig.Line (0, 0)-(1199, 899), RGB(0, 0, 255), B
End Sub
Sub spView_Change ()
lblWhere.Caption = "Top " & spView.ScrollTop & ", left " & spView.ScrollLeft
End Sub
Container: Yes
No default event.
See also: Common Properties, Events, and Methods (Section 2.2).
3.23. Spacer
An invisible layout spacer. Takes up space in the layout without rendering anything. Useful for pushing controls apart: it takes the extra space of its row or column (its Weight is 100 unless set), so a Spacer between two buttons puts them at the two ends. With Weight 0 it is a fixed gap of its MinWidth (in a row) or MinHeight (in a column).
No type-specific properties, events, or methods.
See also: Common Properties, Events, and Methods (Section 2.2).
3.24. SpinButton
A numeric input with up/down buttons. Supports integer mode (default) and real-number mode with configurable decimal places. Up/Down arrows step by the step size, Page Up/Page Down by ten steps. When the control gets the focus its number is selected, so typing replaces it (a click puts the caret where it lands). Typed or pasted text is committed on Enter or when the control loses focus; Esc cancels the edit. Ctrl+Z undoes the last edit of the typed text; once the text is committed or reformatted there is nothing to undo. Reading Value while the user is typing returns the typed number without interrupting the edit. Change also fires as each character is typed, and when the program’s code sets Value or RealValue so that the number shown changes (as a Visual Basic SpinButton’s Value does); stepping at a limit, committing text that parses to the unchanged value, or setting the number it already shows does not fire it.
Its font must be fixed-pitch, every character the same width; the designer’s Font dialog offers only those families for it. Given a proportional font it draws in the system font instead.
3.24.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Value |
Integer |
Current value (in real mode, the value truncated to an integer; setting it there sets RealValue to the whole number). A value outside the range (SetRange, default 0 to 100; SetRealRange in real mode) raises error 380 (Invalid property value) and the value stays, as a Visual Basic UpDown control’s does; set the range first. |
RealMode |
Boolean |
True to use floating-point mode; False for integer mode. |
Decimals |
Integer |
Number of decimal places shown in real mode, 0 to 10; another number raises error 380. |
RealValue |
Double |
The value in real mode, with its fraction (Value is it cut to a whole number). In real mode a value outside the range raises error 380, as Value’s does. |
3.24.2. Type-Specific Methods
| Method | Parameters | Description |
|---|---|---|
SetRange |
Min As Integer, Max As Integer |
Set the allowed value range (used in both integer and real mode; default 0 to 100). |
SetStep |
Step As Integer |
Set the increment per button click. |
SetRealRange |
Min As Double, Max As Double |
The range in real mode, with fractions (SetRange takes whole numbers). One argument raises error 449, three 450. |
SetRealStep |
Step As Double |
The increment per click in real mode (0 or less gives 0.01). No argument raises error 449, two 450. |
Default Event: Change
See also: Common Properties, Events, and Methods (Section 2.2).
3.25. Splitter
A resizable split pane. Holds exactly two child widgets separated by a draggable divider. By default the divider is vertical and the panes sit side by side; set Vertical to False for a horizontal divider with one pane above the other.
3.25.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Position |
Integer |
Position of the divider in pixels from the left (or, when Vertical is False, from the top). |
Vertical |
Boolean |
True (the default): panes side by side. False: one pane above the other. Can be set in the designer or at run time. |
3.25.2. Type-Specific Events
| Event | Description |
|---|---|
Change |
The user moved the divider: raised as it is dragged, Position giving where it is. Not raised for a Position set in code. |
Container: Yes
No default event.
See also: Common Properties, Events, and Methods (Section 2.2).
3.26. StatusBar
A horizontal container styled as a status bar, typically placed at the bottom of a form. Put Labels (or other controls) inside it as its panes: they sit side by side, each drawn with a sunken-panel border for the classic segmented status-bar look. Give the pane that should take the spare room Weight = 100. Panes can be nested in the designer or the .frm, or added at run time with CreateControl(form, "Label", name$, StatusBar1).
Container: Yes
3.26.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Alignment |
Enum |
Where the panes sit along the bar when they do not fill it: Left (the default), Center, or Right. |
Padding |
Integer |
Space in pixels between the edge of the bar and the panes: 1 unless set; 0 is none. |
Spacing |
Integer |
Space in pixels between one pane and the next: 2 unless set; 0 is none. |
No type-specific events or methods.
3.26.2. Example
Begin StatusBar Status1
Begin Label lblStatus
Caption = "Ready"
Weight = 100
End
Begin Label lblPos
Caption = "Line 1, Col 1"
End
End
See also: Common Properties, Events, and Methods (Section 2.2).
3.27. TabStrip
A tabbed container. Each tab page is a separate container that holds child controls. Switching tabs shows one page and hides others.
3.27.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
TabIndex |
Integer |
Index of the active tab (0-based). Setting it switches tabs as SetActive does; a switch to another tab fires Change and then Click, as in Visual Basic. An index below 0 or past the last tab raises error 380 (Invalid property value), as a Visual Basic tabbed dialog’s Tab does (a strip with no tabs yet keeps any index from 0 for the tabs to come). |
3.27.2. Type-Specific Methods
- AddPage title$
-
Add a new tab page with the given title.
- GetActive()
-
Returns the index of the active tab.
- SetActive index%
-
Switch to the tab at the given index (the same as setting TabIndex). An index below 0 or past the last tab raises error 381 (Invalid property array index), the tab staying (a strip with no tabs yet keeps any index from 0 for the tabs to come). Switching closes a drop-down list opened from the page being hidden and moves the focus to the tab strip if it was on a control of the page being hidden. SetActive raises no event (setting TabIndex does), so a program can switch tabs without its handlers running.
3.27.3. Type-Specific Events
| Event | Description |
|---|---|
Change |
The user switched tabs, with the mouse or the keys, or the program’s code set TabIndex to another tab (SetActive raises nothing). GetActive (or TabIndex) says which tab is active now. |
Container: Yes
Default Event: Click
See also: Common Properties, Events, and Methods (Section 2.2).
3.28. Terminal
A VT100/ANSI terminal emulator with a text-mode cell buffer, 16-color CGA palette, and scrollback history. Processes standard ANSI escape sequences (cursor control, erase, scroll, SGR colors, DEC private modes) typically used by DOS BBS software. Default size is 80 columns by 25 rows. Supports text selection with the mouse, Ctrl+C to copy, and Ctrl+V to send clipboard text as input. Shift+PgUp and Shift+PgDn page through the scrollback history and the mouse wheel scrolls it; any other key is sent to the host and returns the view to the live screen.
Its font must be fixed-pitch, every character the same width; given a proportional font it draws in the system font instead. A fixed-pitch font of any size changes the size of every cell.
3.28.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Cols |
Integer |
Number of character columns (1-512). Setting Cols or Rows gives the terminal a new size, starting as a new terminal: empty screen and scrollback, modes the host set reset (its colors and connection stay); set the form’s AutoSize to True afterwards to fit the window to it. |
Music |
Boolean |
Whether ANSI music sequences (ESC[M, ESC[N, ESC[| followed by PLAY text, as BBSes send) are recognized (True at first): each raises the Music event instead of being shown. False: ESC[M is always Delete Line, and ESC[N and ESC[| do nothing. |
Rows |
Integer |
Number of character rows (1-512). |
Scrollback |
Integer |
Maximum number of scrollback lines. Older lines are dropped (default 500). Setting another number keeps the newest lines that fit; setting the same number changes nothing. |
3.28.2. Type-Specific Methods
| Method | Description |
|---|---|
Clear |
Clear the terminal screen and reset the cursor to the home position. |
Copy() |
Copy the selected text to the clipboard and clear the selection. Returns False when nothing is selected. |
Paste |
Send the clipboard’s text to the attached connection as if it were typed (new lines as Enter), as Ctrl+V does. With no connection attached it goes to the Send event. |
Poll |
Poll the attached communication channel for incoming bytes and feed them into the ANSI parser. |
ResetColors |
Back to the standard 16 colors. |
SetColor index%, color& |
The color (RGB(), as ForeColor takes it) of text attribute index (0-15, in CGA order: black, blue, green, cyan, red, magenta, brown, light gray, then their bright forms). An index outside 0-15 is ignored. |
Write text$ |
Write a string to the terminal with full ANSI escape processing. Every byte of the string is written, CHR$(0) included (a CHR$(0) itself is padding and shows nothing, as on other terminals), so text read from a connection of the program’s own can be written as it came. A very long text appears over the next few moments, a part at a time, so the program and the rest of DVX keep going; Clear after it still clears all of it. |
3.28.3. Type-Specific Events
| Event | Description |
|---|---|
Bell |
A bell character (BEL, CHR$(7)) arrived. The terminal makes no sound itself: the program decides (Beep, a sound of its own, or nothing). |
Music (Macro As String) |
An ANSI music sequence arrived (Music True): Macro is its PLAY text, to play with PLAY or MusicLoadMacro. |
Send (Bytes As String) |
The terminal has bytes for the host and no connection is attached: the keys the user typed, a paste, or the terminal’s answer to the host asking where the cursor is. A program with a connection of its own (a TCP socket, a modem it drives itself) sends Bytes on. Bytes may hold any character, CHR$(0) included. |
No default event. The common events are raised too.
3.28.4. Serial Communication
The conn.bas library connects a Terminal the way the Terminal program does — a serial port, a modem, the secure link, or Telnet — with capture, answerback, and file transfers (ConnAttach; see Include Libraries). For a packet link of your own, use the comm.bas library:
Dim link As Long
link = CommOpen(1, 115200, 8, "N", 1, SER_HANDSHAKE_NONE)
If link <> 0 Then
If CommHandshake(link, "secret") Then
CommAttach link, "Terminal1", 0, True
Else
MsgBox "Handshake failed"
End If
End If
The passphrase is optional. Both ends must give the same passphrase, or both give none; otherwise CommHandshake returns False. CommAttach, SerAttach, and ConnAttach find the Terminal by its name as a name written alone in the program’s code is found: called from a form’s code, that form’s Terminal; from a module’s, the one loaded form’s that has one (error 1001, Ambiguous control name, when several forms have one). See comm.bas for the full communications API.
3.28.5. A Connection of Your Own
Without an attached connection, Write shows what the program received and the Send event hands over what the terminal would send back:
Sub Sock_Data ()
Terminal1.Write ReceivedText$
End Sub
Sub Terminal1_Send (Bytes As String)
SendToHost Bytes
End Sub
3.28.6. Example
Begin Terminal Terminal1
MinWidth = 640
MinHeight = 400
End
Sub Form1_Load ()
Terminal1.Write "Welcome!" & Chr$(13) & Chr$(10)
End Sub
See also: Common Properties, Events, and Methods (Section 2.2).
3.29. TextArea
VB Equivalent: TextArea (DVX extension) — DVX Widget: textarea (multi-line text input, default max 65536 chars)
A multi-line text editing area. This is a DVX extension with no direct VB3 equivalent (VB uses a TextBox with MultiLine=True). Supports line numbers, auto-indent, find/replace, and tab configuration.
Its font must be fixed-pitch, every character the same width; the designer’s Font dialog offers only those families for it. Given a proportional font it draws in the system font instead.
3.29.1. Type-Specific Properties
| Property | Type | R/W | Description |
|---|---|---|---|
Text |
String |
R/W |
The full text content. Setting it clears the undo history, and fires Change when the text is different, as in Visual Basic (not the text the .frm gives as the form loads). |
CursorLine |
Integer |
R |
Current cursor line number (1-based). |
CursorCol |
Integer |
R |
Current cursor column (1 = the start of the line; a tab counts as one). |
LineCount |
Integer |
R |
The number of lines (an empty text has one). |
SelStart |
Integer |
R/W |
Where the selection starts, or the cursor when nothing is selected (0 = before the first character). Setting it moves the cursor there and selects nothing; past the end of the text it is the end, and below 0 it raises error 380 (Invalid property value). |
SelLength |
Integer |
R/W |
The number of characters selected (0 = none). Setting it selects that many characters from SelStart, as many as there are; below 0 it raises error 380. |
SelText |
String |
R/W |
The selected text. Setting it replaces the selection (or inserts at the cursor when nothing is selected), leaves the cursor after the new text, and fires Change; Undo takes it back. |
MaxLength |
Integer |
R/W |
The most characters the area holds (0 = the default, 65536; at most 262144). A smaller value cuts the text; below 0 it raises error 380. |
DataSource |
String |
R/W |
Name of a Data control for data binding (see Data Binding). |
DataField |
String |
R/W |
Column name for data binding. |
3.29.2. Type-Specific Methods
| Method | Description |
|---|---|
AppendText text$ |
Add text at the end (as much as MaxLength leaves room for). The cursor and the selection stay where they are, Change does not fire, and Undo has nothing to take back (as after setting Text). |
ClearLineMarkers |
Remove every line marker. |
Copy |
Copy the selection to the clipboard (Ctrl+C). |
CursorToEnd |
Put the cursor after the last character, nothing selected. |
Cut |
Copy the selection to the clipboard and remove it (Ctrl+X); fires Change. |
FindNext needle$, caseSensitive, forward |
Search from the cursor and select the match. A forward search finds a match starting at the cursor; repeating it moves on to the next match. Returns True if found. |
GetLine(line%) |
Returns the text of a line (1 = the first) without its line end; "" past the last line. |
GetSyntaxColor(index%) |
Returns the color the syntax coloring draws that kind of text in (index as for SetSyntaxColor); -1 for the area’s ForeColor. |
GetWordAtCursor() |
Returns the word under the cursor. |
GoToLine line% |
Scroll to the given line and select it. |
Paste |
Put the clipboard’s text in place of the selection (Ctrl+V); fires Change. |
ReplaceAll needle$, replacement$, caseSensitive |
Replace all occurrences. Returns count of replacements. |
ReplaceSelection(needle$, replacement$, caseSensitive, forward) |
When the selection is needle$, replace it (Change fires); then find the next needle$ in that direction, as FindNext does. Returns True when it replaced or found something (a Replace button). |
SelectAll |
Select the whole text (Ctrl+A). |
SetAutoIndent enabled |
Enable or disable automatic indentation. |
SetCaptureTabs enabled |
When True, Tab key inserts a tab/spaces (firing Change) instead of moving focus. |
SetCursor line%, col% |
Move the cursor to a line and column (both start at 1) without selecting anything. Values past the end clamp to the text. |
SetLineMarker line%, gutterColor&, backColor& |
Mark a line (1 = the first): a dot of gutterColor in the line-number gutter (a breakpoint) and / or the line’s background in backColor (the current line). -1 leaves that part out; -1 for both removes the marker. Markers stay on their line numbers when the text changes. |
SetShowLineNumbers show |
Show or hide the line number gutter. |
SetSyntaxColor index%, color& |
The color of one kind of text: 0 plain text, 1 keywords, 2 strings, 3 comments, 4 numbers, 5 operators, 6 types (and True, False, Nothing); -1 restores the default. |
SetSyntaxMode mode$ |
Activate syntax highlighting. Modes: "dhs" (help source), "bas" (BASIC, colored as the DVX BASIC IDE colors it), "custom" (the program colors each line in the Colorize event). Pass "" to disable. |
SetTabWidth width% |
Set the tab stop width in characters. |
SetUseTabChar useChar |
When True, Tab inserts a tab character; when False, inserts spaces. |
Undo |
Take back the last change (Ctrl+Z; characters typed one after another are one change); a second Undo puts it back. |
Cut, Paste, and Undo do nothing in a read-only area.
3.29.3. Type-Specific Events
- GutterClick
-
Parameters: LineNumber As Integer. The line-number gutter (shown by SetShowLineNumbers) was clicked beside a line: toggle a breakpoint there. A click in the gutter does not move the cursor.
- Colorize
-
Parameters: LineText As String, Colors As String. With SetSyntaxMode "custom", for every line as it is drawn: Colors comes with one "0" for each character of LineText; set each to the digit of a syntax color (vbSyntaxText 0 to vbSyntaxType 6, colors as SetSyntaxColor sets them). Characters it leaves out stay plain. It runs when a line is drawn with text it has not colored lately (the colors it gave are kept with the text, so a line drawn again unchanged does not ask again), so it must be quick and must not change the area; its colors should depend only on LineText. SetSyntaxMode "custom" again colors every line afresh (after the program changes how it colors).
TextArea1.SetSyntaxMode "custom"
Sub TextArea1_Colorize (LineText As String, Colors As String)
Dim i As Integer
For i = 1 To Len(LineText)
If Mid$(LineText, i, 1) = "#" Then Mid$(Colors, i, 1) = CStr(vbSyntaxComment)
Next
End Sub
Default Event: Change
3.29.4. Example
TextArea1.SetShowLineNumbers True
TextArea1.SetAutoIndent True
TextArea1.SetTabWidth 4
TextArea1.SetCaptureTabs True
' Search for text
If TextArea1.FindNext("TODO", False, True) Then
Print "Found at line"; TextArea1.CursorLine
End If
'' Replace all occurrences
Dim count As Integer
count = TextArea1.ReplaceAll("old", "new", False)
Print "Replaced"; count; "occurrences"
' A code editor: BASIC colors, a breakpoint dot on the clicked line
TextArea1.SetSyntaxMode "bas"
Sub TextArea1_GutterClick (LineNumber As Integer)
TextArea1.SetLineMarker LineNumber, RGB(200, 0, 0), -1
End Sub
See also: Common Properties, Events, and Methods (Section 2.2).
3.30. TextBox
VB Equivalent: TextBox — DVX Widget: textbox (single-line text input, 256 chars unless MaxLength says otherwise) | Name Prefix: Text
A single-line text input field. Supports data binding via DataSource and DataField properties.
Its font must be fixed-pitch, every character the same width; the designer’s Font dialog offers only those families for it. Given a proportional font it draws in the system font instead.
3.30.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Text |
String |
The text content of the input field. Setting it clears the undo history, and fires Change when the text is different, as in Visual Basic (not the text the .frm gives as the form loads). |
MaxLength |
Integer |
The most characters the box holds (0 = the default, 256; at most 32767). A longer text is cut, and typing stops at the limit. A value below 0 raises error 380 (Invalid property value), as in Visual Basic. |
PasswordChar |
String |
"" for a plain box; a character makes it a password box that shows that character for each one typed and does not copy or cut its text. |
Mask |
String |
"" for a plain box; an input mask makes it a masked box: # takes a digit, A a letter, * any character, and every other character of the mask is fixed text the cursor skips (Mask = "(###) ###-####" for a phone number). The text keeps the mask’s shape (empty places show _), and what the box held fills its places in order. Mask = "" makes it a plain box again holding the formatted text, with its MaxLength from before. A masked box is not a password box. |
DataSource |
String |
Name of a Data control for data binding. |
DataField |
String |
Column name for data binding. |
SelStart |
Integer |
Where the selection starts, or the cursor when nothing is selected (0 = before the first character). Setting it moves the cursor there and selects nothing; past the end of the text it is the end, and below 0 it raises error 380 (Invalid property value), as in Visual Basic. |
SelLength |
Integer |
The number of characters selected (0 = none). Setting it selects that many characters from SelStart, as many as there are; below 0 it raises error 380. |
SelText |
String |
The selected text. Setting it replaces the selection (or inserts at the cursor), leaves the cursor after the new text, and fires Change; in a masked box it fills the places from the selection’s start, as pasting does. |
3.30.2. Type-Specific Methods
| Method | Description |
|---|---|
Copy |
Copy the selection to the clipboard (Ctrl+C); a password box copies nothing. |
Cut |
Copy the selection to the clipboard and remove it (Ctrl+X); fires Change. A password box does nothing. |
Paste |
Put the clipboard’s text in place of the selection (Ctrl+V; line breaks are left out); fires Change. |
SelectAll |
Select the whole text (Ctrl+A). |
Undo |
Take back the last change (Ctrl+Z); a second Undo puts it back. |
The methods do what the keys do, so Cut, Paste, and Undo do nothing in a read-only box. An Edit menu works on whichever box has the focus with Me.ActiveControl (see Form).
Default Event: Change
3.30.3. Example
Begin TextBox Text1
Text = "Enter text here"
End
Sub Text1_Change ()
Label1.Caption = "You typed: " & Text1.Text
End Sub
See also: Common Properties, Events, and Methods (Section 2.2); Data Binding (Section 2.4).
3.31. Timer
A non-visual control that fires its event at a regular interval. The Timer widget is invisible at runtime — it has no on-screen representation.
3.31.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Enabled |
Boolean |
True to start the timer, False to stop it. |
Interval |
Integer |
Timer interval in milliseconds. Setting it restarts the countdown. An Interval of 0 disables the Timer event; one below 0 raises error 380 (Invalid property value), as in Visual Basic. (Visual Basic’s most is 65535; DVX takes longer ones.) The PC’s clock moves in ticks of about 55 ms (18 a second), so an interval comes out as whole ticks: 100 fires about every 110 ms, and anything up to 55 about every 55 ms. |
Repeat |
Boolean |
True (the default) to fire every Interval; False for a one-shot timer that fires once and stops itself (Enabled turns False), until Start or Enabled = True runs it again. |
3.31.2. Type-Specific Methods
| Method | Parameters | Description |
|---|---|---|
Start |
(none) |
Start the timer. |
Stop |
(none) |
Stop the timer. |
3.31.3. Type-Specific Events
| Event | Parameters | Description |
|---|---|---|
Timer |
(none) |
Fires each time the interval elapses. This is the default event. A one-shot timer is already stopped when its event runs, so the handler can call Start to run it again. |
|
Note
|
The Timer control fires the Timer event instead of Change. The onChange callback on the underlying widget is remapped automatically. |
3.31.4. Example
Begin Timer Timer1
Interval = 1000
Enabled = True
End
Dim counter As Integer
Sub Timer1_Timer ()
counter = counter + 1
Label1.Caption = "Ticks: " & Str$(counter)
End Sub
See also: Common Properties, Events, and Methods (Section 2.2).
3.32. Toolbar
A horizontal container styled as a toolbar, with compact padding and spacing. Place buttons, labels, or other controls inside.
Container: Yes
3.32.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Alignment |
Enum |
Where the controls sit along the toolbar when they do not fill it: Left (the default), Center, or Right. |
Padding |
Integer |
Space in pixels between the edge of the toolbar and the controls: 2 unless set; 0 is none. |
Spacing |
Integer |
Space in pixels between one control and the next: 2 unless set; 0 is none. |
No type-specific events or methods.
See also: Common Properties, Events, and Methods (Section 2.2).
3.33. TreeView
A hierarchical tree of expandable/collapsible nodes. Supports multi-select and drag-to-reorder. Items are accessed by depth-first index (0-based): an item’s children follow it, before its next sibling. Adding children under an item that has none puts them right after it (index + 1, index + 2, ...), and moves the items after them along.
3.33.1. Type-Specific Properties
| Property | Type | R/W | Description |
|---|---|---|---|
ListIndex |
Integer |
R/W |
Index of the current (selected) node, -1 when none. Setting it selects that node as a click would: its parents are expanded and it is scrolled into view. It raises no event, as setting the selected node from code raises none in Visual Basic. An index there is no node for raises error 380 (Invalid property value), as a ListBox’s ListIndex does. |
3.33.2. Type-Specific Methods
| Method | Description |
|---|---|
AddChildItem parentIndex%, text$ |
Add a child node under the node at the given index. |
AddItem text$ |
Add a root-level node. |
Clear |
Remove all nodes. |
GetItemTag$(index%) |
Returns the text SetItemTag stored on the node ("" when none). |
GetItemText$(index%) |
Returns the text of the node at the given index. |
HasChildren(index%) |
Returns True if the node has nodes under it. |
IsExpanded(index%) |
Returns True if the node at the given index is expanded. |
IsItemSelected(index%) |
Returns True if the node at the given index is selected. |
ItemCount() |
Returns the total number of nodes (all levels). |
ItemDepth(index%) |
Returns how many nodes the node is under: 0 for a root-level node, 1 for its children, and so on. |
ItemParent(index%) |
Returns the index of the node’s parent, or -1 for a root-level node. |
RemoveItem index% |
Remove the node and every node under it. The nodes after them move up. |
SetExpanded index%, expanded |
Expand or collapse the node at the given index. Collapsing a node that hides the current item moves the current item to that node. |
SetItemSelected index%, selected |
Select or deselect the node at the given index. Without multi-select this sets (or clears) the single selected node. |
SetItemTag index%, tag$ |
Keep any text with the node (like VB’s Node.Tag): a file path, a key. "" removes it. |
SetItemText index%, text$ |
Change the text of the node at the given index. |
SetMultiSelect multi |
Enable or disable multi-select mode. Turning it off clears the multi-selection. |
SetReorderable reorderable |
Enable or disable node reordering. |
Every method that takes a node’s index (AddChildItem’s parentIndex% too) raises error 381 (Invalid property array index) for an index there is no node for (below 0, or ItemCount and past), as an indexed property does, and changes nothing; Visual Basic’s TreeView gives its Nodes collection’s error, Index out of bounds, there. ListIndex refuses one with error 380.
3.33.3. Type-Specific Events
| Event | Parameters | Description |
|---|---|---|
NodeClick |
Node As Integer |
The user clicked a node (even the current one), or moved to another node with the keys (Up, Down, Home to the first node, End to the last one shown, Left to the parent, Right to the first child, or a typed letter). Node is the node’s index, as ListIndex numbers it; Visual Basic passes the Node itself. |
Expand |
Node As Integer |
The user opened the node: a click on its expand icon, a double click on the node, Right, or Enter. |
Collapse |
Node As Integer |
The user closed the node: a click on its expand icon, a double click on the node, Left, or Enter. |
Change fires when the user changes the current node (or, with multi-select, the selected nodes), with a click or the keys; a TreeView’s Change is DVX’s own. For a click on a node the events come in this order: MouseDown, Change (only when the current node changed), NodeClick, Click, and MouseUp; a click on an expand icon raises Expand or Collapse in NodeClick’s place, and moves the current node only when collapsing hid it. A double click on a node that has nodes under it opens or closes the node, as a Windows TreeView does: the first click is a click as above, the second raises Collapse or Expand, then DblClick (on a node without nodes under it, DblClick alone). A click in the empty space below the nodes raises Click alone, and a click on a scroll bar raises nothing, as in Visual Basic. The keys raise Change, NodeClick, Expand, and Collapse, never Click, which is the mouse’s. A change the program’s code makes (ListIndex, SetItemSelected, or SetExpanded) raises no event, as in Visual Basic. The mouse wheel scrolls the tree without moving the current node: it raises Scroll, not Change or NodeClick.
Default Event: Click
3.33.4. Example
TreeView1.AddItem "Animals"
TreeView1.AddChildItem 0, "Cat"
TreeView1.AddChildItem 0, "Dog"
TreeView1.AddItem "Plants"
TreeView1.AddChildItem 3, "Oak"
TreeView1.SetExpanded 0, True
Print "Items:"; TreeView1.ItemCount()
See also: Common Properties, Events, and Methods (Section 2.2).
3.34. VBox
A container that arranges its children vertically, top to bottom. No title or border. Use Weight on children to distribute extra space proportionally.
3.34.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Alignment |
Enum |
Where the children sit along the column when they do not fill it: Left (the top, the default), Center, or Right (the bottom). |
Padding |
Integer |
Space in pixels between the edge of the box and the children: 4 unless set; 0 is none. SizePercent (layout.bas) makes it a percentage of the box’s width. |
Spacing |
Integer |
Space in pixels between one child and the next: 4 unless set; 0 is none. SizePercent (layout.bas) makes it a percentage of the box’s width. |
No type-specific methods or events.
Container: Yes
Default Event: Click
3.34.2. Example
Begin VBox Column1
Spacing = 4
Begin Label Label1
Caption = "Name:"
End
Begin TextBox Text1
End
End
See also: Common Properties, Events, and Methods (Section 2.2); HBox (Section 3.8).
3.35. WrapBox
A container that arranges children in a flowing layout, wrapping to the next row when the available width is exceeded. Similar to CSS flexbox with flex-wrap: wrap.
3.35.1. Type-Specific Properties
| Property | Type | Description |
|---|---|---|
Alignment |
Enum |
Horizontal alignment of items: Left, Center, or Right. |
Padding |
Integer |
Space in pixels between the edge of the box and the items: 2 unless set; 0 is none (pixels only: a SizePercent counts as 0, the box’s height coming from its rows). |
Spacing |
Integer |
Space in pixels between one item and the next, and between rows: 4 unless set; 0 is none (pixels only, as Padding). |
Container: Yes
Default Event: Click
See also: Common Properties, Events, and Methods (Section 2.2).
Chapter 4. The DVX BASIC IDE
4.1. DVX BASIC IDE Guide
DVX BASIC is a BASIC development environment for DVX. It provides a VB3-style integrated development environment with a code editor, form designer, project system, and a full interactive debugger — all integrated into DVX itself.
This guide covers every feature of the IDE: menus, toolbar, editor, form designer, project management, debugger, and auxiliary windows.
4.1.1. IDE Windows
The DVX BASIC IDE is modeled after Visual Basic 3.0. It consists of several floating windows arranged on the DVX desktop:
-
Main Toolbar Window — anchored at the top of the screen. Contains the menu bar, toolbar buttons, and status bar.
-
Code Editor — the primary editing surface for BASIC source code, with Object/Event dropdowns, syntax highlighting, and line numbers.
-
Form Designer — a visual design surface for .frm files, showing a WYSIWYG preview of the form with grab handles for resizing controls.
-
Project Explorer — a tree view listing all files in the project.
-
Toolbox — a palette of available controls for placing on forms.
-
Properties Panel — a tree of controls and a list of editable properties for the selected control.
-
Output Window — displays PRINT output and runtime errors.
-
Immediate Window — an interactive REPL for evaluating expressions and modifying variables at runtime.
-
Debug Windows — Locals, Call Stack, Watch, and Breakpoints windows that appear automatically when debugging.
The IDE compiles BASIC source into bytecode and runs it in an integrated virtual machine. Programs execute in cooperative slices, yielding to DVX between slices so DVX remains responsive. The program’s own events wait until the code that is running ends or calls DoEvents, as in Visual Basic, so a long-running loop that should answer its own buttons calls DoEvents now and then.
See also: Edit Menu (Section 4.1.3); Run Menu (Section 4.1.4); View Menu (Section 4.1.5); Window Menu (Section 4.1.6); Tools Menu (Section 4.1.7); Help Menu (Section 4.1.8); Toolbar (Section 4.2); Code Editor (Section 4.3); Form Designer (Section 4.4); Project System (Section 4.5); Properties Panel (Section 4.8); Toolbox (Section 4.9); Debugger (Section 4.10); Locals Window (Section 4.10.6); Call Stack Window (Section 4.10.7); Watch Window (Section 4.10.8); Breakpoints Window (Section 4.10.9); Immediate Window (Section 4.11); Output Window (Section 4.12); Find / Replace (Section 4.13); Preferences (Section 4.14); Keyboard Shortcuts (Section 4.15).
4.1.2. File Menu
- New Project...
-
Create a new DVX BASIC project, with its first form, Form1 (see Project Operations under Project System).
- Open Project...
-
Open an existing .dbp project file.
- Save Project
-
Save the current project file to disk.
- Close Project
-
Close the current project (prompts to save unsaved changes; Don’t Save also discards unsaved Project Properties changes).
- ---
- Project Properties...
-
Edit project metadata (name, author, version, startup form, icon, etc.) and the command line arguments used when the program is run from the IDE.
- ---
- Add File...
-
Shortcut: Ctrl+O. Add a .bas, .frm, .cls, or .ctl file to the project. The dialog starts in the project’s folder, where its files must be. A name that is no file yet makes a new, empty one, after "Do you want to create it?". If no project is open, creates an implicit project from the file. A file that cannot be read, or is 64 KB or larger, is refused with a message.
- Add Library...
-
Add one of the include libraries that come with DVX BASIC (commdlg.bas, sql.bas, sound.bas, ...: see Include Libraries in the language reference) to the project. The list names each with its title; the library is copied from DVX BASIC’s INCLUDE folder into the project’s folder, so the project keeps working wherever it is copied, and the file you were working on stays in front (the library is listed under Modules in the Project window). A file of that name already in the project’s folder is replaced only after "Replace it with DVX BASIC’s copy?" (No adds that file as it is); a library already in the project is left as it is.
- New Form
-
Add a new, blank form (Form1.frm, Form2.frm, ...: the first name the project does not use) to the project and open it in the Form Designer.
- New Module
-
Add a new module (Module1.bas, Module2.bas, ...) holding only Option Explicit to the project and open it in the Code Editor.
- New Class Module
-
Add a new, empty class module (Class1.cls, Class2.cls, ...) to the project and open it in the Code Editor. See Class Modules under Project System.
- New UserControl
-
Add a new UserControl, a control of your own (UserControl1.ctl, UserControl2.ctl, ...), to the project and open it in the Code Editor. See UserControls in the IDE.
- Save File
-
Shortcut: Ctrl+S. Save the active file to disk.
- Save All
-
Save all modified files in the project.
- ---
- Make Executable...
-
Compile the project and save it as a standalone .app file (the Save dialog suggests one named after the project file, in capitals, such as TODO.APP, in the project’s folder), with the help file and the project’s DATA folder next to it. Prompts for a debug or release build. A release build leaves out debugging information and gives forms and controls short internal names, except in a program that uses names as text (the Name property, Controls, DesignSelection, or a DesignMouse event procedure), which keeps them.
- Make Control...
-
In a control project (Project Properties, Type Control) this item replaces Make Executable: it compiles the project and saves its controls as a control file (.wgt, named after the project). See UserControls in the IDE.
- Make Package...
-
Make the program (or, in a control project, the control file) and its help file into an add-on package (.DPK) that anyone can install with Software. See Making a Package.
- ---
- Rename File...
-
Give the file selected in the Project Explorer a new name, on disk and in the project. See Renaming a File under Project System.
- Remove File
-
Remove the selected file from the project (prompts to save if modified).
- ---
- Exit
-
Close the IDE (prompts to save unsaved changes).
A project (.dbp) or source file (.bas, .frm, .cls, .ctl) named on the IDE’s command line opens when the IDE starts, so double-clicking one in the File Manager, or starting it from the Program Manager, opens it in the IDE.
Files are saved exactly as edited (LF line endings). Each save writes a temporary file first and replaces the original only when the write succeeded. Opening a project that fails to load keeps the current project open and removes the failed entry from the Recent list.
4.1.3. Edit Menu
Cut, Copy, Paste, Select All, and Delete act on the window you last worked in: the form designer’s selected control, or the text of the code, output, or immediate window.
4.1.4. Run Menu
4.1.5. View Menu
4.1.6. Window Menu
4.2. Toolbar
The toolbar is organized into four groups separated by vertical dividers. Each button has a tooltip showing its name and keyboard shortcut.
4.2.1. File Group
| Button | Shortcut | Action |
|---|---|---|
Open |
(none) |
Open a project (same as File > Open Project...). |
Save |
Ctrl+S |
Save the active file. |
4.2.2. Run Group
| Button | Shortcut | Action |
|---|---|---|
Run |
F5 |
Compile and run the program. |
Stop |
Esc |
Stop the running program. |
4.3. Code Editor
The Code Editor is the primary editing window for BASIC source code. It occupies the center of the screen, below the toolbar and above the Output and Immediate windows.
4.3.1. Object and Function Dropdowns
At the top of the Code Editor are two dropdown lists:
-
Object — lists (General) plus all objects (form name, control names, menu item names, and the WithEvents variables the file declares). Selecting an object filters the Function dropdown.
-
Function — lists all event handlers (procedures) for the selected object. Implemented handlers are listed first (plain text); unimplemented handlers follow in brackets (e.g., [Click]). Selecting an unimplemented event creates a new event handler stub, with the caret on its empty line. Only the events the object can get are listed: Paint, for example, appears for the form and for PictureBoxes, the objects a program draws on. Under (General) are the file’s own Subs, Functions, and property procedures, a property procedure with its kind after its name, as Visual Basic lists them (Size [PropertyGet], Size [PropertyLet]).
A WithEvents variable (Dim WithEvents acct As Account, also Private or Public, in a module, a form, or a class module) is listed as an object; its events are the ones its class module declares with Event — or, for one declared As a control type (As TextBox) or As a form (As Form2, As Form), the control’s or the form’s events. Picking one of them creates the handler acct_EventName with the event’s own parameters, so it matches what the object raises. Selecting the variable when it has no handler yet creates the handler for the class’s first event, or for the default event of the control type or form (Change for a TextBox, Load for a form), as a control’s default event is created.
The editor shows one procedure at a time. Each procedure has its own buffer, and switching between them is instantaneous. The (General) section contains module-level declarations and code.
To add a procedure, type its first line in (General), or below the End line of the procedure shown — Sub Greet, Function Total(n As Long) As Long, or Property Get Size, with Public, Private, or Static in front if you like — and press Enter. As in Visual Basic, the IDE makes it a procedure of its own: it adds () when the line has no parameter list, an empty line, and End Sub (or End Function, End Property), shows it, and puts the caret on the empty line. The Function list then names it.
Text outside the procedure being shown is never lost: lines typed above or below the SUB move to (General), a second SUB typed into the buffer becomes a procedure of its own, and a procedure whose SUB line was deleted becomes (General) text. When you leave an event handler that was generated and never edited it is removed; empty SUBs and FUNCTIONs you wrote yourself are kept. After a save the editor shows exactly what was stored (blank lines around a procedure are normalized). A section too large for the editor opens read-only, with a message in the status bar.
4.3.2. Syntax Highlighting
The editor applies real-time syntax coloring as you type. Seven categories are highlighted in distinct colors; the colors themselves are editable in Tools > Preferences > Colors.
| Category | Examples |
|---|---|
Default Text |
Identifiers, whitespace. |
Keywords |
IF, THEN, FOR, NEXT, SUB, FUNCTION, DIM, PRINT, SELECT, CASE, DO, LOOP, WHILE, WEND, END, EXIT, CALL, GOSUB, GOTO, RETURN, DECLARE, CONST, TYPE, AND, OR, NOT, XOR, MOD, etc. |
Types |
INTEGER, LONG, SINGLE, DOUBLE, STRING, BOOLEAN, DATE, VARIANT, OBJECT, COLLECTION, TRUE, FALSE, NOTHING, EMPTY, NULL |
Strings |
"Hello, World!" |
Comments |
' This is a comment, REM This is a comment |
Numbers |
42, 3.14, &HFF, date literals such as #2026-09-30# and #1/15/2026 10:30 AM# |
Operators |
=, <, >, +, -, *, /, \, & |
Date literals are colored as numbers only when they are real dates, as the compiler reads them; the # of a file number (CLOSE #1) is not. Some words are colored like keywords without being reserved — built-in type names, Empty, Null, EACH, EVENT, WITHEVENTS, and the console and graphics statements such as CLS, LOCATE, COLOR, SCREEN, PSET, CIRCLE, PAINT, PCOPY, and PMAP. A program may use them as its own names, and after a dot (Text1.Width, Picture1.Point) they are shown as ordinary names.
4.3.3. Editor Features
-
Line numbers — displayed in the gutter on the left side.
-
Auto-indent — new lines are automatically indented to match the previous line.
-
Tab handling — the Tab key is captured by the editor. Tab width and whether to insert spaces or tab characters are configurable in Preferences (default: 3 spaces).
-
Gutter click — clicking in the line number gutter toggles a breakpoint on that line.
-
Line decorations — breakpoint lines show a red dot in the gutter. The current debug line (when paused) is highlighted with a yellow background.
4.4. Form Designer
The Form Designer provides a visual design surface for editing .frm files. Switch to it with Shift+F7 or the Design toolbar button. It opens in a separate window showing a WYSIWYG preview of the form.
4.4.1. Design Surface
-
Grid snapping — controls snap to an 8-pixel grid when placed or resized.
-
Selection — click a control to select it. The selected control is highlighted with grab handles.
-
Grab handles — 6x6 pixel handles appear on the right edge (E), bottom edge (S), and bottom-right corner (SE) of the selected control. Drag a handle to resize the control: E and SE set its MinWidth, S and SE its MinHeight, each in the kind of size it already has, as Visual Basic gives a dragged size in its container’s scale. Pixels stay pixels (at least 8), a percentage stays a percentage of the container’s inside (to the nearest whole percent), and characters stay characters of the control’s font (to the nearest whole character); a size not set yet becomes pixels. The Properties window shows the new size the same way.
-
Reordering — drag a control to reorder it among its siblings in the layout (VBox/HBox). A container moves together with its contents.
-
Placing controls — select a control type in the Toolbox, then click on the form to place a new instance. The control is auto-named as in Visual Basic (Command1, Command2, Text1, Label1, Check1, List1, Combo1; the other types by their type name, as Timer1), skipping names already used by a control, a menu item, or the form, and shows its name as its Caption (a control made with one, as a CommandButton, Label, CheckBox, or Frame, or one with a Caption of its own, as a Data control), or as its Text for a TextBox, TextArea, or ComboBox; a ListBox, a Timer, and the other controls show none. Clicking the same tool again deselects it (toggles back to pointer mode). Controls nest at most 15 levels deep; a drop into a container that is already that deep goes into its parent container.
-
Menu bar preview — if the form has menu items (defined via the Menu Editor), a preview menu bar is rendered on the design window.
-
Delete key — removes the selected control and everything inside it.
-
The tray — a control with nothing to see while the program runs, such as a Timer, shows in a small window below the design window, the form’s tray, as its Toolbox picture with its name under it. Click it to select it (the Properties window shows it), double-click it to open its default event’s code, and press Delete to remove it. The form keeps in the designer the layout it has when the program runs. The tray is there while the form has such a control; closing it hides it until the form’s controls change.
Opening a form in the designer does not mark it modified. A control whose Visible property is False is still shown on the design surface (the setting applies when the program runs). Disabling a container grays the controls inside it; a control’s own Enabled = False is kept when the container is enabled again. A .frm file without an AutoSize line opens without AutoSize; AutoSize = True wins over Width and Height lines. Text values (Caption, Text, and so on) are limited to 379 characters.
4.4.2. Menu Editor
The Menu Editor (View > Menu Editor, Ctrl+E) edits the active form’s menu bar and popup menus. Menus nest at most 15 levels (0-14); indenting refuses when any item below would go deeper. OK rejects an item nested more than one level below the item above it, and a blank item that has sub-items (it must be named); blank items without sub-items are dropped. The window’s close box cancels. Shortcut is a key that runs the item (F2, Ctrl+X, Alt+Enter ...), shown at its right; Text is key text shown without making a shortcut (see Menu Item Properties); OK rejects a Shortcut it does not know. Index makes the item an element of a menu control array: give the items of the array the same Name and each its own Index (0 to 32767), next to each other in one menu, as in Visual Basic’s Menu Editor; OK rejects one without an Index, an Index used twice, elements apart, and an Index on a menu of the menu bar or a popup menu. Visible unticked hides an item until the program sets its Visible to True (a recent-files list’s separator); on a top-level menu, Popup makes it a popup menu instead. Renaming a menu item renames its event handlers in the code and updates the ContextMenu setting of the form and its controls; inserting, deleting, and moving items does not rename anything. Enter clicks OK (unless a button has the focus) and Esc Cancel, as in a dialog box.
4.4.3. Form Properties
Forms have the following design-time properties: Name, Caption, Width, Height, Left, Top, Layout (VBox or HBox), Centered, AutoSize, Resizable, HelpTopic, ContextMenu, and the font (the Font row; see Properties Panel). A form is resizable unless Resizable is False, as in Visual Basic, and the .frm always records which.
See also: Properties Panel (Section 4.8); Toolbox (Section 4.9).
4.5. Project System
4.5.1. Project Files (.dbp)
-
Name — the project display name (up to 32 characters).
-
Startup Form — which form to show automatically when the program starts.
-
Metadata — Author, Company (the Publisher key), Version, Copyright, Description (a single line), and Icon Path (for compiled binaries), and the rest of the program’s version information, which the App object gives the running program: the [Project] keys Version (App.Major, App.Minor, App.Revision: "2.10.7" gives 2, 10, and 7), Publisher (App.CompanyName), Description (App.FileDescription), Copyright (App.LegalCopyright), Trademarks (App.LegalTrademarks), Product (App.ProductName; none: the Name), and Comments (App.Comments). App.Title starts as the Name.
-
Arguments — the command line the program gets (COMMAND$) when it is run from the IDE, for trying out a program that opens the file it is given. It is not built into the compiled program: there COMMAND$ returns whatever the program was started with.
-
More Than One Copy — "Allow more than one copy to run at once" ([Settings] MultiInstance = True): the compiled program can be started again while it is running, and each copy runs on its own (like the Clock and the File Manager). Without it, starting the program again only says that it is already running.
-
Help File — a compiled help file (.hlp) for the program. It is copied next to the compiled program, and F1 in the running program opens it, at the HelpTopic of the focused control or, failing that, of the form. Add help.bas to the project and call HelpView to open it from a Help menu.
-
Type — what the project makes: a program (an .app, the default) or, with Type = Control, a control file (a .wgt holding the project’s UserControls for every program). See UserControls in the IDE.
-
File list — relative paths of all the project’s files: modules (.bas) in the [Modules] section, class modules (.cls) in the [Classes] section, UserControls (.ctl) in the [Controls] section, and forms (.frm) in the [Forms] section.
-
Fonts — the .DFN fonts the program carries, in the [Fonts] section (see Fonts a Program Carries).
-
Resources — the files the program carries as resources, and its string table, in the [Resources] section (see Resources a Program Carries).
The file sections all have the same shape: one FileN line per file, numbered from 0, and a Count line:
[Modules]
File0 = main.bas
Count = 1
[Classes]
File0 = account.cls
File1 = ledger.cls
Count = 2
[Forms]
File0 = form1.frm
Count = 1
4.5.2. Fonts a Program Carries
A program can carry fonts of its own, so its text looks the same whatever fonts were installed. In Project > Properties, Add... in the Fonts row picks a .DFN font (one outside the project’s directory can be copied into it); Remove takes the chosen one off the list (the file stays). The fonts are listed in the [Fonts] section of the project file. Make builds them into the program as font resources, and the program has them whenever it runs; running it from the IDE gives it the same fonts until it stops. A program carries at most 64 fonts.
A program’s fonts are its own: other programs never see them. Where a font it carries is of a family that is installed too, its sizes and styles come first and the installed family fills in the rest. Fonts are made with the SDK’s mkfont from TrueType, Type 1, and bitmap fonts — one size and only the characters the program uses keeps a font small — or copied from DVX’s FONTS folder. Each .DFN carries the notice and license of the font it was made from.
4.5.3. Resources a Program Carries
A program can carry files of its own — pictures, levels, sounds, any bytes — and a string table of the texts it shows, as a Visual Basic program carries its resource file. On the Resources page of Project Properties, Add... in the Files row picks a file (one outside the project’s directory can be copied into it) and Remove takes the chosen one off the list (the file stays); String Table names a text file of id = text lines (Browse... picks it). They are listed in the [Resources] section of the project file:
[Resources]
File0 = logo.bmp
File1 = levels/level1.dat
Strings = strings.txt
The program reads them with LoadResPicture, LoadResData, and LoadResString (see Program Resources in the language reference). A file is found by its name without the extension ("Logo" finds logo.bmp), so two files cannot share a name, and the name has at most 27 characters; Add... and Make refuse a file that breaks either rule. Make builds the files and the string table into the program, which then needs nothing else to find them; running it from the IDE reads them from the project’s folder, so a changed file is seen at the next run. A program carries at most 128 resource files.
4.5.4. How Projects are Compiled
When the project is compiled, all source files are concatenated into a single source stream: the modules first, then the class modules, then the UserControls, then the forms. The IDE tracks which lines belong to which file so error messages and debugger locations point to the correct .bas, .cls, or .frm file. The code section of each .frm file is preceded by a hidden BEGINFORM marker that ties its code to its form, and the code of each class module and UserControl is likewise marked with its class name; the header lines of a class module or UserControl are not compiled.
4.5.5. Compile-Time Validation
Before the source is handed to the compiler, the IDE scans every .frm file and cross-checks the forms against the widget registry and the statements that reference them. Three classes of error are caught and reported without producing a binary:
-
Unknown widget types — any Begin TypeName ... End block whose TypeName does not match a registered widget is flagged. The error message names the offending form, control, and type, and hints that DVX uses VB6-style names (SpinButton, not Spinner).
-
Unknown properties — statements of the form CtrlName.Property = value, or reads of CtrlName.Property, are checked against the widget’s declared property list. A typo such as btn.Captoin triggers a compile error with the form, control, and property name. A control name that is used with different types on different forms is not checked.
-
Unknown methods — method calls CtrlName.Method ... are checked the same way against the widget’s method list, catching mistakes like list.AddTiem before the program ever runs.
-
Menu items — only Name (read), Checked, and Enabled can be used on a menu item in code; Caption, Visible, RadioCheck, Shortcut, and ShortcutText are design-time settings.
These checks use the same metadata the Properties panel and Toolbox read from each installed control, so property and method names always match the current widget set without any separate list to maintain.
4.5.6. Project Operations
- New Project
-
Asks the project’s name, then where to save it: the Save dialog suggests a folder of its own for it, made in the PROJECTS folder of your user folder (USER\PROJECTS), and a project file named after it, both with a DOS name made from the project’s name (My First Program: MYFIRSTP\MYFIRSTP.DBP; MYFIRST2 when that folder is taken). Enter takes the suggestion; pick another folder and the one made for it is removed again. The project starts with one form, Form1 (Form1.frm, its startup form), open in the Form Designer.
- Open Project
-
Opens a .dbp file and loads all referenced files into memory. A project file that is 64 KB or larger, or cannot be read, is not loaded; opening it later reports "Cannot load <file>: unreadable or larger than 65535 bytes." Carriage returns are removed when files are loaded.
- Save Project
-
Writes the .dbp file to disk.
- Close Project
-
Closes the project, prompting to save unsaved changes.
- Add File
-
Adds a .bas, .frm, .cls, or .ctl file to the project. Opening a file without a project auto-creates an implicit project.
- Add Library
-
Copies one of the include libraries that come with DVX BASIC into the project’s folder and adds it to the project as a module (see the File menu).
- New Form
-
Adds a new, blank form to the project and opens it in the Form Designer.
- New Module
-
Adds a new module to the project and opens it in the Code Editor.
- New Class Module
-
Adds a new class module to the project and opens it (see Class Modules below).
- New UserControl
-
Adds a new UserControl to the project and opens it (see UserControls in the IDE).
- Rename File
-
Gives a file a new name on disk and in the project file (see Renaming a File below).
- Remove File
-
Removes a file from the project, after asking "Remove ... from the project?"; a file with changes not saved yet then asks "Save changes?" in a box titled with its name (No removes it without saving; it stays on the disk as it was). Removing the startup form clears the Startup Form setting.
- Project Properties
-
Opens a dialog with four pages: General (name, type, startup form, icon, help file, the fonts the program carries, OPTION EXPLICIT, whether more than one copy may run at once, and the Arguments for runs from the IDE), Make (the program’s version information: Version, Author, Publisher, Copyright, Trademarks, Product, Description, and Comments, which the App object gives the program), Resources (the files the program carries and its string table: see Resources a Program Carries), and Package (the Package and Needs that File > Make Package uses). Enter clicks OK and Esc Cancel, as in a dialog box.
4.5.7. Renaming a File
Select a file in the Project Explorer and choose File > Rename File. Type the new file name; the extension may be left out (a module stays .bas, a class module .cls, a UserControl .ctl, and a form .frm, and cannot be given another kind’s extension). The file is renamed in the project’s directory and the project file is saved at once with the new name, so the two always agree. Nothing changes, and a message says why, when the name is not a valid file name, when another project file or any file in the directory already has it, or when the file or the project file cannot be written — an existing file is never overwritten. A file that has never been saved is simply given the new name, and is written under it when you save.
A class module named after its file (it has no Attribute VB_Name line, or one that matches the file name, as File > New Class Module writes it) takes the new name as its class name: its Attribute VB_Name line is changed to match (an edit that is saved with the file, like any other). The new name must then be a valid name that no other form, class module, or UserControl uses. Code that uses the old class name is not changed. A UserControl named after its file (as File > New UserControl makes it) takes the new name too, on its Begin UserControl line; forms that use the old name are not changed. A module without an Attribute VB_Name line is named after its file, so it takes the new name (code that uses the old one, Old.Count, is not changed). A form keeps its Name property; rename the form itself in the Properties window.
4.5.8. Project Explorer
The Project Explorer is a tree view window listing all project files, in four groups: Forms, Modules, Classes, and Controls (UserControls). Double-click a file to open it: .bas, .cls, and .ctl files open in Code view, .frm files open in Design view. The selected file in the Project Explorer determines the target for View > Code and View > Designer commands.
4.5.9. Class Modules
A class module (.cls file) defines a kind of object for your program: its member variables, properties, and methods. The BASIC Language Reference describes how to write one (see Objects and Class Modules); this section covers working with them in the IDE.
-
Create — choose File > New Class Module. The IDE adds a new class module named Class1 (Class2, and so on, when that name is taken) to the Classes group, saved in the project’s directory as Class1.cls, and opens it in the Code Editor. The new file holds only its header and Option Explicit; it is written to disk when you save it.
-
Add an existing one — choose File > Add File and pick a .cls file (the Class Modules file type). Class files from Visual Basic can be added as they are.
-
Open — double-click it in the Project Explorer’s Classes group. It opens in Code view; a class module has no designer.
-
Save — File > Save File or Save All, as for any other file. The project file lists class modules in its [Classes] section.
-
Remove — select it in the Project Explorer and choose File > Remove File. The file itself stays on disk.
-
Rename — a class’s name is the one in its Attribute VB_Name line, not the file name. File > Rename File renames the file, and a class named after its file (as a new class module is) takes the new name too; see Renaming a File. To give a class a name different from its file, change its Name in the Properties window (and the code that uses the old name) and save: the IDE writes it in the file’s Attribute VB_Name line. A class module without an Attribute VB_Name line takes its name from the file name.
A new class module’s file starts with these header lines:
VERSION DVX 1.00 CLASS
Attribute VB_Name = "Class1"
Option Explicit
As in Visual Basic, the Code Editor shows the code alone (here Option Explicit): the VERSION and Attribute lines stay with the file, and the class’s Name is in the Properties window while the class module is the active file. A module’s Attribute VB_Name line (a Visual Basic .bas file’s first line) is kept the same way, and a module’s Name is in the Properties window too; giving a module another name than its file’s writes such a line. Line numbers, errors, and breakpoints count the code’s lines. Each class name must be different from the other class names, the UserControl names, and the form names in the project.
See also: UserControls in the IDE (Section 4.7).
4.6. Making a Package
File > Make Package turns the project into an add-on package: one .DPK file holding the program (built as a release build), its help file, and its DATA folder (the files App.Data finds), which anyone can install with the Software program — it puts the program in Program Manager’s Installed Programs — and remove again. In a control project the package holds the control file instead, and installs it for every program to use.
The first time, Make Package asks for the package name: who made it and what it is, with a dot between them, such as acme.chess (each part 1 to 8 lower-case letters, digits, or _). It suggests one from the project’s Publisher and Name. Keep the same package name for every version, so that Software installs a new version over the old one. The name is kept in the project and can be changed under File > Project Properties (Package).
It then asks where to save the package (suggesting a file named after the package, such as CHESS.DPK, in the project’s folder) and which key to sign it with. Signing tells the people who install the package that it came from you and was not changed on the way; the list offers the keys in your KEYS folder (make one with Package Builder’s New Key) and Not signed. The key chosen is offered first the next time.
The package takes the rest from the project: its name, Version (give each version you hand out a higher one, such as 1.0.0, then 1.1.0), Description (shown as its summary), Publisher, and Author. When the program needs other add-on packages to work, list them under Project Properties, Needs: each package name with the oldest version that will do, with commas between them, such as acme.cards 1.0, acme.dice 2.1 (a package name alone takes any version). DVX’s own libraries need not be listed.
A program that puts files in other folders of DVX than its own is packaged with Package Builder, which takes a whole folder laid out like DVX’s.
See also: Project System (Section 4.5).
4.7. UserControls in the IDE
A UserControl is a control you write in BASIC (see UserControls: Your Own Controls in the BASIC Language Reference for how to write one). This topic covers making one in the IDE, editing it, trying it on a form, and turning it into a control file every program can use.
4.7.1. Making a UserControl
Choose File > New UserControl. The IDE adds a new UserControl named UserControl1 (UserControl2, and so on, when that name is taken) to the project’s Controls group, saved in the project’s directory as UserControl1.ctl, and opens it in the Code Editor. It is written to disk when you save it. A new UserControl’s file starts like this:
VERSION DVX 1.00
Begin UserControl UserControl1
Width = 64
Height = 64
End
Option Explicit
Private Sub UserControl_Paint ()
End Sub
The lines up to End are the control’s header; the code follows. As in Visual Basic, the Code Editor shows the code alone: the header is changed in the Properties window (below), and line numbers, errors, and breakpoints count the code’s lines. To use a .ctl file you already have, choose File > Add File and pick it (the UserControls file type). Open, save, rename, and remove .ctl files as you do class modules: a UserControl named after its file takes the new name when the file is renamed.
4.7.2. Writing the Code
In the Code Editor, the Object list of a UserControl holds UserControl (the control itself) beside (General). Its Function list has the events the control gets: Initialize, Terminate, Resize, Paint, Click, DblClick, MouseDown, MouseMove, MouseUp, MouseWheel, KeyDown, KeyPress, KeyUp, GotFocus, and LostFocus. Picking one that has no code yet writes its procedure with the right parameters, for example:
Private Sub UserControl_MouseDown (Button As Integer, Shift As Integer, _
X As Single, Y As Single)
End Sub
These procedures are Private: a Public one would be a method of the control.
4.7.3. The Header in the Properties Window
While a UserControl is the active file, the Properties window shows its header instead of a form’s controls: Name, Width, Height, CanGetFocus, BackColor, ToolboxIcon, Description, and DefaultEvent, each with the value the control takes (its default when the header leaves it out). Double-click a row to change it:
| Row | How it is changed |
|---|---|
Name |
Type a new name. It must be a valid name that no form, class module, or other UserControl of the project uses. Forms that use the old name are not changed. |
Width, Height |
Type the control’s natural size as a size row takes it: pixels (120), a percentage of the container the control is placed in (50%), or characters of its font (20ch); nothing at all removes the line, and the default, 64 pixels, applies. Anything else (12px, 50 %, a size below 0, a percentage above 100) is refused with a message. |
CanGetFocus |
Each double-click switches between True and False. |
BackColor |
Pick a color in the color dialog. |
ToolboxIcon |
Type the name of a 24 x 24 picture file in the project’s folder, or click Browse... to pick it. |
Description |
Type the toolbox tooltip. |
DefaultEvent |
Pick one of the control’s Events (or none): the event the designer opens when a placed control is double-clicked. |
The change is written into the header lines of the file (the rest of the file stays as it is) and saved with the file. The Code Editor shows the new header; breakpoints in the code move with the lines below it. You can also edit the header lines in the Code Editor by hand.
4.7.4. Trying It on a Form
While the project is open, its UserControls are in the Toolbox like the controls DVX comes with: with the picture of their ToolboxIcon (or a plain control picture when they have none), and their Description (or their name) as the tooltip. Place one on a form as any other control; it starts at the natural size of its header’s Width and Height. The control on the design surface is a real one: its code runs, with UserControl.UserMode False, so Initialize, Resize, and Paint draw it as it will look, while your clicks and keys go to the designer.
-
The Properties window lists the control’s properties that can be set (its Public variables and Property Let procedures), with the values its code gives them. A value you change there is passed to its Property Let and saved in the .frm; when the control’s code calls UserControl.PropertyChanged, the window shows the new values.
-
The Code Editor’s Function list for the placed control has the events the control raises, then the events a form gets for any of its controls (GotFocus, LostFocus, Validate, DragDrop, and DragOver); picking one writes its handler with the event’s parameters (Sub Gauge1_Changed (ByVal Level As Integer)).
-
Double-clicking the control on the design surface opens its DefaultEvent’s handler.
The designer compiles the project’s UserControls (with its modules and class modules, but not its forms) when the project opens and again when a .ctl file is saved, added, removed, or renamed, or its header is changed in the Properties window; the controls on the design surface are made again then. While the controls have a compile error the designer cannot show them (the status line says so); compile with F5 to see the error. The code of the project’s modules (outside their procedures) does not run in the designer, so module variables start empty there. A UserControl whose name is the name of a control installed for every program cannot be shown in the designer, and the program stops when it is run ("Control cannot be registered"): give it another name.
When the program runs, its UserControls are its own: they are registered again for the program, separately from the copies in the designer.
4.7.5. Control Projects and Make Control
A project whose controls every program should be able to use is a control project: in File > Project Properties set Type to Control. A control project needs no forms. File > Make Executable becomes File > Make Control: it compiles the project, asks where to save the control file (the project’s name with .wgt) and for a debug or release build, and writes the file — the same file the BASIC compiler makes from the project. Run (F5) only compiles a control project: it is not a program.
To install the control file, copy it into DVX’s WIDGETS folder (in a folder of its own, like the controls DVX comes with). When DVX starts next, every program can use its controls, and the Toolbox shows them with their ToolboxIcon pictures and Descriptions.
A program project can hold UserControls too (list them under Controls): the program built from it (Make Executable) carries them, and only that program uses them.
See also: UserControls: Your Own Controls (Section 2.8); Project System (Section 4.5).
4.8. Properties Panel
-
Control tree — a TreeView at the top listing the form and all its controls in layout order. Click a control name to select it in both the Properties panel and the Form Designer. Drag items in the tree to reorder controls in the form’s layout.
-
Property list — a two-column ListView below the tree showing property names and values for the selected control: Name first, then the rest in alphabetical order, as in Visual Basic. Type a letter to go to the next property that starts with it (T for Text). The property selected stays selected when you choose another control that has it, so Caption can be set on one button after another; otherwise the first row is selected. Double-click a property (or select it and press Enter) to edit its value via an InputBox dialog, which starts with the value selected, so typing replaces it. A True or False property (Default, Enabled) switches to the other value instead, and a property with a list of values (Alignment, BorderStyle) goes on to its next one, back to the first after the last. A TextBox, TextArea, or Label has DataSource and DataField rows, and a DBGrid a DataSource row, for binding it to a Data control (see Data Binding): DataSource offers the form’s Data controls in a list. A file property (Picture, DragIcon, the form’s Icon, and a Data control’s DatabaseName) has Browse... beside its box: a file picked in the project’s folder (or a folder inside it) is kept relative to the project, so the project still works when it is moved. Changes take effect immediately in the designer preview.
Each control type exposes different properties (e.g., Caption, Text, Width, Height, MaxWidth, MaxHeight, Weight, Alignment, Enabled, Visible, and type-specific properties like DataSource and DataField for data-bound controls). A UserControl placed on a form lists the properties its code defines.
A size row — MinWidth (Width), MinHeight (Height), MaxWidth, MaxHeight, Padding, and Spacing — is typed as text: a number of pixels (120), a percentage of the container (50%), or a number of characters (20ch); nothing at all leaves none set. The row shows the size as the .frm file keeps it, and the design surface lays the form out with it. Anything else (12px, 50 %, a size below 0, a percentage above 100) is refused with a message and the property keeps its value. Dragging a control’s handle keeps the kind of size it has (see Grab handles in Form Designer).
Every control has a Name and an Index row, as in Visual Basic. Index is blank for a control in no control array. Type a number from 0 to 32767 to make the control an element of a control array (its name with that index, Text1(0), in the tree and in code), or clear it to take a control that is the only element of its array out of it. The designer refuses, with the reason, an Index that is no number from 0 to 32767, one another control of the same name has, a blank Index for a control whose name others share (its array keeps it), and an Index for a control whose name a control in no array also has. Renaming a control to the name of another control of the same type makes a control array, as Visual Basic does: when that is one control in no array, you are asked "You already have a control named ... Do you want to create a control array?" (Yes makes it element 0 and the renamed control element 1, No leaves the name as it was); a control array of that name takes the renamed control with the next Index. The event procedures in the code are not renamed then: an element’s run Name_Click(Index As Integer). A new name for one element of a control array renames that element alone, as in Visual Basic: it keeps its Index (an element of an array of the new name, Text9(2)), the other elements keep their name, and the event procedures stay as they are, the other elements' still; only when no control keeps the old name do its event procedures take the new one, as for a control in no array.
The Font row shows the font the selected control, or the form, draws with: its family, size in pixels, and styles, such as "DejaVu Sans, 14, Bold". Double-click it to choose a font in the Font dialog; the design surface shows it at once. The choice is kept as the six Font properties (FontName, FontSize, FontBold, FontItalic, FontUnderline, and FontStrikethru), which then appear in the list and can be changed one at a time too. Choosing the font the control would have anyway (its container’s or the form’s) removes them, so the control follows the form’s font again. A font chosen for the form is used by every control that has none of its own. For a TextBox, TextArea, ComboBox, SpinButton, or Terminal the dialog lists only fixed-pitch families.
The panel follows the window in use, as Visual Basic’s: the form designer’s selection while the designer has the keyboard, and, while the Code Editor has it, what its file shows here. For a UserControl (.ctl) that is the control’s header: Name, Width, Height, CanGetFocus, BackColor, ToolboxIcon, Description, and DefaultEvent (see UserControls in the IDE); for a class module or a module, its Name, which double-clicking changes (see Class Modules).
See also: Form Designer (Section 4.4); UserControls in the IDE (Section 4.7).
4.9. Toolbox
The Toolbox (Window > Toolbox) is a floating palette of buttons, one for each available control type. Every widget registered with DVX that has a BASIC name appears in the toolbox: the controls DVX comes with, the controls written in BASIC that are installed for every program (control files in the WIDGETS folder), and the open project’s own UserControls (see UserControls in the IDE). The buttons are in alphabetical order of the control’s name. A button shows the control’s picture, or its name when it has none; its tooltip is the control’s description.
The Toolbox opens four buttons across and as tall as its buttons need, down to the bottom of the screen. Resize it like any window: the buttons rearrange to fill its width, and when they do not all fit, a scroll bar reaches the rest.
Click a tool to select it (the active tool name is stored in the designer state), then click on the form to place a new instance. Click the same tool again to deselect it and return to pointer mode.
4.9.1. Available Controls
| VB Name | Description |
|---|---|
CheckBox |
On/off checkbox. |
ComboBox |
Drop-down combo box. |
CommandButton |
Push button that triggers a Click event. |
Data |
Data control for binding to a database. |
DBGrid |
Data-bound grid for displaying database query results. |
DropDown |
Simple drop-down list. |
Frame |
Grouping container with a labeled border. |
HBox |
Horizontal layout container. |
HelpPane |
One topic of a help file, as DVX Help shows it. |
HScrollBar |
Horizontal slider/scrollbar. |
Label |
Static text label. |
Line |
Horizontal or vertical separator line. |
ListBox |
Scrollable list of items. |
ListView |
Multi-column list with headers. |
OptionButton |
Radio button (mutually exclusive within a group). |
PictureBox |
Canvas for drawing and images. |
ProgressBar |
Progress indicator bar. |
RichEdit |
Text box for text in many fonts, styles, and colors. |
RichLabel |
Text in many fonts, styles, and colors, in aligned paragraphs. |
ScrollPane |
Scrollable container for large content. |
Spacer |
Invisible spacing element for layout. |
SpinButton |
Numeric up/down spinner. |
Splitter |
Resizable split between two child panes. |
StatusBar |
Status bar at the bottom of a form. |
TabPage |
One page of a TabStrip, holding the controls shown on that tab. |
TabStrip |
Tabbed container with multiple pages. |
Terminal |
ANSI terminal emulator control. |
TextArea |
Multi-line text editor. |
TextBox |
Single-line text input field. |
Timer |
Non-visual timer that fires periodic events. |
Toolbar |
Toolbar container for buttons. |
TreeView |
Hierarchical tree control. |
VBox |
Vertical layout container. |
WrapBox |
Flow layout container that wraps items to the next row. |
A new Image or ImageButton starts empty, 32 by 32 pixels so it can be seen and selected: set its Picture property to show a picture.
See also: Form Designer (Section 4.4); UserControls in the IDE (Section 4.7).
4.10. Debugger
| State | Description |
|---|---|
Idle |
No program loaded or running. |
Running |
The program is executing. |
Paused |
Execution is paused at a breakpoint or step point. The IDE is fully interactive — you can inspect and change variables, set or clear breakpoints, step, continue, or stop. |
4.10.1. Starting a Debug Session
-
Shift+F5 (Debug) — compiles the project and starts execution in debug mode. Breakpoints are active but execution does not pause at the first statement.
-
F8 (Step Into) — if idle, starts a debug session and breaks at the first statement.
-
F5 (Run) — compiles and runs without the debugger. No breakpoints are active (a Debug.Assert whose condition is False still pauses). If already paused, resumes execution with debugging disabled.
4.10.2. Breakpoints
Setting Breakpoints
-
Press F9 to toggle a breakpoint on the current editor line.
-
Click in the line number gutter to toggle a breakpoint on that line.
Breakpoint Validation
Not every line can have a breakpoint. The IDE validates the line content and silently refuses to set breakpoints on:
-
Blank lines
-
Comment lines (' or REM)
-
SUB and FUNCTION declaration lines
-
END SUB and END FUNCTION lines
Breakpoint Storage
Each breakpoint records the file it belongs to, the line number within that file, and the procedure name (Object.Event). Breakpoints are stored in the project and survive compilation.
4.10.3. Stepping
| Action | Shortcut | Behavior |
|---|---|---|
Step Into |
F8 |
Execute one statement. If the statement is a SUB/FUNCTION call, step into it. |
Step Over |
Shift+F8 |
Execute one statement. If the statement is a SUB/FUNCTION call, execute the entire call and break at the next line in the current scope. |
Step Out |
Ctrl+Shift+F8 |
Run until the current SUB/FUNCTION returns to its caller. |
Run to Cursor |
Ctrl+F8 |
Run until execution reaches the line under the cursor. |
4.10.4. Debug Run Behavior
When a program is running under the debugger:
-
The program runs in short cooperative slices so the IDE remains responsive.
-
When the program hits a breakpoint, execution pauses immediately. The IDE switches to Code View, navigates to the breakpoint line, highlights it in yellow, and opens the Locals and Call Stack windows if they are not already visible.
-
A Debug.Assert whose condition is False pauses the program at its line the same way, also in a run started with Run (F5), as in Visual Basic (see Debug Object in the language reference).
-
While paused, you can inspect variables in Locals and Watch, evaluate expressions in the Immediate window, assign new values to variables, toggle breakpoints, step, continue, or stop. A pause in module-level code works the same way as a pause in an event handler.
-
Resuming (F5, Shift+F5, or any Step command) returns the program to Running state.
4.10.5. Stopping
Press Esc or click the Stop toolbar button at any time to halt execution. The program is terminated, the debugger returns to Idle, and the IDE restores any designer or code windows that were hidden at the start of the run.
See also: Call Stack Window (Section 4.10.7); Watch Window (Section 4.10.8); Breakpoints Window (Section 4.10.9).
4.10.6. Locals Window
When the debugger pauses, the Locals and Call Stack windows are auto-opened (if not already visible). The Watch and Breakpoints windows can be opened manually from the Window menu.
Shows variables for the current execution scope. Displayed as a three-column ListView:
| Column | Content |
|---|---|
Name |
Variable name (internal mangled names like static variable placeholders are filtered out). |
Type |
Data type: Integer, Long, Single, Double, String, Boolean, Date, Variant, Array, UDT, or the type of object. Array types show the element type (e.g., Integer()). |
Value |
Current value. Strings are shown in quotes. Booleans as True/False. Arrays show bounds and element count (e.g., Integer(0 To 9) [10]). Uninitialized arrays show (uninitialized). |
Variants show the value they currently hold, or Empty or Null; an OPTIONAL Variant parameter the caller left out shows Missing. Object variables show Nothing, or which object they refer to: the class name of a class instance, a Collection with its number of items, or the form or control.
The Locals window displays:
-
Local variables of the current procedure, including its STATIC variables and the module variables it names in a SHARED statement.
-
Module-level variables. While execution is paused inside a SUB or FUNCTION, the variables made by their first use at module level (not declared with DIM) are left out, because the procedure cannot see them. This also applies inside a DEF FN function, although a DEF FN can read every module variable.
-
Form-scoped variables for the current form (if the program is executing within a form context), with the same rule.
-
Member variables of the object, while execution is paused in a procedure of a class module: the variables of the very object the procedure was called for (Me), Private ones included.
The Watch window and the Immediate window follow the same rules. The window is resizable.
4.10.7. Call Stack Window
| Column | Content |
|---|---|
Procedure |
Procedure name (or (module) for module-level code). |
Line |
Line number where execution is paused (shown for the topmost frame). |
The current location is shown first, followed by each caller in the call stack (walking from the deepest frame back to the module entry point). Up to 32 frames are displayed.
4.10.8. Watch Window
Allows monitoring arbitrary expressions while debugging. The window has a text input at the top and a two-column ListView below:
| Column | Content |
|---|---|
Expression |
The watch expression text. |
Value |
Evaluated result, shown as the Locals window shows a value (a number as CStr gives it, text in quotes), as in Visual Basic; <error> if evaluation fails. Blank when not paused. |
Adding Watch Expressions
Type an expression in the text input and press Enter. Up to 16 watch expressions can be active at once.
4.10.9. Breakpoints Window
| Column | Content |
|---|---|
File |
Project file path. |
Procedure |
Procedure name (Object.Event format, or (General)). |
Line |
Code line number within the file. |
-
Double-click a breakpoint to navigate the code editor to that location.
-
Press Delete to remove selected breakpoints (multi-select is supported).
See also: Debugger (Section 4.10).
4.11. Immediate Window
The Immediate window is an interactive REPL at the bottom-right of the screen. Type a line of BASIC and press Enter to evaluate it. Results appear at the end of the window, below your input, where typing goes on. Enter evaluates the whole line it is pressed on, wherever the caret is in it (the line is not split); Enter on an empty line does nothing. A statement that does not finish (for example DO: LOOP) is stopped with "Error: Statement did not finish; stopped."
4.11.1. Expression Evaluation
If the input is not a recognized statement keyword, it is automatically wrapped in a PRINT statement. For example, typing 2 + 2 evaluates as PRINT 2 + 2 and displays 4.
You can also type full statements:
-
PRINT x * 2 — evaluate and print an expression.
-
Debug.Print x; y — the same, as in Visual Basic’s Immediate window.
-
DIM tmp As Integer — declare a temporary variable.
-
LET x = 42 — explicit assignment (see below).
Parse or runtime errors are displayed inline with an Error: prefix.
4.11.2. Inspecting Variables While Paused
When the debugger is paused at a breakpoint, the Immediate window has access to the running program’s state. Expressions like count or name$ & " test" display live values.
4.11.3. Assigning Variables While Paused
When paused, you can modify variables in the running program directly from the Immediate window using assignment syntax:
variableName = newValue
The optional LET keyword is also accepted:
LET variableName = newValue
Assignment works for:
-
Scalar variables — x = 42, name$ = "test", count = count + 1 (any expression is allowed on the right)
-
Array elements — arr(5) = 100, matrix(2, 3) = 7.5
-
UDT fields — player.score = 1000
-
Combined — items(0).price = 9.99
The new value is written directly into the running program’s variable (local, global, or form scope). A confirmation message is displayed, and the Locals and Watch windows update automatically to reflect the change.
If the assignment target cannot be resolved (unknown variable, out-of-bounds index, wrong type), an error message is displayed.
4.12. Output Window
-
PRINT output — PRINT statement output from the running program is appended here, until the program uses a console or graphics statement (CLS, LOCATE, COLOR, SCREEN, LINE, INKEY$, and the others): from then on PRINT and INPUT use the program’s own screen window instead (see Console and Graphics in the language reference).
-
Debug.Print output — always appended here, also while the program has its own screen window (see Debug Object in the language reference).
-
Runtime errors — when the program stops with an error it does not handle (division by zero, a subscript out of range, and so on), the output shows RUNTIME ERROR:, below it where it happened — the procedure (or the file) and the line in it, such as Command1.Click line 2: — and below that the error’s number and message, such as Runtime error 11: Division by zero. The Code window shows that line.
-
Compile errors — when the program does not compile, the output shows COMPILE ERROR:, below it the procedure (or the file) and the line, and below that the message; the caret goes to the error.
The output buffer holds up to 32,768 characters; when it is full the oldest lines are dropped. The window always shows the newest output. Use Run > Clear Output to clear it.
INPUT statements prompt the user via a modal InputBox dialog; the prompt text is also echoed to the Output window. A program that has its own screen window types its INPUT there instead.
4.12.1. The Program’s Screen Window
A program that uses the console or graphics statements gets a window of its own, the size of its screen mode (80x25 text, or 640x480 or 320x200 graphics), titled with the project’s name. Alt+Enter in that window (or FULLSCREEN in the program) shows it on the whole screen; Alt+Tab brings the desktop back and the program continues. Keys typed in the window go to the program (INKEY$ and INPUT). The window stays open after the program’s code has finished, so its output can be read; closing it ends the program.
4.13. Find / Replace
Open with Ctrl+F (Find) or Ctrl+H (Replace). The Find/Replace dialog is modeless — it stays open while you continue editing.
4.13.1. Dialog Controls
| Control | Description |
|---|---|
Find input |
The text to search for. |
Replace checkbox + input |
Enable replacement mode and enter replacement text. |
Scope |
Radio group: Function, Object, File, or Project. Default is Project. |
Direction |
Radio group: Forward or Backward. |
Match Case |
Checkbox: case-sensitive search. |
4.13.2. Buttons
| Button | Action |
|---|---|
Find Next |
Find the next occurrence. Function scope searches the current procedure, Object scope the selected object’s procedures, File scope the current file, and Project scope every file. At the end of the current procedure the search wraps around to its start. |
Replace |
Replace the current match and find the next one. |
Replace All |
Replace all occurrences within the selected scope. |
Close |
Close the dialog. |
Enter clicks Find Next (unless another button is highlighted: then Enter clicks that one), and Esc clicks Close.
4.14. Preferences
Open via Tools > Preferences. Settings are saved to dvxbasic.ini in the IDE’s folder in your user folder (USER\APPS\KPUNCH\DVXBASIC). The dialog has two tabs. As in every dialog box, Enter clicks OK (unless a button or a box of several lines has the focus) and Esc clicks Cancel.
4.14.1. General Tab
Editor Section
| Setting | Description | Default |
|---|---|---|
Skip comments/strings when renaming |
When renaming a control or form, skip occurrences inside comments and string literals. |
On |
Require variable declaration (OPTION EXPLICIT) |
When enabled, newly created projects have OPTION EXPLICIT on by default. |
Off |
Tab width |
Number of spaces per tab stop. |
3 |
Insert spaces instead of tabs |
When enabled, pressing Tab inserts spaces. When disabled, inserts a real tab character. |
On |
New Project Defaults Section
These fields set the default values for new project metadata:
| Field | Description | Default |
|---|---|---|
Author |
Default author name. |
(empty) |
Publisher |
Default publisher/company name. |
(empty) |
Version |
Default version string. |
1.0 |
Copyright |
Default copyright notice. |
(empty) |
Description |
Default project description (one line). |
(empty) |
4.14.2. Colors Tab
Customizes the syntax-highlighting colors used in the code editor. The left side is a list of seven color entries (Default Text, Keywords, Strings, Comments, Numbers, Operators, Types). Select an entry to see its color, and its red, green, and blue amounts, on the right. Click Change... (or double-click the entry) to pick a new color in the color box: click a basic color or mix one with the Red, Green, and Blue sliders or number boxes, then click OK. Changes are applied to the open editor when you click OK in the Preferences dialog.
4.15. Keyboard Shortcuts
See also: Changes in This Release.
Index
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
A
- About, 4.1.8. Help Menu
- ABS, 1.6.11. Math Functions
- Accelerators, 4.15. Keyboard Shortcuts
- AccelKey, 2.3. Drawing on Forms and PictureBoxes
- ActiveControl, 2.1. Form
- ActiveForm, 1.14. Screen Object
- Add, 1.8.15. Collection Object
- Add File, 4.1.2. File Menu
- Add Library, 4.1.2. File Menu
- Add-on packages, 1.17. Include Libraries
- AddChildItem, 3.33. TreeView
- AddItem, 3.15. ListBox, 3.33. TreeView
- AddLineBreak, 3.21. RichLabel
- AddMenuItem, 2.5. Menu System
- AddMenuSeparator, 2.5. Menu System
- AddNew, 3.4. Data
- AddParagraph, 3.21. RichLabel
- AddSubMenu, 2.5. Menu System
- AddText, 3.21. RichLabel
- Align, 3.18. PictureBox
- Alignment, 3.8. HBox, 3.13. Label, 3.26. StatusBar, 3.32. Toolbar
- AND, 1.3. Operators
- ANSI Terminal, 3.28. Terminal
- App, 1.10. App Object
- App.Comments, 1.10. App Object
- App.CompanyName, 1.10. App Object
- App.Data, 1.10. App Object
- App.EXEName, 1.10. App Object
- App.FileDescription, 1.10. App Object
- App.HelpFile, 1.10. App Object
- App.LegalCopyright, 1.10. App Object
- App.LegalTrademarks, 1.10. App Object
- App.Major, 1.10. App Object
- App.Minor, 1.10. App Object
- App.Path, 1.10. App Object
- App.PrevInstance, 1.10. App Object
- App.ProductName, 1.10. App Object
- App.Revision, 1.10. App Object
- App.Title, 1.10. App Object
- App.User, 1.10. App Object
- Arrange, 1.14. Screen Object
- ARRAY, 1.2. Variants
- ASC, 1.6.9. String Functions
- ASCW, 1.6.9. String Functions
- ATN, 1.6.11. Math Functions
- Attribute, 1.8. Objects and Class Modules
- Attribute VB_Name (module), 1.4.2.1. DIM
- Auto-indent, 4.3. Code Editor
- AutoIndent, 3.29. TextArea
- AutoRedraw, 2.3. Drawing on Forms and PictureBoxes
- AutoSize, 2.1. Form
B
- BEEP, 1.4.9. Sound, Joysticks, and Frames
- BINARY STRING, 1.4.2.1. DIM
- BMP, 3.11. Image
- Boolean, 1.1. Data Types
- BorderStyle, 3.18. PictureBox
- Breakpoints, 4.10. Debugger
- Breakpoints Window, 4.10.9. Breakpoints Window
- Button, 3.3. CommandButton
- Byte, 1.1. Data Types
- BYVAL, 1.4.5.1. SUB...END SUB
C
- CALL, 1.4.6.1. EXIT
- Call Stack, 4.10.7. Call Stack Window
- CallByName, 1.8. Objects and Class Modules
- CALLBYNAME, 1.8. Objects and Class Modules
- Cancel, 3.3. CommandButton
- Canvas, 3.18. PictureBox
- Caption, 2.1. Form, 3.13. Label
- CASE, 1.4.3.1. IF...THEN...ELSE...END IF
- CASE ELSE, 1.4.3.1. IF...THEN...ELSE...END IF
- CBOOL, 1.6.12. Conversion Functions
- CBYTE, 1.6.12. Conversion Functions
- CCUR, 1.6.12. Conversion Functions
- CDATE, 1.6.12. Conversion Functions
- CDBL, 1.6.12. Conversion Functions
- CHDIR, 1.6. File System Statements
- CHDRIVE, 1.6. File System Statements
- CheckBox, 3.1. CheckBox
- CHOOSE, 1.6.15. Miscellaneous Functions
- CHR$, 1.6.9. String Functions
- CHRW$, 1.6.9. String Functions
- CINT, 1.6.12. Conversion Functions
- CIRCLE, 1.4.10. Console and Graphics
- Circle method, 2.3. Drawing on Forms and PictureBoxes
- Class Module, 1.8. Objects and Class Modules
- Class Modules, 1.8. Objects and Class Modules
- Class Modules in the IDE, 4.5.1. Project Files (.dbp)
- Class Types, 1.1. Data Types
- Class_Initialize, 1.8. Objects and Class Modules
- Class_Terminate, 1.8. Objects and Class Modules
- Classes Section, 4.5.1. Project Files (.dbp)
- Clear Output, 4.1.4. Run Menu
- Click, 3.3. CommandButton
- Clipboard, 1.12. Clipboard Object
- Clipboard.Clear, 1.12. Clipboard Object
- Clipboard.GetFormat, 1.12. Clipboard Object
- Clipboard.GetText, 1.12. Clipboard Object
- Clipboard.SetText, 1.12. Clipboard Object
- CLNG, 1.6.12. Conversion Functions
- CLOSE, 1.5.1. OPEN
- Close Project, 4.1.2. File Menu
- CLS, 1.4.10. Console and Graphics
- Cls, 2.3. Drawing on Forms and PictureBoxes
- CLS Files, 1.8. Objects and Class Modules
- .cls Files, 1.8. Objects and Class Modules, 4.5.1. Project Files (.dbp)
- Code editor, 3.29. TextArea
- Code Editor, 4.3. Code Editor
- Code editors, 1.17. Include Libraries
- Code View, 4.1.5. View Menu
- Collection, 1.8.15. Collection Object
- COLLECTION, 1.8.15. Collection Object
- Collection Keys, 1.8.15. Collection Object
- COLOR, 1.4.10. Console and Graphics
- Color Dialog, 1.17. Include Libraries
- Colorize, 3.30. TextBox
- ColumnClick, 3.16. ListView
- ComboBox, 3.2. ComboBox
- comm.bas, 1.17. Include Libraries
- Command Line, 1.6.15. Miscellaneous Functions
- COMMAND$, 1.6.15. Miscellaneous Functions
- COMMAND$ (new arguments), 2.1. Form
- CommandButton, 3.3. CommandButton
- commdlg.bas, 1.17. Include Libraries
- Comments, 1.4.1. Statements
- CommHandshake, 1.17. Include Libraries
- CommHandshakeStep, 1.17. Include Libraries
- CommLastError, 1.17. Include Libraries
- Common Events, 2.2. Common Properties, Events, and Methods
- Common Methods, 2.2. Common Properties, Events, and Methods
- Common Properties, 2.2. Common Properties, Events, and Methods
- CommOpenTcp, 1.17. Include Libraries
- CommRecvEncrypted, 1.17. Include Libraries
- CommSetPlain, 1.17. Include Libraries
- CompBuildApp, 1.17. Include Libraries
- CompClassEvents$, 1.17. Include Libraries
- CompCompile, 1.17. Include Libraries
- CompDesignControls, 1.17. Include Libraries
- CompDesignRelease, 1.17. Include Libraries
- CompError$, 1.17. Include Libraries
- CompHelpTopic$, 1.17. Include Libraries
- Compile Errors, 4.12. Output Window
- compiler.bas, 1.17. Include Libraries
- Compiling programs, 1.17. Include Libraries
- CompInCode, 1.17. Include Libraries
- CompKeywordClass, 1.17. Include Libraries
- CompProcList$, 1.17. Include Libraries
- CompRenameInCode$, 1.17. Include Libraries
- CompSourceCreate, 1.17. Include Libraries
- CompSourceFromProject, 1.17. Include Libraries
- CompTokens$, 1.17. Include Libraries
- CompWithEvents$, 1.17. Include Libraries
- conn.bas, 1.17. Include Libraries
- ConnAttach, 1.17. Include Libraries
- ConnCreate, 1.17. Include Libraries
- Connections, 1.17. Include Libraries
- ConnOpen, 1.17. Include Libraries
- ConnPoll, 1.17. Include Libraries
- ConnReceiveFiles, 1.17. Include Libraries
- ConnSendFiles, 1.17. Include Libraries
- Console, 1.4.10. Console and Graphics
- CONST, 1.4.2.1. DIM
- Container, 2.2. Common Properties, Events, and Methods, 3.7. Frame
- Control Array Object, 2.6. Control Arrays
- Control Arrays, 1.7. Form and Control Statements, 2.6. Control Arrays
- Control Arrays (designer), 4.8. Properties Panel
- Control Panel settings, 1.17. Include Libraries
- Control Placement, 4.4. Form Designer
- Control Projects, 4.7. UserControls in the IDE
- Control Properties, 4.8. Properties Panel
- Control Tree, 4.8. Properties Panel
- Control Type, 1.1. Data Types
- Control Types, 1.1. Data Types
- Controls, 4.9. Toolbox
- Controls (form), 2.1. Form
- Controls (project section), 2.8. UserControls: Your Own Controls
- Controls Section, 4.5.1. Project Files (.dbp)
- Copy, 4.1.3. Edit Menu
- COS, 1.6.11. Math Functions
- Count, 1.8.15. Collection Object
- CreateControl, 1.7. Form and Control Statements
- CreateForm, 1.7. Form and Control Statements
- CreateMenu, 2.5. Menu System
- CSNG, 1.6.12. Conversion Functions
- CSRLIN, 1.4.10. Console and Graphics
- CSTR, 1.6.12. Conversion Functions
- .ctl, 2.8. UserControls: Your Own Controls
- .ctl Files, 4.7. UserControls in the IDE
- CtlEventList$, 1.17. Include Libraries
- CtlEventParams$, 1.17. Include Libraries
- CtlPropCount, 1.17. Include Libraries
- CtlPropName$, 1.17. Include Libraries
- CtlPropType, 1.17. Include Libraries
- CtlTypeCount, 1.17. Include Libraries
- CtlTypeEventParams$, 1.17. Include Libraries
- CtlTypeFlags, 1.17. Include Libraries
- CtlTypeName$, 1.17. Include Libraries
- CtlTypeNaturalSize$, 1.17. Include Libraries
- Currency, 1.1. Data Types
- CurrentX, 2.3. Drawing on Forms and PictureBoxes
- CurrentY, 2.3. Drawing on Forms and PictureBoxes
- CursorCol, 3.29. TextArea
- CursorLine, 3.29. TextArea
- Cut, 4.1.3. Edit Menu
- CVAR, 1.2. Variants, 1.6.12. Conversion Functions
D
- DATA, 1.4.7.1. PRINT
- Data, 3.4. Data
- Data Binding, 2.4. Data Binding
- Data Types, 1.1. Data Types
- Data-Bound Grid, 3.5. DBGrid
- Database, 3.4. Data
- DatabaseName, 3.4. Data
- DataField, 2.4. Data Binding, 3.30. TextBox
- DataSource, 2.4. Data Binding, 3.30. TextBox
- Date, 1.1. Data Types
- DATE, 1.6.13. Date and Time Functions
- Date Literals, 1.1. Data Types
- DATE$, 1.6.15. Miscellaneous Functions
- DATEADD, 1.6.13. Date and Time Functions
- DATEDIFF, 1.6.13. Date and Time Functions
- DATEPART, 1.6.13. Date and Time Functions
- DATESERIAL, 1.6.13. Date and Time Functions
- DATEVALUE, 1.6.13. Date and Time Functions
- DAY, 1.6.13. Date and Time Functions
- DbgEval$, 1.17. Include Libraries
- DbgExec$, 1.17. Include Libraries
- DbgLocals$, 1.17. Include Libraries
- DBGrid, 3.5. DBGrid
- DbgSetBreakpoints, 1.17. Include Libraries
- DbgSetVar, 1.17. Include Libraries
- DbgStepOver, 1.17. Include Libraries
- .dbp Files, 4.5.1. Project Files (.dbp)
- Debug, 1.11. Debug Object, 4.1.4. Run Menu
- Debug Layout, 4.1.7. Tools Menu
- Debug Mode, 4.10. Debugger
- Debug.Assert, 1.11. Debug Object
- debug.bas, 1.17. Include Libraries
- Debug.Print, 1.11. Debug Object
- Debugger, 4.10. Debugger
- Debugging programs, 1.17. Include Libraries
- Decimals, 3.24. SpinButton
- DECLARE, 1.4.2.1. DIM
- DECLARE LIBRARY, 1.4.2.1. DIM, 1.17. Include Libraries
- DEF FN, 1.4.5.1. SUB...END SUB
- Default, 3.3. CommandButton
- Default Member, 1.8. Objects and Class Modules
- Default Properties, 2.2. Common Properties, Events, and Methods
- Default Property, 2.2. Common Properties, Events, and Methods
- DEFBYTE, 1.4.2.1. DIM
- DEFCUR, 1.4.2.1. DIM
- DEFDBL, 1.4.2.1. DIM
- DEFINT, 1.4.2.1. DIM
- DEFLNG, 1.4.2.1. DIM
- DEFSNG, 1.4.2.1. DIM
- DEFSTR, 1.4.2.1. DIM
- Delete, 4.1.3. Edit Menu
- Design surface, 2.1. Form
- Design Surface, 4.4. Form Designer
- Design View, 4.1.5. View Menu
- designer.bas, 1.17. Include Libraries
- DesignKey, 2.1. Form
- DesignMode, 2.1. Form
- DesignMouse, 2.1. Form
- DesignPropertyChanged, 2.1. Form
- DesignSelection, 2.1. Form
- DestroyMenu, 2.5. Menu System
- Development Environment, 4.1. DVX BASIC IDE Guide
- DIM, 1.4.2.1. DIM
- Disk full, 1.5.1. OPEN
- DLG_FONT_FIXED, 1.17. Include Libraries
- DlgButtons, 1.17. Include Libraries
- DlgColor, 1.17. Include Libraries
- DlgFileOpenIn$, 1.17. Include Libraries
- DlgFileOpenOrCreate$, 1.17. Include Libraries
- DlgFileSaveAs$, 1.17. Include Libraries
- DlgFileSaveIn$, 1.17. Include Libraries
- DlgFolder$, 1.17. Include Libraries
- DlgFont, 1.17. Include Libraries
- DlgFontName$, 1.17. Include Libraries
- DlgFontSize, 1.17. Include Libraries
- DlgFontStyle, 1.17. Include Libraries
- DlgInputCancelled, 1.17. Include Libraries
- DlgIntInput, 1.17. Include Libraries
- DlgIntInputStep, 1.17. Include Libraries
- DO, 1.4.4.1. FOR...NEXT
- DoEvents, 1.7. Form and Control Statements
- DOEVENTS, 1.7. Form and Control Statements
- Double, 1.1. Data Types
- DPK files, 4.6. Making a Package
- Drag, 2.2. Common Properties, Events, and Methods
- Drag and Drop, 2.2. Common Properties, Events, and Methods
- DragDrop, 2.2. Common Properties, Events, and Methods
- DragIcon, 2.2. Common Properties, Events, and Methods
- DragMode, 2.2. Common Properties, Events, and Methods
- DragOver, 2.2. Common Properties, Events, and Methods
- DRAW, 1.4.10. Console and Graphics
- DrawArrow, 2.3. Drawing on Forms and PictureBoxes
- DrawBevel, 2.3. Drawing on Forms and PictureBoxes
- DrawButtonFace, 2.3. Drawing on Forms and PictureBoxes
- DrawFocusRect, 2.3. Drawing on Forms and PictureBoxes
- Drawing, 3.18. PictureBox
- Drawing Methods, 2.3. Drawing on Forms and PictureBoxes
- DrawScrollArrow, 2.3. Drawing on Forms and PictureBoxes
- DrawScrollBar, 2.3. Drawing on Forms and PictureBoxes
- DrawStyle, 2.3. Drawing on Forms and PictureBoxes
- DrawWidth, 2.3. Drawing on Forms and PictureBoxes
- DropDown, 3.6. DropDown
- DVX BASIC, About This Reference, 4.1. DVX BASIC IDE Guide
- dvxArrowUp, 2.3. Drawing on Forms and PictureBoxes
- dvxFullScreenActive, 2.1. Form
E
- EACH, 1.4.4.1. FOR...NEXT
- Edit Menu, 4.1.3. Edit Menu
- ELSE, 1.4.3.1. IF...THEN...ELSE...END IF
- ELSEIF, 1.4.3.1. IF...THEN...ELSE...END IF
- Empty, 1.2. Variants
- Encryption, 1.17. Include Libraries
- END, 1.4.8.1. Error Handling
- END ENUM, 1.4.2.1. DIM
- END FUNCTION, 1.4.5.1. SUB...END SUB
- END IF, 1.4.3.1. IF...THEN...ELSE...END IF
- END SELECT, 1.4.3.1. IF...THEN...ELSE...END IF
- END SUB, 1.4.5.1. SUB...END SUB
- END TYPE, 1.4.2.1. DIM
- END WITH, 1.8. Objects and Class Modules
- EndDoc, 1.13. Printer Object
- ENUM, 1.4.2.1. DIM
- ENVIRON$, 1.6.15. Miscellaneous Functions
- EOF, 1.6.14. File I/O Functions
- EQV, 1.3. Operators
- ERASE, 1.4.2.1. DIM
- ERL, 1.4.8.1. Error Handling
- ERR, 1.4.8.1. Error Handling
- Err, 1.4.8.1. Error Handling
- Err.Clear, 1.4.8.1. Error Handling
- Err.Description, 1.4.8.1. Error Handling
- Err.Number, 1.4.8.1. Error Handling
- Err.Raise, 1.4.8.1. Error Handling
- Err.Source, 1.4.8.1. Error Handling
- ERROR, 1.4.8.1. Error Handling
- Error 453, 1.17. Include Libraries
- ERROR$, 1.4.8.1. Error Handling
- Event, 1.8.13. Events
- EVENT, 1.8.13. Events
- Event Handlers, 1.7. Form and Control Statements
- Events, 2.2. Common Properties, Events, and Methods
- EXIT, 1.4.6.1. EXIT
- Exit, 4.1.2. File Menu
- EXIT DO, 1.4.4.1. FOR...NEXT
- EXIT FOR, 1.4.4.1. FOR...NEXT
- EXIT FUNCTION, 1.4.5.1. SUB...END SUB
- EXIT PROPERTY, 1.8. Objects and Class Modules
- EXIT SUB, 1.4.5.1. SUB...END SUB
- EXP, 1.6.11. Math Functions
- Expression Evaluation, 4.11. Immediate Window
F
- F1, How This Book Is Organized
- False, 1.16. Predefined Constants
- File Attributes, 1.6. File System Statements
- File Menu, 4.1.2. File Menu
- File Output Errors, 1.5.1. OPEN
- File Transfers, 1.17. Include Libraries
- FILEATTR, 1.6.14. File I/O Functions
- FILECOPY, 1.6. File System Statements
- FILEOPS_ATTR_EDITABLE, 1.17. Include Libraries
- FileOpsBootDrive$, 1.17. Include Libraries
- FileOpsDriveType, 1.17. Include Libraries
- FileOpsFilterMatch, 1.17. Include Libraries
- FileOpsIsWritable, 1.17. Include Libraries
- FileOpsJobBytesDone, 1.17. Include Libraries
- FileOpsJobClearAttr, 1.17. Include Libraries
- FileOpsKindBrowseDir$, 1.17. Include Libraries
- FileOpsKindDir$, 1.17. Include Libraries
- FileOpsKindFind$, 1.17. Include Libraries
- FileOpsKindList, 1.17. Include Libraries
- FileOpsKindName$, 1.17. Include Libraries
- FileOpsLongNames, 1.17. Include Libraries
- FileOpsMakePath, 1.17. Include Libraries
- FileOpsPathIsAbsolute, 1.17. Include Libraries
- FileOpsPathIsInside, 1.17. Include Libraries
- FileOpsPathNative$, 1.17. Include Libraries
- FileOpsPathSep$, 1.17. Include Libraries
- FileOpsReadOnlySystem, 1.17. Include Libraries
- FileOpsReplaceFile, 1.17. Include Libraries
- FileOpsSaveText, 1.17. Include Libraries
- FileOpsSetModified, 1.17. Include Libraries
- FileOpsShortPath$, 1.17. Include Libraries
- FileOpsTempDir$, 1.17. Include Libraries
- FileOpsTotalBytes, 1.17. Include Libraries
- FileOpsUserDir$, 1.17. Include Libraries
- FileOpsUserInTemp, 1.17. Include Libraries
- FileOpsUserPath$, 1.17. Include Libraries
- FileOpsValidLongName, 1.17. Include Libraries
- FileOpsValidName, 1.17. Include Libraries
- FileOpsValidShortName, 1.17. Include Libraries
- FillColor, 2.3. Drawing on Forms and PictureBoxes
- FillStyle, 2.3. Drawing on Forms and PictureBoxes
- FILTER, 1.6.9. String Functions
- Find, 4.1.3. Edit Menu, 4.13. Find / Replace
- Find Next, 4.1.3. Edit Menu, 4.13. Find / Replace
- FindNext, 3.29. TextArea
- FitHeight, 2.1. Form
- FitWidth, 2.1. Form
- FIX, 1.6.11. Math Functions
- Flow Layout, 3.35. WrapBox
- FM synthesizer, 1.17. Include Libraries
- FmAlloc, 1.17. Include Libraries
- FmRawAcquire, 1.17. Include Libraries
- FmWrite, 1.17. Include Libraries
- Focus rectangle, 2.3. Drawing on Forms and PictureBoxes
- Font (form), 2.1. Form
- Font Dialog, 1.17. Include Libraries
- Font properties, 1.17. Include Libraries
- Font row, 4.8. Properties Panel
- font.bas, 1.17. Include Libraries
- FontBold, 2.2. Common Properties, Events, and Methods
- FontFamilyCount, 1.17. Include Libraries
- FontFamilyName$, 1.17. Include Libraries
- FontItalic, 2.2. Common Properties, Events, and Methods
- FontName, 2.2. Common Properties, Events, and Methods
- FontName (form), 2.1. Form
- Fonts, 1.17. Include Libraries
- Fonts (controls), 2.2. Common Properties, Events, and Methods
- Fonts Section, 4.5.1. Project Files (.dbp)
- FontScale, 2.3. Drawing on Forms and PictureBoxes
- FontSize, 2.2. Common Properties, Events, and Methods
- FontStrikethru, 2.2. Common Properties, Events, and Methods
- FontTextWidth, 1.17. Include Libraries
- FontUnderline, 2.2. Common Properties, Events, and Methods
- FOR, 1.4.4.1. FOR...NEXT
- FOR APPEND, 1.5.1. OPEN
- FOR BINARY, 1.5.1. OPEN
- FOR EACH, 1.4.4.1. FOR...NEXT
- FOR INPUT, 1.5.1. OPEN
- FOR OUTPUT, 1.5.1. OPEN
- FOR RANDOM, 1.5.1. OPEN
- Form, 2.1. Form
- Form Designer, 4.4. Form Designer
- Form designers, 1.17. Include Libraries
- Form File, 2.7. FRM File Format
- Form Type, 1.1. Data Types
- FORMAT, 1.6.10. Format Function
- FORMAT$, 1.6.10. Format Function
- FORMATCURRENCY, 1.6.10. Format Function
- FORMATDATETIME, 1.6.10. Format Function
- FORMATNUMBER, 1.6.10. Format Function
- FORMATPERCENT, 1.6.10. Format Function
- Frame, 3.7. Frame
- Frame rate, 1.4.9. Sound, Joysticks, and Frames
- FrameMissed, 1.17. Include Libraries
- FRAMEWAIT, 1.4.9. Sound, Joysticks, and Frames
- FREEFILE, 1.6.14. File I/O Functions
- FRIEND, 1.8. Objects and Class Modules
- Friend, 1.8. Objects and Class Modules
- FRM, 2.7. FRM File Format
- .frm, 2.7. FRM File Format
- Full screen, 1.4.10. Console and Graphics
- FULLSCREEN, 1.4.10. Console and Graphics
- FullScreen (form), 2.1. Form
- FUNCTION, 1.4.5.1. SUB...END SUB
- Function Dropdown, 4.3. Code Editor
G
- game.bas, 1.17. Include Libraries
- GameInput, 2.1. Form
- GameKeyClear, 1.17. Include Libraries
- GameKeyDown, 1.17. Include Libraries
- GameWaitRetrace, 1.17. Include Libraries
- GET, 1.5.1. OPEN
- GETATTR, 1.6. File System Statements
- GETBLUE, 1.6.11. Math Functions
- GETGREEN, 1.6.11. Math Functions
- GetItemTag, 3.33. TreeView
- GetLine, 3.29. TextArea
- GETRED, 1.6.11. Math Functions
- GetSelected, 3.17. OptionButton
- GLOBAL, 1.4.2.1. DIM
- GOSUB, 1.4.6.1. EXIT
- GOTO, 1.4.6.1. EXIT
- GoToLine, 3.29. TextArea
- Grab Handles, 4.4. Form Designer
- Grid Snapping, 4.4. Form Designer
- GutterClick, 3.29. TextArea
H
- HasChildren, 3.33. TreeView
- HBox, 3.8. HBox
- Header Properties, 4.7. UserControls in the IDE
- help
- DVX BASIC, How This Book Is Organized
- Help Files, 1.17. Include Libraries
- Help Menu, 4.1.8. Help Menu
- Help topic display, 3.9. HelpPane
- Help viewer in BASIC, 1.17. Include Libraries
- help.bas, 1.17. Include Libraries
- HelpCompileMessages$, 1.17. Include Libraries
- HelpPane, 3.9. HelpPane
- HelpPane (help files), 1.17. Include Libraries
- HelpViewTopic, 1.17. Include Libraries
- HEX$, 1.6.9. String Functions
- Hide, 1.7. Form and Control Statements, 2.1. Form
- hlpfile.bas, 1.17. Include Libraries
- HlpLoadTopic, 1.17. Include Libraries
- HlpOpen, 1.17. Include Libraries
- HlpSearch, 1.17. Include Libraries
- Horizontal Layout, 3.8. HBox
- HostLookup$, 1.17. Include Libraries
- HostLookupStart, 1.17. Include Libraries
- HostName$, 1.17. Include Libraries
- HotkeyNames$, 1.17. Include Libraries
- Hotkeys, 4.15. Keyboard Shortcuts
- HotkeySystemUse$, 1.17. Include Libraries
- HOUR, 1.6.13. Date and Time Functions
- HScrollBar, 3.10. HScrollBar
- http.bas, 1.17. Include Libraries
- HttpOpen, 1.17. Include Libraries
- HttpRunFor, 1.17. Include Libraries
- HttpSetBodyFile, 1.17. Include Libraries
I
- Icon (form), 2.1. Form
- Icon views you draw yourself, 1.17. Include Libraries
- IDE, 4.1. DVX BASIC IDE Guide
- IF, 1.4.3.1. IF...THEN...ELSE...END IF
- IIF, 1.6.15. Miscellaneous Functions
- Image, 3.11. Image
- ImageButton, 3.12. ImageButton
- Immediate Window, 4.11. Immediate Window
- IMP, 1.3. Operators
- Implements, 1.8.14. Interfaces (Implements)
- IMPLEMENTS, 1.8.14. Interfaces (Implements)
- Include Libraries, 1.17. Include Libraries
- Index Property, 2.6. Control Arrays
- Index row, 4.8. Properties Panel
- INI, 1.15. INI Functions
- IniRead, 1.15. INI Functions
- Initialize (form), 2.1. Form
- IniWrite, 1.15. INI Functions
- INKEY$, 1.4.10. Console and Graphics
- INPUT, 1.4.7.1. PRINT
- INPUT #, 1.5.1. OPEN
- INPUT$, 1.6.14. File I/O Functions
- InputBox$, 1.7. Form and Control Statements
- INPUTBOX$, 1.7. Form and Control Statements
- INSTR, 1.6.9. String Functions
- INSTRREV, 1.6.9. String Functions
- INT, 1.6.11. Math Functions
- Integer, 1.1. Data Types
- Interface, 1.8.14. Interfaces (Implements)
- Interval, 3.31. Timer
- Invalid use of Null, 1.2. Variants
- IS, 1.3. Operators
- ISARRAY, 1.2. Variants
- ISDATE, 1.6.13. Date and Time Functions
- ISEMPTY, 1.2. Variants
- ISNULL, 1.2. Variants
- ISNUMERIC, 1.2. Variants
- ISOBJECT, 1.2. Variants
- Item, 1.8.15. Collection Object
- ItemCheck, 3.15. ListBox
- ItemData, 3.2. ComboBox, 3.6. DropDown, 3.15. ListBox
- ItemDepth, 3.33. TreeView
- ItemParent, 3.33. TreeView
J
- JOIN$, 1.6.9. String Functions
- JoyAxis, 1.17. Include Libraries
- JoyButton, 1.17. Include Libraries
- JoyCalibration, 1.17. Include Libraries
- JoyCount, 1.17. Include Libraries
- JoyHat, 1.17. Include Libraries
- JoyIsKeyboard, 1.17. Include Libraries
- JoyKeyCode, 1.17. Include Libraries
- JoyKeyIndex, 1.17. Include Libraries
- JoyKeyNameOf$, 1.17. Include Libraries
- Joystick, 1.17. Include Libraries
- joystick.bas, 1.17. Include Libraries
- JoyX, 1.17. Include Libraries
- JoyY, 1.17. Include Libraries
- JSON, 1.17. Include Libraries
- json.bas, 1.17. Include Libraries
- JsonParse, 1.17. Include Libraries
K
- Key Codes, 1.12. Clipboard Object
- Keyboard Shortcuts, 4.15. Keyboard Shortcuts
- KILL, 1.6. File System Statements
- KillDoc, 1.13. Printer Object
L
- Label, 3.13. Label
- Labels, 1.4.6.1. EXIT
- LastError, 3.4. Data
- Late Binding, 1.8. Objects and Class Modules
- layout.bas, 1.17. Include Libraries
- LBOUND, 1.6.14. File I/O Functions
- LCASE$, 1.6.9. String Functions
- LEFT$, 1.6.9. String Functions
- LEN, 1.6.9. String Functions
- LET, 1.4.2.1. DIM
- Library not installed, 1.17. Include Libraries
- Light pen, 1.4.10. Console and Graphics
- LIKE, 1.3. Operators
- Line, 3.14. Line
- LINE (graphics), 1.4.10. Console and Graphics
- LINE INPUT, 1.4.10. Console and Graphics, 1.5.1. OPEN
- Line method, 2.3. Drawing on Forms and PictureBoxes
- Line Numbers, 1.4.6.1. EXIT, 4.3. Code Editor
- LineCount, 3.29. TextArea
- LineNumbers, 3.29. TextArea
- LinkClick, 3.9. HelpPane
- LinkTopic, 3.9. HelpPane
- ListBox, 3.15. ListBox
- ListCount, 3.15. ListBox
- listhelp.bas, 1.17. Include Libraries
- ListIconLabel$, 1.17. Include Libraries
- ListIconMetric, 1.17. Include Libraries
- ListIndex, 3.15. ListBox
- Lists you draw yourself, 1.17. Include Libraries
- ListSelCreate, 1.17. Include Libraries
- ListSelNavigate, 1.17. Include Libraries
- ListSelTypeAhead, 1.17. Include Libraries
- ListTypeAhead, 1.17. Include Libraries
- ListView, 3.16. ListView
- LOAD, 1.7. Form and Control Statements
- Load, 2.1. Form
- LoadFile, 3.20. RichEdit
- LoadFormText, 1.7. Form and Control Statements
- LOADFORMTEXT, 1.7. Form and Control Statements
- LOADPICTURE, 1.6.15. Miscellaneous Functions
- LOADPICTUREDATA, 1.6.15. Miscellaneous Functions
- LOADRESDATA, 1.6.15. Miscellaneous Functions
- LOADRESPICTURE, 1.6.15. Miscellaneous Functions
- LOADRESSTRING, 1.6.15. Miscellaneous Functions
- LOC, 1.6.14. File I/O Functions
- Locals Window, 4.10.6. Locals Window
- LOCATE, 1.4.10. Console and Graphics
- LOF, 1.6.14. File I/O Functions
- LOG, 1.6.11. Math Functions
- Long, 1.1. Data Types
- Long File Names, 1.17. Include Libraries
- LOOP, 1.4.4.1. FOR...NEXT
- LPRINT, 1.4.7.1. PRINT
- LPRINT USING, 1.4.7.1. PRINT
- LSET, 1.4.2.1. DIM
- LTRIM$, 1.6.9. String Functions
M
- Make Control, 4.1.2. File Menu, 4.7. UserControls in the IDE
- Make Package, 4.6. Making a Package
- Mask, 3.30. TextBox
- MaskColor, 3.11. Image, 3.12. ImageButton
- Masked input, 3.30. TextBox
- Master-Detail, 2.4. Data Binding
- Max, 3.10. HScrollBar
- MaxHeight (form), 2.1. Form
- MaxWidth (form), 2.1. Form
- MB, 1.4.9. Sound, Joysticks, and Frames
- Me, 1.7. Form and Control Statements
- Me in Classes, 1.8. Objects and Class Modules
- Menu, 2.5. Menu System
- Menu Bar, 2.5. Menu System
- Menu Control Arrays, 1.7. Form and Control Statements, 2.5. Menu System
- Menu Editor, 4.1.5. View Menu
- Methods, 2.2. Common Properties, Events, and Methods
- MF, 1.4.9. Sound, Joysticks, and Frames
- MID$, 1.6.9. String Functions
- MIDI, 1.17. Include Libraries
- MIDI keyboard, 1.17. Include Libraries
- MidiAcquire, 1.17. Include Libraries
- MidiInClock, 1.17. Include Libraries
- MidiInMessage, 1.17. Include Libraries
- MidiInOpen, 1.17. Include Libraries
- MidiInTime, 1.17. Include Libraries
- MidiPortInfo$, 1.17. Include Libraries
- MidiPut, 1.17. Include Libraries
- MidiRecordNew, 1.17. Include Libraries
- MidiRecordPause, 1.17. Include Libraries
- MidiRecordResume, 1.17. Include Libraries
- MidiRecordSave, 1.17. Include Libraries
- MidiRecordTime, 1.17. Include Libraries
- Min, 3.10. HScrollBar
- MINUTE, 1.6.13. Date and Time Functions
- Missing, 1.2. Variants
- MKDIR, 1.6. File System Statements
- MOD, 1.3. Operators
- Modem, 1.17. Include Libraries
- Module Names, 1.4.2.1. DIM
- MONTH, 1.6.13. Date and Time Functions
- MONTHNAME, 1.6.13. Date and Time Functions
- Mouse Constants, 1.16. Predefined Constants
- MOUSE_DBLCLICK_DEFAULT_MS, 1.17. Include Libraries
- MOUSE_WHEEL_STEP_MAX, 1.17. Include Libraries
- MousePointer, 1.14. Screen Object, 2.2. Common Properties, Events, and Methods
- MousePointer (form), 2.1. Form
- Move (form), 2.1. Form
- MoveBefore, 2.2. Common Properties, Events, and Methods
- MoveFirst, 3.4. Data
- MoveNext, 3.4. Data
- MsgBox, 1.7. Form and Control Statements
- MSGBOX, 1.7. Form and Control Statements
- Multi-Column List, 3.16. ListView
- MultiSelect, 3.15. ListBox, 3.16. ListView
- Music, 1.17. Include Libraries
- Music macro language, 1.4.9. Sound, Joysticks, and Frames
- music.bas, 1.17. Include Libraries
- MusicControl, 1.17. Include Libraries
- MusicError$, 1.17. Include Libraries
- MusicFree, 1.17. Include Libraries
- MusicGetVolume, 1.17. Include Libraries
- MusicInfo$, 1.17. Include Libraries
- MusicLength, 1.17. Include Libraries
- MusicLoad, 1.17. Include Libraries
- MusicLoadMacro, 1.17. Include Libraries
- MusicMidiOpen, 1.17. Include Libraries
- MusicMidiSend, 1.17. Include Libraries
- MusicNoteOff, 1.17. Include Libraries
- MusicNoteOn, 1.17. Include Libraries
- MusicPatchSet$, 1.17. Include Libraries
- MusicPause, 1.17. Include Libraries
- MusicPitchBend, 1.17. Include Libraries
- MusicPlay, 1.17. Include Libraries
- MusicPlaying, 1.17. Include Libraries
- MusicPosition, 1.17. Include Libraries
- MusicProgram, 1.17. Include Libraries
- MusicResume, 1.17. Include Libraries
- MusicRomBank$, 1.17. Include Libraries
- MusicSeek, 1.17. Include Libraries
- MusicSetBank, 1.17. Include Libraries
- MusicStop, 1.17. Include Libraries
- MusicVolume, 1.17. Include Libraries
N
- NAME, 1.6. File System Statements
- Name Resolution, 1.4.2.1. DIM
- Named Arguments, 1.4.5.1. SUB...END SUB
- Named Formats, 1.6.10. Format Function
- Names, 1.4.2.1. DIM
- net.bas, 1.17. Include Libraries
- NetState, 1.17. Include Libraries
- NEW, 1.4.2.1. DIM
- New (forms), 2.1. Form
- New Class Module, 4.1.2. File Menu
- New Form, 4.1.2. File Menu
- New Module, 4.1.2. File Menu
- New Project, 4.1.2. File Menu
- New UserControl, 4.1.2. File Menu, 4.7. UserControls in the IDE
- NewArgs, 2.1. Form
- NewIndex, 3.2. ComboBox, 3.6. DropDown, 3.15. ListBox
- NewPage, 1.13. Printer Object
- NEXT, 1.4.4.1. FOR...NEXT
- NOT, 1.3. Operators
- Nothing, 1.4.2.1. DIM, 1.7. Form and Control Statements
- NOW, 1.6.13. Date and Time Functions
- Null, 1.2. Variants
- Number input dialog, 1.17. Include Libraries
O
- Object Dropdown, 4.3. Code Editor
- Object Type, 1.1. Data Types
- Objects, 1.8. Objects and Class Modules
- OCT$, 1.6.9. String Functions
- ON ERROR, 1.4.8.1. Error Handling
- ON ERROR RESUME NEXT, 1.4.8.1. Error Handling
- ON GOSUB, 1.4.6.1. EXIT
- ON GOTO, 1.4.6.1. EXIT
- OPEN, 1.5.1. OPEN
- Open Project, 4.1.2. File Menu
- Operators, 1.3. Operators
- OPTION, 1.4.2.1. DIM
- OPTION BASE, 1.4.2.1. DIM
- OPTION COMPARE, 1.4.2.1. DIM
- OPTION EXPLICIT, 1.4.2.1. DIM
- Option Explicit, 4.14. Preferences
- OPTIONAL, 1.4.5.1. SUB...END SUB
- OptionButton, 3.17. OptionButton
- OptionIndex, 3.17. OptionButton
- OR, 1.3. Operators
- Output Window, 4.12. Output Window
P
- Package name, 4.6. Making a Package
- Packages, 4.6. Making a Package
- Padding, 2.1. Form, 3.8. HBox, 3.26. StatusBar, 3.32. Toolbar, 3.35. WrapBox
- PAINT, 1.4.10. Console and Graphics
- Paint event, 2.3. Drawing on Forms and PictureBoxes
- PaintPicture, 2.3. Drawing on Forms and PictureBoxes
- PALETTE, 1.4.10. Console and Graphics
- PALETTE USING, 1.4.10. Console and Graphics
- PARAMARRAY, 1.4.5.1. SUB...END SUB
- Parent, 2.2. Common Properties, Events, and Methods
- Paste, 4.1.3. Edit Menu
- Path Separators, 1.17. Include Libraries
- PCOPY, 1.4.10. Console and Graphics
- PEN, 1.4.10. Console and Graphics
- PEN ON, 1.4.10. Console and Graphics
- Percent sizes (.frm), 2.7. FRM File Format
- Picture, 3.11. Image
- PictureBox, 3.18. PictureBox
- pkg.bas, 1.17. Include Libraries
- PkgBuildStart, 1.17. Include Libraries
- PkgCheckData, 1.17. Include Libraries
- PkgFileOwner$, 1.17. Include Libraries
- PkgInstallStart, 1.17. Include Libraries
- PkgKeygen, 1.17. Include Libraries
- PkgKeysRows$, 1.17. Include Libraries
- pkgnet.bas, 1.17. Include Libraries
- PkgNetOpenIn, 1.17. Include Libraries
- PkgOpen, 1.17. Include Libraries
- PkgOpenIn, 1.17. Include Libraries
- PkgPlan, 1.17. Include Libraries
- PkgRemoveStart, 1.17. Include Libraries
- PkgRunFor, 1.17. Include Libraries
- PkgSignData$, 1.17. Include Libraries
- PkgSignStart, 1.17. Include Libraries
- PkgUntrustKey, 1.17. Include Libraries
- PkgVerifyStart, 1.17. Include Libraries
- PkgVersionCompare, 1.17. Include Libraries
- PkgZipCreateStart, 1.17. Include Libraries
- PkgZipExtractStart, 1.17. Include Libraries
- PkgZipListStart, 1.17. Include Libraries
- PkgZipRows$, 1.17. Include Libraries
- PLAY, 1.4.9. Sound, Joysticks, and Frames
- PLAY function, 1.4.9. Sound, Joysticks, and Frames
- PlayNoise, 1.17. Include Libraries
- PlayTone, 1.17. Include Libraries
- PlayTriangle, 1.17. Include Libraries
- PlayWave, 1.17. Include Libraries
- PlayWaveLoop, 1.17. Include Libraries
- PMAP, 1.4.10. Console and Graphics
- POINT, 1.4.10. Console and Graphics
- Point method, 2.3. Drawing on Forms and PictureBoxes
- PopupMenu, 2.5. Menu System
- POS, 1.4.10. Console and Graphics
- Precedence, 1.3. Operators
- Predefined Constants, 1.16. Predefined Constants
- Preferences, 4.1.7. Tools Menu, 4.14. Preferences
- prefs.bas, 1.17. Include Libraries
- PrefsApplyChanges, 1.17. Include Libraries
- PrefsChoiceDefault, 1.17. Include Libraries
- PrefsChoiceLabel$, 1.17. Include Libraries
- PrefsCreate, 1.17. Include Libraries
- PrefsDvxIni$, 1.17. Include Libraries
- PrefsGetChoice, 1.17. Include Libraries
- PrefsGetChoiceFrom, 1.17. Include Libraries
- PrefsGetSecret$, 1.17. Include Libraries
- PrefsKeyName$, 1.17. Include Libraries
- PrefsLoad, 1.17. Include Libraries
- PrefsLoadFailed, 1.17. Include Libraries
- PrefsSaveAs, 1.17. Include Libraries
- PrefsSetSecret, 1.17. Include Libraries
- PrefsVideoWidth, 1.17. Include Libraries
- PRESET, 1.4.10. Console and Graphics
- PRINT, 1.4.7.1. PRINT
- PRINT #, 1.5.1. OPEN
- Print method, 2.3. Drawing on Forms and PictureBoxes
- PRINT Output, 4.12. Output Window
- PRINT USING, 1.4.7.1. PRINT
- print.bas, 1.17. Include Libraries
- PrintAccel, 2.3. Drawing on Forms and PictureBoxes
- PrintChoose, 1.17. Include Libraries
- Printer Object, 1.13. Printer Object
- Printer.Circle, 1.13. Printer Object
- Printer.Copies, 1.13. Printer Object
- Printer.EndDoc, 1.13. Printer Object
- Printer.FontSize, 1.13. Printer Object
- Printer.KillDoc, 1.13. Printer Object
- Printer.Line, 1.13. Printer Object
- Printer.NewPage, 1.13. Printer Object
- Printer.Page, 1.13. Printer Object
- Printer.PaintPicture, 1.13. Printer Object
- Printer.Print, 1.13. Printer Object
- Printer.PSet, 1.13. Printer Object
- PrintForm, 1.17. Include Libraries
- PrintPageSetting, 1.17. Include Libraries
- PrintPageSetup, 1.17. Include Libraries
- PrintPictureDialog, 1.17. Include Libraries
- PrintPortStatus, 1.17. Include Libraries
- PrintTextDialog, 1.17. Include Libraries
- PRIVATE, 1.4.2.1. DIM
- PROGMAN.INI, 1.17. Include Libraries
- Program groups, 1.17. Include Libraries
- Program priority, 1.17. Include Libraries
- Program Resources, 4.5.1. Project Files (.dbp)
- Program Screen Window, 4.12. Output Window
- ProgressBar, 3.19. ProgressBar
- ProjCtlHeader$, 1.17. Include Libraries
- ProjCtlKeys$, 1.17. Include Libraries
- ProjCtlNew$, 1.17. Include Libraries
- ProjCtlSetHeader$, 1.17. Include Libraries
- Project Explorer, 4.5.1. Project Files (.dbp)
- Project files, 1.17. Include Libraries
- Project Files, 4.5.1. Project Files (.dbp)
- Project Fonts, 4.5.1. Project Files (.dbp)
- Project Properties, 4.1.2. File Menu
- Project System, 4.5.1. Project Files (.dbp)
- Project Type, 4.5.1. Project Files (.dbp)
- ProjGet$, 1.17. Include Libraries
- ProjNew, 1.17. Include Libraries
- ProjOpen, 1.17. Include Libraries
- Properties, 2.2. Common Properties, Events, and Methods
- Properties Panel, 4.8. Properties Panel
- PROPERTY, 1.8. Objects and Class Modules
- PROPERTY GET, 1.8. Objects and Class Modules
- PROPERTY LET, 1.8. Objects and Class Modules
- Property List, 4.8. Properties Panel
- PROPERTY SET, 1.8. Objects and Class Modules
- PSET, 1.4.10. Console and Graphics
- PSet method, 2.3. Drawing on Forms and PictureBoxes
- PUBLIC, 1.4.2.1. DIM
- PUT, 1.5.1. OPEN
Q
- QBCOLOR, 1.6.11. Math Functions
- QueryUnload, 2.1. Form
R
- Radio Button, 3.17. OptionButton
- RaiseEvent, 1.8.13. Events
- RAISEEVENT, 1.8.13. Events
- RANDOMIZE, 1.4.8.1. Error Handling
- RANDOMIZE TIMER, 1.4.8.1. Error Handling
- Raster Operations, 2.3. Drawing on Forms and PictureBoxes
- READ, 1.4.7.1. PRINT
- RealMode, 3.24. SpinButton
- Recent files menu, 2.5. Menu System
- RecordCancel, 1.17. Include Libraries
- Recording, 1.17. Include Libraries
- RecordPause, 1.17. Include Libraries
- RecordResume, 1.17. Include Libraries
- RecordSource, 3.4. Data
- RecordStart, 1.17. Include Libraries
- RecordStop, 1.17. Include Libraries
- REDIM, 1.4.2.1. DIM
- Reference Counting, 1.8. Objects and Class Modules
- REM, 1.4.1. Statements
- Remove, 1.8.15. Collection Object
- Remove File, 4.1.2. File Menu
- RemoveControl, 1.7. Form and Control Statements
- RemoveItem, 3.15. ListBox, 3.33. TreeView
- RemoveMenuItem, 2.5. Menu System
- Rename File, 4.1.2. File Menu
- Repeat, 3.31. Timer
- REPL, 4.11. Immediate Window
- Replace, 4.1.3. Edit Menu, 4.13. Find / Replace
- REPLACE$, 1.6.9. String Functions
- ReplaceAll, 3.29. TextArea
- ReplaceSelection, 3.29. TextArea
- Reposition, 3.4. Data
- RES_NAME_ICON, 1.17. Include Libraries
- ResAddData, 1.17. Include Libraries
- RESET, 1.5.1. OPEN
- ResGetData$, 1.17. Include Libraries
- Resizable, 2.1. Form
- resource.bas, 1.17. Include Libraries
- Resources, 1.6.15. Miscellaneous Functions
- Resources Section, 4.5.1. Project Files (.dbp)
- RESTORE, 1.4.7.1. PRINT
- RESUME, 1.4.8.1. Error Handling
- RESUME NEXT, 1.4.8.1. Error Handling
- RETURN, 1.4.6.1. EXIT
- RGB, 1.6.11. Math Functions
- RichEdit, 1.17. Include Libraries, 3.20. RichEdit
- RichLabel, 1.17. Include Libraries, 3.21. RichLabel
- richtext.bas, 1.17. Include Libraries
- RIGHT$, 1.6.9. String Functions
- RMDIR, 1.6. File System Statements
- RND, 1.6.11. Math Functions
- ROUND, 1.6.11. Math Functions
- RSET, 1.4.2.1. DIM
- RTF, 3.20. RichEdit
- rtfCenter, 1.16. Predefined Constants
- rtfLeft, 1.16. Predefined Constants
- rtfRight, 1.16. Predefined Constants
- RTRIM$, 1.6.9. String Functions
- Run, 4.1.4. Run Menu
- Run Menu, 4.1.4. Run Menu
- Run to Cursor, 4.1.4. Run Menu
- Run Without Recompile, 4.1.4. Run Menu
- RunCreate, 1.17. Include Libraries
- Running programs, 1.17. Include Libraries
- RunOutput$, 1.17. Include Libraries
- RunPoll, 1.17. Include Libraries
- RunStart, 1.17. Include Libraries
- Runtime Errors, 4.12. Output Window
S
- Save All, 4.1.2. File Menu
- Save File, 4.1.2. File Menu
- Save on Run, 4.1.4. Run Menu
- Save Project, 4.1.2. File Menu
- SaveFile, 3.20. RichEdit
- SaveScreenshot, 2.1. Form
- Scale, 2.3. Drawing on Forms and PictureBoxes
- ScaleHeight, 2.3. Drawing on Forms and PictureBoxes
- ScaleLeft, 2.3. Drawing on Forms and PictureBoxes
- ScaleMode, 2.3. Drawing on Forms and PictureBoxes
- ScaleTop, 2.3. Drawing on Forms and PictureBoxes
- ScaleWidth, 2.3. Drawing on Forms and PictureBoxes
- ScaleX, 2.3. Drawing on Forms and PictureBoxes
- ScaleY, 2.3. Drawing on Forms and PictureBoxes
- SCREEN, 1.4.10. Console and Graphics
- SCREEN function, 1.4.10. Console and Graphics
- Screen Object, 1.14. Screen Object
- Screen pages, 1.4.10. Console and Graphics
- Screen.ActiveControl, 1.14. Screen Object
- Screen.ActiveForm, 1.14. Screen Object
- Screen.Arrange, 1.14. Screen Object
- Screen.BitsPerPixel, 1.14. Screen Object
- Screen.DebugLayout, 1.14. Screen Object
- Screen.Height, 1.14. Screen Object
- Screen.MousePointer, 1.14. Screen Object
- Screen.Width, 1.14. Screen Object
- Scrollable Container, 3.22. ScrollPane
- ScrollBarClick, 2.3. Drawing on Forms and PictureBoxes
- ScrollBarsNeeded, 2.3. Drawing on Forms and PictureBoxes
- ScrollPane, 3.22. ScrollPane
- ScrollToControl, 2.2. Common Properties, Events, and Methods
- Search, 4.13. Find / Replace
- SecAeadLock$, 1.17. Include Libraries
- SecAeadUnlock$, 1.17. Include Libraries
- SecCipherCreate, 1.17. Include Libraries
- SecDhCreate, 1.17. Include Libraries
- SecDhStep, 1.17. Include Libraries
- SecEd25519Check, 1.17. Include Libraries
- SecEd25519Sign$, 1.17. Include Libraries
- SecHmac$, 1.17. Include Libraries
- SECOND, 1.6.13. Date and Time Functions
- SecRandom$, 1.17. Include Libraries
- SecSha256$, 1.17. Include Libraries
- security.bas, 1.17. Include Libraries
- SecX25519$, 1.17. Include Libraries
- SEEK, 1.5.1. OPEN
- SelAlignment, 3.20. RichEdit
- SelBold, 3.20. RichEdit
- SelColor, 3.20. RichEdit
- Select All, 4.1.3. Edit Menu
- SELECT CASE, 1.4.3.1. IF...THEN...ELSE...END IF
- SelectAll, 3.30. TextBox
- Selected, 3.15. ListBox, 3.16. ListView
- SelectedRows, 3.16. ListView
- SelFontName, 3.20. RichEdit
- SelFontSize, 3.20. RichEdit
- SelItalic, 3.20. RichEdit
- SelLength, 3.29. TextArea
- SelRTF, 3.20. RichEdit
- SelStart, 3.29. TextArea
- SelStrikethru, 3.20. RichEdit
- SelText, 3.29. TextArea, 3.30. TextBox
- SelUnderline, 3.20. RichEdit
- Send Event, 3.28. Terminal
- SendKeys, 1.17. Include Libraries
- Separator, 2.5. Menu System, 3.14. Line
- SerLastError, 1.17. Include Libraries
- SerSet, 1.17. Include Libraries
- SET, 1.4.2.1. DIM
- SetActive, 3.27. TabStrip
- SETATTR, 1.6. File System Statements
- SetColor, 3.21. RichLabel
- SetColumns, 3.16. ListView
- SetCursor, 3.29. TextArea
- SetEvent, 1.7. Form and Control Statements
- SetFont, 3.21. RichLabel
- SetItemTag, 3.33. TreeView
- SetItemText, 3.33. TreeView
- SetLineMarker, 3.29. TextArea
- SetPenColor, 3.18. PictureBox
- SetPenSize, 3.18. PictureBox
- SetPictureData, 3.11. Image, 3.12. ImageButton, 3.18. PictureBox
- SetRange, 3.24. SpinButton
- SetRows, 3.16. ListView
- SetSelected, 3.17. OptionButton
- SetSort, 3.16. ListView
- SetStep, 3.24. SpinButton
- SetStyle, 3.21. RichLabel
- SetSyntaxColor, 3.29. TextArea
- Settings, 4.14. Preferences
- Settings Files, 1.17. Include Libraries
- Several copies of a form, 2.1. Form
- SGN, 1.6.11. Math Functions
- SHARED, 1.4.2.1. DIM
- SHELL, 1.4.8.1. Error Handling
- SHELL_PRIORITY_NORMAL, 1.17. Include Libraries
- ShellAppId, 1.17. Include Libraries
- ShellAppIsHung, 1.17. Include Libraries
- ShellAppMemory, 1.17. Include Libraries
- ShellArg$, 1.17. Include Libraries
- ShellArgCount, 1.17. Include Libraries
- ShellArgQuote$, 1.17. Include Libraries
- ShellCommandArgs$, 1.17. Include Libraries
- ShellCommandProgram$, 1.17. Include Libraries
- ShellGroupMove, 1.17. Include Libraries
- ShellGroupsLoad, 1.17. Include Libraries
- ShellItemGet$, 1.17. Include Libraries
- ShellItemIcon$, 1.17. Include Libraries
- ShellItemKeyError$, 1.17. Include Libraries
- ShellItemKeyValid, 1.17. Include Libraries
- ShellMemoryRetained, 1.17. Include Libraries
- ShellPriority, 1.17. Include Libraries
- ShellProgramsFolder$, 1.17. Include Libraries
- ShellReturnedFromDos, 1.17. Include Libraries
- ShellRunDosWait, 1.17. Include Libraries
- ShellRunningActivate, 1.17. Include Libraries
- ShellRunningClose, 1.17. Include Libraries
- ShellRunningFind, 1.17. Include Libraries
- ShellRunningId, 1.17. Include Libraries
- ShellRunningKill, 1.17. Include Libraries
- ShellRunningName$, 1.17. Include Libraries
- ShellRunningPriority, 1.17. Include Libraries
- ShellRunningSetPriority, 1.17. Include Libraries
- ShellSetPriority, 1.17. Include Libraries
- Shortcut, 2.5. Menu System
- Shortcut Keys, 2.5. Menu System
- ShortcutText, 2.5. Menu System
- Show, 1.7. Form and Control Statements, 2.1. Form
- ShowTopic, 3.9. HelpPane
- Signatures, 1.17. Include Libraries
- Signing a package, 4.6. Making a Package
- SIN, 1.6.11. Math Functions
- Single, 1.1. Data Types
- SizeChars, 1.17. Include Libraries
- SizePercent, 1.17. Include Libraries
- Sizes (Properties window), 4.8. Properties Panel
- Sizes in a .frm, 2.7. FRM File Format
- Sizes in characters, 1.17. Include Libraries
- SLEEP, 1.4.8.1. Error Handling
- Slider, 3.10. HScrollBar
- SortColumn, 3.16. ListView
- Sorted, 3.2. ComboBox, 3.6. DropDown, 3.15. ListBox
- SortOrder, 3.16. ListView
- SOUND, 1.4.9. Sound, Joysticks, and Frames
- Sound, 1.17. Include Libraries
- sound.bas, 1.17. Include Libraries
- SoundCaps, 1.17. Include Libraries
- SoundCreate, 1.17. Include Libraries
- SoundError$, 1.17. Include Libraries
- SoundFont, 1.17. Include Libraries
- SoundFree, 1.17. Include Libraries
- SoundGetVolume, 1.17. Include Libraries
- SoundInfo$, 1.17. Include Libraries
- SoundLength, 1.17. Include Libraries
- SoundLoad, 1.17. Include Libraries
- SoundPause, 1.17. Include Libraries
- SoundPlay, 1.17. Include Libraries
- SoundPlayEvent, 1.17. Include Libraries
- SoundPlaying, 1.17. Include Libraries
- SoundResume, 1.17. Include Libraries
- SoundSetFrequency, 1.17. Include Libraries
- SoundSetPan, 1.17. Include Libraries
- SoundSetPitch, 1.17. Include Libraries
- SoundSetVolume, 1.17. Include Libraries
- SoundStreamClose, 1.17. Include Libraries
- SoundStreamFlush, 1.17. Include Libraries
- SoundStreamOpen, 1.17. Include Libraries
- SoundStreamWrite, 1.17. Include Libraries
- SoundVolume, 1.17. Include Libraries
- Source Map, 4.5.1. Project Files (.dbp)
- SPACE$, 1.6.9. String Functions
- Spacer, 3.23. Spacer
- Spacing, 2.1. Form, 3.8. HBox, 3.26. StatusBar, 3.32. Toolbar, 3.35. WrapBox
- SPC, 1.4.7.1. PRINT
- SpinButton, 3.24. SpinButton
- Spinner, 3.24. SpinButton
- SPLIT, 1.6.9. String Functions
- Split Pane, 3.25. Splitter
- Splitter, 3.25. Splitter
- sql.bas, 1.17. Include Libraries
- SQLAffected, 1.9. SQL Functions
- SQLClose, 1.9. SQL Functions
- SQLEof, 1.9. SQL Functions
- SQLError$, 1.9. SQL Functions
- SQLEscape$, 1.9. SQL Functions
- SQLExec, 1.9. SQL Functions
- SQLField$, 1.9. SQL Functions
- SQLFieldCount, 1.9. SQL Functions
- SQLFieldDbl, 1.9. SQL Functions
- SQLFieldInt, 1.9. SQL Functions
- SQLFieldName$, 1.9. SQL Functions
- SQLFieldText$, 1.9. SQL Functions
- SQLFreeResult, 1.9. SQL Functions
- SQLite, 1.9. SQL Functions, 3.4. Data
- SQLNext, 1.9. SQL Functions
- SQLOpen, 1.9. SQL Functions
- SQLQuery, 1.9. SQL Functions
- SQR, 1.6.11. Math Functions
- Stack Trace, 4.10.7. Call Stack Window
- Start, 3.31. Timer
- Statement Targets, 1.4.2.1. DIM
- Statements, 1.4.1. Statements
- STATIC, 1.4.2.1. DIM
- Status Bar Toggle, 4.1.5. View Menu
- StatusBar, 3.26. StatusBar
- STEP, 1.4.4.1. FOR...NEXT
- Step Into, 4.1.4. Run Menu
- Step Out, 4.1.4. Run Menu
- Step Over, 4.1.4. Run Menu
- Stepping, 4.10. Debugger
- STICK, 1.4.9. Sound, Joysticks, and Frames
- Stop, 3.31. Timer, 4.1.4. Run Menu
- StopAllSounds, 1.17. Include Libraries
- StopWave, 1.17. Include Libraries
- STR$, 1.6.9. String Functions
- STRCOMP, 1.6.9. String Functions
- STRIG, 1.4.9. Sound, Joysticks, and Frames
- String, 1.1. Data Types
- String Constants, 1.16. Predefined Constants
- String Table, 1.6.15. Miscellaneous Functions, 4.5.1. Project Files (.dbp)
- STRING$, 1.6.9. String Functions
- STRREVERSE$, 1.6.9. String Functions
- Style (ListBox), 3.15. ListBox
- SUB, 1.4.5.1. SUB...END SUB
- Submenu, 2.5. Menu System
- SWAP, 1.4.2.1. DIM
- Syntax Highlighting, 4.3. Code Editor
- SYS_VIDEO_DEFAULT_WIDTH, 1.17. Include Libraries
- SysFontGlyphRow, 1.17. Include Libraries
- SysGetColor, 1.17. Include Libraries
- SysLibraryLoaded, 1.17. Include Libraries
- SysLoadTheme, 1.17. Include Libraries
- SysMemoryFreeKb, 1.17. Include Libraries
- SysMemoryTotalKb, 1.17. Include Libraries
- SysMouseButtons, 1.17. Include Libraries
- SysMouseX, 1.17. Include Libraries
- SysPicturePatterns$, 1.17. Include Libraries
- SysScreenshot, 1.17. Include Libraries
- SysSendKey, 1.17. Include Libraries
- SysSetColor, 1.17. Include Libraries
- SysSetMouse, 1.17. Include Libraries
- SysSetMousePos, 1.17. Include Libraries
- SysSetTextSmoothing, 1.17. Include Libraries
- SysSetVideoMode, 1.17. Include Libraries
- SysSetWallpaper, 1.17. Include Libraries
- SysShiftState, 1.17. Include Libraries
- System font glyphs, 1.17. Include Libraries
- system.bas, 1.17. Include Libraries
T
- TAB, 1.4.7.1. PRINT
- Tab Width, 4.14. Preferences
- TabControl, 3.27. TabStrip
- TabStrip, 3.27. TabStrip
- Tag, 2.2. Common Properties, Events, and Methods
- Tag (form), 2.1. Form
- TAN, 1.6.11. Math Functions
- TcpConnect, 1.17. Include Libraries
- TcpConnectStart, 1.17. Include Libraries
- TcpPeek$, 1.17. Include Libraries
- TcpPeer$, 1.17. Include Libraries
- TcpRecv$, 1.17. Include Libraries
- TcpSendSome, 1.17. Include Libraries
- Telnet, 1.17. Include Libraries
- Terminal, 3.28. Terminal
- Terminate (form), 2.1. Form
- Text, 3.30. TextBox
- Text smoothing, 1.17. Include Libraries
- TextArea, 3.29. TextArea
- TextBox, 3.30. TextBox
- TextHeight, 2.3. Drawing on Forms and PictureBoxes
- TextRTF, 3.20. RichEdit
- TextWidth, 2.3. Drawing on Forms and PictureBoxes
- TextWidthAccel, 2.3. Drawing on Forms and PictureBoxes
- THEN, 1.4.3.1. IF...THEN...ELSE...END IF
- TIME, 1.6.13. Date and Time Functions
- TIME$, 1.6.15. Miscellaneous Functions
- TIMER, 1.6.11. Math Functions
- Timer, 3.31. Timer
- TIMESERIAL, 1.6.13. Date and Time Functions
- TIMEVALUE, 1.6.13. Date and Time Functions
- Toggle Breakpoint, 4.1.4. Run Menu
- Toolbar, 3.32. Toolbar, 4.2. Toolbar
- Toolbar Toggle, 4.1.5. View Menu
- Toolbox, 4.9. Toolbox
- Tools Menu, 4.1.7. Tools Menu
- TopIndex, 3.2. ComboBox, 3.6. DropDown, 3.15. ListBox
- TreeView, 3.33. TreeView
- TRIM$, 1.6.9. String Functions
- True, 1.16. Predefined Constants
- TYPE, 1.4.2.1. DIM
- TYPENAME, 1.2. Variants
- TypeOf, 1.1. Data Types
- TYPEOF, 1.3. Operators
U
- UBOUND, 1.6.14. File I/O Functions
- UCASE$, 1.6.9. String Functions
- UdpSend, 1.17. Include Libraries
- UNLOAD, 1.7. Form and Control Statements
- Unload, 2.1. Form
- UnloadMode, 2.1. Form
- UNTIL, 1.4.4.1. FOR...NEXT
- UseMaskColor, 3.11. Image, 3.12. ImageButton
- User Folder, 1.17. Include Libraries
- UserControl, 2.8. UserControls: Your Own Controls
- USERCONTROL, 2.8. UserControls: Your Own Controls
- UserControls in the IDE, 4.7. UserControls in the IDE
- UserMode in the Designer, 4.7. UserControls in the IDE
V
- VAL, 1.6.9. String Functions
- Validate, 3.4. Data
- Value, 3.1. CheckBox, 3.3. CommandButton
- Variable Assignment, 4.11. Immediate Window
- Variable Inspection, 4.10.6. Locals Window
- Variant, 1.2. Variants
- VARIANT, 1.2. Variants
- Variant Type, 1.1. Data Types
- VARPTR$, 1.4.10. Console and Graphics
- VARTYPE, 1.2. Variants
- VB_Name, 1.8. Objects and Class Modules
- VB_UserMemId, 1.8. Objects and Class Modules
- vbAlignBottom, 1.16. Predefined Constants
- vbAlignLeft, 1.16. Predefined Constants
- vbAlignNone, 1.16. Predefined Constants
- vbAlignRight, 1.16. Predefined Constants
- vbAlignTop, 1.16. Predefined Constants, 3.18. PictureBox
- vbAppTaskManager, 1.16. Predefined Constants
- vbAppWindows, 1.16. Predefined Constants
- vbArchive, 1.16. Predefined Constants
- vbArray, 1.16. Predefined Constants
- vbArrow, 2.2. Common Properties, Events, and Methods
- vbAutomatic, 1.16. Predefined Constants
- vbBack, 1.16. Predefined Constants
- vbBeginDrag, 1.16. Predefined Constants
- vbBinaryCompare, 1.16. Predefined Constants
- vbBlack, 1.16. Predefined Constants
- vbBlue, 1.16. Predefined Constants
- vbBoolean, 1.16. Predefined Constants
- vbBoth, 2.3. Drawing on Forms and PictureBoxes
- vbBringToFront, 1.16. Predefined Constants
- vbByte, 1.16. Predefined Constants
- vbCancel, 1.16. Predefined Constants
- vbCascade, 1.14. Screen Object
- vbCenter, 1.16. Predefined Constants
- vbCentimeters, 1.16. Predefined Constants
- vbCFText, 1.12. Clipboard Object, 1.16. Predefined Constants
- vbCharacters, 1.16. Predefined Constants
- vbCr, 1.16. Predefined Constants
- vbCritical, 1.16. Predefined Constants
- vbCrLf, 1.16. Predefined Constants
- vbCross, 1.16. Predefined Constants
- vbCrosshair, 2.2. Common Properties, Events, and Methods
- vbCtrlMask, 1.12. Clipboard Object
- vbCurrency, 1.16. Predefined Constants
- vbCyan, 1.16. Predefined Constants
- vbDash, 1.16. Predefined Constants
- vbDashDot, 1.16. Predefined Constants
- vbDashDotDot, 1.16. Predefined Constants
- vbDataAction, 1.16. Predefined Constants, 3.4. Data
- vbDataActionCancel, 1.16. Predefined Constants
- vbDataActionUnload, 1.16. Predefined Constants
- vbDataObject, 1.16. Predefined Constants
- vbDate, 1.16. Predefined Constants
- vbDefault, 1.16. Predefined Constants
- vbDiagonalCross, 1.16. Predefined Constants
- vbDirectory, 1.16. Predefined Constants
- vbDot, 1.16. Predefined Constants
- vbDouble, 1.16. Predefined Constants
- vbDownwardDiagonal, 1.16. Predefined Constants
- vbEmpty, 1.16. Predefined Constants
- vbEndDrag, 1.16. Predefined Constants
- vbEnter, 1.16. Predefined Constants
- vbError, 1.16. Predefined Constants
- vbExclamation, 1.16. Predefined Constants
- vbFalse, 1.16. Predefined Constants
- vbFirstFourDays, 1.16. Predefined Constants
- vbFirstFullWeek, 1.16. Predefined Constants
- vbFirstJan1, 1.16. Predefined Constants
- vbFormCode, 1.16. Predefined Constants
- vbFormControlMenu, 1.16. Predefined Constants
- vbFormFeed, 1.16. Predefined Constants
- vbFormMDIForm, 1.16. Predefined Constants
- vbFormOwner, 1.16. Predefined Constants
- vbFriday, 1.16. Predefined Constants
- vbFSSolid, 1.16. Predefined Constants
- vbFSTransparent, 1.16. Predefined Constants
- vbGeneralDate, 1.6.10. Format Function, 1.16. Predefined Constants
- vbGet, 1.16. Predefined Constants
- vbGrayCopy, 2.3. Drawing on Forms and PictureBoxes
- vbGreen, 1.16. Predefined Constants
- vbHidden, 1.16. Predefined Constants
- vbHimetric, 1.16. Predefined Constants, 2.3. Drawing on Forms and PictureBoxes
- vbHorizontal, 2.3. Drawing on Forms and PictureBoxes
- vbHorizontalLine, 1.16. Predefined Constants
- vbHourglass, 1.14. Screen Object
- vbInches, 1.16. Predefined Constants
- vbInformation, 1.16. Predefined Constants
- vbInsideSolid, 1.16. Predefined Constants
- vbInteger, 1.16. Predefined Constants
- vbInvisible, 1.16. Predefined Constants
- vbKeyBack, 1.12. Clipboard Object
- vbKeyDelete, 1.12. Clipboard Object
- vbKeyReturn, 1.12. Clipboard Object
- vbLeave, 1.16. Predefined Constants
- vbLeftButton, 1.16. Predefined Constants
- vbLeftJustify, 1.16. Predefined Constants
- vbLet, 1.16. Predefined Constants
- vbLf, 1.16. Predefined Constants
- vbListBoxCheckbox, 1.16. Predefined Constants, 3.15. ListBox
- vbListBoxStandard, 1.16. Predefined Constants
- vbLong, 1.16. Predefined Constants
- vbLongDate, 1.16. Predefined Constants
- vbLongTime, 1.16. Predefined Constants
- vbMagenta, 1.16. Predefined Constants
- vbManual, 1.16. Predefined Constants
- vbMaximized, 1.16. Predefined Constants, 2.1. Form
- vbMethod, 1.16. Predefined Constants
- vbMiddleButton, 1.16. Predefined Constants
- vbMillimeters, 1.16. Predefined Constants
- vbMinimized, 1.16. Predefined Constants, 2.1. Form
- vbModal, 1.7. Form and Control Statements, 2.1. Form
- vbMonday, 1.16. Predefined Constants
- vbMultiSelectExtended, 1.16. Predefined Constants
- vbMultiSelectNone, 1.16. Predefined Constants
- vbMultiSelectSimple, 1.16. Predefined Constants
- vbNewLine, 1.16. Predefined Constants
- vbNo, 1.16. Predefined Constants
- vbNoDrop, 2.2. Common Properties, Events, and Methods
- vbNormal, 1.16. Predefined Constants
- vbNull, 1.16. Predefined Constants
- vbNullChar, 1.16. Predefined Constants
- vbNullString, 1.16. Predefined Constants
- vbObject, 1.16. Predefined Constants
- vbObjectError, 1.16. Predefined Constants
- vbOK, 1.16. Predefined Constants
- vbOKCancel, 1.16. Predefined Constants
- vbOKOnly, 1.16. Predefined Constants
- vbOver, 1.16. Predefined Constants
- VBox, 3.34. VBox
- vbPicTypeBitmap, 1.16. Predefined Constants
- vbPicTypeNone, 1.16. Predefined Constants
- vbPixels, 1.16. Predefined Constants
- vbPoints, 1.16. Predefined Constants
- vbPopupMenuCenterAlign, 1.16. Predefined Constants
- vbPopupMenuLeftAlign, 1.16. Predefined Constants
- vbPopupMenuLeftButton, 1.16. Predefined Constants
- vbPopupMenuRightAlign, 1.16. Predefined Constants
- vbPopupMenuRightButton, 1.16. Predefined Constants
- vbPRCMColor, 1.13. Printer Object
- vbPRCMMonochrome, 1.13. Printer Object
- vbPRORLandscape, 1.13. Printer Object
- vbPRORPortrait, 1.13. Printer Object
- vbQuestion, 1.16. Predefined Constants
- vbReadOnly, 1.16. Predefined Constants
- vbRed, 1.16. Predefined Constants
- vbRetry, 1.16. Predefined Constants
- vbRetryCancel, 1.16. Predefined Constants
- vbRightButton, 1.16. Predefined Constants
- vbRightJustify, 1.16. Predefined Constants
- vbSaturday, 1.16. Predefined Constants
- vbSBNone, 2.3. Drawing on Forms and PictureBoxes
- vbSendToBack, 1.16. Predefined Constants
- vbSet, 1.16. Predefined Constants
- vbShortDate, 1.16. Predefined Constants
- vbShortTime, 1.16. Predefined Constants
- vbSingle, 1.16. Predefined Constants
- vbSizeNESW, 2.2. Common Properties, Events, and Methods
- vbSizeNS, 2.2. Common Properties, Events, and Methods
- vbSizeNWSE, 2.2. Common Properties, Events, and Methods
- vbSizeWE, 2.2. Common Properties, Events, and Methods
- vbSolid, 1.16. Predefined Constants
- vbSrcCopy, 2.3. Drawing on Forms and PictureBoxes
- vbString, 1.16. Predefined Constants
- vbSunday, 1.16. Predefined Constants
- vbSyntaxComment, 1.16. Predefined Constants
- vbSyntaxKeyword, 1.16. Predefined Constants
- vbSyntaxNumber, 1.16. Predefined Constants
- vbSyntaxOperator, 1.16. Predefined Constants
- vbSyntaxString, 1.16. Predefined Constants
- vbSyntaxText, 1.16. Predefined Constants
- vbSyntaxType, 1.16. Predefined Constants
- vbSystem, 1.16. Predefined Constants
- vbTab, 1.16. Predefined Constants
- vbTextCompare, 1.16. Predefined Constants
- vbThursday, 1.16. Predefined Constants
- vbTileGrid, 1.14. Screen Object
- vbTileHorizontal, 1.14. Screen Object
- vbTileVertical, 1.14. Screen Object
- vbTransparentCopy, 2.3. Drawing on Forms and PictureBoxes
- vbTrue, 1.16. Predefined Constants
- vbTuesday, 1.16. Predefined Constants
- vbTwips, 1.16. Predefined Constants
- vbUpwardDiagonal, 1.16. Predefined Constants
- vbUseCompareOption, 1.16. Predefined Constants
- vbUseDefault, 1.6.10. Format Function, 1.16. Predefined Constants
- vbUser, 1.16. Predefined Constants
- vbUserDefinedType, 1.16. Predefined Constants
- vbUseSystem, 1.16. Predefined Constants
- vbUseSystemDayOfWeek, 1.16. Predefined Constants
- vbVariant, 1.16. Predefined Constants
- vbVertical, 2.3. Drawing on Forms and PictureBoxes
- vbVerticalLine, 1.16. Predefined Constants
- vbVerticalTab, 1.16. Predefined Constants
- vbWednesday, 1.16. Predefined Constants
- vbWhite, 1.16. Predefined Constants
- vbYellow, 1.16. Predefined Constants
- vbYes, 1.16. Predefined Constants
- vbYesNo, 1.16. Predefined Constants
- vbYesNoCancel, 1.16. Predefined Constants
- Vertical, 3.14. Line
- Vertical Layout, 3.34. VBox
- VIEW, 1.4.10. Console and Graphics
- View Menu, 4.1.5. View Menu
- VIEW PRINT, 1.4.10. Console and Graphics
- Visual Basic, 4.1. DVX BASIC IDE Guide
- VT100, 3.28. Terminal
W
- Watch Expressions, 4.10.8. Watch Window
- Watch Window, 4.10.8. Watch Window
- Wavetable synthesizer, 1.17. Include Libraries
- Web requests, 1.17. Include Libraries
- WEEKDAY, 1.6.13. Date and Time Functions
- WEEKDAYNAME, 1.6.13. Date and Time Functions
- WEND, 1.4.4.1. FOR...NEXT
- WHILE, 1.4.4.1. FOR...NEXT
- Whole-Number Arguments, 1.1. Data Types
- Widget Palette, 4.9. Toolbox
- WIDTH, 1.4.10. Console and Graphics
- WIDTH #, 1.5.1. OPEN
- WIDTH LPRINT, 1.5.1. OPEN
- WINDOW, 1.4.10. Console and Graphics
- Window, 2.1. Form
- Window Menu, 4.1.6. Window Menu
- WindowState, 2.1. Form
- With, 1.7. Form and Control Statements
- WITH, 1.8. Objects and Class Modules
- WITH…END WITH, 1.8. Objects and Class Modules
- WithEvents, 1.8.13. Events
- WITHEVENTS, 1.8.13. Events
- WordWrap, 3.13. Label
- WrapBox, 3.35. WrapBox
- WRITE #, 1.5.1. OPEN
- Writing a control, 2.8. UserControls: Your Own Controls
- WtAlloc, 1.17. Include Libraries
- WtInfo$, 1.17. Include Libraries
- WtStart, 1.17. Include Libraries
- WtUpload, 1.17. Include Libraries
- WYSIWYG, 4.4. Form Designer
X
- xfer.bas, 1.17. Include Libraries
- XferAnswer, 1.17. Include Libraries
- XferCrc32, 1.17. Include Libraries
- XferStatus, 1.17. Include Libraries
- XOR, 1.3. Operators
Y
Z
- ZIP Files, 1.17. Include Libraries
- ZMODEM, 1.17. Include Libraries
- ZOrder, 2.1. Form