BM Cimplicity Basic Control Engine and Scripting Reference Master
BM Cimplicity Basic Control Engine and Scripting Reference Master
CIMPLICITY 2022
Basic Control Engine and
Scripting Reference
No part of this publication may be reproduced in any form, or stored in a database or retrieval system, or transmitted or distributed in any
form by any means, electronic, mechanical photocopying, recording or otherwise, without the prior written permission of General Electric
Company. Information contained herein is subject to change without notice.
Trademark Notices
GE, the GE Monogram, and Predix are either registered trademarks or trademarks of General Electric Company.
Microsoft® is a registered trademark of Microsoft Corporation, in the United States and/or other countries.
We want to hear from you. If you have any comments, questions, or suggestions about our documentation, send them to the following email
address:
doc@ge.com
Chapter 1. Script Editors.................................................................................................................. 42
Arrays................................................................................................................................. 177
Clipboard............................................................................................................................ 178
Comments........................................................................................................................... 178
Comparison Operators........................................................................................................178
Conversion..........................................................................................................................180
Data Types..........................................................................................................................181
Database..............................................................................................................................181
Date/time.............................................................................................................................182
DDE.................................................................................................................................... 182
Contents | v
Error Handling....................................................................................................................183
File System.........................................................................................................................184
Financial............................................................................................................................. 184
INI Files..............................................................................................................................185
Logical/binary Operators....................................................................................................185
Math....................................................................................................................................186
Miscellaneous..................................................................................................................... 186
Objects................................................................................................................................ 187
Parsing................................................................................................................................ 187
Printing............................................................................................................................... 188
Procedures...........................................................................................................................188
Strings................................................................................................................................. 188
User Dialogs.......................................................................................................................189
Variants...............................................................................................................................191
Symbols...................................................................................................................................... 191
Symbols.............................................................................................................................. 191
- (operator)..........................................................................................................................192
#Const (directive)............................................................................................................... 193
#If...Then...#Else (directive)...............................................................................................194
& (operator)........................................................................................................................196
() (keyword)........................................................................................................................196
* (operator).........................................................................................................................197
. (keyword)......................................................................................................................... 197
/ (operator)..........................................................................................................................198
\ (operator)..........................................................................................................................199
^ (operator)......................................................................................................................... 199
_ (keyword)........................................................................................................................ 200
+ (operator).........................................................................................................................200
< (operator).........................................................................................................................201
= (operator).........................................................................................................................202
= (statement).......................................................................................................................202
Contents | vii
> (operator).........................................................................................................................202
AnswerBox (function)........................................................................................................205
AppActivate (statement).....................................................................................................207
AppGetActive$ (function)..................................................................................................209
AppList (statement)............................................................................................................211
AppMaximize (statement)..................................................................................................212
AppMinimize (statement)...................................................................................................212
AppMove (statement).........................................................................................................213
AppRestore (statement)......................................................................................................214
Contents | viii
AppType (function)............................................................................................................216
Atn (function).....................................................................................................................223
B..................................................................................................................................................223
B..........................................................................................................................................223
Basic.Architecture$ (property)...........................................................................................224
Basic.Capability (method)..................................................................................................224
Basic.CodePage (property).................................................................................................225
Basic.HomeDir$ (property)................................................................................................226
Basic.Locale$ (property).................................................................................................... 227
Basic.OperatingSystem$ (property)................................................................................... 227
Basic.OperatingSystemVendor$ (property)....................................................................... 228
Basic.OperatingSystemVersion$ (property).......................................................................228
Contents | ix
Basic.OS (property)............................................................................................................229
Beep (statement).................................................................................................................231
ByRef (keyword)................................................................................................................234
ByVal (keyword)................................................................................................................234
C..................................................................................................................................................235
C..........................................................................................................................................235
CInt (function)....................................................................................................................243
Clipboard $ (statement)......................................................................................................244
Clipboard.Clear (method)...................................................................................................245
CreateObject (function)......................................................................................................245
CLng (function)..................................................................................................................248
Close (statement)................................................................................................................248
Const (statement)................................................................................................................252
Cos (function).....................................................................................................................257
Contents | xi
CStr (function)....................................................................................................................258
DateDiff (function).............................................................................................................266
DateValue (function)..........................................................................................................268
DDEExecute (statement)....................................................................................................270
Contents | xii
DDEPoke (statement).........................................................................................................271
DDESend (statement).........................................................................................................273
DefType (statement)...........................................................................................................276
DeleteSetting (statement)................................................................................................... 277
Dim (statement)..................................................................................................................279
DiskDrives (statement).......................................................................................................281
DiskFree (function)............................................................................................................ 282
DlgCaption (function)........................................................................................................ 282
DlgCaption (statement)...................................................................................................... 282
DlgEnable (function)..........................................................................................................284
DlgEnable (statement)........................................................................................................285
Contents | xiii
DlgListBoxArray (function)...............................................................................................287
DlgListBoxArray (statement).............................................................................................288
DlgProc (function)..............................................................................................................289
DlgSetPicture (statement)...................................................................................................291
DlgText (statement)............................................................................................................292
DlgText$ (function)............................................................................................................293
Do...Loop (statement).........................................................................................................298
DropListBox (statement)....................................................................................................301
E..................................................................................................................................................302
E..........................................................................................................................................302
Contents | xiv
ebAbort (constant)..............................................................................................................305
ebAbortRetryIgnore (constant)...........................................................................................305
ebApplicationModal (constant)..........................................................................................305
ebBoolean (constant)..........................................................................................................307
ebDate (constant)................................................................................................................308
ebDirectory (constant)........................................................................................................310
ebDos (constant).................................................................................................................310
ebError (constant)...............................................................................................................311
ebIgnore (constant).............................................................................................................312
ebInteger (constant)............................................................................................................313
ebLong (constant)...............................................................................................................314
ebQuestion (constant).........................................................................................................317
Err (function)......................................................................................................................326
Contents | xvii
Err (statement)....................................................................................................................326
FileDateTime (function).....................................................................................................341
FileDirs (statement)............................................................................................................341
Fix (function)......................................................................................................................345
For Each...Next (statement)............................................................................................... 346
For...Next (statement).........................................................................................................347
FreeFile (function)..............................................................................................................353
Fv (function).......................................................................................................................353
G................................................................................................................................................. 354
G......................................................................................................................................... 354
GetAttr (function)...............................................................................................................357
GoSub (statement)..............................................................................................................360
HLine (statement)...............................................................................................................364
Hour (function)...................................................................................................................364
HWND.Value (property)....................................................................................................366
I................................................................................................................................................... 367
I........................................................................................................................................... 367
IIf (function).......................................................................................................................369
IMEStatus (function)..........................................................................................................369
Is (operator)........................................................................................................................ 379
IsError (function)................................................................................................................381
Item$ (function)..................................................................................................................383
ItemCount (function)..........................................................................................................384
K................................................................................................................................................. 385
K......................................................................................................................................... 385
Keywords (topic)................................................................................................................385
Kill (statement)...................................................................................................................385
L..................................................................................................................................................386
Contents | xxi
L..........................................................................................................................................386
LBound (function)..............................................................................................................387
Len (function).....................................................................................................................389
Let (statement)....................................................................................................................390
Like (operator)....................................................................................................................391
Line$ (function)..................................................................................................................392
LineCount (function)..........................................................................................................393
Loc (function).....................................................................................................................395
Lock (statement).................................................................................................................396
MIRR (function).................................................................................................................404
Msg.Thermometer (property).............................................................................................408
Net.CancelCon (method)....................................................................................................415
Net.GetCaps (method)........................................................................................................416
New (keyword)...................................................................................................................418
Not (operator).....................................................................................................................418
Nothing (constant)..............................................................................................................419
NPer (function)...................................................................................................................420
Null (constant)....................................................................................................................421
O................................................................................................................................................. 422
O......................................................................................................................................... 422
OptionGroup (statement)....................................................................................................435
Or (operator).......................................................................................................................435
P.................................................................................................................................................. 437
P.......................................................................................................................................... 437
Pi (constant)........................................................................................................................437
Picture (statement)..............................................................................................................438
PictureButton (statement)...................................................................................................439
Private (statement)..............................................................................................................445
Public (statement)...............................................................................................................446
Put (statement)....................................................................................................................448
Pv (function).......................................................................................................................450
Q................................................................................................................................................. 450
QueEmpty (statement)........................................................................................................450
R..................................................................................................................................................451
R..........................................................................................................................................451
Randomize (statement).......................................................................................................452
Rate (function)....................................................................................................................453
RCPDownload (statement).................................................................................................454
RCPDownloadEx (function).............................................................................................. 454
RCPGroupExport (statement)............................................................................................ 455
RCPGroupExportEx (function)..........................................................................................455
RCPGroupImport (statement)............................................................................................ 456
RCPGroupImportEx (function)..........................................................................................456
RCPUpload (statement)......................................................................................................457
RCPUploadEx (function)................................................................................................... 457
RmDir (statement)..............................................................................................................463
Screen.DlgBaseUnitsX (property)......................................................................................468
Screen.DlgBaseUnitsY (property)......................................................................................469
Screen.Width (property).....................................................................................................470
SendKeys (statement).........................................................................................................474
Set (statement)....................................................................................................................476
Sgn (function).....................................................................................................................478
Shell (function)...................................................................................................................478
Sin (function)......................................................................................................................479
Sln (function)......................................................................................................................480
Spc (function).....................................................................................................................481
SQLBind (function)............................................................................................................482
SQLOpen (function)...........................................................................................................487
SQLQueryTimeout (statement)..........................................................................................488
SQLRetrieve (function)......................................................................................................489
Stop (statement)..................................................................................................................491
Switch (function)................................................................................................................496
SYD (function)...................................................................................................................497
System.Exit (method).........................................................................................................497
System.TotalMemory (property)........................................................................................499
Tab (function).....................................................................................................................501
Tan (function).....................................................................................................................501
Text (statement)..................................................................................................................502
Type (statement).................................................................................................................508
TypeOf (function).............................................................................................................. 508
TypeName (function)......................................................................................................... 509
U................................................................................................................................................. 510
U......................................................................................................................................... 510
VarType (function).............................................................................................................516
Viewport.Clear (method)....................................................................................................517
Viewport.Close (method)................................................................................................... 518
Viewport.Open (method)....................................................................................................518
VLine (statement)...............................................................................................................519
Weekday (function)............................................................................................................521
While...Wend (statement)...................................................................................................522
Contents | xxxi
WinActivate (statement).....................................................................................................523
WinFind (function).............................................................................................................525
WinList (statement)............................................................................................................525
WinMaximize (statement)..................................................................................................526
WinMinimize (statement)...................................................................................................526
WinMove (statement).........................................................................................................527
WinRestore (statement)......................................................................................................528
Word$ (function)................................................................................................................529
Write# (statement)..............................................................................................................530
X or (operator)................................................................................................................... 532
Y................................................................................................................................................. 533
CimEMEvent.PointEvent................................................................................................... 556
CimEMPointEvent.Id......................................................................................................... 557
CimEMPointEvent (object)................................................................................................557
CimProjectData.GetNext (function)...................................................................................563
CimProjectData (object).....................................................................................................574
CimProjectData.Reset (method).........................................................................................576
CimRemoveUnusedPoints (method)..................................................................................576
DoQINTMath (function).................................................................................................... 576
DoUQINTMath (function)................................................................................................. 577
GetCurTimeHR (function)................................................................................................. 578
GetSystemWindowsDirectory (function)...........................................................................583
Contents | xxxv
IsTerminalServices (function)............................................................................................585
Point.Cancel (method)........................................................................................................586
Point.ChangeApproval (property, write)............................................................................586
Point.ChangeApprovalInfo (property, read)...................................................................... 587
Point.EnableAlarm (method)..............................................................................................589
Point.Get (statement)..........................................................................................................590
Point.OnAlarmAck (statement)..........................................................................................597
Point.SetRawArray (statement)..........................................................................................606
PointGet (function).............................................................................................................613
Contents | xxxviii
PointSetMultiple (function)................................................................................................618
Trace (statement)................................................................................................................624
4. Select Events..................................................................................................................633
9. Trigger Events................................................................................................................635
Control Scripts............................................................................................................................636
Control Scripts....................................................................................................................636
Resume Scripts...................................................................................................................637
Schedules............................................................................................................................ 729
Security............................................................................................................................... 738
Component Description
Event Editor Provides the tools to defines actions to take in response to events that occur in a
process. An event can be a changing point, alarm state, or even a particular time of
day. One event may invoke multiple actions, or one action may be invoked by many
events.
Script Editors Provide a set of sophisticated development tools that let you create programs.
These programs can then be executed as actions in response to events. Following
are the three script editors provided by CIMPLICITY:
Basic Control Engine Monitors for events and executes the configured actions. The Basic Control Engine
is based on a multi-threaded design that allows the system to invoke and execute
multiple Visual Basic programs concurrently.
Either Or
3. Right-click Scripts.
7. Do the following.
Either Or
4. Right-click Scripts.
6. Right-click a script.
The Program Editor window can be divided into the following sections:
rect 7, 262, 455, 292 Program Editor Toolbars and Status Bar (page 51)
rect 3, 223, 451, 262 4. Perform Traces in Scripts (page 139)
rect -1, 136, 334, 212 Scripting Language Reference (page 174)
rect 0, 99, 428, 130 5. Use a Watch Variable (page 142)
rect 4, 65, 452, 95 Program Editor Toolbars and Status Bar (page 51)
rect 4, 31, 452, 61 Program Editor Toolbars and Status Bar (page 51)
rect 4, 12, 452, 33 Program Editor Menu Functions (page 47)
rect 333, 131, 475, 210 Program Editor Shortcut Keys (page 53)
1 Menu bar
(page
47)
2 Toolbars
(page
51)
3 Watch area
(page
142)
4 Script area
(page
174)
Basic Control Engine and Scripting Reference | 1 - Script Editors | 47
5 Trace area
(page
139)
6 Status bar
(page
53)
7 Shortcut keys
(page
53)
You can use the menu options to open, close, print, and compile files, to edit a file, to run a file, to
debug a file, to access tools, to view status and toolbars, to arrange windows, and access help.
• File menu
• Edit menu
• Run menu
• Debug menu
• Tools menu
• View menu
• Window menu
• Help menu
File Menu
Save All Saves all the open files in the Program Editor.
Edit Menu
Goto Line Opens a Goto Line dialog box. The insertion point goes to the line number that is entered in the Line
Number field.
View Menu
Toolbars Displays the list of available toolbars. You can toggle the display of each toolbar.
Status Bar Toggles the display of the Status Bar at the bottom of program windows.
Run Menu
Debug Menu
Add Watch Displays the Add Watch dialog box, in which you can specify the name of a script variable
Quick Do a quick check of a variable value, without adding the variable to the Watch list.
Watch
Step Executes the next line of the script. If the line calls a procedure, the called procedure is run in its entirety.
Step Into Executes the next line of the script. If the line calls a procedure, the next line to execute will be the first
line of the called procedure.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 50
Set Next Sets the next statement to be executed in a paused program to the currently selected line.
statement
Set Set the command line for the script. This can be retrieved via the basic Command$ parameter. The
Command Basic Control Engine will pass the Event & Action which caused the script to be run. See BCE Manual
Line
Set Event
Information
Reset Re-set's the contents of public and private variables to an empty state.
Public
Variables
Tools Menu
Points Displays a submenu that lets you browse for points, edit a point, and create a new point. You can also use
this menu item to include Setpoints, Get Points, and create local variables in the program.
Alarms Displays a submenu that lets you generate or update alarms in the program.
Log Displays a dialog box that lets you generate messages for the Status Log.
Status
Window Menu
Arrange Icons Arranges the program icons in the Program Editor window.
Help Menu
Index Displays the main Help window for the Program Editor.
Using Help Displays the main Help window for Microsoft Windows.
About... Displays program information, version number, and copyright for the Program Editor
Standard Main
Tool Main
Application Script
Standard Toolbar
Tools Toolbar
Application Toolbar
Status bar
F3 Finds the next occurrence of the string in the Find dialog box.
Alt+D+R Trace.
Shift+F8 Steps to the next line in the script. If the section is a procedure call, the next line is the first line in the
procedure.
String space Holds all string variables, arrays, and public data.
The changes apply to all Basic Control Engine scripts that run as executables within the Program
Editor or from the Event Manager.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 55
Field Description
4. Click OK.
You must stop and restart CIMPLICITY for the changes to take effect.
5. Click OK.
Note:
• You can substantially reduce your stack usage by explicitly defining the types of variables
(in other words, don't use variants).
• Recursive routines have an impact on Stack Space.
• If you use arrays or arrays of User Defined Types, allocation occurs in the String Space
that may alleviate some stack usage.
Although, in some respects, editing code with the Program Editor is like editing regular text with a
word-processing program, the Program Editor also has certain capabilities specifically designed to
help you edit your code.
This section describes how to move around within your script, select and edit text, add comments
to your script, break long statements across multiple lines, search for and replace selected text, and
Basic Control Engine and Scripting Reference | 1 - Script Editors | 56
perform a syntax check of your script. The section ends with a brief discussion of editing dialog box
templates.
1 Program Editor: Navigate within a script.
(page
56)
When you move the insertion point with a keyboard shortcut, (page 53) the Program Editor
scrolls the new location of the insertion point into view if it is not already displayed.
You can also reposition the insertion point with the mouse and the Goto Line command.
Note: The Program Editor allows you to place the insertion point anywhere within your script,
including in "empty spaces." (Empty spaces are areas within the script that do not contain text, such
as a tabs expanded space or the area beyond the last character on a line.)
Basic Control Engine and Scripting Reference | 1 - Script Editors | 57
1. Use the scroll bars at the right and bottom of the display to scroll the target area of the script
into view if it is not already visible.
2. Place the cursor where you want to position the insertion point.
Note:
• This approach is especially fast if the area of the screen to which you want to move the
insertion point is currently visible.
• When you scroll the display with the mouse, the insertion point remains in its original
position until you reposition it with a mouse click. If you attempt to perform an editing
operation when the insertion point is not in view, Program Editor automatically scrolls the
insertion point into view before performing the operation.
4. Press F4.
5. Enter the number of the line in your script to which you want to move the insertion point.
The insertion point is positioned at the start of the line you specified. If that line was not already
displayed, the Program Editor scrolls it into view.
Note:
• This approach is especially fast if the area of the screen to which you want to move the insertion
point is not currently visible but you know the number of the target line.
• The insertion point cannot be moved so far below the end of a script as to scroll the script
entirely off the display. When the last line of your script becomes the first line on your screen,
Basic Control Engine and Scripting Reference | 1 - Script Editors | 58
the script will stop scrolling, and you will be unable to move the insertion point below the
bottom of that screen.
Position the insertion point at the desired location in the script and start typing.
guide: Guidelines
• Text does not wrap. If you continue typing on a given line, eventually you will reach a point at
which you can enter no more text on that line.
• Press Enter to control the line breaks when you want to insert a new line in your script.
The effect of pressing Enter depends on where the insertion point is located at the time:
Insertion point location When Enter is pressed
At or beyond the end of a line A new line is inserted after the current line.
At the start of a line A new line is inserted before the current line.
Within a line The current line is broken into two lines at that location.
The tab character is inserted at the location of the insertion point, which causes text after the tab to be
moved to the next tab position.
If you insert new text within a tab's expanded space, the text that originally appeared on that line
is moved to the next tab position each time the new text that you are entering reaches the start of
another tab position.
Tip: Because you can position the insertion point in empty spaces, you can also insert text in
empty spaces. This is useful for inserting a comment (page 71) in the space beyond the end of a
line in the script.
When you insert characters beyond the end of a line, the space between the insertion point and the
last character on the line is back filled with tab characters.
• Select text.
• Delete text.
Select text
You can use either the mouse or the keyboard to select text and other characters in your script.
Important: Regardless of which method you use, you can select either a portion of one line or a
series of whole lines, but you cannot select a portion of one line plus one or more whole lines.
When you select multiple lines and start or end your selection partially through a line, the Program
Editor automatically extends the selection to include the entire starting and ending lines.
1. Place the insertion point where you want your selection to begin
3. Place the insertion point where you want your selection to begin.
4. While pressing Shift, use one of the navigating keyboard shortcuts to extend the selection to the
desired ending point.
Note: When you intend to select an entire single line of text in your script, it is important to
remember to extend your selection far enough to include the hidden end-of-line character, which
is the character that inserts a new line in your script.
5. Place the insertion point at the beginning of the line you want to select.
9. Press Ctrl+Y.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 61
10. Place the insertion point after the last character on the current line.
Place material from your script on the Clipboard by either cutting it or copying it.
• Cut a selection.
• Copy a selection.
• Paste text.
Cut a selection
Result: The selection is cut from the script and placed on the Clipboard.
Copy a selection
Result: The selection remains in the script, and a copy of it is placed on the Clipboard.
Paste text
5. Position the insertion point where the copied or cut text should be placed.
The contents of the Clipboard are pasted at the insertion point location.
Note: If text is selected when you paste Clipboard text, the Clipboard text is inserted before the
selected text.
Any of the following editing operations that produce a change in the script can be undone.
• Press Ctrl+Z
• Click Edit>Undo on the Program Editor menu bar.
Result: The script is restored to the way it looked before you performed the editing operation.
Note: Operations that do not produce any change in the script and cannot be undone include:
Program Editor makes it easy to search for specified text in your script and automatically replace
instances of specified text.
3. Do the following.
Feature Description
Match Check to limit the results to the case entered in the Find what field.
case
Find Next Click to start the search and continue the search when a match is found. Tip: You can also press
Enter.
Results
• The Find dialog box remains open
• The Program Editor either highlights the first instance of the specified text or reports that
the text cannot be found.
4. If the specified text has been found, click Find Next or press Enter to search for the next
instance.
Tip: If the Find dialog box blocks your view of an instance of the specified text, you can do
either of the following.
• Move the dialog box out of your way and continue with your search.
• Click Cancel.
The Find dialog box closes, but maintains the established search criteria.
Press F3 to find successive occurrences of the specified text without re-opening the Find dialog
box.
Note: If you press F3 when there is no entry in the Find what field the Program Editor opens
the Find dialog box.
5. Move the insertion point to where you the replacement operation should start.
7. Do the following.
Feature Description
Match Check to limit the results to the case entered in the Find what field.
case
Find Click to start the search and continue the search when a match is found. Tip: You can also press
Next Enter.
Replace Click to replace a found instance of the text. Result: When the text is replaced either of the following
happens.
• The cursor highlights the next found instance
• A message reports that there are no more instances of the Find what text.
Replace (Optional) Click to automatically replace all found instances of the Find what text with the replacement
All text. Result: All instances are replaced with no requests for confirmation.
The Program Editor provides tools to facilitate working with points in a script, as follows.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 65
2 Edit
(page
66)
3 New
(page
67)
4 Set
(page
67)
5 Get
(page
68)
6 Dim
(page
68)
1 Browse
1. Place the insertion point in the script where the selected point will be inserted.
4. Click OK.
2 Edit
The Point Properties dialog box opens for the selected point.
3 New
9. Place the insertion point in the script where the new point will be inserted.
11. Create and configure a new point (in the Point Properties dialog box).
Result: The new point ID is inserted in the script at the insertion point.
4 Set
13. Place the insertion point in the script where the PointSet (page 617) statement will be
inserted.
Field Description
Example
5 Get
17. Place the insertion point in the script where the PointGet (page 613) function will be
inserted.
Field Description
Example
P = PointGet ("TANKLEVEL")
6 Dim
21. Place the insertion point in the script where a Dim (page 279) statement will be inserted.
Field Description
A Dim statement for a point or new point variable is inserted at the insertion point in the script.
Example
The Program Editor provides tools to facilitate working with alarms in a script, as follows.
The Generate tool in the Program Editor is available for $CIMBASIC alarms.
1. Place the insertion point in the script where the selected alarm will be inserted.
2. Click Tools>Alarms>Generate on the Program Editor menu bar.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 70
1. Fill in the fields for a $CIMBASIC alarm in the Generate Alarm dialog box.
Note: The fields in the Generate Alarm dialog box correspond to the AlarmGenerate (page
540) (method) syntax.
1. Click OK.
Result: The Program Editor inserts the specified AlarmGenerate (page 540) (method) code at the
location of the insertion point in the script.
2 Update
The Update tool in the Program Editor is available for any CIMPLICITY alarm.
1. Place the insertion point in the script where the selected alarm will be inserted.
2. Click Tools>Alarms>Update on the Program Editor menu bar.
Note: The fields in the Update Alarm dialog box correspond to the AlarmUpdate (page 545)
(method) syntax.
1. Click OK.
Result: The Program Editor inserts the specified AlarmUpdate (page 545) (method) code at the
location of the insertion point in the script.
The fields correspond to the LogStatus (page 585) (property, read/write) syntax.
You can add comments to your script to remind yourself or others of how your code works.
Comments are ignored when your script is executed.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 72
The apostrophe symbol ( ' ) is used to indicate that the text from the apostrophe to the end of the line
is a comment.
Add a:
Result: When the script is run, the presence of the apostrophe at the start of the line will cause
the entire line to be ignored.
3. Position the insertion point in the empty space beyond the end of the line of code.
When the script is run, the code on the first portion of the line will be executed, but the presence of
the apostrophe at the start of the comment will cause the remainder of the line to be ignored.
Note: Although you can place a comment at the end of a line containing executable code,
you cannot place executable code at the end of a line containing a comment; the presence of the
apostrophe at the start of the comment will cause the balance of the line (including the code) to be
ignored.
1. Type the statement on multiple lines, exactly the way you want it to appear.
2. Place the insertion point at the end of the first line in the series.
4. Type an underscore ( _ ).
Basic Control Engine and Scripting Reference | 1 - Script Editors | 73
Note: The underscore is the line-continuation character, which indicates that the statement
continues on the following line.
5. Repeat 2 - 4 to place a line-continuation character at the end of each line in the series, except the
last.
If Program Editor has found a syntax error, the line containing the error is highlighted on your
display.
4. Repeat the procedure until you have found and corrected all syntax errors.
Basic Control Engine syntax provides several options for adding dialog boxes to a script.
Dialog Editor
Dialog Editor
Basic Control Engine and Scripting Reference | 1 - Script Editors | 74
You can use a custom dialog box to display information to a user while providing an opportunity
for the user to respond. The Dialog Editor is a tool that enables you to create and modify custom
dialog boxes for use in your scripts. Although the statements used to display a custom dialog box and
respond to the choices made by a user of the dialog box may seem complicated, the Dialog Editor
makes it easy to generate these statements.
Feature Description
1 Toolbar Collection of tools that you can use to provide instructions to the Dialog Editor, as discussed in the
following subsection
2 Dialog Visual layout of the dialog box that you are currently creating or editing.
box
3 Status Provides key information about the operation you are currently performing, including the name of the
bar currently selected control or dialog box, together with its position on the display and its dimensions;
the name of a control you are about to add to the dialog box with the mouse pointer, together with the
pointer's position on the display; the function of the currently selected menu command; and the activation
of Dialog Editor's testing or capturing functions.
Tool Function
2 Information Displays the Information dialog box for the selected dialog box or control.
7 Select Lets you select, move, and resize items and control the insertion point.
19 Drop List Box Adds a drop list box to the dialog box.
• File menu
• Edit menu
• Controls menu
• Help menu
File Menu
Basic Control Engine and Scripting Reference | 1 - Script Editors | 77
Selection Function
Open... Opens the Open Dialog File dialog box, which you can use to open an existing dialog box template.
Update Updates the template. Does one of the following in the open Program Editor script.
Save As... Opens a Save As Dialog File dialog box, which you can use to save the current dialog box template in a
file under the same or new name.
Capture Captures the standard Windows controls from a standard Windows dialog box in another Windows
Dialog application.
Exit & Closes the Dialog Editor and returns you to the host application.
Return
Edit Menu
Selection Function
Undo Undo up to 10 preceding operations. The Undo command continually indicates the next operation you can
undo by selecting it and grays out when there are no more operations that can be undone.
Cut Cuts the selected dialog box or control from the Dialog Editor window and places it on the Clipboard.
Copy Copies the selected dialog box or item, without removing it from the Dialog Editor window, and places it on
the Clipboard.
Paste Inserts cut or copied dialog box or items into the Dialog Editor.
Clear Deletes the selected dialog box or control from Dialog Editor's application window without placing it on the
Clipboard.
Size to Adjusts the borders of certain items to fit the text displayed on them.
Text
Info... Displays an Information dialog box for the selected dialog box or item.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 78
Controls Menu
Selection Function
Drop list box Adds a drop list box to the dialog box.
Help Menu
Selection Function
The following keyboard shortcuts can be used for some of the operations you will perform most
frequently in Dialog Editor.
Key(s) Function
Ctrl+C Copies the selected dialog box or control, without removing it from Dialog Editor's application window, and
places it on the Clipboard.
Ctrl+I Displays the Information dialog box for the selected dialog box or control.
Ctrl+V Inserts the contents of the Clipboard into Dialog Editor. If the Clipboard contains script statements describing
one or more controls, then Dialog Editor adds those controls to the current dialog box. If the Clipboard contains
the script template for an entire dialog box, then Dialog Editor creates a new dialog box from the statements in
the template.
Ctrl+X Removes the selected dialog box or control from Dialog Editor's application window and places it on the
Clipboard.
Del Removes the selected dialog box or control from Dialog Editor's application window without placing it on the
Clipboard.
• Available controls
• Control guidelines
Available Controls
The Dialog Editor supports the following types of standard Windows controls, all of which are
illustrated in the above dialog box:
Feature Description
Check Box that users can check or clear to indicate their preference regarding the alternative specified on the check
box box label.
Combo Text field with a displayed, scroll list beneath it. Users can either select an item from the list or enter the name
box of the desired item in the text field. The currently selected item is displayed in the text field. If the item was
selected from the scrolling list, it is highlighted there as well.
Drop Field that displays the currently selected item, followed by a downward-pointing arrow, which users can click
list box to temporarily display a scrolling list of items. Once a user selects an item in the list, the list disappears and
the newly selected item displays in the field.
Group Rectangular design element used to enclose a group of related controls. An optional group box label is
box available to display a title for the controls in the box..
List box Displayed scroll list from which users can select one item. The currently selected item is highlighted on the
list.
Option One of a group of two or more linked buttons that allows users select only one from a group of mutually
button exclusive choices. Clicking an unselected button in the group selects that button and automatically de-selects
the previously selected button in that group.
Text Field into which users can enter text (potentially, as much as 32K).
box
• By default, the Text box holds a single line of non-wrapping text.
• The field can multiple lines of wrapping text.
Control Guidelines
• General guidelines
• Tabbing order.
• Option button grouping.
• Accelerator keys.
General guidelines
An OK button and a Cancel button are provided by default on a new dialog box.
• Group boxes, text controls, and pictures are passive elements in a dialog box, inasmuch as they
are used purely for decorative or informative purposes. Users cannot act upon these controls,
and when they tab through the dialog box, the focus skips over these controls.
• A Windows bitmap or metafile can be obtained from a file or from a specified library.
Tabbing order
The order in which you create the controls is what determines the tabbing order, not the position of
the controls in the dialog box.
The closer you can come to creating controls in the order in which you want them to receive the
tabbing focus, the fewer tabbing-order adjustments you will have to make later on.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 82
If you want a series of option buttons to work together as a mutually exclusive group, you must
create all the buttons in that group one right after the other, in an unbroken sequence.
If you create a different type of control before you have finished creating all the option buttons in
your group, you will split the buttons into two or more separate groups.
Example
2. A list box.
3. Two buttons
When you test the dialog box, the five buttons will not work together as a mutually exclusive
group.
Instead the:
• First three buttons will form one mutually exclusive group.
• Last two buttons will form another mutually exclusive group.
Accelerator keys
To do this, you must create the text control or group box first, followed immediately by the
controls that you want to associate with it. If the controls are not created in the correct order,
they will not be associated in your dialog box template and any accelerator key you assign to the
text control or group box label will not work properly.
Note: You can only insert a control within the borders of the dialog box you are creating. You
cannot insert a control on the dialog box's title bar or outside its borders.
B Click the button (page 75) on the Dialog Editor toolbar that corresponds to the type of control you
want to add.
2. Place the cursor in the dialog box where you want the upper left corner of the control to be
positioned.
• As soon as you place the cursor in the dialog box it changes to a crossbar accompanied by
a small image of the selected object.
• The Dialog Editor status bar displays the crossbar's coordinates.
Results
• The selected control is placed in the dialog box. The upper left corner of the control
corresponds to the position of the pointer's crossbar at the moment you clicked the mouse
button.
• The object's upper left corner coordinates, width and height display on the Dialog Editor
status bar.
Note: The status bar displays this information anytime the mouse passes over a control or the
control is selected.
• A frame that surrounds the object identifies it as selected.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 84
Tip: Press Ctrl+D on the keyboard to add another control that is the same type as the
control that was just added.
Note: Dialog units represent increments of the font (8 point Helvetica) in which the Dialog
Editor creates dialog boxes.
Option Description
Horizontal (X) Space between horizontal grid marks. The higher the number the further apart the grid marks.
Vertical (Y) Space between vertical grid marks. The higher the number the further apart the grid marks.
Important: The X and Y settings entered in the Grid dialog box remain in effect regardless
of whether you choose to display the grid.
The Dialog Editor displays or hides the grid with the settings you specified.
With the grid displayed, you can line up the crossbar on the mouse pointer with the dots on the grid
to position controls precisely and align them with respect to other controls.
3. Click Save.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 86
The dialog box is saved as a .dlg file. The .dlg file can be moved, opened, modified, saved with a
different name at any time.
In the preceding section, you learned how to create controls and determine where they initially
appear within your dialog box. In this section, you'll learn how to make various types of changes to
both the dialog box and the controls in it. The following topics are included:
3.1 Open a dialog box template.
(page
86)
A message opens asking if you want to save the template for the current dialog box.
The current dialog box template code is inserted (page 108) into the Program Editor script.
• Click No.
The Open Dialog File dialog box opens after either selection.
2. Select the file containing the dialog box template that you want to edit.
3. Click Open.
The Dialog Editor creates a dialog box from the statements in the template and displays it in the
application window.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 88
Note: If there are any errors in the statements that describe the dialog box, the Dialog
Translation Errors dialog box will open when you attempt to load the file into Dialog Editor. This
dialog box shows the lines of code containing the errors and provides a brief description of the nature
of each error.
1. Click the Select (page 76) button on the Dialog Editor toolbar.
Control
3. Click the Select (page 76) button on the Dialog Editor toolbar.
The Dialog Editor creates the tabbing order based on the order in which you create the controls, not
the position of the controls in the dialog box.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 90
The closer you can come to creating controls in the order in which you want them to receive the
tabbing focus, the fewer tabbing-order adjustments you will have to make later on.
When a control is pasted into the dialog box, the Dialog Editor places the descriptions of at the end
of the dialog box template.
Therefore, you can use a simple cut-and-paste technique to adjust the tabbing order.
1. Determine what item should be the starting point in the dialog box.
Note: Because the OK button and Cancel button display on a new dialog box by default, the OK
button is the starting point and the Cancel button is the first tab.
2. Cut (page 76) and paste (page 76) the controls to establish the desired tabbing order.
Note: If the controls were place in the dialog box in the correct order you can simply cut/paste
the OK and Cancel buttons so they are tabbed to last.
3. Test (page 118) the tabbing order to make sure it is correct. Items that users cannot interact
with, e.g. group boxes, are not included in the tabbing order.
Information dialog box enable you to check and adjust various attributes of dialog boxes and dialog
box items.
3.4.1 Dialog box information
(page
90)
The Dialog Box Information dialog box opens when you use any method.
Attribute Description
Position (Optional) Dialog box position (dialog units (page 84)) in the window/screen in which it opens
Size Dialog box size includes the number of dialog units (page 84) in the:
Title Dialog box title bar. Note: Title is enabled if Close box is cleared. If Close box is checked so
the Close box button displays, the title bar must display.
Text$ (Optional) Text displayed on the title bar of the dialog box.
Variable Check to identify the Text$ entry as a variable. Note: if Text$ is a variable, spaces cannot
Name be used in the entry.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 92
Name Name used for the dialog box template in script code
Picture (Optional) Picture library (.dll file) from which one or more pictures in the dialog box are obtained
Library
Browse Opens a Select a Picture Library browser to help find the .dll file.
The <Item> Information dialog box opens when you use any method.
Option Description
Position Position of the check box in the dialog box from the:
Size Size of the checkbox, including the label, in dialog units (page 84).
Text$ (Optional) Text that displays as the checkbox label. Note: if Text$ is a variable, spaces cannot be used
in the entry.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 94
Option Description
Position Position of the combo box in the dialog box from the:
.Identifier (Optional) Name used for the combo box in a script's code.
Option Description
Basic Control Engine and Scripting Reference | 1 - Script Editors | 95
Position Position of the drop list box in the dialog box from the:
Size Size of the drop list box in dialog units (page 84).
.Identifier (Optional) Name used for the drop list box in a script's code.
Option Description
Position Position of the group box in the dialog box from the:
Text$ (Optional) Text that displays as the group box label. Note: if Text$ is a variable, spaces cannot be used
in the entry.
.Identifier (Optional) Name used for the group box in a script's code.
Option Description
Position Position of the list box in the dialog box from the:
.Identifier (Optional) Name used for the list box in a script's code.
Option Description
Option Description
Position Position of the picture button in the dialog box from the:
Option Description
Position Position of the Push Button box in the dialog box from the:
Text$ (Optional) Text that displays as the push button label. Note: if Text$ is a variable, spaces cannot be
used in the entry.
.Identifier (Optional) Name used for the push button in a script's code.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 99
Option Description
Position Position of the option button in the dialog box from the:
Size Size of the option button, including the label, in dialog units (page 84).
Text$ (Optional) Text that displays as the checkbox label. Note: if Text$ is a variable, spaces cannot be used
in the entry.
Option Description
Text$ Text that displays up to 255 characters Note: if Text$ is a variable, spaces cannot be used in the
entry.
Font Opens a Font dialog box to select the text font type, style and size.
Option Description
Position Position of the text box in the dialog box from the:
Basic Control Engine and Scripting Reference | 1 - Script Editors | 101
Check Require a password for a user to make a text entry if the text box is read/write.
Clear Allow text entries without a password if the text box is read/write.
Text$ Text that displays up to 255 characters Note: if Text$ is a variable, spaces cannot be used in the entry.
Font Opens a Font dialog box to select the text font type, style and size.
The Dialog Editor provides several ways to reposition dialog boxes and items.
• Mouse.
• Arrow keys.
• Dialog Box Information dialog box.
• Item with the Information dialog box.
Mouse
1. Click the Select (page 76) button on the Dialog Editor toolbar.
3. Hold the left-mouse button down and drag the dialog box or control to the desired location.
Note: The increments by which you can move a control with the mouse are governed by the
grid setting (page 84).
Basic Control Engine and Scripting Reference | 1 - Script Editors | 102
Example
This feature is useful if you are trying to align controls in your dialog box. If you want to move
controls in smaller or larger increments.
Arrow Keys
Note: When you reposition an item with the arrow keys, a faint, partial afterimage of the
item may remain visible in the item's original position. These afterimages are rare and will
disappear once you test your dialog box.
If you specified X and Y coordinates, the dialog box moves to that position. If you left the X
coordinate blank, the dialog box will be centered horizontally static to the parent window of the
dialog box when the dialog box is run. If you left the Y coordinate blank, the dialog box will be
centered vertically static to the parent window of the dialog box when the dialog box is run.
9. Open (page 90) the Information dialog box for the control that you want to move.
Note: When you move a dialog box or control with the arrow keys or with the Information
dialog box, the item's movement is not restricted to the increments specified in the grid
setting. When you attempt to test a dialog box containing hidden controls (i.e., controls
positioned entirely outside the current borders of your dialog box), the Dialog Editor displays a
message advising you that there are controls outside the dialog box's borders and asks requests
confirmation to proceed with the test. If you proceed, the hidden controls will be disabled for
testing purposes.
Dialog boxes and controls can be resized either by directly manipulating them with the mouse or by
using the Information dialog box. Certain controls can also be resized automatically to fit the text
displayed on them.
1. Click the Select (page 76) button on the Dialog Editor toolbar.
2. Place the cursor over a border or corner of the dialog box or a control..
3. Hold the the left-mouse button down and drag the border or corner until the dialog box or
control reaches the desired size.
4. Open (page 90) the Information dialog box for the dialog box or a selected control.
5. Change the Width and Height settings in the Size group box.
7. Click the Select (page 76) button on the Dialog Editor toolbar.
The borders of the control will expand or contract to fit the text displayed on it.
Note:
• Windows metafiles always expand or contract proportionally to fit within the picture control or
picture button control containing them.
• Windows bitmaps are of a fixed size.
• Smaller than the bitmap, the bitmap is clipped off on the right and bottom.
• Larger than the bitmap, the bitmap is centered within the borders of the control.
Text Text
Note:
Basic Control Engine and Scripting Reference | 1 - Script Editors | 105
• The OK and Cancel buttons also have labels that cannot be changed.
• The following controls do not have their own labels. You can position a text control above or
beside these controls to serve as a de facto label
• Combo boxes
• Drop list boxes
• List boxes
• Pictures
• Picture buttons.
• Text boxes
1. Open (page 90) the Information dialog box for the dialog box title you want to change or for
the control label you want to change.
Note: Dialog box titles and control labels are optional; you can leave the Text$ field blank.
3. Check the Variable Name checkbox if the information in the Text$ field should be interpreted
as a variable name rather than a literal string.
The Information dialog box closes; the new title or label displays in the title bar or on the control.
Accelerator keys:
• Enable users to access dialog box controls by pressing Alt + <specified letter>.
• Are essentially a single letter from a control's label.
• Group box
• Currently selected item in one of the following.
• List box.
• Combo box.
• Drop list box..
1. Open the Information dialog box for the control that will have an assigned an accelerator key.
3. Type an ampersand (&) before the letter designated as the accelerator key.
The designated letter is now underlined on the control's label; users will be able to access the control
by pressing Alt +<underlined letter>.
• Accelerator keys can be assigned directly to the following controls that have their own label
• Check boxes
• Group boxes
• Option buttons
• Push buttons
Basic Control Engine and Scripting Reference | 1 - Script Editors | 107
• A de facto accelerator key can be created for certain controls that do not have their own labels
by assigning an accelerator key to an associated text control.
• Combo boxes
• Drop list boxes
• List boxes
• Text boxes
• Accelerator key assignments must be unique within a particular dialog box. If you attempt to
assign the same accelerator key to more than one control, a message displays reporting that the
letter has already been assigned.
Note: In order for such a de facto accelerator key to work properly, the text control or group box
label to which you assign the accelerator key must be associated with the control(s) to which you
want to provide user access that is, in the dialog box template, the description of the text control or
group box must immediately precede the description of the control(s) that you want associated with
it. The simplest way to establish such an association is to create the text control or group box first,
followed immediately by the associated control(s)
• Duplicate a Control.
• Delete a Single Control.
• Delete all the Controls in a dialog box.
Duplicate a Control
3. Repeat 2 as many times as necessary to create the desired number of duplicate controls.
If the dialog box contains more than one control a message displays asking:
All the controls are deleted, but the dialog box's title bar and close box (if displayed) remain
unchanged.
1. Place the cursor in a Program Editor script where the dialog box code will be inserted.
Click On the
Press On the
Ctrl+N Keyboard
Ctrl+O Keyboard
A message box opens asking if you want to save the dialog box template.
5. Click Yes.
Result: The dialog box template code is inserted into the Program Editor script at the specified
location.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 110
The Dialog script is pasted at the insertion point in the Program Editor script.
There are three ways to edit an existing dialog box: (1) You can copy the template of the dialog box
you want to edit from a script to the Clipboard and paste it into Dialog Editor. (2) You can use the
capture feature to "grab" an existing dialog box from another application and insert a copy of it into
Dialog Editor. (3) You can open a dialog box template file that has been saved on a disk.
5.1 Paste an existing dialog box into the Dialog Editor.
(page
112)
You can use the Dialog Editor to modify the statements in your script that correspond to an entire
dialog box or to one or more dialog box controls.
1. Select code in the Program Editor for the entire dialog box.
The code:
• Begins with Begin Dialog (page 231) (statement).
• Ends with End Dialog (page 322) (statement).
3. Select the dialog box in the Dialog Editor that will be replaced.
5. Click Yes.
Result: The dialog box template code copied from the Program Editor script replaces the
selected dialog box template. The dialog box changes according to the pasted code.
6. Select code in the Program Editor that defines one or more controls for a dialog box.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 114
8. Select the dialog box in the Dialog Editor that will be modified.
The selected controls are pasted into the dialog box based on the location specifications in the code.
• When you paste a dialog box template into the Dialog Editor, the tabbing order of the controls is
determined by the order in which the controls are described in the template.
• When you paste one or more controls into Dialog Editor, they will come last in the tabbing
order, following the controls that are already present in the current dialog box.
• If there are any errors in the statements that describe the dialog box or controls, the Dialog
Translation Errors dialog box will open when you attempt to paste these statements into Dialog
Editor. This dialog box shows the lines of code containing the errors and provides a brief
description of the nature of each error.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 115
The Dialog Editor provides a quick way to capture standard Windows dialog box controls from
another application and insert those controls into Dialog Editor for editing.
Important: The Dialog Editor only supports standard Windows controls and standard Windows
dialog boxes.
• Contains both standard Windows controls and custom controls, only the standard Windows
controls will appear in Dialog Editor's application window.
• Is not a standard Windows dialog box, you will be unable to capture the dialog box or any of its
controls.
1. Open a standard Windows dialog box that has controls you want to use.
5. Click OK.
A message opens to confirm if you want to replace the dialog box that is currently in the Dialog
Editor.
6. Click Yes.
The captured dialog box with standard controls replaces the current dialog box.
7. Modify the layout the same as you would for any other dialog box.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 117
8. Use any of the Dialog Editor methods to save the dialog box or insert/paste the dialog box
template code into a script.
The captured dialog box template code displays in the Program Editor. The code can be modified to
fill the script's requirements.
It is recommended that you check the dialog box for these errors before testing it.
When all statements on the list are True, the dialog box is ready to be tested.
Statement T/F
The dialog box contains a command button, i.e. a default OK or Cancel button, a push button, or a picture button.
All of the controls are labelled with their own labels or de-facto text labels.
Testing a dialog box is an iterative process that involves running the dialog box to see how well it
works, identifying problems, stopping the test and fixing those problems, then running the dialog box
again to make sure the problems are fixed.
1 Start a test.
(page
119)
Start a Test
Do one of the following.
Test the control on the running dialog box to make sure they are functioning correctly.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 120
If a statement is False, stop the dialog box and make the required corrections.
Statement T/
F
The Tab key moves through the control selection in a logical order. Note: Objects that users cannot act on, e.g.
Group boxes, text controls and pictures are not selected.
Results:
a. The Dialog Editor closes.
b. The dialog box template code is inserted into the Program Editor script.
• Click Cancel.
After using Dialog Editor to insert a custom dialog box template into your script, you'll need to make
the following modifications to your script:
8.1 Create a dialog record.
(page
123)
To store the values retrieved from a custom dialog box, you create a dialog record with a Dim
statement, using the following syntax:
Examples
Sample script
This sample script that illustrates how to create a dialog record named b within a dialog box
template named UserDialog . Notice that the order of the statements within the script is as follows:
the dialog box template precedes the statement that creates the dialog record, and the Dialog
statement follows both of them.
Sub Main()
Dim ListBox1$() 'Initialize list box array.
'Define the dialog box template.
Begin Dialog UserDialog ,,163,94,"Grocery Order"
Text 13,6,32,8,"&Quantity:",.Text1
TextBox 48,4,28,12,.TextBox1
ListBox 12,28,68,32,ListBox1$,.ListBox1
OKButton 112,8,40,14
CancelButton 112,28,40,14
End Dialog
Dim b As UserDialog 'Create the dialog record.
Dialog b 'Display the dialog box.
End Sub
If you open and run the sample script shown in the preceding subsection, you will see a dialog box
that resembles the following.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 124
b.TextBox1 = "12"
To display a custom dialog box, you can use either of the following.
Dialog() function
Dialog statement.
Dialog() Function
You can use a Dialog() function to determine how the user closed your custom dialog box. For
example, the following statement will return a value when the user clicks an OK button or a Cancel
button or takes another action:
response% = Dialog(b)
–1 The OK button.
>0 A push button. The returned number represents which button was clicked based on its order in the dialog
box template (1 is the first push button, 2 is the second push button, and so on).
Dialog Statement
You can use the Dialog statement when you don't need to determine how the user closed your
dialog box. You'll still be able to retrieve other information from the dialog box record, such as the
value of a list box or other dialog box control.
Dialog mydlg
Where
After displaying a custom dialog box for your user, your script must retrieve the values of the dialog
controls. You retrieve these values by referencing the appropriate identifiers in the dialog record.
You'll find an example of how to retrieve values from a custom dialog box in the following
subsection.
Sample
In the following sample script several of the techniques described earlier in this section have been
used.
In this script, the array named ListBox1 is filled with three elements ( "Apples" , "Oranges" ,
and "Pears" ). The default value of TextBox1 is set to 12. A variable named response is used
to store information about how the custom dialog box was closed. An identifier named ListBox1
is used to determine whether the user chose "Apples" , "Oranges" , or "Pears" in the list box
named ListBox$ . Finally, a Select Case . . . End Select statement is used to display a message box
appropriate to the manner in which the user dismissed the dialog box.
Sub Main()
Dim ListBox1$(2) 'Initialize list box array.
Dim response%
ListBox1$(0) = "Apples"
ListBox1$(1) = "Oranges"
ListBox1$(2) = "Pears"
Begin Dialog UserDialog ,,163,94,"Grocery Order"
Text 13,6,32,8,"&Quantity:",.Text1 'First control in
'template gets the focus.
TextBox 48,4,28,12,.TextBox1
ListBox 12,28,68,32,ListBox1$,.ListBox1
OKButton 112,8,40,14
CancelButton 112,28,40,14
End Dialog
Dim b As UserDialog 'Create the dialog record.
b.TextBox1 = "12" 'Set default value of the text box
'to 1 dozen.
response = Dialog(b) 'Display the dialog box.
Select Case response%
Case -1
Fruit$ = ListBox1$(b.ListBox1)
Basic Control Engine and Scripting Reference | 1 - Script Editors | 127
MsgBox "Thank you for ordering " + b.TextBox1 + " " + Fruit$ + "."
Case 0
MsgBox "Your order has been canceled."
End Select
End Sub
You can retrieve values from a custom dialog box while the dialog box is displayed, using the
dynamic dialog boxes feature.
9.1 Sample script for a dynamic dialog box.
(page
127)
The following script illustrates the most important concepts you'll need to understand in order to
create a dynamic dialog box in your script:
nd Select
End Function
Sub Main()
Dim ListBox1$() 'Initialize array for use by ListBox
'statement in template.
Dim Produce$
'Assign values to elements in the "Fruits" and "Vegetables"
'arrays.
Fruits(0) = "Apples"
Fruits(1) = "Oranges"
Fruits(2) = "Pears"
Vegetables(0) = "Carrots"
Vegetables(1) = "Peas"
Vegetables(2) = "Lettuce"
'Define the dialog box template.
Begin Dialog UserDialog ,,163,94,"Grocery Order",.DialogControl
Text 13,6,32,8,"&Quantity:",.Text1 'First control in
'template gets the focus.
TextBox 48,4,28,12,.TextBox1
ListBox 12,28,68,32,ListBox1$,.ListBox1
OptionGroup .OptionGroup1
OptionButton 12,68,48,8,"&Fruit",.OptionButton1
OptionButton 12,80,48,8,"&Vegetables",.OptionButton2
OKButton 112,8,40,14
CancelButton 112,28,40,14
End Dialog
im b As UserDialog 'Create the dialog record.
b.TextBox1 = "12" 'Set the default value of the text
'box to 1 dozen.
response% = Dialog(b) 'Display the dialog box.
Select Case response%
Case -1
If b.OptionGroup1 = 0 Then
produce$ = fruits(b.ListBox1)
Else
produce$ = vegetables(b.ListBox1)
End If
MsgBox "Thank you for ordering " & b.TextBox1 & " " & produce$ & "."
ase 0
MsgBox "Your order has been canceled."
End Select
End Sub
The first thing to notice about the preceding script is that an identifier named DialogControl
has been added to the Begin Dialog statement. As you will learn in the following subsection,
this parameter to the Begin Dialog statement tells the Basic Control Engine to pass control to a
function procedure named DialogControl.
After completing its initialization process, the Basic Control Engine displays your custom dialog box.
When the user selects an item in a list box, clears a check box, or carries out certain other actions
within the dialog box, the Basic Control Engine will again call your dialog function.
1 This action is sent immediately before the dialog box is shown for the first time.
An option button is selected. In this case, ControlName$ contains the name of the option button that was
clicked, and SuppValue contains the index of the option button within the option button group (0 is the first
option button, 1 is the second, and so on).
The current selection is changed in a list box, drop list box, or combo box. In this case, ControlName$ contains
the name of the list box, combo box, or drop list box, and SuppValue contains the index of the new item (0 is the
first item, 1 is the second, and so on).
3 This action is sent when the content of a text box or combo box has been changed and that control loses
focus.
5 This action is sent continuously when the dialog box is idle. The user should return a 0 or idle processing will
use up the CPU.
You'll find a more complete explanation of these action codes in the A–Z Reference. See the
DlgProc (Function) entry in that documentation.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 130
Debug Scripts
Debug Scripts
• Debug overview
• Debug options
Debug Overview
While debugging, you are actually executing the code in a script line by line.
A The Program Editor displays an instruction pointer on the line of code that is about to be executed. When the
instruction pointer is on a line of code, the text on that line appears in black on a gray background that spans
the width of the entire line.
B The edit pane is read-only during the debugging process. You are free to move the insertion point throughout
the script, select text and copy it to the Clipboard as necessary, set breakpoints, and add and remove watch
variables, but you cannot make any changes to the script until you stop running it.
Debug Options
1 Fabricate event information.
(page
131)
3 Use breakpoints.
(page
136)
The Event Editor allows the user to configure a script to run in response to an event. When a project
is running, the Event Manager runs a script either when a specified event or any event occurs,
depending on what is specified in the script.
However
• On one hand, when you build the script in the Program Editor there is no real event to trigger
the script.
• On the other hand, when the script runs with the Event Manager, you can not debug it in the
Program Editor.
An Event Information dialog box is available to fabricate the event information that the APIs would
provide in a real environment.
Using this fabrication you can safely test the accuracy of your script.
Because you are using the Event Information dialog box to fabricate a real world environment, what
you enter depends on what is included in your script. If the script includes specific entries for any of
the fields, you have to enter what is in the script. For any entries that are not specifically referred to
in the script, you can enter whatever you want.
Example
Resource ID as $SYSTEM .
As a result, Alarm Generated and $SYSTEM are selected in the Event Information dialog box.
Whenever, you run the script, it will draw its information from what you entered. You only have to
change your entries in the Event Information dialog box if a script requires a change in a specific
entry.
Procedure Does not step into calls to user defined functions and subroutines. The procedure step does execute
step the calls.
1. Use either method to start stepping through your script with either the single step or procedure
step method.
Single step • Click Debug>Step on the CIMPLICITY Program Editor menu bar.
• Press F8 on the keyboard.
Procedure step • Click Debug>Step Into on the CIMPLICITY Program Editor menu bar.
• Press Shift + F8 on the keyboard.
The Program Editor places the instruction pointer on the sub main line of the script.
Each time you repeat the Step command, Program Editor executes the line containing the
instruction pointer and moves the instruction pointer to the next line to be executed.
3. Do one of the following when you finish stepping through the script execution.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 134
Note: When script execution is initiated, the script will first be compiled, if necessary.
Therefore, there may be a slight pause before execution actually begins. If the script contains
any compile errors, it will not be executed.
Do the following.
6. Repeat the Step command to continue stepping through the script line by line,
When stepping through a subroutine, you can determine the procedure calls made to arrive at
the paused point in the script..
The Calls dialog box opens when you use either method.
The Calls dialog box lists the procedure calls made by the script to arrive at the selected
subroutine.
Click Description
When stepping through a subroutine, you can move the insertion point to another line within a
subroutine to repeat or skip execution of a section of code.
9. Place the insertion point in the line where you want to resume stepping through the script.
The instruction pointer moves to the line you selected; you can resume stepping through your script
from there.
Note: You can only use the Set Next Statement command to move the instruction pointer within
the same subroutine.
3. Use Breakpoints
1 Select breakpoints.
(page
137)
3 Remove breakpoints.
(page
139)
Basic Control Engine and Scripting Reference | 1 - Script Editors | 137
If you only need to debug one or more portions of a long script one or more breakpoints can be set at
selected lines in your script.
Valid breakpoints can only be set on lines in your script that contain code, including lines in
functions and subroutines. Although you can set a breakpoint anywhere within a script prior to
execution, when you compile and run the script, invalid breakpoints (breakpoints on lines that don't
contain code) are automatically removed. While you are debugging your script, the Program Editor
will beep if you try to set a breakpoint on a line that does not contain code.
Select Breakpoints
1. Place the insertion point in the line where you want to do one of the following.
• A select point.
• A line outside the current subroutine.
• Selected portions of a program.
Results
• A select point
Runs the script at full speed until it reaches the line containing the breakpoint and then pauses with
the instruction pointer on that line.
The line will be executed next when you either proceed with debugging or resume running the script.
If you want to continue debugging at another line in your script, you can use the Set Next Statement
command in the Debug menu to move the instruction pointer to the desired line—provided the line is
within the same subroutine.
Runs the script at full speed until it reaches the line containing the breakpoint and then pauses with
the instruction pointer on that line.
You can now resume stepping through your script from that point.
Runs the script at full speed until it reaches the line containing the first breakpoint and then pauses
with the instruction pointer on that line.
2. To resume running your script, click the Start button on the toolbar or press F5.
The script executes at full speed until it reaches the line containing the second breakpoint and then
pauses with the instruction pointer on that line.
1. Repeat 1 and 2 until you have finished debugging the selected portions of your script.
Remove breakpoints
Breakpoints can be removed either manually or automatically.
1. Place the insertion point on the line containing the breakpoint that you want to remove.
2. Do one of the following.
Result: The breakpoint is removed, and the line no longer displays in contrasting type.
Result: The Program Editor removes all breakpoints from your script.
• When a script is compiled and executed, breakpoints are removed from lines that don't contain
code.
• When you exit from the Program Editor, all breakpoints are cleared.
The Trace command can be used in Basic Control Engine scripts to print output to the Program
Editor window's Trace section.
1 Enable tracing.
(page
140)
3 Disable tracing.
(page
142)
Enable Tracing
Example
Trace is enabled.
Result: The trace results display in the Program Editor window trace section.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 141
Result: The trace results are deleted from the Program Editor trace section.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 142
Disable Tracing
Do one of the following.
Result: The trace entries are ignored when the script is run.
As you debug your script, you can use Program Editor's watch pane to monitor selected variables.
For each of the variables on this watch variable list, Program Editor displays the name of the
variable, where it is defined, its value (if the variable is not in scope, its value is shown as <not in
context>), and other key information such as its type and length (if it is a string). The values of the
variables on the watch list are updated each time you enter break mode.
5.1 Add a Watch variable to the Program Editor's Watch variable list.
(page
143)
5.1. Add a Watch Variable to the Program Editor's Watch Variable List
Field Description
Variable Name of the variable you want to add to the watch variable list.
If this is the first variable you are placing on the watch variable list, the watch pane opens far enough
to display that variable. If the watch pane was already open, it expands far enough to display the
variable you just added.
Cannot watch
Can watch
Examples
• Integer
• Long
• Variant
• Individual elements of arrays or structure members using the following syntax:
Where
variable = Name of the structure or array variable,
Example
Basic Control Engine and Scripting Reference | 1 - Script Editors | 145
company(10,23).person.age Member age of structure person that is at element 10,23 within the array of structures
named company
1. Display the names of all the variables that are in scope or defined within the current function or
subroutine on the drop-down Variable Name list.
2. Select the variable you want from that list.
• You can add as many watch variables to the list as you want.
The Watch pane only expands until it fills half of Program Editor's application window. If your list
of watch variables becomes longer than that, you can use the watch pane's scroll bars to bring hidden
portions of the list into view.
When the debugger has control (page 130) , you can modify the value of any of the variables on
Program Editor's Watch variable list.
Field Description
Name Name of the variable to be modified. Note: If the line was double-clicked the Name field:
• Displays the selected variable.
• Is read-only.
• When changing the value of a variable, the Program Editor converts the new value to be of the
same type as the variable being changed.
Example
An Integer value is 3.
• When modifying a Variant variable, the Program Editor needs to determine both the type and
value of the data. Program Editor uses the following logic in performing this assignment (in this
order):
number The value of number. The type of the variant is the smallest data type that fully represents that number.
You can force the data type of the variable using a type-declarator letter following number, such as %, #, &,
!, or @.
• The Program Editor will not assign a new value if it cannot be converted to the same type as the
specified variable.
When the debugger has control (page 130) , you can use the Quick Watch window to do a quick
check of a variable value, without adding the variable to the Watch list (page 143) .
The QuickWatch window opens displaying the value for the selected variable.
The variable is evaluated; if it has a known value, the value displays in the evaluation box.
Basic Control Engine and Scripting Reference | 1 - Script Editors | 149
4. Click Close.
The QuickWatch window closes; you can continue debugging the script.
Note: You must close the QuickWatch window in order to return to the script window.
Run a Program
Important: The CIMPLICITY project must be running in order to run the script.
Once you have finished editing your programs, you will want to run it to make sure it performs the
way you intended. You can also suspend or stop an executing script.
Run a script
Note: This will also compile your script, if necessary, and then execute it.
The script is compiled (if it has not already been compiled), the focus is switched to the parent
window, and the script is executed.
Execution of the script is suspended, and the instruction pointer (a gray highlight) appears on the line
of code where the script stopped executing.
Note: The instruction pointer designates the line of code that will be executed next if you resume
running your script.
Error Messages
Error Messages
This section contains listings of all the runtime errors. It is divided into two subsections, the first
describing errors messages compatible with "standard" Basic as implemented by Microsoft Visual
Basic and the second describing error messages specific to the Basic Control Engine.
A few error messages contain placeholders that get replaced by the runtime when forming the
completed runtime error message. These placeholders appear in the following list as the italicized
word placeholder.
1 Visual Basic compatible error messages.
(page
151)
6 Overflow
7 Out of memory
11 Division by zero
13 Type mismatch
19 No Resume
51 Internal error
61 Disk full
68 Device unavailable
70 Permission denied
140 Dialog control identifier does not match any current control
141 The placeholder statement is not available on this dialog control type
143 The dialog control with the focus may not be hidden or disabled
163 This statement can only be used when a user dialog is active
432 File name or class name not found during OLE Automation operation
3129 Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'
The following table contains a list of all the errors generated by the Basic Control Engine compiler.
With some errors, the compiler changes placeholders within the error to text from the script being
compiled. These placeholders are represented in this table by the word placeholder.
Number Message
25 Out of memory
42 Duplicate label
48 Unknown type
52 0 expected
58 Expecting 0 or 1
65 Internal error 1
67 Internal error 3
68 Division by zero
69 Overflow in expression
An overview of how to open and take advantage of the CimScriptIDE editor includes the following.
1 Open the CimScriptIDE editor.
(page
171)
Important: If you are familiar with the Program Editor for CimBasic, it is important to note that
the CimScriptIDE Editor for .NET scripting behaves differently than the CimBasic Program Editor in
regard to Compiling. Selecting Compile (page 166) for a .NET script saves the script file to disk;
selecting Compile (page 47) for CimBasic it does not.
Either Or
Do the following.
Basic Control Engine and Scripting Reference | 2 - CimScriptIDE Editor | 161
Cancel Closes the Create Script dialog box without creating a script.
3. Right-click Scripts.
5. Right-click anywhere.
8. Opens the script editor window for the selected script type.
Either Or
4. Right-click Scripts.
6. Right-click a script.
Important: CimScriptIDE editor uses .NET 4.5, which was a required installation when
CIMPLICITY v9.0 was installed. However, the CimScriptIDE editor does not recognize certain
keywords that are new in .NET 4.5 and will display an error message when one is not recognized.
However, you can still compile and run scripts that contain the unrecognized keywords.
Example
• async
• await
rect 266, 138, 307, 170 2.4. CimScriptIDE Editor: Right-Pane (page 169)
rect 17, 90, 42, 122 2.3. CimScriptIDE Editor: Class View Pane (page 168)
rect -1, 349, 24, 373 2.2. CimScriptIDE Editor: Toolbars and Status Bar (page 167)
rect -1, 41, 24, 65 2.2. CimScriptIDE Editor: Toolbars and Status Bar (page 167)
rect -1, 19, 24, 43 2.1. CimScriptIDE Editor: Menus (page 164)
2.1 CimScriptIDE Editor: Menus.
(page
164)
• File menu.
• Edit menu.
• View menu.
• Run menu.
• Tools menu.
• Window menu.
• Help menu.
File Menu
Print Setup Opens the Setup dialog box for the default printer.
Basic Control Engine and Scripting Reference | 2 - CimScriptIDE Editor | 165
Edit Menu
Redo Redoes the actions that have been undone, beginning with the last undo.
View Menu
Toolbars and Docking Displays the list of available toolbars. You can toggle the display of each toolbar.
Windows
Status Bar Toggles the Status Bar at the bottom of the CimScriptIDE Editor.
Basic Control Engine and Scripting Reference | 2 - CimScriptIDE Editor | 166
Run Menu
Tools Menu
Points Displays a submenu that enables you to browse for points, edit a point, and create a new point. You can
also use this menu item to include Setpoints, Getpoints and create local variables in the program.
Alarms Displays a submenu that lets you generate or update alarms in the program.
Log Opens a Log Status dialog box enabling you to generate messages for the Status Log.
Status
Dynamic Toggles Dynamic Configuration of points, alarm, etc. Note: When the project is running, dynamic is enabled
for users who have been assigned the Dynamic Configuration privilege.
Basic Control Engine and Scripting Reference | 2 - CimScriptIDE Editor | 167
Window Menu
Help Menu
About Opens an About CimScriptIDE message box with details about the distribution number and installed
CimScriptIDE service upgrades.
• Standard
• Tools
Standard Toolbar
Tools Toolbar
Buttons on the Tools toolbar open the following browser and dialog boxes.
A Displays status messages or tool tips when the mouse hovers over selected items, e.g. Ready or Copy the
selection and put it on the clipboard.
• CAP
• NUM
• SCRL
• Scan a script's imports, class nodes, function, properties, constants and class variables.
• Move the cursor to any selection by double-clicking the instance in the tree.
A Based on the scripting type, a Using or Imports node can be expanded to list each entry in the script.
C# Using
VB .NET Imports
B Class node
Note: This name must be the same as the script filename. If it is changed, make sure the filename is changed.
C Functions, nested classes, constants and class variables that are included in the class.
The CimScriptIDE editor right-pane provides a robust environment for creating and editing C Sharp
and/or VB .NET scripts.
A Multiple scripts, which can be open at the same time, are identified by tabs at the top of the right-pane. The script
for the selected tab (identified by an x) displays for editing.
C As code is being written a CodeComplete Popup lists keywords, variables and members (methods, properties, and
events) that can be used based on what was just written. Any item can be selected and automatically inserted.
E A Trace tab traces messages from the script when the script is run.
Important: The CimScriptIDE editor does not debug scripts; however, scripts written in the
CimScriptIDE editor can be debugged live using Visual Studio.
5. Find the script in the location you had saved it when you were in the CimScriptIDE editor.
9. Do the following.
Feature Action
CIMPLICITY provides default .NET assembly references for C# and VB .NET; additional
references can be added or removed in the (Event Editor) Setup dialog box.
2. Do the following.
C Click Settings.
A Add a .Net Assembly a. Click the Open button to the right of the .Net Assembly References
reference. field.
b. An Open dialog box opens.
c. Select the .dll file that should be added to the list.
d. Click Add.
Result: The selected file is listed as one of the .Net Assembly references.
C Modify the list. Click Modify. The .Net Assembly Reference field is cleared.
4. Click the Open button to the right of the .Net Assembly References field.
7. Click Add.
Category Description
data type Any of the support data types, such as Integer, String, and so on.
function Language element that takes zero or more parameters, performs an action, and returns a value
keyword Language element that doesn't fit into any of the other categories
operator Language elements that cause an evaluation to be performed either on one or two operands
statement Language element that takes zero or more parameters and performs an action.
Each entry in the Basic Control Engine Language Reference documentation contains the following
headings:
Heading Description
Syntax The syntax of the language element. The conventions used in describing the syntax are described in
Chapter 1 of the Basic Control Engine Language Reference documentation.
Comments Contains any other important information about that language keyword.
Example Contains an example of that language keyword in use. An example is provided for every language
keyword.
See Also Contains a list of other entries in the Reference section that relate either directly or indirectly to that
language element.
Double-click Locate on the Help toolbar to locate the topic in the Table of Contents.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 175
Symbols
(page
191)
A G N T
(page (page (page (page
203) 354) 412) 500)
B H O U
(page (page (page (page
223) 362) 422) 510)
C I (page P V
(page 367) (page (page
235) 437) 514)
D K Q W
(page (page (page (page
261) 385) 450) 521)
E L R X
(page (page (page (page
302) 386) 451) 532)
F M S Y
(page (page (page (page
338) 400) 465) 533)
Object Model
CIMPLICITY Configuration
CimLangMapper
CimEdit / CimView
CIMPLICITY XY Plot
Tracker Agents
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 176
TADB
Notation Description
While...Wend Elements belonging to the Basic Control Engine script language, referred to in this manual as
keywords, appear in the typeface shown to the left.
variable Items that are to be replaced with information that you supply appear in italics. The type of replacement
is indicated in the following description.
text$ The presence of a type-declaration character following a parameter signifies that the parameter must
be a variable of that type or an expression that evaluates to that type. If a parameter does not appear
with a type-declaration character, then its type is described in the text.
[parameter] Square brackets indicate that the enclosed items are optional. In Basic Control Engine script language,
you cannot end a statement with a comma, even if the parameters are optional:
{Input | Braces indicate that you must choose one of the enclosed items, which are separated by a vertical bar.
Binary}
... Ellipses indicate that the preceding expression can be repeated any number of times.
The following subsections list Basic Control Engine language elements by category.
Arrays
Clipboard
Comments
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 177
Comparison operators
Conversion
Data types
Database
Date/time
DDE
Error handling
File I/O
File system
Financial
INI Files
Logical/binary operators
Math
Miscellaneous
Numeric operators
Objects
Parsing
Predefined dialogs
Printing
Procedures
String operators
Strings
User Dialogs
Variants
Arrays
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 178
Option Base Change the default lower bound for array declarations
Clipboard
Comments
Comparison Operators
= Equal
Conversion
Data Types
Double Data type used to hold real number with 15-16 digits of precision
Integer Data type used to hold whole numbers with 4 digits of precision
Long Data type used to hold whole numbers with 10 digits of precision
Single Data type used to hold real number with 7 digits of precision
Variant Data type that holds a number, string, or OLE automation objects
Database
Date/time
DDE
Error Handling
Err (function) Return the error that caused the current error trap
File I/O
Loc Return the record position of the file pointer within a file
Seek Return the byte position of the file pointer within a file
Seek Set the byte position of the file pointer which a file
File System
FileDateTime Return the date and time when a file was last modified
Financial
IRR Return the internal rate of return for a series of payments and receipts
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 185
INI Files
ReadIniSection Read all the item names from a given section of an INI file
Logical/binary Operators
Math
Miscellaneous
_ Line continuation
Numeric Operators
* Multiply
+ Add
- Subtract
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 187
/ Divide
\ Integer divide
^ Power
Mod Remainder
Objects
GetObject Return an OLE automation object from a file, or returns a previously instantiated OLE automation object
Parsing
Predefined Dialogs
Printing
Procedures
String Operators
Strings
Option Compare Change the default comparison between text and binary
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 189
User Dialogs
DlgListBoxArray Set the content of a list box or combo box in a dynamic dialog
DlgListBoxArray Set the content of a list box or combo box in a dynamic dialog
= Assignment
Variants
Symbols
Symbols
' (keyword)
- (operator)
#Const (directive)
#If...Then...#Else (directive)
& (operator)
() (keyword)
* (operator)
. (keyword)
/ (operator)
\ (operator)
^ (operator)
_ (keyword)
+ (operator)
< (operator)
<= (operator)
<> (operator)
= (operator)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 192
= (statement)
> (operator)
>= (operator)
' (keyword)
Description Causes the compiler to skip all characters between this character and the end of the current line.
Comments This is very useful for commenting your code to make it more readable.
Example
Sub Main()
'This whole line is treated as a comment.
i$ = "Strings" 'This is a valid assignment with a comment.
This line will cause an error (the apostrophe is missing).
End Sub
See Also Rem (page 460) (statement); Comments (page 260) (topic).
- (operator)
Syntax 2 – expression
Description Returns the difference between expression1 and expression2 or, in the second syntax, returns the
negation of expression.
Comments Syntax 1 The type of the result is the same as that of the most precise expression, with the following
exceptions:
If one expression is and the other expression is then the type result is
A runtime error is generated if the result overflows its legal range. When either or both expressions are
Variant , then the following additional rules apply:
• If expression1 is Null and expression2 is Boolean , then the result is Empty . Otherwise, if either
expression is Null , then the result is Null .
• Empty is treated as an Integer of value 0 .
• If the type of the result is an Integer variant that overflows, then the result is a Long variant.
• If the type of the result is a Long , Single , or Date variant that overflows, then the result is a
Double variant.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 193
Syntax 2 If expression is numeric, then the type of the result is the same type as expression, with the
following exception:
In 2's compliment arithmetic, unary minus may result in an overflow with Integer and Long variables
when the value of expression is the largest negative number representable for that data type. For
example, the following generates an overflow error:
Sub Main()
Dim a As Integer
a = -32768
a = -a '<-- Generates overflow here.
End Sub
When negating variants, overflow will never occur because the result will be automatically promoted:
integers to longs and longs to doubles.
Example This example assigns values to two numeric variables and their difference to a third variable, then
displays the result.
Sub Main()
i% = 100
j# = 22.55
k# = i% - j#
MsgBox "The difference is: " & k#
End Sub
#Const (directive)
Comments Internally, all preprocessor constants are of type Variant. Thus, the expression parameter can be any
type. Variables defined using #Const can only be used within the #If...Then...#Else statement and other
#Const statements. Use the Const statement to define constants that can be used within your code.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 194
Example
#Const
SUBPLATFORM = "XP"
#Const PLATFORM = MANUFACTURER & " " & SUBPLATFORM & " " & TYPE
Sub Main()
#End If
End Sub
#If...Then...#Else (directive)
Syntax
#If expression Then
[statements]
[
#ElseIf expression Then
[statements]]
[
#Else
[statements]]
#End If
Description Causes the compiler to include or exclude sections of code based on conditions.
Comments The expression represents any valid BasicScript Boolean expression evaluating to TRUE of FALSE.
The expression may consist of literals, operators, constants defined with #Const, and any of the following
predefined constants:
Constant Value
Empty Empty
FALSE False
NULL Null
TRUE True
The expression can use any of the following operators: +, -, *, /, \, ^, + (unary), - (unary), Mod, &, =, <>,
>=, >, <=, <, And, Or, Xor, Imp, Eqv.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 195
Evaluates to a: Result
Zero FALSE
Text comparisons within expression are always case-insensitive, regardless of the Option Compare
setting You can define your own constants using the #Const directive, and test for these constants within
the expression parameter as shown below:
#Const VERSION = 2
Sub Main
#If VERSION =
1 Then
directory$ = "\apps\widget"
#ElseIf VERSION =
2 Then
directory$ = "\apps\widget32"
#Else
MsgBox "Unknown version."
#End If
End Sub
Any constant not already defined evaluates to Empty. A common use of the #If...Then...#Else directive
is to optionally include debugging statements in your code. The following example shows how debugging
code can be conditionally included to check parameters to a function:
#Const DEBUG = 1
Sub ChangeFormat(NewFormat As Integer,StatusText As String)
#If DEBUG =
1 Then
If NewFormat <> 1 And NewFormat <> 2 Then
MsgBox "Parameter ""NewFormat"" is invalid."
Exit Sub
End If
If Len(StatusText) > 78 Then
MsgBox "Parameter ""StatusText"" is too long."
Exit Sub
End If
#End If
Rem Change the format here...
End Sub
Excluded section are not compiled by BasicScript, allowing you to exclude sections of code that has
errors or doesn’t even represent valid BasicScript syntax. For example, the following code uses the
#If...Then...#Else statement to include a multi-line comment:
Sub Main
#If 0
The following section of code displays
a dialog box containing a message and an
OK button.
#End If
MsgBox "Hello, world."
End Sub
In the above example, since the expression #If 0 never evaluates to TRUE, the text between that and the
matching #End If will never be compiled.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 196
& (operator)
Comments If both expressions are strings, then the type of the result is String . Otherwise, the type of the result is a
String variant. When nonstring expressions are encountered, each expression is converted to a String
variant. If both expressions are Null , then a Null variant is returned. If only one expression is Null ,
then it is treated as a zero-length string. Empty variants are also treated as zero-length strings. In many
instances, the plus (+) operator can be used in place of & . The difference is that + attempts addition
when used with at least one numeric expression, whereas & always concatenates.
Example This example assigns a concatenated string to variable s$ and a string to s2$, then concatenates the two
variables and displays the result in a dialog box.
Sub Main()
s$ = "This string" & " is concatenated"
s2$ = " with the '&' operator."
MsgBox s$ & s2$
End Sub
See Also + (page 200) (operator); Operator Precedence (page 431) (topic).
() (keyword)
Description Forces parts of an expression to be evaluated before others or forces a parameter to be passed by value.
Comments Parentheses within Expressions Parentheses override the normal precedence order of the scripts
operators, forcing a subexpression to be evaluated before other parts of the expression. For example, the
use of parentheses in the following expressions causes different results: i = 1 + 2 * 3 'Assigns 7. i =
(1 + 2) * 3 'Assigns 9. Use of parentheses can make your code easier to read, removing any ambiguity in
complicated expressions.
Parentheses Used in Parameter Passing Parentheses can also be used when passing parameters to
functions or subroutines to force a given parameter to be passed by value, as shown below: ShowForm
i 'Pass i by reference. ShowForm (i) 'Pass i by value. Enclosing parameters within parentheses can
be misleading. For example, the following statement appears to be calling a function called ShowForm
without assigning the result: ShowForm(i) The above statement actually calls a subroutine called
ShowForm , passing it the variable i by value. It may be clearer to use the ByVal keyword in this case,
which accomplishes the same thing: ShowForm ByVal i The result of an expression is always passed
by value.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 197
See Also ByVal (page 234) (keyword); Operator Precedence (page 431) (topic).
* (operator)
Comments The result is the same type as the most precise expression, with the following exceptions:
If one expression is and the other expression is then the type the result is
When the * operator is used with variants, the following additional rules apply:
• Empty is treated as 0.
• If the type of the result is an Integer variant that overflows, then the result is automatically promoted
to a Long variant.
• If the type of the result is a Single , Long , or Date variant that overflows, then the result is
automatically promoted to a Double variant.
• If expression1 is Null and expression2 is Boolean , then the result is Empty . Otherwise, If either
expression is Null , then the result is Null .
Example This example assigns values to two variables and their product to a third variable, then displays the
product of s# * t#.
Sub Main()
s# = 123.55
t# = 2.55
u# = s# * t#
MsgBox s# & " * " & t# & " = " & s# * t#
End Sub
. (keyword)
Syntax 2 structure.member
Examples This example uses the period to separate an object from a property. Sub Main() MsgBox "The clipboard
text is: " & Clipboard.GetText() End Sub
/ (operator)
Comments The type of the result is Double , with the following exceptions:
If one expression is and the other expression is then the type the result is
A runtime error is generated if the result overflows its legal range. When either or both expressions is
Variant , then the following additional rules apply:
• If expression1 is Null and expression2 is Boolean , then the result is Empty . Otherwise, if either
expression is Null , then the result is Null .
• Empty is treated as an Integer of value 0 .
• If both expressions are either Integer or Single variants and the result overflows, then the result is
automatically promoted to a Double variant.
Example This example assigns values to two variables and their quotient to a third variable, then displays the
result.
Sub Main()
i% = 100
j# = 22.55
k# = i% / j#
MsgBox "The quotient of i/j is: " & k#
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 199
See Also \ (page 199) (operator): Operator Precedence (page 431) (topic)
\ (operator)
Comments Before the integer division is performed, each expression is converted to the data type of the most precise
expression. If the type of the expressions is either Single, Double, Date , or Currency , then each is
rounded to Long . If either expression is a Variant , then the following additional rules apply:
Example This example assigns the quotient of two literals to a variable and displays the result.
Sub Main()
s% = 100.99 \ 2.6
MsgBox "Integer division of 100.99\2.6 is: " & s%
End Sub
See Also / (page 198) (operator); Operator Precedence (page 431) (Topic)
^ (operator)
n^0 1
0^-n Undefined
0^+n 0
1^n 1
The type of the result is always Double, except with Boolean expressions, in which case the result is
Boolean. Fractional and negative exponents are allowed. If either expression is a Variant containing
NULL, then the result is NULL. It is important to note that raising a number to a negative exponent
produces a fractional result.
Example
Sub Main()
s# = 2 ^ 5 'Returns 2 to the 5th power.
r# = 16 ^ .5 'Returns the square root of 16.
MsgBox "2 to the 5th power is: " & s#
MsgBox "The square root of 16 is: " & r#
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 200
_ (keyword)
Syntax s$ = "This is a very long line that I want to split " & _ "onto two lines"
Description Line-continuation character, which allows you to split a single script onto more than one line.
Comments The line-continuation character cannot be used within strings and must be preceded by white space
(either a space or a tab). The line-continuation character can be followed by a comment, as shown below:
i = 5 + 6 & _ 'Continue on the next line. "Hello"
Example
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
'The line-continuation operator is useful when concatenating
'long strings.
msg1 = "This line is a line of text that" & crlf & "extends beyond " _
& "the borders of the editor" & crlf & "so it is split into " _
& "multiple lines"
'It is also useful for separating and continuing long calculation lines.
b# = .124
a# = .223
s# = ( (((Sin(b#) ^ 2) + (Cos(a#) ^ 2)) ^ .5) / _
(((Sin(a#) ^ 2) + (Cos(b#) ^ 2)) ^ .5) ) * 2.00
MsgBox msg1 & crlf & crlf & "The value of s# is: " & s#
End Sub
+ (operator)
Comments Addition operates differently depending on the type of the two expressions:
Empty variant Any data type Return the non- Empty expression unchanged.
When using + to concatenate two variants, the result depends on the types of each variant at runtime.
You can remove any ambiguity by using the & operator. Numeric Add A numeric add is performed
when both expressions are numeric (i.e., not variant or string). The result is the same type as the most
precise expression, with the following exceptions:.
A runtime error is generated if the result overflows its legal range Variant Add If both expressions are
variants, or one expression is numeric and the other expression is Variant , then a variant add is
performed. The rules for variant add are the same as those for normal numeric add, with the following
exceptions:
• If the type of the result is an Integer variant that overflows, then the result is a Long variant.
• If the type of the result is a Long , Single , or Date variant that overflows, then the result is a
Double variant.
Example This example assigns string and numeric variable values and then uses the + operator to concatenate
the strings and form the sums of numeric variables.
Sub Main()
i$ = "concatenate " + "strings!"
j% = 95 + 5 'Addition of numeric literals
k# = j% + j% 'Addition of numeric variable
MsgBox "You can " + i$
MsgBox "You can add literals or variables:" + Str(j%) + ", " + Str(k#)
End Sub
See Also & (page 196) (Operator); Operator Precedence (page 431) (topic)
< (operator)
<= (operator)
<> (operator)
= (operator)
= (statement)
Comments When assigning expressions to variables, internal type conversions are performed automatically between
any two numeric quantities. Thus, you can freely assign numeric quantities without regard to type
conversions. However, it is possible for an overflow error to occur when converting from larger to smaller
types. This occurs when the larger type contains a numeric quantity that cannot be represented by the
smaller type. For example, the following code will produce a runtime error: Dim amount As Long
Dim quantity As Integer amount = 400123 'Assign a value out of range for int. quantity =
amount 'Attempt to assign to Integer. When performing an automatic data conversion, underflow is
not an error.
The assignment operator ( = ) cannot be used to assign objects. Use the Set statement instead.
Example
Sub Main()
a$ = "This is a string"
b% = 100
c# = 1213.3443
MsgBox a$ & "," & b% & "," & c#
End Sub
See Also Let (page 390) (statement); Operator Precedence (page 431) (topic); Set (page 476) (statement);
Expression Evaluation (page 336) (topic).
> (operator)
>= (operator)
Abs (function)
And (operator)
AnswerBox (function)
AppActivate (statement)
AppClose (statement)
AppGetActive$ (function)
AppGetPosition (statement)
AppGetState (function)
AppHide (statement)
AppList (statement)
AppMaximize (statement)
AppMinimize (statement)
AppMove (statement)
AppRestore (statement)
AppSetState (statement)
AppShow (statement)
AppSize (statement)
AppType (function)
ArrayDims (function)
Arrays (topic)
ArraySort (statement)
Atn (function)
Abs (function)
Comments If expression is Null , then Null is returned. Empty is treated as 0 . The type of the result is the same
as that of expression, with the following exceptions:
• If expression is an Integer that overflows its legal range, then the result is returned as a Long .
This only occurs with the largest negative Integer :
Dim a As Variant
Dim i As Integer
i = -32768
a = Abs(i) 'Result is a Long.
i = Abs(i) 'Overflow!
• If expression is a Long that overflows its legal range, then the result is returned as a Double . This
only occurs with the largest negative Long :
Dim a As Variant
Dim l As Long
l = -2147483648
a = Abs(l) 'Result is a Double.
l = Abs(l) 'Overflow!
• If expression is a Currency value that overflows its legal range, an overflow error is generated.
Example This example assigns absolute values to variables of four types and displays the result.
Sub Main()
s1% = Abs(-10.55)
s2& = Abs(-10.55)
s3! = Abs(-10.55)
s4# = Abs(-10.55)
MsgBox "The absolute values are: " & s1% & "," & s2& & "," & s3! & "," & s4#
End Sub
And (operator)
Comments If both expressions are either Boolean, Boolean variants, or Null variants, then a logical conjunction is
performed as follows:
If the first expression is and the second expression is then the result is
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 205
Binary Conjunction If the two expressions are Integer, then a binary conjunction is performed, returning
an Integer result. All other numeric types (including Empty variants) are converted to Long, and a binary
conjunction is then performed, returning a Long result. Binary conjunction forms a new value based on a
bit-by-bit comparison of the binary representations of the two expressions according to the following table:
1 And 1 = 1 Example:
0 And 1 = 0 5 00001001
1 And 0 = 0 6 00001010
Example
Sub Main()
n1 = 1001
n2 = 1000
b1 = True
b2 = False
'This example performs a numeric bitwise And operation and stores
'the result in N3.
n3 = n1 And n2
'This example performs a logical And comparing b1 and b2 and displays
'the result.
If b1 And b2 Then
MsgBox "b1 And b2 are True; n3 is: " & n3
Else
MsgBox "b1 And b2 are False; n3 is: " & n3
End If
End Sub
See Also Operator Precedence (page 431) (topic); Or (page 435) (operator); Xor (page 532)
(operator); Eqv (page 323));(operator); (operator) (page 371).
AnswerBox (function)
Description Displays a dialog box prompting the user for a response and returns an Integer indicating which button
was clicked (1 for the first button, 2 for the second, and so on).
Parameter Description
Prompt Text to be displayed above the text box. The prompt parameter can be any expression
convertible to a String .
The Basic Control Engine script resizes the dialog box to hold the entire contents of prompt,
up to a maximum width of 5/8 of the width of the screen and a maximum height of 5/8 of the
height of the screen. It also word-wraps any lines too long to fit within the dialog box and
truncates all lines beyond the maximum number of lines that fit in the dialog box.
You can insert a carriage-return/line-feed character in a string to cause a line break in your
message.
Button1 Text for the first button. If omitted, then "OK" and "Cancel" are used. A runtime error is
generated if this parameter is Null .
Button2 Text for the second button. A runtime error is generated if this parameter is Null .
Button3 Text for the third button. A runtime error is generated if this parameter is Null .
The width of each button is determined by the width of the widest button. The AnswerBox function
returns 0 if the user selects Cancel. R% = AnswerBox("Copy files?")
R% = AnswerBox("Copy files?","Save","Restore","Cancel")
Example This example displays a dialog box containing three buttons. It displays an additional message based on
which of the three buttons is selected.
Sub Main()
r% = AnswerBox("Temporary File Operation?","Save","Remove","Cancel")
Select Case r%
Case 1
MsgBox "Files will be saved."
Case 2
MsgBox "Files will be removed."
Case Else
MsgBox "Operation canceled."
End Select
End Sub
See Also MsgBox (page 411) (statement); AskBox$ (page 221) (function); AskPassword$ (page
222) (function); InputBox, InputBox$ (page 374) (functions); OpenFilename$ (page 429)
(function); SaveFilename$ (page 467) (function); SelectBox (page 473) (function).
Notes AnswerBox displays all text in its dialog box in 8-point MS Sans Serif.
Description Used with the Declare statement to indicate that type checking is not to be performed with a given
argument.
Example The following example calls the FindWindow to determine if Program Manager is running. This example
uses the Any keyword to pass a NULL pointer, which is accepted by the FindWindow function.
Declare Function FindWindow16 Lib "user" Alias "FindWindow" (ByVal Class _
As Any,ByVal Title As Any) As Integer
Declare Function FindWindow32 Lib "user32" Alias "FindWindowA" (ByVal Class _
As Any,ByVal Title As Any) As Long
Sub Main()
Dim hWnd As Variant
If Basic.Os = ebWin16 Then
hWnd = FindWindow 16("PROGMAN",0&)
ElseIf Basic.Os = ebWin32 Then
hWnd = FindWindow32("PROGMAN",0&)
Else
hWnd = 0
End If
If hWnd <> 0 Then
MsgBox "Program manager is running, window handle is " & hWnd
End If
End Sub
AppActivate (statement)
Parameter Description
TaskID Number specifying the task ID of the application to be activated. Acceptable task IDs are
returned by the Shell function
When activating applications using the task ID, it is important to declare the variable used to hold the task
ID as a Variant . The type of the ID depends on the platform on which The Basic Control Engine script is
running.
Example 2 This example runs another application, activates it, and maximizes it.
Sub Main()
Dim id as variant
id = Shell("notepad.exe") 'Run Notepad minimized.
AppActivate id 'Now activate Notepad.
AppMaximize
End Sub
See Also Shell (page 478) (function); SendKeys (page 474) (statement); WinActivate (page 523) (statement).
Notes
• The name$ parameter is the exact string appearing in the title bar of the named application's main
window. If no application is found whose title exactly matches name$, then a second search is
performed for applications whose title string begins with name$. If more than one application is found
that matches name$, then the first application encountered is used.
• Minimized applications are not restored before activation. Thus, activating a minimized DOS
application will not restore it; rather, it will highlight its icon.
• A runtime error results if the window being activated is not enabled, as is the case if that application is
currently displaying a modal dialog box.
AppClose (statement)
Comments The name$ parameter is a String containing the name of the application. If the name$ parameter is
absent, then the AppClose statement closes the active application.
See Also AppMaximize (page 212) (statement); AppMinimize (page 212) (statement); AppRestore (page 214)
(statement); AppMove (page 213) (statement); AppSize (page 215) (statement).
Notes A runtime error results if the application being closed is not enabled, as is the case if that application is
currently displaying a modal dialog box. The name$ parameter is the exact string appearing in the title bar
of the named application's main window. If no application is found whose title exactly matches name$,
then a second search is performed for applications whose title string begins with name$. If more than one
application is found that matches name$, then the first application encountered is used.
Description Returns a String containing the full name of the application matching either title or taskID.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 209
Comments The title parameter specifies the title of the application to find. If there is no exact match, BasicScript will
find an application whose title begins with title. Alternatively, you can specify the ID of the task as returned
by the Shell function. The AppFind$ functions returns a String, whereas the AppFind function returns a
String variant. If the specified application cannot be found, then AppFind$ returns a zero-length string and
AppFind returns Empty. Using AppFind allows you detect failure when attempting to find an application
with no caption (i.e., Empty is returned instead of a zero-length String). AppFind$ is generally used to
determine whether a given application is running. The following expression returns True if Microsoft Word
is running:
AppFind$("Microsoft Word")
Example
'This example checks to see whether Excel is running before
'activating it.
Sub Main()
If AppFind$("Microsoft Excel") <> "" Then
AppActivate "Microsoft Excel"
Else
MsgBox "Excel is not running."
End If
End Sub
Notes This function returns a String containing the exact text appearing in the title bar of the active
application's main window.
AppGetActive$ (function)
Syntax AppGetActive$()
Comments If no application is active, the AppGetActive$ function returns a zero-length string. You can use
AppGetActive$ to retrieve the name of the active application. You can then use this name in calls to
routines that require an application name.
Example
Sub Main()
n$ = AppGetActive$()
AppMinimize n$
End Sub
See Also AppActivate (page 207) (statement); WinFind (page 525) (function).
Notes This function returns a String containing the exact text appearing in the title bar of the active
application's main window.
AppGetPosition (statement)
Parameter Description
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 210
width, Names of Integer variables to receive the size of the application's window.
height
Name$ String containing the name of the application. If the name$ parameter is omitted, then the
active application is used.
The x, y, width, and height variables are filled with the position and size of the application's window. If an
argument is not a variable, then the argument is ignored, as in the following example, which only retrieves
the x and y parameters and ignores the width and height parameters:
Dim x As Integer,y As Integer
AppGetPosition x,y,0,0,"Program Manager"
Example
Sub Main()
Dim x As Integer,y As Integer
Dim cx As Integer,cy As Integer
AppGetPosition x,y,cx,cy,"Program Manager"
End Sub
See Also AppMove (page 213) (statement); AppSize (page 215) (statement).
Note The position and size of the window are returned in twips. The name$ parameter is the exact string
appearing in the title bar of the named application's main window. If no application is found whose title
exactly matches name$, then a second search is performed for applications whose title string begins with
name$. If more than one application is found that matches name$, then the first application encountered
is used.
AppGetState (function)
Maximized ebMaximized
Minimized ebMinimized
Restored ebRestored
The name$ parameter is a String containing the name of the desired application. If it is omitted, then the
AppGetState function returns the name of the active application.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 211
Examples This example saves the state of Program Manager, changes it, then restores it to its original setting.
Sub Main()
If AppFind$("Program Manager") = "" Then
MsgBox "Can't find Program Manager."
Exit Sub
End If
AppActivate "Program Manager" 'Activate Program Manager.
state = AppGetState 'Save its state.
AppMinimize 'Minimize it.
MsgBox "Program Manager is now minimized. Select OK to restore it."
AppActivate "Program Manager"
AppSetState state 'Restore it.
End Sub
See Also AppMaximize (page 212) (statement); AppMinimize (page 212) (statement); AppRestore (page 214)
(statement).
Notes The name$ parameter is the exact string appearing in the title bar of the named application's main
window. If no application is found whose title exactly matches name$, then a second search is performed
for applications whose title string begins with name$. If more than one application is found that matches
name$, then the first application encountered is used.
AppHide (statement)
Comments If the named application is already hidden, the AppHide statement will have no effect. The name$
parameter is a String containing the name of the desired application. If it is omitted, then the AppHide
statement hides the active application. AppHide generates a runtime error if the named application is
not enabled, as is the case if that application is displaying a modal dialog box.
Notes The name$ parameter is the exact string appearing in the title bar of the named application's main
window. If no application is found whose title exactly matches name$, then a second search is performed
for applications whose title string begins with name$. If more than one application is found that matches
name$, then the first application encountered is used.
AppList (statement)
Comments The AppNames$ parameter must specify either a zero- or one-dimensioned dynamic String array or a
one-dimensional fixed String array. If the array is dynamic, then it will be redimensioned to match the
number of open applications. For fixed arrays, AppList first erases each array element, then begins
assigning application names to the elements in the array. If there are fewer elements than will fit in the
array, then the remaining elements are unused. The script returns a runtime error if the array is too small
to hold the new elements. After calling this function, you can use LBound and UBound to determine
the new size of the array.
Notes The name of an application is considered to be the exact text that appears in the title bar of the
application's main window.
AppMaximize (statement)
Comments The name$ parameter is a String containing the name of the desired application. If it is omitted, then the
AppMaximize function maximizes the active application.
Example
Sub Main()
AppMaximize "Program Manager" 'Maximize Program Manager.
See Also AppMinimize (page 212) (statement); AppRestore (page 214) (statement); AppMove (page 213)
(statement); AppSize (page 215) (statement); AppClose (page 208) (statement).
Notes If the named application is maximized or hidden, the AppMaximize statement will have no effect. The
name$ parameter is the exact string appearing in the title bar of the named application's main window.
If no application is found whose title exactly matches name$, then a second search is performed for
applications whose title string begins with name$. If more than one application is found that matches
name$, then the first application encountered is used. AppMaximize generates a runtime error if the
named application is not enabled, as is the case if that application is displaying a modal dialog box.
AppMinimize (statement)
Comments The name$ parameter is a String containing the name of the desired application. If it is omitted, then the
AppMinimize function minimizes the active application.
Example
Sub Main()
AppMinimize "Program Manager" 'Maximize Program Manager.
See Also AppMaximize (page 212) (statement); AppRestore (page 214) (statement); AppMove (page 213)
(statement); AppSize (page 215) (statement); AppClose (page 208) (statement).
Notes If the named application is minimized or hidden, the AppMinimize statement will have no effect. The
name$ parameter is the exact string appearing in the title bar of the named application's main window.
If no application is found whose title exactly matches name$, then a second search is performed for
applications whose title string begins with name$. If more than one application is found that matches
name$, then the first application encountered is used. AppMinimize generates a runtime error if the
named application is not enabled, as is the case if that application is displaying a modal dialog box.
AppMove (statement)
Description Sets the upper left corner of the named application to a given location.
Parameter Description
X, Y Integer coordinates specifying the upper left corner of the new location of the application,
static to the upper left corner of the display.
name$ String containing the name of the application to move. If this parameter is omitted, then the
active application is moved.
Example This example activates Program Manager, then moves it 10 pixels to the right.
Sub Main()
Dim x%,y%
AppActivate "Program Manager" 'Activate Program Manager.
AppGetPosition x%,y%,0,0 'Retrieve its position.
x% = x% + Screen.TwipsPerPixelX * 10 'Add 10 pixels.
AppMove x% + 10,y% 'Nudge it 10 pixels to the right.
End Sub
See Also AppMaximize (page 212) (statement); AppMinimize (page 212) (statement); AppRestore (page 214)
(statement); AppSize (page 215) (statement); AppClose (page 208) (statement).
Note If the named application is maximized or hidden, the AppMove statement will have no effect. The X
and Y parameters are specified in twips. AppMove will accept X and Y parameters that are off the
screen. The name$ parameter is the exact string appearing in the title bar of the named application's main
window. If no application is found whose title exactly matches name$, then a second search is performed
for applications whose title string begins with name$. If more than one application is found that matches
name$, then the first application encountered is used. AppMove generates a runtime error if the named
application is not enabled, as is the case if that application is currently displaying a modal dialog box.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 214
AppRestore (statement)
Comments The name$ parameter is a String containing the name of the application to restore. If this parameter is
omitted, then the active application is restored.
See Also AppMaximize (page 212) (statement); AppMinimize (page 212) (statement); AppMove (page 213)
(statement); AppSize (page 215) (statement); AppClose (page 208) (statement).
Notes The name$ parameter is the exact string appearing in the title bar of the named application's main
window. If no application is found whose title exactly matches name$, then a second search is performed
for applications whose title string begins with name$. If more than one application is found that matches
name$, then the first application encountered is used. AppRestore will have an effect only if the main
window of the named application is either maximized or minimized. AppRestore will have no effect if the
named window is hidden. AppRestore generates a runtime error if the named application is not enabled,
as is the case if that application is currently displaying a modal dialog box.
AppSetState (statement)
Description Maximizes, minimizes, or restores the named application, depending on the value of newstate.
Parameter Description
Newstate Integer specifying the new state of the window. It can be any of the following values.
Value Description
Name$ String containing the name of the application to change. If this parameter is omitted, then
the active application is used.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 215
Example This example saves the state of Program Manager, changes it, then restores it to its original setting.
Sub Main()
If AppFind$("Program Manager") = "" Then
MsgBox "Can't find Program Manager."
Exit Sub
End If
AppActivate "Program Manager" 'Activate Program Manager.
state = AppGetState 'Save its state.
AppMinimize 'Minimize it.
MsgBox "Program Manager is now minimized. Select OK to restore it."
AppActivate "Program Manager"
AppSetState state 'Restore it.
End Sub
See Also AppGetState (page 210) (function); AppRestore (page 214) (statement); AppMaximize (page 212)
(statement); AppMinimize (page 212) (statement)
Notes The name$ parameter is the exact string appearing in the title bar of the named application's main
window. If no application is found whose title exactly matches name$, then a second search is performed
for applications whose title string begins with name$. If more than one application is found that matches
name$, then the first application encountered is used.
AppShow (statement)
Comments The name$ parameter is a String containing the name of the application to show. If this parameter is
omitted, then the active application is shown.
Notes: If the named application is already visible, AppShow will have no effect. The name$ parameter is the
exact string appearing in the title bar of the named application's main window. If no application is found
whose title exactly matches name$, then a second search is performed for applications whose title string
begins with name$. If more than one application is found that matches name$, then the first application
encountered is used. AppShow generates a runtime error if the named application is not enabled, as is
the case if that application is displaying a modal dialog box.
AppSize (statement)
Parameter Description
Name$ String containing the name of the application to resize. If this parameter is omitted, then the
active application is used.
Example This example enlarges the active application by 10 pixels in both the vertical and horizontal directions.
Sub Main()
Dim w%,h%
AppGetPosition 0,0,w%,h% 'Get current width/height.
x% = x% + Screen.TwipsPerPixelX * 10 'Add 10 pixels.
y% = y% + Screen.TwipsPerPixelY * 10 'Add 10 pixels.
AppSize w%,h% 'Change to new size.
End Sub
See Also AppMaximize (page 212) (statement); AppMinimize (page 212) (statement); AppRestore (page 214)
(statement); AppMove (page 213) (statement); AppClose (page 208) (statement).
Note The width and height parameters are specified in twips. This statement will only work if the named
application is restored (i.e., not minimized or maximized). The name$ parameter is the exact string
appearing in the title bar of the named application's main window. If no application is found whose title
exactly matches name$, then a second search is performed for applications whose title string begins with
name$. If more than one application is found that matches name$, then the first application encountered
is used. A runtime error results if the application being resized is not enabled, which is the case if that
application is displaying a modal dialog box when an AppSize statement is executed.
AppType (function)
Description Returns an Integer indicating the executable file type of the named application:
Comments The name$ parameter is a String containing the name of the application. If this parameter is omitted,
then the active application is used.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 217
Example This example creates an array of strings containing the names of all the running Windows applications.
It uses the AppType command to determine whether an application is a Windows application or a DOS
application.
Sub Main()
Dim apps$(),wapps$()
AppList apps 'Retrieve a list of all Windows and DOS apps.
If ArrayDims(apps) = 0 Then
MsgBox "There are no running applications."
Exit Sub
End If
'Create an array to hold only the Windows apps.
ReDim wapps$(UBound(apps))
n = 0 'Copy the Windows apps from one array to the target array.
For i = LBound(apps) to UBound(apps)
If AppType(apps(i)) = ebWindows Then
wapps(n) = apps(i)
n = n + 1
End If
Next I
If n = 0 Then 'Make sure at least one Windows app was found.
MsgBox "There are no running Windows applications."
Exit Sub
End If
ReDim Preserve wapps(n - 1) 'Resize to hold the exact number.
'Let the user pick one.
index% = SelectBox("Windows Applications","Select a Windows application:",wapps)
End Sub
Notes The name$ parameter is the exact string appearing in the title bar of the named application's main
window. If no application is found whose title exactly matches name$, then a second search is performed
for applications whose title string begins with name$. If more than one application is found that matches
name$, then the first application encountered is used.
ArrayDims (function)
Comments This function can be used to determine whether a given array contains any elements or if the array is
initially created with no dimensions and then redimensioned by another function, such as the FileList
function, as shown in the following example.
Example This example allocates an empty (null-dimensioned) array; fills the array with a list of filenames, which
resizes the array; then tests the array dimension and displays an appropriate message.
Sub Main()
Dim f$()
FileList f$,"c:\*.bat"
If ArrayDims(f$) = 0 Then
MsgBox "The array is empty."
Else
MsgBox "The array size is: " & (UBound(f$) - UBound(f$) + 1)
End If
End Sub
See Also LBound (page 387) (function); UBound (page 510) (function); Arrays (topic)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 218
Arrays (topic)
Declaring Array Variables Arrays in a Basic Control Engine script are declared using any of the following statements:
Dim
Public
Private
For example:
Dim a(10) As Integer
Public LastNames(1 to 5,-2 to 7) As Variant
Private
Arrays of any data type can be created, including Integer, Long, Single, Double, Boolean, Date, Variant, Object,
user-defined structures, and data objects. The lower and upper bounds of each array dimension must be within the
following range:
-32768 <= bound <= 32767
Arrays can have up to 60 dimensions. Arrays can be declared as either fixed or dynamic, as described below.
Fixed Arrays The dimensions of fixed arrays cannot be adjusted at execution time. Once declared, a fixed array will
always require the same amount of storage. Fixed arrays can be declared with the Dim,Private, or Public statement by
supplying explicit dimensions. The following example declares a fixed array of ten strings:
Dim a(10) As String
Fixed arrays can be used as members of user-defined data types. The following example shows a structure containing
fixed-length arrays:
Type Foo
rect(4) As Integer
colors(10) As Integer
End Type
Dynamic Arrays Dynamic arrays are declared without explicit dimensions, as shown below:
Public Ages() As Integer
Dynamic arrays can be resized at execution time using the Redim statement:
Redim Ages$(100)
Subsequent to their initial declaration, dynamic arrays can be redimensioned any number of times. When
redimensioning an array, the old array is first erased unless you use the Preserve keyword, as shown below:
Redim Preserve Ages$(100)
Querying Arrays The following table describes the functions used to retrieve information about arrays.
Use this to
function
LBound Retrieve the lower bound of an array. A runtime error is generated if the array has no dimensions.
UBound Retrieve the upper bound of an array. A runtime error is generated if the array has no dimensions.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 219
ArrayDims Retrieve the number of dimensions of an array. This function returns 0 if the array has no
dimensions
Operations on Arrays
The following table describes the function that operate on arrays:
Use this command to
ArraySort Sort an array of integers, longs, singles, doubles, currency, Booleans, dates, or variants.
ReadIniSection Fill an array with the item names from a section in an ini file.
ArraySort (statement)
Comments If a string array is specified, then the routine sorts alphabetically in ascending order using case-sensitive
string comparisons. If a numeric array is specified, the ArraySort statement sorts smaller numbers to the
lowest array index locations. The script generates a runtime error if you specify an array with more than
one dimension. When sorting an array of variants, the following rules apply:
String comparison is case-sensitive (this function is not affected by the Option Compare setting).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 220
Example This example dimensions an array and fills it with filenames using FileList, then sorts the array and
displays it in a select box.
Sub Main()
Dim f$()
FileList f$,"c:\*.*"
ArraySort f$
r% = SelectBox("Files","Choose one:",f$)
End Sub
See Also ArrayDims (page 217) (function); LBound (page 387) (function); UBound (page 510) (function)
Description Returns an Integer containing the numeric code for the first character of string.
Comments This function returns the character value of the first character of string. On single-byte systems, this
function returns a number between 0 and 255, whereas on MBCS systems, this function returns a
number between -32768 and 32767. On wide platforms, this function returns the MBCS character code
after converting the wide character to MBCS. To return the value of the first byte of a string, use the AscB
function. This function is used when you need the value of the first byte of a string known to contain byte
data rather than character data. On single-byte systems, the AscB function is identical to the Asc function.
On platforms where BasicScript uses wide string internally (such as Win32), the AscW function returns
the character value native to that platform. For example, on Win32 platforms, this function returns the
UNICODE character code. On single-byte and MBCS platforms, the AscW function is equivalent to the Asc
function. The following table summarizes the values returned by these functions:
Example This example fills an array with the ASCII values of the string s components and displays the result.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
s$ = InputBox("Please enter a string.","Enter String")
If s$ = "" Then End 'Exit if no string entered.
msg1 = ""
For i = 1 To Len(s$)
msg1 = msg1 & Asc(Mid(s$,i,1)) & crlf
Next i
MsgBox "The Asc values of the string are:" & msg1
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 221
Description Displays a dialog box requesting input from the user and returns that input as a String .
Parameter Description
prompt$ String containing the text to be displayed above the text box. The dialog box is sized to the
appropriate width depending on the width of prompt$. A runtime error is generated if prompt
$ is Null.
default$ String containing the initial content of the text box. The user can return the default by
immediately selecting OK. A runtime error is generated if default$ is Null.
title$ String specifying the title of the dialog. If missing, then the default title is used.
helpfile Name of the file containing context-sensitive help for this dialog. If this parameter is
specified, then context must also be specified.
context Number specifying the ID of the topic within helpfile for this dialog's help. If this parameter is
specified, then helpfile must also be specified.
Function Returns
AskBox$ String containing the input typed by the user in the text box. A zero-length string is returned
if the user selects Cancel.
AskBox String variant containing the input typed by the user in the text box. An Empty variant is
returned if the user selects Cancel.
When the dialog box is displayed, the text box has the focus. The user can type a maximum of 255
characters into the text box displayed by AskBox$. If both the helpfile and context parameters are
specified, then a Help button is added in addition to the OK and Cancel buttons. Context-sensitive help
can be invoked by selecting this button or using the help key (F1). Invoking help does not remove the
dialog.
Example This example asks the user to enter a filename and then displays what he or she has typed.
Sub Main()
s$ = AskBox$("Type in the filename:")
MsgBox "The filename was: " & s$
End Sub
See Also MsgBox (page 409) (statement); AskPassword$ (function); InputBox, InputBox$ (page 374)
(functions); OpenFilename$ (page 429) (function); SaveFilename$ (page 467) (function); SelectBox
(page 473) (function).
Note The text in the dialog box is displayed in 8-point MS Sans Serif.
Description Returns a String containing the text that the user typed.
Comments Unlike the AskBox/AskBox$ functions, the user sees asterisks in place of the characters that are actually
typed. This allows the hidden input of passwords. The AskPassword/AskPassword$ functions take the
following parameters:
Parameter Description
prompt$ String containing the text to be displayed above the text box. The dialog box is sized to
the appropriate width depending on the width of prompt$. A runtime error is generated if
prompt$ is Null.
title$ String specifying the title of the dialog. If missing, then the default title is used.
helpfile Name of the file containing context-sensitive help for this dialog. If this parameter is
specified, then context must also be specified.
context Number specifying the ID of the topic within helpfile for this dialog's help. If this parameter
is specified, then helpfile must also be specified.
When the dialog box is first displayed, the text box has the focus. A maximum of 255 characters can be
typed into the text box.
Function Returns
AskPassword text typed into the text box, up to a maximum of 255 characters. A zero-length string is
$ returned if the user selects Cancel.
AskPassword String variant. An Empty variant is returned if the user selects Cancel.
If both the helpfile and context parameters are specified, then a Help button is added in addition to the OK
and Cancel buttons. Context-sensitive help can be invoked by selecting this button or using the help key
(F1 on most platforms). Invoking help does not remove the dialog.
Example
Sub Main()
s$ = AskPassword$("Type in the password:")
MsgBox "The password entered is: " & s$
End Sub
See Also MsgBox (page 409) (statement); AskBox$ (page 221) (function); InputBox, InputBox$ (page 374)
(functions); OpenFilename$ (page 429) (function); SaveFilename$ (page 467) (function); SelectBox
(page 473) (function); AnswerBox (page 205) (function).
Notes The text in the dialog box is displayed in 8-point MS Sans Serif.
Atn (function)
Example This example finds the angle whose tangent is 1 (45 degrees) and displays the result.
Sub Main()
a# = Atn(1.00)
MsgBox "1.00 is the tangent of " & a# & " radians (45 degrees)."
End Sub
See Also Tan (page 501) (function); Sin (page 479) (function); Cos (page 257) (function).
Basic.Architecture$ (property)
Basic.Capability (method)
Basic.CodePage (property)
Basic.Eoln$ (property)
Basic.FreeMemory (property)
Basic.HomeDir$ (property)
Basic.Locale$ (property)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 224
Basic.OperatingSystem$ (Property)
Basic.OperatingSystemVendor$
Basic.OperatingSystemVersion$
Basic.OS (property)
Basic.Pathseparator$ (property)
Basic.Processor$ (Property)
Basic.ProcessorCount$ (property)
Basic.Version$ (property)
Beep (statement)
ByRef (keyword)
ByVal (keyword)
Basic.Architecture$ (property)
Syntax Basic.Architecture$
Description Returns a String containing the CPU architecture on which BasicScript is executing.
Example
'
'Print the CPU architecture...
'
Sub Main()
MsgBox Basic.Architecture
$
End Sub
Basic.Capability (method)
Syntax Basic.Capability(which)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 225
Description Returns True if the specified capability exists on the current platform; returns False otherwise.
Comments The which parameter is an Integer specifying the capability for which to test. It can be any of the
following values:
1 Disk drives
Example This example tests to see whether your current platform supports disk drives and hidden file attributes and
displays the result.
Sub Main()
msg1 = "This operating system "
If Basic.Capability(1) Then
msg1 = msg1 & "supports disk drives."
Else
msg1 = msg1 & "does not support disk drives."
End If
MsgBox msg1
End Sub
Basic.CodePage (property)
Syntax Basic.CodePage
Description Returns an Integer representing the code page for the current locale.
Comments Basic.CodePage returns ANSI code page for the current locale, such as 437 for MS-DOS Latin US or 932
for Japanese.
Example
Sub Main
If Basic.OS = ebWin16 And Basic.CodePage = 437 Then
MsgBox "Running US Windows"
Else if Basic.OS = ebWin32 And Basic.CodePage = 932 Then
MsgBox "Japanese XP"
End If
End Sub
See Also Basic.Locale$ (page 227) (property); Basic.OS (page 229) (property)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 226
Basic.Eoln$ (property)
Syntax Basic.Eoln$
Description Returns a String containing the end-of-line character sequence appropriate to the current platform.
Comments This string will be either a carriage return, a carriage return/line feed, or a line feed.
Basic.FreeMemory (property)
Syntax Basic.FreeMemory
Description Returns a Long representing the number of bytes of free memory in the script's data space.
Comments This function returns the size of the largest free block in the script's data space. Before this number is
returned, the data space is compacted, consolidating free space into a single contiguous free block. The
script's data space contains strings and dynamic arrays.
See Also System.TotalMemory (page 499) (property); System.FreeMemory (page 498) (property);
System.FreeResources (page 498) (property); Basic.FreeMemory (page 226) (property).
Basic.HomeDir$ (property)
Syntax Basic.HomeDir$
Description Returns the path to the basic script runtime engine components, e.g. c:\Program Files\Proficy\Proficy
CIMPLICITY\exe.
Comments This method is used to find the HMI/SCADA CIMPLICITY exe directory.
Example This example assigns the home directory to HD and displays it.
Sub Main()
hd$ = Basic.HomeDir$
MsgBox "The Basic Control Engine home directory is: " & hd$
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 227
Basic.Locale$ (property)
Syntax Basic.Locale$
Description Returns a String containing the locale under which BasicScript is running.
Comments The locale helps you identify information about your environment, such as the date formats, time
format, and other country-sensitive information. The following table describes the returned value from
Basic.Locale$ on the Win32 platform.
abbrevlang,langid,nativelang,englang
abbrevlang Three-letter name of the language. This name is formed by taking the two-letter language
abbreviation as found in the ISO Standard 639 and adding a third letter, as appropriate, to
indicate the sublanguage.
englang: Full English name of the language as defined by ISO standard 639.
Example
'This example checks to see if we are running in a Japanese
'version of Windows.
Sub Main
If Basic.OS = ebWin16 And Item$(Basic.Locale$,1) = "jpn" Then
MsgBox "Running Windows on a Japanese computer."
End If
End Sub
See Also Basic.OS (page 229) (property) , Basic.CodePage (page 225) (property)
Basic.OperatingSystem$ (property)
Syntax Basic.OperatingSystem$
Comments The value returned by this function for the Win32 operating systems is Win32s.
Example
'This script checks the Windows version for special networking
’capabilities.
'
Sub Main()
If Basic.OS = ebWin16 Then
If Basic.OperatingSystem$ = "Windows" Then
MsgBox "Special networking capabilities aren’t present."
ElseIf Basic.OperatingSystem$ = "Windows for Workgroups" Then
MsgBox "Network capabilities are present."
End If
End Sub
Basic.OperatingSystemVendor$ (property)
Syntax Basic.OperatingSystemVendor$
Description Returns a String containing the version of the operating system under which BasicScript is running.
Example
'
'The following example prints the operating system vendor
'
Sub Main
MsgBox "The manufacturer of the operating system is: " & _
Basic.OperatingSystemVendor$
End Sub
Basic.OperatingSystemVersion$ (property)
Syntax Basic.OperatingSystemVersion$
Description Returns a String containing the version of the operating system under which BasicScript is running.
Comments The version number is returned in the following format: major.minor.buildnumber The parts of the
version number are as follows.
Example
'
'This example checks the Windows version to ensure that a
'feature is supported.
'
Sub Main
If Basic.OperatingSystem$ = "Windows"
If Basic.OperatingSystemVersion$ <= 2000 Then
MsgBox "That feature is not supported."
Else
MsgBox "Windows version 2000 or greater"
End If
End If
End Sub
Basic.OS (property)
Syntax Basic.OS
The value returned is not necessarily the platform under which the Basic Control Language script is
running but rather an indicator of the platform for which the script was created.
Example This example determines the operating system for which this version was created and displays the
appropriate message.
Sub Main()
Select Case Basic.OS
Case ebWin32
s = "Windows XP"
Case Else
s = "not Wndows XP"
End Select
MsgBox "You are currently running " & s
End Sub
Basic.PathSeparator$ (property)
Syntax Basic.PathSeparator$
Description Returns a String containing the path separator appropriate for the current platform.
Comments The returned string is any one of the following characters: / (slash), \ (back slash), : (colon)
Example
Sub Main()
MsgBox "The path separator for this platform is: " & Basic.PathSeparator$
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 230
Basic.Processor$ (property)
Syntax Basic.Processor$
Description Returns a String containing the name of the CPU in the computer on which BasicScript is running.
PowerPC 601
603
604
603+
604+
620
Example
'
'This example prints the CPU of the computer on which
'BasicScript is executing.
'
Sub Main()
MsgBox "Processor = " & Basic.Processor
$
End Sub
Note You can retrieve the number of processors within the computer using the Basic.ProcessorCount
property.
Basic.ProcessorCount$ (property)
Syntax Basic.ProcessorCount
Description Returns the number of CPUs installed on the computer on which BasicScript is running.
Comments Basic.ProcessorCount$ returns 1 if the CPU has only one processor or is otherwise incapable of
containing more than one processor.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 231
Example
'
'Print the number of processors in the computer.
'
Sub Main()
MsgBox "There are " & Basic.ProcessorCount & _
" processor(s) in the computer."
End Sub
Basic.Version$ (Property)
Syntax Basic.Version$
Comments This function returns the major and minor version numbers in the format major.minor.BuildNumber, as in
"2.00.30."
Example This example displays the current version of the Basic Control Engine.
Sub Main()
MsgBox "Version " & Basic.Version$ & " of Basic Control Engine is running"
End Sub
Beep (statement)
Syntax Beep
Example This example causes the system to beep five times and displays a reminder message.
Sub Main()
For i = 1 To 5
Beep
Sleep 200
Next i
MsgBox "You have an upcoming appointment!"
End Sub
Syntax Begin Dialog DialogName [x],[y],width,height,title$ [,[.DlgProc] [,[PicName$] [,style]]] Dialog Statements
End Dialog
Description Defines a dialog box template for use with the Dialog statement and function.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 232
Comments A dialog box template is constructed by placing any of the following statements between the Begin Dialog
and End Dialog statements (no other statements besides comments can appear within a dialog box
template):
PushButton OKButton
Parameter Description
x, y Integer coordinates specifying the position of the upper left corner of the dialog box
static to the parent window. These coordinates are in dialog units. If either coordinate is
unspecified, then the dialog box will be centered in that direction on the parent window.
width, height Integer coordinates specifying the width and height of the dialog box (in dialog units).
DialogName Name of the dialog box template. Once a dialog box template has been created, a variable
can be dimensioned using this name.
title$ String containing the name to appear in the title bar of the dialog box. If this parameter
specifies a zero-length string, then the name "Basic Control Engine" is used.
.DlgProc Name of the dialog function. The routine specified by .DlgProc will be called by the script
when certain actions occur during processing of the dialog box. (See DlgProc [prototype]
for additional information about dialog functions.) If this omitted, then the script processes
the dialog box using the default dialog box processing behavior.
style Specifies extra styles for the dialog. It can be any of the following values:
Value Meaning
2 (or omitted) Dialog contains both the title and close box.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 233
The script generates an error if the dialog box template contains no controls. A dialog box template must
have at least one PushButton , OKButton , or CancelButton statement. Otherwise, there will be no
way to close the dialog box. Dialog units are defined as ¼ the width of the font in the horizontal direction
and 1/8 the height of the font in the vertical direction. Any number of user dialog boxes can be created,
but each one must be created using a different name as the DialogName. Only one user dialog box
may be invoked at any time. Expression Evaluation within the Dialog Box Template The Begin Dialog
statement creates the template for the dialog box. Any expression or variable name that appears within
any of the statements in the dialog box template is not evaluated until a variable is dimensioned of type
DialogName. The following example shows this behavior:
Sub Main()
MyTitle$ = "Hello, World"
Begin Dialog MyTemplate 16,32,116,64,MyTitle$
OKButton 12,40,40,14
End Dialog
MyTitle$ = "Sample Dialog"
Dim dummy As MyTemplate
rc% = Dialog(dummy)
End Sub
The above example creates a dialog box with the title " Sample Dialog ". Expressions within dialog box
templates cannot reference external subroutines or functions. All controls within a dialog box use the
same font. The fonts used for text and text box control can be changed explicitly by setting the font
parameters in the Text and TextBox statements. A maximum of 128 fonts can be used within a single
dialog, although the practical limitation may be less.
See Also CancelButton (page 243) (statement); CheckBox (page 240) (statement); ComboBox (page 249)
(statement); Dialog (page 278) (function); Dialog (page 279) (statement); DropListBox (page
301) (statement); End Dialog (page 322) (statement); GroupBox (page 361) (statement); ListBox
(page 394) (statement); OKButton (page 426) (statement); OptionButton (page 434) (statement);
OptionGroup (page 435) (statement); Picture (statement; PushButton (page 447) (statement); Text
(page 502) (statement); TextBox (page 503) (statement); DlgProc (page 289) (function).
Note Within user dialog boxes, the default font is 8-point MS Sans Serif.
Syntax Boolean
Description A data type capable of representing the logical values TRUE and FALSE .
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 234
Comments Boolean variables are used to hold a binary value—either TRUE or FALSE. Variables can be declared
as Boolean using the Dim , Public , or Private statement. Variants can hold Boolean values when
assigned the results of comparisons or the constants TRUE or FALSE. Internally, a Boolean variable
is a 2-byte value holding –1 (for TRUE) or 0 (for FALSE). Any type of data can be assigned to Boolean
variables. When assigning, non-0 values are converted to TRUE , and 0 values are converted to FALSE.
When appearing as a structure member, Boolean members require 2 bytes of storage. When used
within binary or random files, 2 bytes of storage are required. When passed to external routines, Boolean
values are sign-extended to the size of an integer on that platform (either 16 or 32 bits) before pushing
onto the stack. There is no type-declaration character for Boolean variables.
Boolean variables that have not yet been assigned are given an initial value of False .
See Also Currency (page 259) (data type); Date (page 263) (data type); Double (page 300) (data type);
Integer (page 377) (data type); Long (page 398) (data type); Object (page 422) (data type); Single
(page 479) (data type); String (page 494) (data type); Variant (page 515) (data type); DefType (page
276) (statement); CBool (page 237) (function); True (page 507) (constant); False (page 338)
(constant).
ByRef (keyword)
Description Used within the Sub...End Sub, Function...End Function, or Declare statement to specify that a given
parameter can be modified by the called routine.
Comments Passing a parameter by reference means that the caller can modify that variable's value. Unlike the
ByVal keyword, the ByRef keyword cannot be used when passing a parameter. The absence of the ByVal
keyword is sufficient to force a parameter to be passed by reference:
MySub ByVal I '<-- Pass i by value.
MySub ByRef i '<-- Illegal (will not compile).
MySub i '<-- Pass i by reference.
Example
Sub Test(ByRef a As Variant)
a = 14
End Sub
Sub Main()
b = 12
Test b
MsgBox "The ByRef value is: " & b ' <-- Displays 14.
End Sub
ByVal (keyword)
Comments The ByVal keyword can appear before any parameter passed to any function, statement, or method to
force that parameter to be passed by value. Passing a parameter by value means that the caller cannot
modify that variable's value. Enclosing a variable within parentheses has the same effect as the ByVal
keyword:
Foo ByVal i 'Forces i to be passed by value.
Foo(i) 'Forces i to be passed by value.
When calling external statements and functions (that is, routines defined using the Declare statement), the
ByVal keyword forces the parameter to be passed by value regardless of the declaration of that parameter
in the Declare statement. The following example shows the effect of the ByVal keyword used to passed an
Integer to an external routine:
Declare Sub Foo Lib "MyLib" (ByRef i As Integer)
i% = 6
Foo ByVal i% 'Pass a 2-byte Integer.
Foo i% 'Pass a 4-byte pointer to an Integer.
Since the Foo routine expects to receive a pointer to an Integer , the first call to Foo will have
unpredictable results.
Call (statement)
CancelButton (statement)
CBool (function)
CCur (function)
CDbl (function)
ChDir (statement)
ChDrive (statement)
CheckBox (statement)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 236
Choose (function)
Clnt (function)
Clipboard$ (function)
Clipboard$ (statement)
Clipboard.Clear (method)
Clipboard.GetFormat (method)
Clipboard.GetText (method)
Clipboard.SetText (method)
CLng (function)
Close (statement)
ComboBox (statement)
Comments (topic)
Const (statement)
Constants (topic)
Cos (function)
CreateObject (function)
CSng (function)
CStr (function)
CVar (function)
CVErr (function)
Call (statement)
Description Transfers control to the given subroutine, optionally passing the specified arguments.
Comments Using this statement is equivalent to: subroutine_name [arguments] Use of the Call statement is
optional. The Call statement can only be used to execute subroutines; functions cannot be executed with
this statement. The subroutine to which control is transferred by the Call statement must be declared
outside of the Main procedure, as shown in the following example.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 237
Example This example demonstrates the use of the Call statement to pass control to another function.
Sub Example_Call(s$)
'This subroutine is declared externally to Main and displays the text
'passed in the parameter s$.
MsgBox "Call: " & s$
End Sub
Sub Main()
'This example assigns a string variable to display, then calls subroutine
'Example_Call, passing parameter S$ to be displayed in a message box
'within the subroutine.
s$ = "DAVE"
Example_Call s$
Call Example_Call("SUSAN")
End Sub
See Also Goto (page 361) (statement); GoSub (page 360) (statement); Declare (page 276) (statement).
CDbl (function)
Syntax CDbl(expression)
Comments This function accepts any expression convertible to a Double , including strings. A runtime error is
generated if expression is Null . Empty is treated as 0.0 . When passed a numeric expression, this
function has the same effect as assigning the numeric expression number to a Double . When used with
variants, this function guarantees that the variant will be assigned a Double ( VarType 5 ).
See Also CCur (page 238) (function); CBool (page 237) (function); CDate, CVDate (page 238) (functions);
CInt (page 243) (function); CLng (page 248) (function); CSng (page 258) (function); CStr (page
258) (function); CVar (page 259) (function); CVErr (page 260) (function); Double (page 300) (data
type).
CBool (function)
Comments The expression parameter is any expression that can be converted to a Boolean . A runtime error is
generated if expression is Null . All numeric data types are convertible to Boolean . If expression is
zero, then the CBool returns False ; otherwise, CBool returns True . Empty is treated as False . If
expression is a String , then CBool first attempts to convert it to a number, then converts the number to
a Boolean . A runtime error is generated if expression cannot be converted to a number. A runtime error
is generated if expression cannot be converted to a Boolean .
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 238
Example This example uses CBool to determine whether a string is numeric or just plain text.
Sub Main()
Dim IsNumericOrDate As Boolean
s$ = 34224.54
IsNumeric = CBool(IsNumeric(s$))
If IsNumeric = True Then
MsgBox s$ & " is either a valid number!"
Else
MsgBox s$ & " is not a valid number!"
End If
End Sub
See Also CCur (page 238) (function); CDate, CVDate (page 238) (functions); CDbl (page 237) (function); CInt
(page 243) (function); CLng (page 248) (function); CSng (page 258) (function); CStr (page 258)
(function); CVar (page 259) (function); CVErr (page 260) (function); Boolean (page 233) (data type).
CCur (function)
Comments This function accepts any expression convertible to a Currency , including strings. A runtime error is
generated if expression is Null or a String not convertible to a number. Empty is treated as 0. When
passed a numeric expression, this function has the same effect as assigning the numeric expression
number to a Currency . When used with variants, this function guarantees that the variant will be
assigned a Currency ( VarType 6).
Example This example displays the value of a String converted into a Currency value.
Sub Main()
i$ = "100.44"
MsgBox "The currency value is: " & CCur(i$)
End Sub
See Also CBool (page 237) (function); CDate, CVDate (page 238) (functions); CDbl (page 237) (function);
CInt (page 243) (function); CLng (page 248) (function); CSng (page 258) (function); CStr (page
258) (function); CVar (page 259) (function); CVErr (page 260) (function); Currency (page 259)
(data type).
Comments The expression parameter is any expression that can be converted to a Date . A runtime error is
generated if expression is Null . If expression is a String , an attempt is made to convert it to a Date
using the current country settings. If expression does not represent a valid date, then an attempt is made
to convert expression to a number. A runtime error is generated if expression cannot be represented as
a date. These functions are sensitive to the date and time formats of your computer. The CDate and
CVDate functions are identical.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 239
Example This example takes two dates and computes the difference between them.
Sub Main()
Dim date1 As Date
Dim date2 As Date
Dim diff As Date
date1 = CDate(#1/1/1994#)
date2 = CDate("February 1, 1994")
diff = DateDiff("d",date1,date2)
MsgBox "The date difference is " & CInt(diff) & " days."
End Sub
See Also CCur (page 238) (function); CBool (page 237) (function); CDbl (page 237) (function); CInt (page
243) (function); CLng (page 248) (function); CSng (page 258) (function); CStr (page 258)
(function); CVar (page 259) (function); CVErr (page 260) (function); Date (page 263) (data type).
ChDir (statement)
Description Changes the current directory of the specified drive to newdir$. This routine will not change the current
drive. (See ChDrive [statement].)
Example This example saves the current directory, then changes to the root directory, displays the old and new
directories, restores the old directory, and displays it.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
save$ = CurDir$
ChDir(Basic.PathSeparator$)
MsgBox "Old directory: " & save$ & crlf & "New directory: " & CurDir$
ChDir(save$)
MsgBox "Directory restored to: " & CurDir$
End Sub
See Also ChDrive (page 239) (statement); CurDir, CurDir$ (page 259) (functions); Dir, Dir$ (page 280)
(functions); MkDir (page 405) (statement); RmDir (page 463) (statement).
ChDrive (statement)
Comments Only the first character of DriveLetter$ is used. DriveLetter$ is not case-sensitive. If DriveLetter$ is empty,
then the current drive is not changed.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 240
Example This example allows the user to select a new current drive and uses ChDrive to make their choice the new
current drive.
Const crlf$ = Chr$(13) + Chr$(10)
Sub Main()
Dim d()
old$ = FileParse$(CurDir,1)
DiskDrives d
Again:
r = SelectBox("Available Drives","Select new current drive:",d)
On Error Goto Error_Trap
If r <> -1 Then ChDrive d®
MsgBox "Old Current Drive: " & old$ & crlf & "New Current Drive: " & CurDir
End
Error_Trap:
MsgBox Error(err)
Resume Again
End Sub
See Also ChDir (page 239) (statement); CurDir, CurDir$ (page 259) (functions); Dir, Dir$ (page 280)
(functions); MkDir (page 405) (statement); RmDir (page 463) (statement); DiskDrives (page 281)
(statement).
CheckBox (statement)
Comments Check box controls are either on or off, depending on the value of .Identifier. This statement can only
appear within a dialog box template (i.e., between the Begin Dialog and End Dialog statements). The
CheckBox statement requires the following parameters:
Parameter Description
X, Y Integer coordinates specifying the position of the control (in dialog units) static to the upper
left corner of the dialog box.
Width, Integer coordinates specifying the dimensions of the control in dialog units.
height
Title$ String containing the text that appears within the check box. This text may contain an
ampersand character to denote an accelerator letter, such as "&Font" for Font (indicating
that the Font control may be selected by pressing the F accelerator key).
Identifier Name by which this control can be referenced by statements in a dialog function (such as
DlgFocus and DlgEnable ). This parameter also creates an integer variable whose value
corresponds to the state of the check box (1 = checked; 0 = unchecked). This variable can
be accessed using the syntax: DialogVariable.Identifier.
When the dialog box is first created, the value referenced by .Identifier is used to set the initial state of the
check box. When the dialog box is dismissed, the final state of the check box is placed into this variable.
By default, the .Identifier variable contains 0, meaning that the check box is unchecked.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 241
Example This example displays a dialog box with two check boxes in different states.
Sub Main()
Begin Dialog SaveOptionsTemplate 36,32,151,52,"Save"
GroupBox 4,4,84,40,"GroupBox"
CheckBox 12,16,67,8,"Include heading",.IncludeHeading
CheckBox 12,28,73,8,"Expand keywords",.ExpandKeywords
OKButton 104,8,40,14,.OK
CancelButton 104,28,40,14,.Cancel
End Dialog
Dim SaveOptions As SaveOptionsTemplate
SaveOptions.IncludeHeading = 1 'Check box initially on.
SaveOptions.ExpandKeywords = 0 'Check box initially off.
r% = Dialog(SaveOptions)
If r% = -1 Then
MsgBox "OK was pressed."
End If
End Sub
See Also CancelButton (page 243) (statement); Dialog (page 278) (function); Dialog (page 279) (statement);
DropListBox (page 301) (statement); GroupBox (page 361) (statement); ListBox (page 394)
(statement); OKButton (page 426) (statement); OptionButton (page 434) (statement); OptionGroup
(page 435) (statement); Picture (page 438) (statement); PushButton (page 447) (statement); Text
(page 502) (statement); TextBox (page 503) (statement); Begin Dialog (page 231) (statement),
PictureButton (page 447) (statement).
Notes Accelerators are underlined, and the accelerator combination Alt+letter is used.
Choose (function)
Syntax Choose(index,expression1,expression2,...,expression13)
Comments The index parameter specifies which expression is to be returned. If index is 1, then expression1 is
returned; if index is 2, then expression2 is returned, and so on. If index is less than 1 or greater than the
number of supplied expressions, then Null is returned. The Choose function returns the expression
without converting its type. Each expression is evaluated before returning the selected one.
See Also Switch (page 496) (function); IIf (page 369) (function); If...Then...Else (page 368) (statement);
Select...Case (page 472) (statement).
Comments The Chr$, ChrB$, and ChrW$ functions return a String, whereas the Chr, ChrB, and ChrW functions return a
String variant. These functions behave differently depending on the string format used by BasicScript.
These differences are summarized in the following table:
ChrW[$] SBCS 0 and 255 1-byte character string (same as the Chr and Chr$
functions)
The Chr$ function can be used within constant declarations, as in the following example: Const crlf = Chr
$(13) + Chr$(10) Some common uses of this function are:
Chr$(9) Tab
Chr$(26) End-of-file
Chr$(0) Null
Example
Sub Main()
'Concatenates carriage return (13) and line feed (10) to
'CRLF$, then displays a multiple-line message using CRLF$
'to separate lines.
crlf$ = Chr$(13) + Chr$(10)
MsgBox "First line." & crlf$ & "Second line."
See Also Asc, AscB, AscW (page 220) (functions); Str, Str$ (page 492) (functions).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 243
CInt (function)
Syntax CInt(expression)
Comments This function accepts any expression convertible to an Integer , including strings. A runtime error is
generated if expression is Null . Empty is treated as 0 . The passed numeric expression must be within
the valid range for integers:
–32768 <= expression <= 32767
A runtime error results if the passed expression is not within the above range. When passed a numeric
expression, this function has the same effect as assigning a numeric expression to an Integer . Note that
integer variables are rounded before conversion. When used with variants, this function guarantees that
the expression is converted to an Integer variant ( VarType 2).
Example This example demonstrates the various results of integer manipulation with CInt.
Sub Main()
'(1) Assigns i# to 100.55 and displays its integer representation (101).
I# = 100.55
MsgBox "The value of CInt(i) = " & CInt(i#)
'(2) Sets j# to 100.22 and displays the CInt representation (100).
j# = 100.22
MsgBox "The value of CInt(j) = " & CInt(j#)
'(3) Assigns k% (integer) to the CInt sum of j# and k% and displays k% '(201).
k% = CInt(i# + j#)
MsgBox "The integer sum of 100.55 and 100.22 is: " & k%
'(4) Reassigns i# to 50.35 and recalculates k%, then displays the result
'(note rounding).
i# = 50.35
k% = CInt(i# + j#)
MsgBox "The integer sum of 50.35 and 100.22 is: " & k%
End Sub
See Also CCur (page 238) (function); CBool (page 237) (function); CDate, CVDate (page 238) (functions);
CDbl (page 237) (function); CLng (page 248) (function); CSng (page 258) (function); CStr (page
258) (function); CVar (page 259) (function); CVErr (page 260) (function); Integer (page 377) (data
type).
CancelButton (statement)
Description Defines a Cancel button that appears within a dialog box template.
Comments This statement can only appear within a dialog box template (i.e., between the Begin Dialog and End
Dialog statements). Selecting the Cancel button (or pressing Esc) dismisses the user dialog box, causing
the Dialog function to return 0 . (Note: A dialog function can redefine this behavior.) Pressing the Esc
key or double-clicking the close box will have no effect if a dialog box does not contain a CancelButton
statement. The CancelButton statement requires the following parameters:
Parameter Description
X, Y Integer coordinates specifying the position of the control (in dialog units) static to the upper
left corner of the dialog box.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 244
width, Integer coordinates specifying the dimensions of the control in dialog units.
height
Identifier Optional parameter specifying the name by which this control can be referenced by
statements in a dialog function (such as DlgFocus and DlgEnable ). If omitted, then the
word Cancel is used.
A dialog box must contain at least one OKButton, CancelButton, or PushButton statement; otherwise,
the dialog box cannot be dismissed.
Example This example creates a sample dialog box with OK and Cancel buttons.
Sub Main()
Begin Dialog QuitDialogTemplate 16,32,116,64,"Quit"
Text 4,8,108,8,"Are you sure you want to exit?"
CheckBox 32,24,63,8,"Save Changes",.SaveChanges
OKButton 12,40,40,14
CancelButton 60,40,40,14
End Dialog
Dim QuitDialog As QuitDialogTemplate
rc% = Dialog(QuitDialog)
Select Case rc%
Case -1
MsgBox "OK was pressed!"
Case 1
MsgBox "Cancel was pressed!"
End Select
End Sub
See Also CheckBox (page 240) (statement); ComboBox (page 249) (statement); Dialog (page 278) (function);
Dialog (page 279) (statement); DropListBox (page 301) (statement); GroupBox (page 361)
(statement); ListBox (page 394) (statement); OKButton (page 426) (statement); OptionButton (page
434) (statement); OptionGroup (page 435) (statement); Picture (page 438) (statement); PushButton
(page 447) (statement); Text (page 502) (statement); TextBox (page 503) (statement); Begin (page
231) Dialog (page 231) (statement), PictureButton (page 439) (statement).
Clipboard$ (function)
Syntax Clipboard$[()]
Comments If the Clipboard doesn't contain text or the Clipboard is empty, then a zero-length string is returned.
Example This example puts text on the Clipboard, displays it, clears the Clipboard, and displays the Clipboard
again.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
Clipboard$ "Hello out there!"
MsgBox "The text in the Clipboard is:" & crlf & Clipboard$
Clipboard.Clear
MsgBox "The text in the Clipboard is:" & crlf & Clipboard$
End Sub
See Also Clipboard$ (page 244) (statement); Clipboard.GetText (page 247) (method); Clipboard.SetText (page
247) (method).
Clipboard $ (statement)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 245
Example This example puts text on the Clipboard, displays it, clears the Clipboard, and displays the Clipboard
again.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
Clipboard$ "Hello out there!"
MsgBox "The text in the Clipboard is:" & crlf & Clipboard$
Clipboard.Clear
MsgBox "The text in the Clipboard is now:" & crlf & Clipboard$
End Sub
See Also Clipboard$ (page 244) (function); Clipboard.GetText (page 247) (method); Clipboard.SetText (page
247) (method).
Clipboard.Clear (method)
Syntax Clipboard.Clear
Example This example puts text on the Clipboard, displays it, clears the Clipboard, and displays the Clipboard
again.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
Clipboard$ "Hello out there!"
MsgBox "The text in the Clipboard before clearing:" & crlf & Clipboard$
Clipboard.Clear
MsgBox "The text in the Clipboard after clearing:" & crlf & Clipboard$
End Sub
CreateObject (function)
Description Creates an OLE automation object and returns a reference to that object.
Comments The class$ parameter specifies the application used to create the object and the type of object being
created. It uses the following syntax: "application.class", where application is the application used to
create the object and class is the type of the object to create. At runtime, CreateObject looks for the
given application and runs that application if found. Once the object is created, its properties and methods
can be accessed using the dot syntax (e.g., object.property = value). There may be a slight delay when
an automation server is loaded (this depends on the speed with which a server can be loaded from disk).
This delay is reduced if an instance of the automation server is already loaded.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 246
Examples This first example instantiates Microsoft Excel. It then uses the resulting object to make Excel visible and
then close Excel.
Sub Main()
Dim Excel As Object
On Error GoTo Trap1 'Set error trap.
Set Excel = CreateObject("excel.application"'Instantiate object.
Excel.Visible = True 'Make Excel visible.
Sleep 5000 'Wait 5 seconds.
Excel.Quit 'Close Excel.
Exit Sub 'Exit before error trap.
Trap1:
MsgBox "Can't create Excel object." 'Display error message.
Exit Sub 'Reset error handler.
End Sub
This second example uses CreateObject to instantiate a Visio object. It then uses the resulting object to
create a new document.
Sub Main()
Dim Visio As Object
Dim doc As Object
Dim page As Object
Dim shape As Object
On Error Goto NO_VISIO
Set Visio = CreateObject("visio.application")'Create Visio object.
On Error Goto 0
Set doc = Visio.Documents.Add("") 'Create a new document.
Set page = doc.Pages(1) 'Get first page.
Set shape = page.DrawRectangle(1,1,4,4) 'Create a new shape.
shape.text = "Hello, world." 'Set text within shape.
End
NO_VISIO:
MsgBox "'Visio' cannot be found!",ebExclamation
End Sub
See Also GetObject (page 358) (function); Object (page 422) (data type).
Clipboard.GetFormat (method)
Description Returns TRUE if data of the specified format is available in the Clipboard; returns FALSE otherwise.
Comments This method is used to determine whether the data in the Clipboard is of a particular format. The format
parameter is an Integer representing the format to be queried:
Format Description
1 Text
2 Bitmap
3 Metafile
9 Color palette
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 247
Example This example checks to see whether there is any text on the Clipboard, if so, it searches the text for a
string matching what the user entered.
Option Compare Text
Sub Main()
r$ = InputBox("Enter a word to search for:","Scan Clipboard")
If Clipboard.GetFormat(1) Then
If Instr(Clipboard.GetText(1),r) = 0 Then
MsgBox """" & r & """" & " was not found in the clipboard."
Else
MsgBox """" & r & """" & " is definitely in the clipboard."
End If
Else
MsgBox "The Clipboard does not contain any text."
End If
End Sub
See Also Clipboard$ (page 244) (function); Clipboard$ (page 244) (statement).
Example This example checks to see whether there is any text on the Clipboard, if so, it searches the text for a
string matching what the user entered.
Option Compare Text
Sub Main()
r$ = InputBox("Enter a word to search for:","Scan Clipboard")
If Clipboard.GetFormat(1) Then
If Instr(Clipboard.GetText(1),r) = 0 Then
MsgBox """" & r & """" & " was not found in the clipboard."
Else
MsgBox """" & r & """" & " is definitely in the clipboard."
End If
Else
MsgBox "The Clipboard does not contain any text."
End If
End Sub
See Also Clipboard$ (page 244) (statement); Clipboard$ (page 244) (function); Clipboard.SetText (page 247)
(method).
Comments The data$ parameter specifies the text to be copied to the Clipboard. The format parameter, if specified,
must be 1 .
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 248
Example This example gets the contents of the Clipboard and uppercases it.
Sub Main()
If Not Clipboard.GetFormat(1) Then Exit Sub
Clipboard.SetText UCase(Clipboard.GetText(1)),1
End Sub
See Also Clipboard$ (page 244) (statement); Clipboard.GetText (page 247) (method); Clipboard$ (page 244)
(function).
CLng (function)
Comments This function accepts any expression convertible to a Long , including strings. A runtime error is
generated if expression is Null . Empty is treated as 0 . The passed expression must be within the
following range:
–2147483648 <= expression <= 2147483647
A runtime error results if the passed expression is not within the above range. When passed a numeric
expression, this function has the same effect as assigning the numeric expression to a Long . Note that
long variables are rounded before conversion. When used with variants, this function guarantees that the
expression is converted to a Long variant ( VarType 3 ).
Example This example displays the results for various conversions of i and j (note rounding).
Sub Main()
I% = 100
j& = 123.666
MsgBox "The result of i * j is: " & CLng(i% * j&) 'Displays 12367.
MsgBox "The new variant type of i is: " & Vartype(CLng(i%))
End Sub
See Also CCur (page 238) (function); CBool (page 237) (function); CDate, CVDate (page 238) (functions);
CDbl (page 237) (function); CInt (page 243) (function); CSng (page 258) (function); CStr (page
258) (function); CVar (page 259) (function); CVErr (page 260) (function); Long (page 398) (data
type).
Close (statement)
Example This example opens four files and closes them in various combinations.
Sub Main()
Open "test1" For Output As #1
Open "test2" For Output As #2
Open "test3" For Random As #3
Open "test4" For Binary As #4
MsgBox "The next available file number is: " & FreeFile()
Close #1 'Closes file 1 only.
Close #2,#3 'Closes files 2 and 3.
Close 'Closes all remaining files(4).
MsgBox "The next available file number is: " & FreeFile()
End Sub
See Also Open (page 428) (statement); Reset (page 460) (statement); End
(page 322) (statement).
ComboBox (statement)
Description This statement defines a combo box within a dialog box template.
Comments When the dialog box is invoked, the combo box will be filled with the elements from the specified array
variable. This statement can only appear within a dialog box template (i.e., between the Begin Dialog
and End Dialog statements). The ComboBox statement requires the following parameters:
Parameter Description
X, Y Integer coordinates specifying the position of the control (in dialog units) static to the
upper left corner of the dialog box.
width, height Integer coordinates specifying the dimensions of the control in dialog units.
ArrayVariable Single-dimensioned array used to initialize the elements of the combo box. If this array
has no dimensions, then the combo box will be initialized with no elements. A runtime
error results if the specified array contains more than one dimension. ArrayVariable can
specify an array of any fundamental data type (structures are not allowed). Null and
Empty values are treated as zero-length strings.
Identifier Name by which this control can be referenced by statements in a dialog function (such
as DlgFocus and DlgEnable ). This parameter also creates a string variable whose
value corresponds to the content of the edit field of the combo box. This variable can be
accessed using the syntax: DialogVariable.Identifier
When the dialog box is invoked, the elements from ArrayVariable are placed into the combo box.
The .Identifier variable defines the initial content of the edit field of the combo box. When the dialog box is
dismissed, the .Identifier variable is updated to contain the current value of the edit field.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 250
Example This example creates a dialog box that allows the user to select a day of the week.
Sub Main()
Dim days$(6)
days$(0) = "Monday"
days$(1) = "Tuesday"
days$(2) = "Wednesday"
days$(3) = "Thursday"
days$(4) = "Friday"
days$(5) = "Saturday"
days$(6) = "Sunday"
See Also CancelButton (page 243) (statement); CheckBox (page 240) (statement); Dialog (page 278)
(function); Dialog (page 279) (statement); DropListBox (page 301) (statement); GroupBox (page
361) (statement); ListBox (page 394) (statement); OKButton (page 426) (statement); OptionButton
(page 434) (statement); OptionGroup (page 435) (statement); Picture (page 438) (statement);
PushButton (page 447) (statement); Text (page 502) (statement); TextBox (page 503) (statement);
Begin (page 231) Dialog (page 231) (statement), PictureButton (page 439) (statement).
Syntax Command[$][()]
Description Returns the argument from the command line used to start the application.
Example This example checks to see if any command line parameters were used. If parameters were used they
are displayed and a check is made to see if the user used the "/s" switch.
Sub Main()
cmd$ = Command
If cmd$ <> "" Then
If (InStr(cmd$,"/s")) <> 0 Then
MsgBox "Safety Mode On!"
Else
MsgBox "Safety Mode Off!"
End If
MsgBox "The command line startup options were: " & cmd$
Else
MsgBox "No command line startup options were used!"
End If
End Sub
This operator behaves differently depending on the types of the expressions, as shown in the following
table:
String Comparisons If the two expressions are strings, then the operator performs a text comparison
between the two string expressions, returning True if expression1 is less than expression2. The
text comparison is case-sensitive if Option Compare is Binary; otherwise, the comparison is case-
insensitive. When comparing letters with regard to case, lowercase characters in a string sort greater than
uppercase characters, so a comparison of "a" and "A" would indicate that "a" is greater than "A". Numeric
Comparisons When comparing two numeric expressions, the less precise expression is converted to
be the same type as the more precise expression. Dates are compared as doubles. This may produce
unexpected results as it is possible to have two dates that, when viewed as text, display as the same date
when, in fact, they are different. This can be seen in the following example:
Sub Main()
Dim date1 As Date
Dim date2 As Date
date1 = Now
date2 = date1 + 0.000001 'Adds a fraction of a second.
MsgBox date2 = date1 'Prints False (the dates are different).
MsgBox date1 & "," & date2 'Prints two dates that are the same.
End Sub
Variant Comparisons When comparing variants, the actual operation performed is determined at
execution time according to the following table:
Example
Sub Main()
'Tests two literals and displays the result.
If 5 < 2 Then
MsgBox "5 is less than 2."
Else
MsgBox "5 is not less than 2."
End If
'Tests two strings and displays the result.
If "This" < "That" Then
MsgBox "'This' is less than 'That'."
Else
MsgBox "'That' is less than 'This'."
End If
End Sub
See Also Operator Precedence (page 431) (topic); Is (page 379) (operator); Like (page 391) (operator);
Option Compare (page 432) (statement).
Const (statement)
Comments The name is only valid within the current Basic Control Engine script. Constant names must follow these
rules: 1. Must begin with a letter. 2. May contain only letters, digits, and the underscore character.
3. Must not exceed 80 characters in length. 4. Cannot be a reserved word. Constant names are not
case-sensitive.
The expression must be assembled from literals or other constants. Calls to functions are not allowed
except calls to the Chr$ function, as shown below:
Const s$ = "Hello, there" + Chr(44)
Constants can be given an explicit type by declaring the name with a type-declaration character, as
shown below:
Const a% = 5 'Constant Integer whose value is 5
Const b# = 5 'Constant Double whose value is 5.0
Const c$ = "5" 'Constant String whose value is "5"
Const d! = 5 'Constant Single whose value is 5.0
Const e& = 5 'Constant Long whose value is 5
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 253
If an explicit type is not given, then the Basic Control Engine script will choose the most imprecise type
that completely represents the data, as shown below:
Const a = 5 'Integer constant
Const b = 5.5 'Single constant
Const c = 5.5E200 'Double constant
Constants defined within a Sub or Function are local to that subroutine or function. Constants defined
outside of all subroutines and function can be used anywhere within that script. The following example
demonstrates the scoping of constants:
Const DefFile = "default.txt"
Sub Test1
Const DefFile = "foobar.txt"
MsgBox DefFile 'Displays "foobar.txt".
End Sub
Sub Test2
MsgBox DefFile 'Displays "default.txt".
End Sub
Example This example displays the declared constants in a dialog box (crlf produces a new line in the dialog box).
Const crlf = Chr$(13) + Chr$(10)
Const greeting As String = "Hello, "
Const question1 As String = "How are you today?"
Sub Main()
r = InputBox("Please enter your name","Enter Name")
MsgBox greeting & r & crlf & crlf & question1
End Sub
See Also DefType (page 276) (statement); Let (page 390) (statement); = (statement); Constants (page 253)
(topic).
Constants (topic)
Constants are variables that cannot change value during script execution. The following constants are
predefined by the Basic Control Engine:
Constant Value Description
Nothing 0 Value indicating that an object variable no longer references a valid object.
Null Null Variant of type 1, indicating that the variant contains no data.
ebCFText 1 Text.
ebCFBitmap 2 Bitmap
ebCFMetafile 3 Metafile.
ebCFPalette 9 Palette
ebSunday 1 Sunday.
ebMonday 2 Monday
ebTuesday 3 Tuesday
ebWednesday 4 Wednesday.
ebThursday 5 Thursday
ebFriday 6 Friday
ebSaturday 7 Saturday.
ebFirstFourDays 2 Start with first week with at least four days in the new year.
ebDirectory 16 Subdirectory
ebIMEOn 1 IME on
ebApplicationModal 0 The current application is suspended until the dialog box is closed.
ebSystemModal 4096 All applications are suspended until the dialog box is closed.
ebNormalFocus 1 Application is displayed at the default position and has the focus.
ebNormalNoFocus 4 Application is displayed at the default position and does not have the focus.
ebArray 8192 Added to any of the other types to indicate an array of that type.
ebNullString 0 Special string value used to pass null pointers to external routines.
Constant Value
Empty Empty
False False
Null Null
True True
You can define your own constants using the Const statement. Preprocessor constants are defined using #Const.
Cos (function)
Example This example assigns the cosine of pi/4 radians (45 degrees) to C# and displays its value.
Sub Main()
c# = Cos(3.14159 / 4)
MsgBox "The cosine of 45 degrees is: " & c#
End Sub
See Also Tan (page 501) (function); Sin (page 479) (function); Atn (page 223) (function).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 258
CSng (function)
Comments This function accepts any expression convertible to a Single , including strings. A runtime error is
generated if expression is Null . Empty is treated as 0.0 . A runtime error results if the passed
expression is not within the valid range for Single . When passed a numeric expression, this function has
the same effect as assigning the numeric expression to a Single . When used with variants, this function
guarantees that the expression is converted to a Single variant ( VarType 4 ).
See Also CCur (page 238) (function); CBool (page 237) (function); CDate, CVDate (page 238) (functions);
CDbl (page 237) (function); CInt (page 243) (function); CLng (page 248) (function); CStr (page
258) (function); CVar (page 259) (function); CVErr (page 260) (function); Single (page 479) (data
type).
CStr (function)
Comments Unlike Str$ or Str , the string returned by CStr will not contain a leading space if the expression is
positive. Further, the CStr function correctly recognizes thousands and decimal separators for your
locale. Different data types are converted to String in accordance with the following rules:
Any numeric type A string containing the number without the leading space for positive values.
See Also CCur (page 238) (function); CBool (page 237) (function); CDate, CVDate (page 238) (functions);
CDbl (page 237) (function); CInt (page 243) (function); CLng (page 248) (function); CSng (page
258) (function); CVar (page 259) (function); CVErr (page 260) (function); String (page 494) (data
type); Str, Str$ (page 492) (functions).
Description Returns the current directory on the specified drive. If no drive$ is specified or drive$ is zero-length, then
the current directory on the current drive is returned.
Comments CurDir$ returns a String , whereas CurDir returns a String variant. The script generates a runtime
error if drive$ is invalid.
Example This example saves the current directory, changes to the next higher directory, and displays the change;
then restores the original directory and displays the change. Note: The dot designators will not work with
all platforms.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
save$ = CurDir
ChDir ("..")
MsgBox "Old directory: " & save$ & crlf & "New directory: " & CurDir
ChDir (save$)
MsgBox "Directory restored to: " & CurDir
End Sub
See Also ChDir (page 239) (statement); ChDrive (page 239) (statement); Dir, Dir$ (page 280) (functions);
MkDir (page 405) (statement); RmDir (page 463) (statement).
Syntax Currency
Description A data type used to declare variables capable of holding fixed-point numbers with 15 digits to the left of
the decimal point and 4 digits to the right.
Comments Currency variables are used to hold numbers within the following range:
–922,337,203,685,477.5808 <= currency <= 922,337,203,685,477.5807
Due to their accuracy, Currency variables are useful within calculations involving money. The type-
declaration character for Currency is @ . Storage Internally, currency values are 8-byte integers scaled
by 10000. Thus, when appearing within a structure, currency values require 8 bytes of storage. When
used with binary or random files, 8 bytes of storage are required.
See Also Date (page 263) (data type); Double (page 300) (data type); Integer (data type); Long (page 398)
(data type); Object (page 422) (data type); Single (page 479) (data type); String (page 494)
(data type); Variant (page 515) (data type); Boolean (page 233) (data type); DefType (page 276)
(statement); CCur (page 238) (function).
CVar (function)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 260
Comments This function is used to convert an expression into a variant. Use of this function is not necessary (except
for code documentation purposes) because assignment to variant variables automatically performs the
necessary conversion:
Sub Main()
Dim v As Variant
v = 4 & "th" 'Assigns "4th" to v.
MsgBox "You came in: " & v
v = CVar(4 & "th") 'Assigns "4th" to v.
MsgBox "You came in: " & v
End Sub
See Also CCur (page 238) (function); CBool (page 237) (function); CDate, CVDate (page 238) (functions);
CDbl (page 237) (function); CInt (page 243) (function); CLng (page 248) (function); CSng (page
258) (function); CStr (page 258) (function); CVErr (page 260) (function); Variant (page 515) (data
type).
CVErr (function)
Comments This function is used to convert an expression into a user-defined error number. A runtime error is
generated under the following conditions: If expression is Null . If expression is a number outside the
legal range for errors, which is as follows:
0 <= expression <= 65535
If expression is Boolean . If expression is a String that can't be converted to a number within the legal
range. Empty is treated as 0.
Example This example simulates a user-defined error and displays the error number.
Sub Main()
MsgBox "The error is: " & CStr(CVErr(2046))
End Sub
See Also CCur (page 238) (function); CBool (page 237) (function); CDate, CVDate (page 238) (functions);
CDbl (page 237) (function); CInt (page 243) (function); CLng (page 248) (function); CSng (page
258) (function); CStr (page 258) (function); CVar (page 259) (function), IsError (page 381)
(function).
Comments (topic)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 261
Comments can be added to Basic Control Engine script code in the following manner: All text between a single
quotation mark and the end of the line is ignored:
MsgBox "Hello" 'Displays a message box.
The REM statement causes the compiler to ignore the entire line:
REM This is a comment.
The Basic Control Engine supports C-style multiline comment blocks /*...*/, as shown in the following example:
MsgBox "Before comment"
/* This stuff is all commented out.
This line, too, will be ignored.
This is the last line of the comment. */
MsgBox "After comment"
DateAdd (function)
DateDiff (function)
DatePart (function)
DateSerial (function)
DateValue (function)
Day (function)
DDB (function)
DDEExecute (statement)
DDEInitiate (function)
DDEPoke (statement)
DDESend (statement)
DDETerminate (statement)
DDETerminateAll (statement)
DDETimeout (statement)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 262
Declare (statement)
DefType (statement)
DeleteSetting (statement)
Dialog (function)
Dialog (statement)
Dim (statement)
DiskDrives (statement)
DiskFree (function)
DlgCaption (function)
DlgCaption (statement)
DlgControlId (function)
DlgEnable (function)
DlgEnable (statement)
DlgFocus (function)
DlgFocus (statement)
DlgListBoxArray (function)
DlgListBoxArray (statement)
DlgProc (function)
DlgSetPicture (statement)
DlgText (statement)
DlgText$ (function)
DlgValue (function)
DlgValue (statement)
DlgVisible (function)
DlgVisible (statement)
Do...Loop (statement)
DoEvents (function)
DoEvents (statement)
DropListBox (statement)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 263
Syntax Date
Comments Date variables are used to hold dates within the following range:
January 1, 100 00:00:00 <= date <= December 31, 9999 23:59:59
–6574340 <= date <= 2958465.99998843
Internally, dates are stored as 8-byte IEEE double values. The integer part holds the number of days
since December 31, 1899, and the fractional part holds the number of seconds as a fraction of the day.
For example, the number 32874.5 represents January 1, 1990 at 12:00:00. When appearing within a
structure, dates require 8 bytes of storage. Similarly, when used with binary or random files, 8 bytes of
storage are required. There is no type-declaration character for Date .
Date variables that haven't been assigned are given an initial value of 0 (i.e., December 31, 1899).
Date Literals Literal dates are specified using number signs, as shown below:
Dim d As Date
d = #January 1, 1990#
The interpretation of the date string (i.e., January 1, 1990 in the above example) occurs at runtime,
using the current country settings. This is a problem when interpreting dates such as 1/2/1990. If the date
format is M/D/Y, then this date is January 2, 1990. If the date format is D/M/Y, then this date is February
1, 1990. To remove any ambiguity when interpreting dates, use the universal date format: date_variable
= #YY/MM/DD HH:MM:SS# The following example specifies the date June 3, 1965 using the universal
date format:
Dim d As Date
d = #1965/6/3 10:23:45#
See Also Currency (page 259) (data type); Double (page 300) (data type); Integer (page 377) (data type);
Long (page 398) (data type); Object (page 422) (data type); Single (page 479) (data type); String
(page 494) (data type); Variant (page 515) (data type); Boolean (page 233) (data type); DefType
(page 276) (statement); CDate, CVDate (page 238) (functions).
Comments The Date$ function returns the date using the short date format. The Date function returns the date as
a Date variant. Use the Date/Date$ statements to set the system date. The date is returned using the
current short date format (defined by the operating system).
The Date$ function does not properly support international formats. Use the Date function instead.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 264
Example This example saves the current date to TheDate$, then changes the date and displays the result. It then
changes the date back to the saved date and displays the restored date.
' When run with non-US Regional or International settings,
' the two message boxes may display different dates.
' One set of International Date Formats which shows this is:
' Short Date Format: dd.M.yy (ex: 02.01.97 for 2 January 1997)
' Long Date Format: ddddd, dd M, yyyy (Thursday, 02 January 1997)
Sub Main()
' Save the current date
TheDate$ = Date
' Set the date to one that may confuse the library functions
' (month and day < 12)
Date = "01/02/97" ' 1 Feb 1997
MsgBox(Format$ (Date$, "dddddd")) ' This may show 2 Jan
MsgBox(Format$ (Date, "dddddd")) ' This may show 1 Feb
See Also CDate, CVDate (page 238) (functions); Time, Time$ (page 504) (functions); Date, Date$ (page 264)
(statements); Now (page 419) (function); Format, Format$ (page 348) (functions); DateSerial (page
268) (function); DateValue (page 268) (function).
Comments The Date$ statement requires a string variable using one of the following formats: MM-DD-YYYY MM-
DD-YY MM/DD/YYYY MM/DD/YY, Where MM is a two-digit month between 1 and 31, DD is a two-
digit day between 1 and 31, and YYYY is a four-digit year between 1/1/100 and 12/31/9999. The Date
statement converts any expression to a date, including string and numeric values. Unlike the Date$
statement, Date recognizes many different date formats, including abbreviated and full month names and
a variety of ordering options. If newdate contains a time component, it is accepted, but the time is not
changed. An error occurs if newdate cannot be interpreted as a valid date.
Example This example saves the current date to Cdate$, then changes the date and displays the result. It then
changes the date back to the saved date and displays the result.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
TheDate$ = Date
Date = "01/01/95"
MsgBox "Saved date is: " & TheDate$ & crlf & "Changed date is: " & Date
Date = TheDate$
MsgBox "Restored date to: " & TheDate$
End Sub
See Also Date, Date$ (page 263) (functions); Time, Time$ (page 504) (statements).
Notes If you do not have permission to change the date, runtime error 70 will be generated.
DateAdd (function)
Description Returns a Date variant representing the sum of date and a specified number (increment) of time intervals
(interval$).
Comments This function adds a specified number (increment) of time intervals (interval$) to the specified date (date).
The following table describes the parameters to the DateAdd function:
Parameter Description
Interval$ String expression indicating the time interval used in the addition.
Increment Integer indicating the number of time intervals you wish to add. Positive values result in
dates in the future; negative values result in dates in the past.
The interval$ parameter specifies what unit of time is to be added to the given date. It can be any of the
following:
Time Intervale
"yyyy" Year
"d" Day
"m" Month
"q" Quarter
"ww" Week
"h" Hour
"n" Minute
"s" Second
"w" Weekday
To add days to a date, you may use either day, day of the year, or weekday, as they are all equivalent ("
d ", " y ", " w "). The DateAdd function will never return an invalid date/time expression. The following
example adds two months to December 31, 1992:
s# = DateAdd("m",2,"December 31,1992")
In this example, s is returned as the double-precision number equal to " February 28, 1993 ", not "
February 31, 1993 ". A runtime error is generated if you try to subtract a time interval that is larger than
the time value of the date.
Example This example gets today's date using the Date$ function; adds three years, two months, one week, and
two days to it; and then displays the result in a dialog box.
Sub Main()
Dim sdate$
sdate$ = Date$
NewDate# = DateAdd("yyyy",4,sdate$)
NewDate# = DateAdd("m",3,NewDate#)
NewDate# = DateAdd("ww",2,NewDate#)
NewDate# = DateAdd("d",1,NewDate#)
s$ = "Four years, three months, two weeks, and one day from now will be: "
s$ = s$ & Format(NewDate#,"long date")
MsgBox s$
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 266
DateDiff (function)
Description Returns a Date variant representing the number of given time intervals between date1 and date2.
Parameter Description
Interval$ String expression indicating the specific time interval you wish to find the difference between.
Date1 Any expression convertible to a Date . An example of a valid date/time string would be "
January 1, 1994 ".
Date2 Any expression convertible to a Date . An example of a valid date/time string would be "
January 1, 1994 ".
The following table lists the valid time interval strings and the meanings of each. The Format$ function
uses the same expressions.
Time Interval
"yyyy" Year
"d" Day
"m" Month
"q" Quarter
"ww" Week
"h" Hour
"n" Minute
"s" Second
"w" Weekday
To find the number of days between two dates, you may use either day or day of the year, as they are
both equivalent ("d", "y").
The time interval weekday (" w ") will return the number of weekdays occurring between date1 and date2,
counting the first occurrence but not the last. However, if the time interval is week (" ww "), the function
will return the number of calendar weeks between date1 and date2, counting the number of Sundays. If
date1 falls on a Sunday, then that day is counted, but if date2 falls on a Sunday, it is not counted. The
DateDiff function will return a negative date/time value if date1 is a date later in time than date2.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 267
Example This example gets today's date and adds ten days to it. It then calculates the difference between the two
dates in days and weeks and displays the result.
Sub Main()
Today$ = Format(Date$,"Short Date")
NextWeek = Format(DateAdd("d",14,today$),"Short Date")
DifDays# = DateDiff("d",today$,NextWeek)
DifWeek# = DateDiff("w",today$,NextWeek)
s$ = "The difference between " & today$ & " and " & NextWeek
s$ = s$ & " is: " & DifDays# & " days or " & DifWeek# & " weeks"
MsgBox s$
End Sub
DatePart (function)
Comments The DatePart function decomposes the specified date and returns a given date/time element. The
following table describes the parameters:
Parameter Description
Interval$ String expression indicating the specific time interval you wish to find the difference between.
Date Any expression convertible to a Date. An example of a valid date/time string would be "
January 1, 1995" .
The following table lists the valid time interval strings and the meanings of each. The Format$ function
uses the same expressions.
Time Interval
"yyyy" Year
"d" Day
"m" Month
"q" Quarter
"ww" Week
"h" Hour
"n" Minute
"s" Second
"w" Weekday
The weekday expression starts with Sunday as 1 and ends with Saturday as 7.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 268
See Also Day (page 269) (function); Minute (page 404) (function); Second (page 471) (function); Month (page
406) (function); Year (page 533) (function); Hour (page 364) (function); Weekday (page 521)
(function), Format (page 348) (function).
DateSerial (function)
Parameter Description
Example This example converts a date to a real number representing the serial date in days since
December 30, 1899 (which is day 0).
Sub Main()
tdate# = DateSerial(1993,08,22)
MsgBox "The DateSerial value for August 22, 1993, is: " & tdate#
End Sub
See Also DateValue (page 268) (function); TimeSerial (page 505) (function); TimeValue (page
506) (function); CDate, CVDate (page 238) (functions).
DateValue (function)
Description Returns a Date variant representing the date contained in the specified string argument.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 269
Example This example returns the day of the month for today's date.
Sub Main()
Tdate$ = Date$
tday$ = DateValue(tdate$)
MsgBox "The date value of " & tdate$ & " is: " & tday$
End Sub
See Also TimeSerial (page 505) (function); TimeValue (page 506) (function); DateSerial
(page 268) (function).
Platform(s) All.
Day (function)
Comments The value returned is an Integer between 0 and 31 inclusive. The date parameter is any expression that
converts to a Date .
Example This example gets the current date and then displays it.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
CurDate = Now()
MsgBox "Today is day " & Day(CurDate) & " of the month." & crlf & "Tomorrow is day " &
Day(CurDate + 1) & "."
End Sub
See Also Minute (page 404) (function); Second (page 471) (function); Month (page 406) (function); Year
(page 533) (function); Hour (page 364) (function); Weekday (page 521) (function); DatePart (page
267) (function).
DDB (function)
Description Calculates the depreciation of an asset for a specified Period of time using the double-declining balance
method.
Comments The double-declining balance method calculates the depreciation of an asset at an accelerated rate. The
depreciation is at its highest in the first period and becomes progressively lower in each additional period.
DDB uses the following formula to calculate the depreciation:
DDB = ((Cost – Total_depreciation_from_all_other_periods) * 2) / Life
Parameter Description
Salvage Double representing the estimated value of the asset at the end of its predicted useful life
Life Double representing the predicted length of the asset's useful life
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 270
Period Double representing the period for which you wish to calculate the depreciation
Life and Period must be expressed using the same units. For example, if Life is expressed in months,
then Period must also be expressed in months.
Example This example calculates the depreciation for capital equipment that cost $10,000, has a service life of ten
years, and is worth $2,000 as scrap. The dialog box displays the depreciation for each of the first four
years.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
s$ = "Depreciation Table" & crlf & crlf
For yy = 1 To 4
CurDep# = DDB(10000.0,2000.0,10,yy)
s$ = s$ & "Year " & yy & " : " & CurDep# & crlf
Next yy
MsgBox s$
End Sub
See Also Sln (page 480) (function); SYD (page 497) (function).
DDEExecute (statement)
Parameter Description
Channel Integer containing the DDE channel number returned from DDEInitiate. An error will result if
channel is invalid.
Command String containing the command to be executed. The format of command$ depends on the
$ receiving application.
If the receiving application does not execute the instructions, a runtime error is generated.
Example This example sets and retrieves a cell in an Excel spreadsheet. The command strings being created
contain Microsoft Excel macro commands and may be concatenated and sent as one string to speed
things up.
Sub Main()
Dim cmd,q,ch%
Q = Chr(34) ' Define quotation marks.
DDETerminate ch%
Msgbox "Finished..."
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 271
See Also DDEInitiate (page 271) (function); DDEPoke (page 271) (statement); DDERequest, DDERequest$
(page 272) (functions); DDESend (page 273) (function); DDETerminate (page 274) (statement);
DDETerminateAll (page 274) (statement); DDETimeout (page 275) (statement).
DDEInitiate (function)
Description Initializes a DDE link to another application and returns a unique number subsequently used to refer to the
open DDE channel.
Parameter Description
Application String containing the name of the application (the server) with which a DDE conversation
$ will be established.
Topic$ String containing the name of the topic for the conversation. The possible values for this
parameter are described in the documentation for the server application.
This function returns 0 if the link cannot be established. This will occur under any of the following
circumstances:
DDETerminate ch%
Msgbox "Finished..."
End Sub
See Also DDEExecute (page 270) (statement); DDEPoke (page 271) (statement); DDERequest, DDERequest
$ (page 272) (functions); DDESend (page 273) (function); DDETerminate (page 274) (statement);
DDETerminateAll (page 274) (statement); DDETimeout (page 275) (statement).
DDEPoke (statement)
Description Sets the value of a data item in the receiving application associated with an open DDE link.
Parameter Description
Channel Integer containing the DDE channel number returned from DDEInitiate. An error will result if
channel is invalid.
DataItem Data item to be set. This parameter can be any expression convertible to a String. The
format depends on the server.
Value The new value for the data item. This parameter can be any expression convertible to a
String. The format depends on the server. A runtime error is generated if value is Null.
DDETerminate ch%
Msgbox "Finished..."
End Sub
See Also DDEExecute (page 270) (statement); DDEInitiate (page 271) (function); DDERequest, DDERequest
$ (page 272) (functions); DDESend (page 273) (function); DDETerminate (page 274) (statement);
DDETerminateAll (page 274) (statement); DDETimeout (page 275) (statement).
Description Returns the value of the given data item in the receiving application associated with the open DDE
channel.
Comments DDERequest$ returns a String , whereas DDERequest returns a String variant. The DDERequest/
DDERequest$ functions take the following parameters:
Parameter Description
channel Integer containing the DDE channel number returned from DDEInitiate. An error will result if
channel is invalid.
DataItem$ String containing the name of the data item to request. The format for this parameter
depends on the server.
DDETerminate ch%
Msgbox "Finished..."
End Sub
See Also DDEExecute (page 270) (statement); DDEInitiate (page 271) (function); DDEPoke (page
271) (statement); DDESend (page 273) (function); DDETerminate (page 274) (statement);
DDETerminateAll (page 274) (statement); DDETimeout (page 275) (statement).
DDESend (statement)
Description Initiates a DDE conversation with the server as specified by application$ and topic$ and sends that server
a new value for the specified item.
Parameter Description
application String containing the name of the application (the server) with which a DDE conversation
$ will be established.
topic$ String containing the name of the topic for the conversation. The possible values for this
parameter are described in the documentation for the server application.
DataItem Data item to be set. This parameter can be any expression convertible to a String. The
format depends on the server.
value New value for the data item. This parameter can be any expression convertible to a String.
The format depends on the server. A runtime error is generated if value is Null.
Example This example sets the content of the first cell in an Excel spreadsheet.
Sub Main()
Dim cmd,ch%
id = Shell("c:\excel5\excel.exe",3) 'Start Excel.
ExcelError:
MsgBox "Error sending data to Excel."
Exit Sub 'Reset error handler.
End Sub
See Also DDEExecute (page 270) (statement); DDEInitiate (page 271) (function); DDEPoke (page 271)
(statement); DDERequest (page 272), DDERequest$ (page 272) (functions); DDETerminate (page
274) (statement); DDETerminateAll (page 274) (statement); DDETimeout (page 275) (statement).
DDETerminate (statement)
Comments The channel parameter is an Integer containing the DDE channel number returned from DDEInitiate
. An error will result if channel is invalid. All open DDE channels are automatically terminated when the
script ends.
DDETerminate ch%
Msgbox "Finished..."
End Sub
See Also DDEExecute (page 270) (statement); DDEInitiate (page 271) (function); DDEPoke (page 271)
(statement); DDERequest (page 272), DDERequest$ (page 272) (functions); DDESend (page 273)
(function); DDETerminateAll (page 274) (statement); DDETimeout (page 275) (statement).
DDETerminateAll (statement)
Syntax DDETerminateAll
Comments All open DDE channels are automatically terminated when the script ends.
DDETerminateAll
Msgbox "Finished "
End Sub
See Also DDEExecute (page 270) (statement); DDEInitiate (page 271) (function); DDEPoke (page 271)
(statement); DDERequest (page 272), DDERequest$ (page 272) (functions); DDESend (page 273)
(function); DDETerminate (page 274) (statement); DDETimeout (page 275) (statement).
DDETimeout (statement)
Description Sets the number of milliseconds that must elapse before any DDE command times out.
Comments The milliseconds parameter is a Long and must be within the following range: 0 <= milliseconds <=
2,147,483,647 The default is 10,000 (10 seconds).
Example This example sets and retrieves a cell in an Excel spreadsheet. The timeout has been set to wait 2
seconds for Excel to respond before timing out.
Sub Main()
Dim cmd,q,ch%
q = Chr(34) ' Define quotation marks.
DDETerminate ch%
Msgbox "Finished "
End Sub
See Also DDEExecute (page 270) (statement); DDEInitiate (page 271) (function); DDEPoke (page 271)
(statement); DDERequest (page 272), DDERequest$ (page 272) (functions); DDESend (page 273)
(function); DDETerminate (page 274) (statement); DDETerminateAll (page 274) (statement).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 276
Declare (statement)
If the libname$ parameter does not contain an explicit path to the DLL, the following search will be
performed for the DLL (in this order):
DefType (statement)
Syntax DefInt letterrange DefLng letterrange DefStr letterrange DefSng letterrange DefDbl letterrange
DefCur letterrange DefObj letterrange DefVar letterrange DefBool letterrange DefDate
letterrange
Comments The Def Type statement controls automatic type declaration of variables. Normally, if a variable is
encountered that hasn't yet been declared with the Dim , Public , or Private statement or does not
appear with an explicit type-declaration character, then that variable is declared implicitly as a variant (
DefVar A–Z) . This can be changed using the Def Type statement to specify starting letter ranges for
type other than integer. The letterrange parameter is used to specify starting letters. Thus, any variable
that begins with a specified character will be declared using the specified Type.
The syntax for letterrange is: letter [-letter] [,letter [-letter]]... Def Type variable types are superseded by
an explicit type declaration¾using either a type-declaration character or the Dim , Public , or Private
statement.
The Def Type statement only affects how the Basic Control Engine compiles scripts and has no effect
at runtime. The Def Type statement can only appear outside all Sub and Function declarations. The
following table describes the data types referenced by the different variations of the Def Type statement:
DefInt Integer
DefLng Long
DefStr String
DefSng Single
DefDbl Double
DefCur Currency
DefObj Object
DefVar Variant
DefBool Boolean
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 277
DefDate Date
Example
DefStr a-m
DefLng n-r
DefSng s-u
DefDbl v-w
DefInt x-z
See Also Currency (page 259) (data type); Date (page 263) (data type); Double (page 300) (data type); Long
(page 398) (data type); Object (page 422) (data type); Single (page 479) (data type); String (page
494) (data type); Variant (page 515) (data type); Boolean (page 233) (data type); Integer (page
377) (data type).
DeleteSetting (statement)
Comments You can control the behavior of DeleteSetting by omitting parameters. If you specify all three parameters,
then DeleteSetting deletes your specified setting. If you omit key, then DeleteSetting deletes all of the
keys from section. If both section and key are omitted, then DeleteSetting removes that application’s
entry from the system registry. The following table describes the named parameters to the DeleteSetting
statement:
Parameter Description
appname String expression indicating the name of the application whose setting will be deleted.
section String expression indicating the name of the section whose setting will be deleted.
key String expression indicating the name of the setting to be deleted from the registry.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 278
Example
'The following example adds two entries to the Windows registry
'if run under Win32 or to NEWAPP.INI on other platforms,
'using the SaveSetting statement. It then uses DeleteSetting
'first to remove the Startup section, then to remove
'the NewApp key altogether.
Sub Main()
SaveSetting appname := "NewApp", section := "Startup", _
key := "Height", setting := 200
SaveSetting appname := "NewApp", section := "Startup", _
key := "Width", setting := 320
DeleteSetting "NewApp", "Startup" 'Remove Startup section
DeleteSetting "NewApp" 'Remove NewApp key
End Sub
See Also SaveSetting (page 468) (statement), GetSetting (page 359) (function), GetAllSettings (page 356)
(function)
Notes Under Win32, this statement operates on the system registry. All settings are saved under the following
entry in the system registry: HKEY_CURRENT_USER\Software\BasicScript Program Settings\appname
\section\key
Dialog (function)
Description Displays the dialog box associated with DialogVariable, returning an Integer indicating which button was
clicked.
>0 A push button was clicked. The returned number represents which button was clicked based on its
order in the dialog box template (1 is the first push button, 2 is the second push button, and so on).
Parameter Description
DialogVariable Name of a variable that has previously been dimensioned as a user dialog box. This is
accomplished using the Dim statement:
All dialog variables are local to the Sub or Function in which they are defined. Private
and public dialog variables are not allowed.
DefaultButton An Integer specifying which button is to act as the default button in the dialog box. The
value of DefaultButton can be any of the following:
-1 This value indicates that the OK button, if present, should be used as the default.
0 This value indicates that the Cancel button, if present, should be used as the default.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 279
>0 This value indicates that the Nth button should be used as the default. This number is
the index of a push button within the dialog box template.
Timeout An Integer specifying the number of milliseconds to display the dialog box before
automatically dismissing it. If TimeOut is not specified or is equal to 0 , then the dialog box
will be displayed until dismissed by the user. If a dialog box has been dismissed due to a
timeout, the Dialog function returns 0 .
See Also CancelButton (page 243) (statement); CheckBox (page 240) (statement); ComboBox (page 249)
(statement); Dialog (page 279) (statement); DlgProc (page 289) (function); DropListBox (page 301)
(statement); GroupBox (page 361) (statement); ListBox (page 394) (statement); OKButton (page
426) (statement); OptionButton (page 434) (statement); OptionGroup (page 435) (statement);
Picture (page 438) (statement); PushButton (page 447) (statement); Text (page 502) (statement);
TextBox (page 503) (statement); Begin (page 231) Dialog (page 231) (statement), PictureButton
(page 439) (statement).
Dialog (statement)
Description Same as the Dialog (page 278) function, except that the Dialog statement does not
return a value.
See Also Dialog (page 278) (function); DlgProc (page 289) (function)
Dim (statement)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 280
Description Returns a String containing the first or next file matching filespec$. If filespec$ is specified, then the first
file matching that filespec$ is returned. If filespec$ is not specified, then the next file matching the initial
filespec$ is returned.
Comments Dir$ returns a String , whereas Dir returns a String variant. The Dir$ / Dir functions take the
following parameters:
Parameter Description
filespec$ String containing a file specification. If this parameter is specified, then Dir$ returns
the first file matching this file specification. If this parameter is omitted, then the next file
matching the initial file specification is returned. If no path is specified in filespec$, then
the current directory is used.
attributes Integer specifying attributes of files you want included in the list, as described below. If
omitted, then only the normal, read-only, and archive files are returned.
An error is generated if Dir$ is called without first calling it with a valid filespec$. If there is no matching
filespec$, then a zero-length string is returned.
Wildcards The filespec$ argument can include wildcards, such as * and ?. The * character matches any
sequence of zero or more characters, whereas the ? character matches any single character. Multiple *'s
and ?'s can appear within the expression to form complete searching patterns. The following table shows
some examples:
* (All files)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 281
Attributes You can control which files are included in the search by specifying the optional attributes
parameter. The Dir, Dir$ functions always return all normal, read-only, and archive files ( ebNormal Or
ebReadOnly Or ebArchive ). To include additional files, you can specify any combination of the following
attributes (combined with the Or operator):
Example This example uses Dir to fill a SelectBox with the first 10 directory entries.
Const crlf = Chr$(13) + Chr$(10)
Option Base 1
Sub Main()
Dim a$(10)
i% = 1
a(i%) = Dir("*.*")
See Also ChDir (page 239) (statement); ChDrive (page 239) (statement); CurDir, CurDir$ (page 259)
(functions); MkDir (page 405) (statement); RmDir (page 463) (statement); FileList (page 343)
(statement).
DiskDrives (statement)
Description Fills the specified String or Variant array with a list of valid drive letters.
Comments The array () parameter specifies either a zero- or a one-dimensioned array of strings or variants. The
array can be either dynamic or fixed. If array () is dynamic, then it will be redimensioned to exactly hold
the new number of elements. If there are no elements, then the array will be redimensioned to contain no
dimensions. You can use the LBound , UBound , and ArrayDims functions to determine the number
and size of the new array's dimensions. If the array is fixed, each array element is first erased, then the
new elements are placed into the array. If there are fewer elements than will fit in the array, then the
remaining elements are initialized to zero-length strings (for String arrays) or Empty (for Variant
arrays). A runtime error results if the array is too small to hold the new elements.
Example This example builds and displays an array containing the first three available disk drives.
Sub Main()
Dim drive$()
DiskDrives drive$
r% = SelectBox("Available Disk Drives",,drive$)
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 282
See Also ChDrive (page 239) (statement); DiskFree (page 282) (function).
DiskFree (function)
Description Returns a Long containing the free space (in bytes) available on the specified drive.
Comments If drive$ is zero-length or not specified, then the current drive is assumed. Only the first character of the
drive$ string is used.
Example This example uses DiskFree to set the value of i and then displays the result in a message box.
Sub Main()
s$ = "c"
i# = DiskFree(s$)
MsgBox "Free disk space on drive '" & s$ & "' is: " & i#
End Sub
See Also ChDrive (page 239) (statement); DiskDrives (page 281) (statement).
DlgCaption (function)
Syntax DlgCaption[()]
Description Returns a string containing the caption of the active user-defined dialog box.
Comments This function returns a zero-length string if the active dialog has no caption.
DlgCaption (statement)
Example
'This example displays a dialog
box, adjusting the caption
'to contain the text of the
currently selected option
'button.
Function DlgProc(c As String,a
As Integer,v As Integer)
If a = 1 Then
DlgCaption choose(DlgValue("OptionGroup1") + 1, _
"Blue","Green")
ElseIf a = 2 Then
DlgCaption choose(DlgValue("OptionGroup1") + 1, _
"Blue","Green")
End If
End Function
Sub Main()
Begin Dialog
UserDialog ,,149,45,"Untitled",.DlgProc
OKButton 96,8,40,14
OptionGroup .OptionGroup1
OptionButton
12,12,56,8,"Blue",.OptionButton1
OptionButton
12,28,56,8,"Green",.OptionButton2
End Dialog
Dim d As UserDialog
Dialog d
End Sub
DlgControlId (function)
Description Returns an Integer containing the index of the specified control as it appears in the dialog box template.
Comments The first control in the dialog box template is at index 0, the second is at index 1, and so on. The
ControlName$ parameter contains the name of the .Identifier parameter associated with that control in the
dialog box template.
The Basic Control Engine statements and functions that dynamically manipulate dialog box controls
identify individual controls using either the .Identifier name of the control or the control's index. Using the
index to refer to a control is slightly faster but results in code that is more difficult to maintain.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 284
Example This example uses DlgControlId to verify which control was triggered and branches the dynamic dialog
script accordingly.
Function DlgProc(ControlName$,Action%,SuppValue%) As Integer
If Action% = 2 Then
'Enable the next three controls.
If DlgControlId(ControlName$) = 2 Then
For i = 3 to 5
DlgEnable i,DlgValue("CheckBox1")
Next i
DlgProc = 1 'Don't close the dialog box.
End If
ElseIf Action% = 1 Then
'Set initial state upon startup
For i = 3 to 5
DlgEnable i,DlgValue("CheckBox1")
Next i
End If
End Function
Sub Main()
Begin Dialog UserDialog ,,180,96,"Untitled",.DlgProc
OKButton 132,8,40,14
CancelButton 132,28,40,14
CheckBox 24,16,72,8,"Click Here",.CheckBox1
CheckBox 36,32,60,8,"Sub Option 1",.CheckBox2
CheckBox 36,44,72,8,"Sub Option 2",.CheckBox3
CheckBox 36,56,60,8,"Sub Option 3",.CheckBox4
CheckBox 24,72,76,8,"Main Option 2",.CheckBox5
End Dialog
Dim d As UserDialog
Dialog d
End Sub
See Also DlgEnable (page 284) (function); DlgEnable (page 285) (statement); DlgFocus (page 286) (function);
DlgFocus (page 287) (statement); DlgListBoxArray (page 287) (function); DlgListBoxArray (page
288) (statement); DlgSetPicture (page 291) (statement); DlgText (page 292) (statement); DlgText$
(page 293) (function); DlgValue (page 294) (function); DlgValue (page 295) (statement); DlgVisible
(page 296) (statement); DlgVisible (page 296) (function).
DlgEnable (function)
Description Returns True if the specified control is enabled; returns False otherwise.
Comments Disabled controls are dimmed and cannot receive keyboard or mouse input. The ControlName$
parameter contains the name of the .Identifier parameter associated with a control in the dialog box
template. A case-insensitive comparison is used to locate the specific control within the template.
Alternatively, by specifying the ControlIndex parameter, a control can be referred to using its index in the
dialog box template (0 is the first control in the template, 1 is the second, and so on). You cannot disable
the control with the focus.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 285
Example This example checks the status of a checkbox at the end of the dialog procedure and notifies the user
accordingly.
Function DlgProc(ControlName$,Action%,SuppValue%) As Integer
If Action% = 2 Then
'Enable the next three controls.
If DlgControlId(ControlName$) = 2 Then
For i = 3 to 5
DlgEnable i,DlgValue("CheckBox1")
Next i
DlgProc = 1 'Don't close the dialog box.
End If
ElseIf Action% = 1 Then
'Set initial state upon startup
For i = 3 to 5
DlgEnable i,DlgValue("CheckBox1")
Next i
End If
Sub Main()
Begin Dialog UserDialog ,,180,96,"Untitled",.DlgProc
OKButton 132,8,40,14
CancelButton 132,28,40,14
CheckBox 24,16,72,8,"Click Here",.CheckBox1
CheckBox 36,32,60,8,"Sub Option 1",.CheckBox2
CheckBox 36,44,72,8,"Sub Option 2",.CheckBox3
CheckBox 36,56,60,8,"Sub Option 3",.CheckBox4
CheckBox 24,72,76,8,"Main Option 2",.CheckBox5
End Dialog
Dim d As UserDialog
Dialog d
End Sub
See Also DlgControl (page 283) (statement); DlgEnable (page 285) (statement); DlgFocus (page 286)
(function); DlgFocus (page 287) (statement); DlgListBoxArray (page 287) (function); DlgListBoxArray
(page 288) (statement); DlgSetPicture (page 291) (statement); DlgText (page 292) (statement);
DlgText$ (page 293) (function); DlgValue (page 294) (function); DlgValue (page 295) (statement);
DlgVisible (page 296) (statement); DlgVisible (page 296) (function).
DlgEnable (statement)
Comments Disabled controls are dimmed and cannot receive keyboard or mouse input. The isOn parameter is an
Integer specifying the new state of the control. It can be any of the following values: 0 The control is
disabled. 1 The control is enabled. Omitted Toggles the control between enabled and disabled.
Option buttons can be manipulated individually (by specifying an individual option button) or as a group
(by specifying the name of the option group).
The ControlName$ parameter contains the name of the .Identifier parameter associated with a control in
the dialog box template. Alternatively, by specifying the ControlIndex parameter, a control can be referred
to using its index in the dialog box template (0 is the first control in the template, 1 is the second, and so
on).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 286
Example This example uses DlgEnable to turn on/off various dialog options.
Function DlgProc(ControlName$,Action%,SuppValue%) As Integer
If Action% = 2 Then
'Enable the next three controls.
If DlgControlId(ControlName$) = 2 Then
For i = 3 to 5
DlgEnable i,DlgValue("CheckBox1")
Next i
DlgProc = 1 'Don't close the dialog box.
End If
ElseIf Action% = 1 Then
'Set initial state upon startup
For i = 3 to 5
DlgEnable i,DlgValue("CheckBox1")
Next i
End If
End Function
Sub Main()
Begin Dialog UserDialog ,,180,96,"Untitled",.DlgProc
OKButton 132,8,40,14
CancelButton 132,28,40,14
CheckBox 24,16,72,8,"Click Here",.CheckBox1
CheckBox 36,32,60,8,"Sub Option 1",.CheckBox2
CheckBox 36,44,72,8,"Sub Option 2",.CheckBox3
CheckBox 36,56,60,8,"Sub Option 3",.CheckBox4
CheckBox 24,72,76,8,"Main Option 2",.CheckBox5
End Dialog
Dim d As UserDialog
Dialog d
End Sub
See Also DlgEnable (page 285) (function); DlgFocus (page 286) (function); DlgFocus (page 287) (statement);
DlgListBoxArray (page 287) (function); DlgListBoxArray (page 288) (statement); DlgSetPicture (page
291) (statement); DlgText (page 292) (statement); DlgText$ (page 293) (function); DlgValue (page
294) (function); DlgValue (page 295) (statement); DlgVisible (page 296) (statement); DlgVisible
(page 296) (function).
DlgFocus (function)
Syntax DlgFocus$[()]
Description Returns a String containing the name of the control with the focus.
Comments The name of the control is the .Identifier parameter associated with the control in the dialog box template.
Example This code fragment makes sure that the control being disabled does not currently have the focus
(otherwise, a runtime error would occur).
Sub Main()
If DlgFocus = "Files" Then 'Does it have the focus?
DlgFocus "OK" 'Change the focus to another control.
End If
DlgEnable "Files",False 'Now we can disable the control.
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 287
See Also DlgEnable (page 284) (function); DlgEnable (page 285) (statement); DlgFocus (page 287)
(statement); DlgListBoxArray (page 287) (function); DlgListBoxArray (page 288) (statement);
DlgSetPicture (page 291) (statement); DlgText (page 292) (statement); DlgText$ (page 293)
(function); DlgValue (page 294) (function); DlgValue (page 295) (statement); DlgVisible (page 296)
(statement); DlgVisible (page 296) (function).
DlgFocus (statement)
Comments A runtime error results if the specified control is hidden, disabled, or nonexistent. The ControlName
$ parameter contains the name of the .Identifier parameter associated with a control in the dialog box
template. A case-insensitive comparison is used to locate the specific control within the template.
Alternatively, by specifying the ControlIndex parameter, a control can be referred to using its index in the
dialog box template (0 is the first control in the template, 1 is the second, and so on).
Example This code fragment makes sure the user enters a correct value. If not, the control returns focus back to
the TextBox for correction.
Function DlgProc(ControlName$,Action%,SuppValue%) As Integer
If Action% = 2 and ControlName$ = "OK" Then
If IsNumeric(DlgText$("TextBox1")) Then
Msgbox "Duly Noted."
Else
Msgbox "Sorry, you must enter a number."
DlgFocus "TextBox1"
DlgProc = 1
End If
End If
End Function
Sub Main()
Dim ListBox1$()
Begin Dialog UserDialog ,,112,74,"Untitled",.DlgProc
TextBox 12,20,88,12,.TextBox1
OKButton 12,44,40,14
CancelButton 60,44,40,14
Text 12,11,88,8,"Enter Desired Salary:",.Text1
End Dialog
Dim d As UserDialog
Dialog d
End Sub
See Also DlgEnable (page 284) (function); DlgEnable (page 285) (statement); DlgFocus (page 286) (function);
DlgListBoxArray (page 287) (function); DlgListBoxArray (page 288) (statement); DlgSetPicture (page
291) (statement); DlgText (page 292) (statement); DlgText$ (page 293) (function); DlgValue (page
294) (function); DlgValue (page 295) (statement); DlgVisible (page 296) (statement); DlgVisible
(page 296) (function).
DlgListBoxArray (function)
Description Fills a list box, combo box, or drop list box with the elements of an array, returning an Integer containing
the number of elements that were actually set into the control.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 288
Comments The ControlName$ parameter contains the name of the .Identifier parameter associated with a control
in the dialog box template. A case-insensitive comparison is used to locate the specific control within the
template. Alternatively, by specifying the ControlIndex parameter, a control can be referred to using its
index in the dialog box template (0 is the first control in the template, 1 is the second, and so on).
The ArrayVariable parameter specifies a single-dimensioned array used to initialize the elements of the
control. If this array has no dimensions, then the control will be initialized with no elements. A runtime
error results if the specified array contains more than one dimension. ArrayVariable can specify an array
of any fundamental data type (structures are not allowed). Null and Empty values are treated as zero-
length strings.
Sub Main()
Dim ListBox1$()
Begin Dialog UserDialog ,,180,96,"Untitled",.DlgProc
OKButton 132,8,40,14
CancelButton 132,28,40,14
ListBox 8,12,112,72,ListBox1$,.Files
End Dialog
Dim d As UserDialog
Dialog d
End Sub
See Also DlgEnable (page 284) (function); DlgEnable (page 285) (statement); DlgFocus (page 286) (function);
DlgFocus (page 287) (statement); DlgListBoxArray (page 288) (statement); DlgSetPicture (page
291) (statement); DlgText (page 292) (statement); DlgText$ (page 293) (function); DlgValue (page
294) (function); DlgValue (page 295) (statement); DlgVisible (page 296) (statement); DlgVisible
(page 296) (function).
DlgListBoxArray (statement)
Description Fills a list box, combo box, or drop list box with the elements of an array.
Comments The ControlName$ parameter contains the name of the .Identifier parameter associated with a control
in the dialog box template. A case-insensitive comparison is used to locate the specific control within the
template. Alternatively, by specifying the ControlIndex parameter, a control can be referred to using its
index in the dialog box template (0 is the first control in the template, 1 is the second, and so on).
The ArrayVariable parameter specifies a single-dimensioned array used to initialize the elements of the
control. If this array has no dimensions, then the control will be initialized with no elements. A runtime
error results if the specified array contains more than one dimension. ArrayVariable can specify an array
of any fundamental data type (structures are not allowed). Null and Empty values are treated as zero-
length strings.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 289
Sub Main()
Dim ListBox1$()
Begin Dialog UserDialog ,,180,96,"Untitled",.DlgProc
OKButton 132,8,40,14
CancelButton 132,28,40,14
ListBox 8,12,112,72,ListBox1$,.Files
End Dialog
Dim d As UserDialog
Dialog d
End Sub
See Also DlgEnable (page 284) (function); DlgEnable (page 285) (statement); DlgFocus (page 286) (function);
DlgFocus (page 287) (statement); DlgListBoxArray (page 287) (function); DlgSetPicture (page 291)
(statement); DlgText (page 292) (statement); DlgText$ (page 293) (function); DlgValue (page 294)
(function); DlgValue (page 295) (statement); DlgVisible (page 296) (statement); DlgVisible (page
296) (function).
DlgProc (function)
Description Describes the syntax, parameters, and return value for dialog functions.
Comments Dialog functions are called by a script during the processing of a custom dialog box. The name of a dialog
function (DlgProc) appears in the Begin Dialog statement as the .DlgProc parameter. Dialog functions
require the following parameters:
Parameter Description
ControlName$ String containing the name of the control associated with Action.
Action Integer containing the action that called the dialog function.
SuppValue Integer of extra information associated with Action. For some actions, this
parameter is not used.
When a script displays a custom dialog box, the user may click on buttons, type text into edit fields, select
items from lists, and perform other actions. When these actions occur, the Basic Control Engine calls the
dialog function, passing it the action, the name of the control on which the action occurred, and any other
relevant information associated with the action. The following table describes the different actions sent to
dialog functions:
Action Description
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 290
1 This action is sent immediately before the dialog box is shown for the first time. This gives the
dialog function a chance to prepare the dialog box for use. When this action is sent, ControlName
$ contains a zero-length string, and SuppValue is 0. The return value from the dialog function
is ignored in this case. Before Showing the Dialog Box After action 1 is sent, the Basic Control
Engine performs additional processing before the dialog box is shown. Specifically, it cycles
though the dialog box controls checking for visible picture or picture button controls. For each
visible picture or picture button control, the Basic Control Engine attempts to load the associated
picture. In addition to checking picture or picture button controls, the Basic Control Engine will
automatically hide any control outside the confines of the visible portion of the dialog box. This
prevents the user from tabbing to controls that cannot be seen. However, it does not prevent you
from showing these controls with the DlgVisible statement in the dialog function.
• A button is clicked, such as OK, Cancel, or a push button. In this case, ControlName$
contains the name of the button. SuppValue contains 1 if an OK button was clicked and 2 if a
Cancel button was clicked; SuppValue is undefined otherwise.
If the dialog function returns 0 in response to this action, then the dialog box will be closed. Any
other value causes the Basic Control Engine to continue dialog processing.
• A check box's state has been modified. In this case, ControlName$ contains the name of the
check box, and SuppValue contains the new state of the check box (1 if on, 0 if off).
• An option button is selected. In this case, ControlName$ contains the name of the option
button that was clicked, and SuppValue contains the index of the option button within the
option button group (0-based).
• The current selection is changed in a list box, drop list box, or combo box. In this case,
ControlName$ contains the name of the list box, combo box, or drop list box, and SuppValue
contains the index of the new item (0 is the first item, 1 is the second, and so on).
3 This action is sent when the content of a text box or combo box has been changed. This action
is only sent when the control loses focus. When this action is sent, ControlName$ contains the
name of the text box or combo box, and SuppValue contains the length of the new content. The
dialog function's return value is ignored with this action.
4 This action is sent when a control gains the focus. When this action is sent, ControlName$
contains the name of the control gaining the focus, and SuppValue contains the index of the
control that lost the focus (0-based). The dialog function's return value is ignored with this action.
5 This action is sent continuously when the dialog box is idle. If the dialog function returns 1 in
response to this action, then the idle action will continue to be sent. If the dialog function returns
0, then the Basic Control Engine will not send any additional idle actions. When the idle action is
sent, ControlName$ contains a zero-length string, and SuppValue contains the number of times
the idle action has been sent so far. Note: Not returning zero will cause your application to use
all available CPU time and may adversely affect your CIMPLICITY System.
6 This action is sent when the dialog box is moved. The ControlName$ parameter contains a zero-
length string, and SuppValue is 0. The dialog function's return value is ignored with this action.
User-defined dialog boxes cannot be nested. In other words, the dialog function of one dialog box cannot
create another user-defined dialog box. You can, however, invoke any built-in dialog box, such as
MsgBox or InputBox$ .
Within dialog functions, you can use the following additional statements and functions. These statements
allow you to manipulate the dialog box controls dynamically.
DlgVisible DlgText$ DlgText
DlgSetPicture DlgListBoxArray DlgFocus
DlgEnable DlgControlId
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 291
The dialog function can optionally be declared to return a Variant . When returning a variable, the
Basic Control Engine will attempt to convert the variant to an Integer . If the returned variant cannot be
converted to an Integer , then 0 is assumed to be returned from the dialog function.
Example This dialog function enables/disables a group of option buttons when a check box is clicked.
Function SampleDlgProc(ControlName$,Action%,SuppValue%)
If Action% = 2 And ControlName$ = "Printing" Then
DlgEnable "PrintOptions",SuppValue%
SampleDlgProc = 1 'Don't close the dialog box.
End If
End Function
Sub Main()
Begin Dialog SampleDialogTemplate 34,39,106,45,"Sample",.SampleDlgProc
OKButton 4,4,40,14
CancelButton 4,24,40,14
CheckBox 56,8,38,8,"Printing",.Printing
OptionGroup .PrintOptions
OptionButton 56,20,51,8,"Landscape",.Landscape
OptionButton 56,32,40,8,"Portrait",.Portrait
End Dialog
Dim SampleDialog As SampleDialogTemplate
SampleDialog.Printing = 1
r% = Dialog(SampleDialog)
End Sub
DlgSetPicture (statement)
Description Changes the content of the specified picture or picture button control.
Parameter Description
ControlName String containing the name of the .Identifier parameter associated with a control in the
$ dialog box template. A case-insensitive comparison is used to locate the specified control
within the template. Alternatively, by specifying the ControlIndex parameter, a control
can be referred to using its index in the dialog box template (0 is the first control in the
template, 1 is the second, and so on).
PictureName String containing the name of the picture. If PictureType is 0, then this parameter
$ specifies the name of the file containing the image. If PictureType is 10, then PictureName
$ specifies the name of the image within the resource of the picture library. If PictureName
$ is empty, then the current picture associated with the specified control will be deleted.
Thus, a technique for conserving memory and resources would involve setting the picture
to empty before hiding a picture control.
PictureType Integer specifying the source for the image. The following sources are supported:
10 The image is contained in the picture library specified by the Begin Dialog
statement. When this type is used, the PictureName$ parameter must be specified
with the Begin Dialog statement.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 292
Example
Sub Main()
DlgSetPicture "Picture1","\windows\checks.bmp",0 'Set picture from a file.
DlgSetPicture 27,"FaxReport",10 'Set control 10's image
'from a library.
End Sub
See Also DlgEnable (page 284) (function); DlgEnable (page 285) (statement); DlgFocus (page 286) (function);
DlgFocus (page 287) (statement); DlgListBoxArray (page 287) (function); DlgListBoxArray (page
288) (statement); DlgText (page 292) (statement); DlgText$ (page 293) (function); DlgValue (page
294) (function); DlgValue (page 295) (statement); DlgVisible (page 296) (statement); DlgVisible
(page 296) (function), Picture (page 438) (statement), PictureButton (page 439) (statement).
Notes Picture controls can contain either bitmaps or WMFs (Windows metafiles). When extracting images from
a picture library, the Basic Control Engine assumes that the resource type for metafiles is 256. Picture
libraries are implemented as DLLs on the Windows and Win32 platforms.
DlgText (statement)
Comments The effect of this statement depends on the type of the specified control:
Drop Sets the current selection to the item matching NewText$. If an exact match cannot be found,
list box the DlgText statement searches from the first item looking for an item that starts with NewText
$. If no match is found, then the selection is removed.
List Sets the current selection to the item matching NewText$. If an exact match cannot be found,
box the DlgText statement searches from the first item looking for an item that starts with NewText
$. If no match is found, then the selection is removed.
Combo Sets the content of the edit field of the combo box to NewText$.
box
The ControlName$ parameter contains the name of the .Identifier parameter associated with a control
in the dialog box template. A case-insensitive comparison is used to locate the specific control within the
template. Alternatively, by specifying the ControlIndex parameter, a control can be referred to using its
index in the dialog box template (0 is the first control in the template, 1 is the second, and so on).
Example
Sub Main()
DlgText "GroupBox1","Save Options" 'Change text of group box 1.
If DlgText$(9) = "Save Options" Then
DlgText 9,"Editing Options" 'Change text to "Editing Options".
End If
End Sub
See Also DlgEnable (page 284) (function); DlgEnable (page 285) (statement); DlgFocus (page 286) (function);
DlgFocus (page 287) (statement); DlgListBoxArray (page 287) (function); DlgListBoxArray (page
288) (statement); DlgSetPicture (page 291) (statement); DlgText (page 292) (statement); DlgValue
(page 295) (statement); DlgValue (page 294) (function); DlgVisible (page 296) (statement);
DlgVisible (page 296) (function).
DlgText$ (function)
Comments The text returned depends on the type of the specified control:
Drop list box Returns the currently selected item. A zero-length string is returned if no item is currently
selected.
List box Returns the currently selected item. A zero-length string is returned if no item is currently
selected.
Combo box Returns the content of the edit field portion of the combo box.
The ControlName$ parameter contains the name of the .Identifier parameter associated with a control
in the dialog box template. A case-insensitive comparison is used to locate the specific control within the
template. Alternatively, by specifying the ControlIndex parameter, a control can be referred to using its
index in the dialog box template (0 is the first control in the template, 1 is the second, and so on).
Example This code fragment makes sure the user enters a correct value. If not, the control returns focus back to
the TextBox for correction.
Function DlgProc(ControlName$,Action%,SuppValue%) As Integer
If Action% = 2 and ControlName$ = "OK" Then
If IsNumeric(DlgText$("TextBox1")) Then
Msgbox "Duly Noted."
Else
Msgbox "Sorry, you must enter a number."
DlgFocus "TextBox1"
DlgProc = 1
End If
End If
End Function
Sub Main()
Dim ListBox1$()
Begin Dialog UserDialog ,,112,74,"Untitled",.DlgProc
TextBox 12,20,88,12,.TextBox1
OKButton 12,44,40,14
CancelButton 60,44,40,14
Text 12,11,88,8,"Enter Desired Salary:",.Text1
End Dialog
Dim d As UserDialog
Dialog d
End Sub
See Also DlgControlId (page 283) (function); DlgEnable (page 284) (function); DlgEnable (page 285)
(statement); DlgFocus (page 286) (function); DlgFocus (page 287) (statement); DlgListBoxArray (page
287) (function); DlgListBoxArray (page 288) (statement); DlgSetPicture (page 291) (statement);
DlgText (page 292) (statement); DlgValue (page 294) (function); DlgValue (page 295) (statement);
DlgVisible (page 296) (statement); DlgVisible (page 296) (function).
DlgValue (function)
Comments The value of any given control depends on its type, according to the following table:
Option The index of the selected option button within the group (0 is the first option button, 1 is the
group second, and so on).
A runtime error is generated if DlgValue is used with controls other than those listed in the above table.
The ControlName$ parameter contains the name of the .Identifier parameter associated with a control in
the dialog box template. Alternatively, by specifying the ControlIndex parameter, a control can be referred
to using its index in the dialog box template (0 is the first control in the template, 1 is the second, and so
on).
See Also DlgControlId (page 283) (function); DlgEnable (page 284) (function); DlgEnable (page 285)
(statement); DlgFocus (page 286) (function); DlgFocus (page 287) (statement); DlgListBoxArray (page
287) (function); DlgListBoxArray (page 288) (statement); DlgSetPicture (page 291) (statement);
DlgText (page 292) (statement); DlgText$ (page 293) (function); DlgValue (page 295) (statement);
DlgVisible (page 296) (statement); DlgVisible (page 296) (function).
DlgValue (statement)
Comments The value of any given control is an Integer and depends on its type, according to the following table:
Option The index of the new selected option button within the group (0 is the first option button, 1 is
group the second, and so on).
A runtime error is generated if DlgValue is used with controls other than those listed in the above table.
The ControlName$ parameter contains the name of the .Identifier parameter associated with a control
in the dialog box template. A case-insensitive comparison is used to locate the specific control within the
template. Alternatively, by specifying the ControlIndex parameter, a control can be referred to using its
index in the dialog box template (0 is the first control in the template, 1 is the second, and so on).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 296
See Also DlgControlId (page 283) (function); DlgEnable (page 284) (function); DlgEnable (page 285)
(statement); DlgFocus (page 286) (function); DlgFocus (page 287) (statement); DlgListBoxArray (page
287) (function); DlgListBoxArray (page 288) (statement); DlgSetPicture (page 291) (statement);
DlgText (page 292) (statement); DlgText$ (page 293) (function); DlgValue (page 294) (function);
DlgVisible (page 296) (statement); DlgVisible (page 296) (function).
DlgVisible (function)
Description Returns True if the specified control is visible; returns False otherwise .
The ControlName$ parameter contains the name of the .Identifier parameter associated with a control in
the dialog box template. Alternatively, by specifying the ControlIndex parameter, a control can be referred
to using its index in the template (0 is the first control in the template, 1 is the second, and so on). A
runtime error is generated if DlgVisible is called with no user dialog is active.
Example
Sub Main()
If DlgVisible("Portrait") Then Beep
See Also DlgControlId (page 283) (function); DlgEnable (page 284) (function); DlgEnable (page 285)
(statement); DlgFocus (page 286) (function); DlgFocus (page 287) (statement); DlgListBoxArray (page
287) (function); DlgListBoxArray (page 288) (statement); DlgSetPicture (page 291) (statement);
DlgText (page 292) (statement); DlgText$ (page 293) (function); DlgValue (page 295) (statement);
DlgValue (page 295) (statement); DlgVisible (page 296) (function).
DlgVisible (statement)
Comments Hidden controls cannot be seen in the dialog box and cannot receive the focus using Tab. The isOn
parameter is an Integer specifying the new state of the control. It can be any of the following values:
Omitted Toggles the visibility of the control. Option buttons can be manipulated individually (by specifying
an individual option button) or as a group (by specifying the name of the option group).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 297
The ControlName$ parameter contains the name of the .Identifier parameter associated with a control
in the dialog box template. A case-insensitive comparison is used to locate the specific control within the
template. Alternatively, by specifying the ControlIndex parameter, a control can be referred to using its
index in the dialog box template (0 is the first control in the template, 1 is the second, and so on).
Picture Caching When the dialog box is first created and before it is shown, the Basic Control Engine
calls the dialog function with action set to 1. At this time, no pictures have been loaded into the picture
controls contained in the dialog box template. After control returns from the dialog function and before the
dialog box is shown, the Basic Control Engine will load the pictures of all visible picture controls. Thus, it
is possible for the dialog function to hide certain picture controls, which prevents the associated pictures
from being loaded and causes the dialog box to load faster. When a picture control is made visible for the
first time, the associated picture will then be loaded.
Example This example creates a dialog box with two panels. The DlgVisible statement is used to show or hide the
controls of the different panels.
Sub EnableGroup(start%,finish%)
For i = 6 To 13 'Disable all options.
DlgVisible i,False
Next i
For i = start% To finish% 'Enable only the right ones.
DlgVisible i,True
Next i
End Sub
Function DlgProc(ControlName$,Action%,SuppValue%)
If Action% = 1 Then
DlgValue "WhichOptions",0 'Set to save options.
EnableGroup 6,8 'Enable the save options.
End If
If Action% = 2 And ControlName$ = "SaveOptions" Then
EnableGroup 6,8 'Enable the save options.
DlgProc = 1 'Don't close the dialog box.
End If
If Action% = 2 And ControlName$ = "EditingOptions" Then
EnableGroup 9,13 'Enable the editing options.
DlgProc = 1 'Don't close the dialog box.
End If
End Function
Sub Main()
Begin Dialog OptionsTemplate 33,33,171,134,"Options",.DlgProc
'Background (controls 0-5)
GroupBox 8,40,152,84,""
OptionGroup .WhichOptions
OptionButton 8,8,59,8,"Save Options",.SaveOptions
OptionButton 8,20,65,8,"Editing Options",.EditingOptions
OKButton 116,7,44,14
CancelButton 116,24,44,14
See Also DlgControlId (page 283) (function); DlgEnable (page 284) (function); DlgEnable (page 285)
(statement); DlgFocus (page 286) (function); DlgFocus (page 287) (statement); DlgListBoxArray (page
287) (function); DlgListBoxArray (page 288) (statement); DlgSetPicture (page 291) (statement);
DlgText (page 292) (statement); DlgText$ (page 293) (function); DlgValue (page 295) (statement);
DlgValue (page 294) (function); DlgVisible (page 296) (statement).
Do...Loop (statement)
Description Repeats a block of Basic Control Engine statements while a condition is True or until a condition is True
.
Comments If the {While | Until} conditional clause is not specified, then the loop repeats the statements forever
(or until the script encounters an Exit Do statement). The condition parameter specifies any Boolean
expression.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 299
Examples
Sub Main()
'This first example uses the Do...While statement, which performs
'the iteration, then checks the condition, and repeats if the
'condition is True.
Dim a$(100)
i% = -1
Do
i% = i% + 1
If i% = 0 Then
a(i%) = Dir("*")
Else
a(i%) = Dir
End If
Loop While(a(i%) <> "" And i% <= 99)
r% = SelectBox(i% & " files found",,a)
End Sub
Sub Main()
'This second example uses the Do While...Loop, which checks the
'condition and then repeats if the condition is True.
Dim a$(100)
i% = 0
a(i%) = Dir("*")
Do While (a(i%) <> "") And (i% <= 99)
i% = i% + 1
a(i%) = Dir
Loop
r% = SelectBox(i% & " files found",,a)
End Sub
Sub Main()
'This third example uses the Do Until...Loop, which does the
'iteration and then checks the condition and repeats if the
'condition is True.
Dim a$(100)
i% = 0
a(i%) = Dir("*")
Do Until (a(i%) = "") Or (i% = 100)
i% = i% + 1
a(i%) = Dir
Loop
r% = SelectBox(i% & " files found",,a)
End Sub
Sub Main()
'This last example uses the Do...Until Loop, which performs the
'iteration first, checks the condition, and repeats if the
'condition is True.
Dim a$(100)
i% = -1
Do
i% = i% + 1
If i% = 0 Then
a(i%) = Dir("*")
Else
a(i%) = Dir
End If
Loop Until (a(i%) = "") Or (i% = 100)
r% = SelectBox(i% & " files found",,a)
End Sub
See Also For...Next (page 347) (statement); While ...WEnd (page 522) (statement).
Notes: Due to errors in program logic, you can inadvertently create infinite loops in your code. You can break out
of infinite loops using Ctrl+Break.
DoEvents (function)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 300
Syntax DoEvents[()]
Comments This statement yields control to the operating system, allowing other applications to process mouse,
keyboard, and other messages. If a SendKeys statement is active, this statement waits until all the keys
in the queue have been processed.
Example The following routine explicitly yields to allow other applications to execute and refresh on a regular basis.
Sub Main()
Open "test.txt" For Output As #1
For i = 1 To 10000
Print #1,"This is a test of the system and such."
r = DoEvents
Next i
MsgBox "The DoEvents return value is: " & r
Close #1
End Sub
DoEvents (statement)
Syntax DoEvents
Comments This statement yields control to the operating system, allowing other applications to process mouse,
keyboard, and other messages. If a SendKeys statement is active, this statement waits until all the keys
in the queue have been processed.
Examples This first example shows a script that takes a long time and hogs the system. The following routine
explicitly yields to allow other applications to execute and refresh on a regular basis.
Sub Main()
Open "test.txt" For Output As #1
For i = 1 To 10000
Print #1,"This is a test of the system and stuff."
DoEvents
Next i
Close #1
End Sub
In this second example, the DoEvents statement is used to wait until the queue has been completely
flushed.
Sub Main()
id = Shell("notepad.exe",3) 'Start new instance of Notepad.
SendKeys "This is a test.",False 'Send some keys.
oEvents 'Wait for the keys to play back.
End Sub
Syntax Double
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 301
Description A data type used to declare variables capable of holding real numbers with 15–16 digits of precision.
Comments Double variables are used to hold numbers within the following ranges:
Sign Range
-4.94066E-324
• Internally, doubles are 8-byte (64-bit) IEEE values. Thus, when appearing within a structure, doubles
require 8 bytes of storage. When used with binary or random files, 8 bytes of storage are required.
• A 1-bit sign
• An 11-bit exponent
• A 53-bit significand (mantissa)
See Also Currency (page 259) (data type); Date (page 263) (data type); Integer (page 377) (data type); Long
(page 398) (data type); Object (page 422) (data type); Single (page 479) (data type); String (page
494) (data type); Variant (page 515) (data type); Boolean (page 233) (data type); DefType (page
276) (statement); CDbl (page 237) (function).
DropListBox (statement)
Comments When the dialog box is invoked, the drop list box will be filled with the elements contained in
ArrayVariable. Drop list boxes are similar to combo boxes, with the following exceptions:
• The list box portion of a drop list box is not opened by default. The user must open it by clicking the
down arrow.
• The user cannot type into a drop list box. Only items from the list box may be selected. With combo
boxes, the user can type the name of an item from the list directly or type the name of an item that is
not contained within the combo box.
This statement can only appear within a dialog box template (i.e., between the Begin Dialog and End
Dialog statements). The DropListBox statement requires the following parameters:
Parameter Description
X, Y Integer coordinates specifying the position of the control (in dialog units) static to the
upper left corner of the dialog box.
width, height Integer coordinates specifying the dimensions of the control in dialog units.
ArrayVariable Single-dimensioned array used to initialize the elements of the drop list box. If this array
has no dimensions, then the drop list box will be initialized with no elements. A runtime
error results if the specified array contains more than one dimension.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 302
ArrayVariable can specify an array of any fundamental data type (structures are not
allowed). Null and Empty values are treated as zero-length strings.
.Identifier Name by which this control can be referenced by statements in a dialog function (such
as DlgFocus and DlgEnable ). This parameter also creates an integer variable whose
value corresponds to the index of the drop list box's selection (0 is the first item, 1 is the
second, and so on). This variable can be accessed using the following syntax:
DialogVariable.Identifier
Example This example allows the user to choose a field name from a drop list box.
Sub Main()
Dim FieldNames$(4)
FieldNames$(0) = "Last Name"
FieldNames$(1) = "First Name"
FieldNames$(2) = "Zip Code"
FieldNames$(3) = "State"
FieldNames$(4) = "City"
Begin Dialog FindTemplate 16,32,168,48,"Find"
Text 8,8,37,8,"&Find what:"
DropListBox 48,6,64,80,FieldNames,.WhichField
OKButton 120,7,40,14
CancelButton 120,27,40,14
End Dialog
Dim FindDialog As FindTemplate
FindDialog.WhichField = 1
Dialog FindDialog
End Sub
See Also CancelButton (page 243) (statement); CheckBox (page 240) (statement); ComboBox (page 249)
(statement); Dialog (page 278) (function); Dialog (page 279) (statement); GroupBox (page 361)
(statement); ListBox (page 394) (statement); OKButton (page 426) (statement); OptionButton (page
434) (statement); OptionGroup (page 435) (statement); Picture (page 438) (statement); PushButton
(page 447) (statement); Text (page 502) (statement); TextBox (page 503) (statement); Begin (page
231) Dialog (page 231) (statement), PictureButton (page 439) (statement).
ebAbort (constant)
ebAbortRetryIgnore (constant)
ebApplicationModal (constant)
ebArchive (constant)
ebBold (constant)
ebBoldItalic (constant)
ebBoolean (constant)
ebCancel (constant)
ebCritical (constant)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 303
ebCurrency (constant)
ebDataObject (constant)
ebDate (constant)
ebDefaultButton1 (constant)
ebDefaultbutton2 (constant)
ebDefaultbutton3 (constant)
ebDirectory (constant)
ebDos (constant)
ebDouble (constant)
ebEmpty (constant)
ebError (constant)
ebExclamation (constant)
ebHidden (constant)
ebIgnore (constant)
ebInformation (constant)
ebInteger (constant)
ebItalic (constant)
ebLong (constant)
ebNo (constant)
ebNone (constant)
ebNormal (constant)
ebNull (constant)
ebObject (constant)
ebOK (constant)
ebOKCancel (constant)
ebOKOnly (constant)
ebQuestion (constant)
ebReadOnly (constant)
ebRegular (constant)
ebRetry (constant)
ebRetryCancel (constant)
ebSingle (constant)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 304
ebString (constant)
ebSystem (constant)
ebSystemModal (constant)
ebVariant (constant)
ebVolume (constant
ebYes (constant)
ebYesNo (constant)
ebYesNoCancel (constant)
Empty (constant)
End (statement)
EOF (function)
Eqv (operator)
Erase (statement)
Erl (function)
Err (statement)
Err.Clear (method)
Err.Description (property)
Err.HelpContext (property)
Err.HelpFile (property)
Err.LastDLLError (property)
Err.Number (property)
Err.Raise (method)
Err.Source (property)
Error (statement)
Exit Do (statement)
Exp (function)
ebAbort (constant)
Description Returned by the MsgBox function when the Abort button is chosen.
Example This example displays a dialog box with Abort, Retry, and Ignore buttons.
Sub Main()
Again:
rc% = MsgBox("Do you want to continue?",ebAbortRetryIgnore)
If rc% = ebAbort or rc% = ebIgnore Then
End
ElseIf rc% = ebRetry Then
Goto Again
End If
End Sub
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement).
ebAbortRetryIgnore (constant)
Example This example displays a dialog box with Abort, Retry, and Ignore buttons.
Sub Main()
Again:
rc% = MsgBox("Do you want to continue?",ebAbortRetryIgnore)
If rc% = ebAbort or rc% = ebIgnore Then
End
ElseIf rc% = ebRetry Then
Goto Again
End If
End Sub
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement).
ebApplicationModal (constant)
Example This example displays an application-modal dialog box (which is the default).
Sub Main()
MsgBox "This is application-modal.",ebOKOnly Or ebApplicationModal
End Sub
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement).
ebArchive (constant)
Description Bit position of a file attribute indicating that a file hasn't been backed up.
Example This example dimensions an array and fills it with filenames with the Archive bit set.
Sub Main()
Dim s$()
FileList s$,"*",ebArchive
a% = SelectBox("Archived Files", "Choose one", s$)
If a% >= 0 Then 'If a% is -1, then the user pressed Cancel.
MsgBox "You selected Archive file: " & s$(a)
Else
MsgBox "No selection made."
End If
End Sub
See Also Dir, Dir$ (page 280) (functions); FileList (page 343) (statement); SetAttr (page 477)
(statement); GetAttr (page 357) (function); FileAttr (page 339) (function).
ebBold (constant)
Description Used with the Text and TextBox statement to specify a bold
font.
Example
Sub Main()
Begin Dialog UserDialog 16,32,232,132,"Bold Font Demo"
Text 10,10,200,20,"Hello, world.",,"Helv",24,ebBold
TextBox 10,35,200,20,.Edit,,"Times New Roman",16,ebBold
OKButton 96,110,40,14
End Dialog
Dim a As UserDialog
Dialog a
End Sub
See Also Text (page 502) (statement), TextBox (page 503) (statement).
ebBoldItalic (constant)
Description Used with the Text and TextBox statement to specify a bold-italic font.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 307
Example
Sub Main()
Begin Dialog UserDialog 16,32,232,132,"Bold-Italic Font Demo"
Text 10,10,200,20,"Hello, world.",,"Helv",24,ebBoldItalic
TextBox 10,35,200,20,.Edit,,"Times New Roman",16,ebBoldItalic
OKButton 96,110,40,14
End Dialog
Dim a As UserDialog
Dialog a
End Sub
See Also Text (page 502) (statement), TextBox (page 503) (statement).
ebBoolean (constant)
Example
Sub Main()
Dim MyVariant as variant
MyVariant = True
If VarType(MyVariant) = ebBoolean Then
MyVariant = 5.5
End If
End Sub
ebCancel (constant)
Description Returned by the MsgBox function when the Cancel button is chosen.
Example
Sub Main()
'Invoke MsgBox and check whether the Cancel button was pressed.
rc% = MsgBox("Are you sure you want to quit?",ebOKCancel)
If rc% = ebCancel Then
MsgBox "The user clicked Cancel."
End If
End Sub
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement).
ebCritical (constant)
Example
Sub Main()
'Invoke MsgBox with Abort, Retry, and Ignore buttons and a Stop icon.
rc% = MsgBox("Disk drive door is open.",ebAbortRetryIgnore Or ebCritical)
If rc% = 3 Then
'The user selected Abort from the dialog box.
MsgBox "The user clicked Abort."
End If
End Sub
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement).
ebCurrency (constant)
See Also VarType (page 516) (function); Variant (page 515) (data type).
ebDataObject (constant)
See Also VarType (page 516) (function); Variant (page 515) (data
type).
ebDate (constant)
Example
Sub Main()
Dim MyVariant as Variant
If VarType(MyVariant) = ebDate Then
MsgBox "This variable is a Date type!"
Else
MsgBox "This variable is not a Date type!"
End If
End Sub
ebDefaultButton1 (constant)
Example This example invokes MsgBox with the focus on the OK button by default.
Sub Main()
rc% = MsgBox("Are you sure you want to quit?",ebOKCancel Or ebDefaultButton1)
End Sub
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement).
ebDefaultButton2 (constant)
Example This example invokes MsgBox with the focus on the Cancel button by default.
Sub Main()
rc% = MsgBox("Are you sure you want to quit?",ebOKCancel Or ebDefaultButton2)
End Sub
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement).
ebDefaultButton3 (constant)
Example This example invokes MsgBox with the focus on the Ignore button by default.
Sub Main()
rc% = MsgBox("Disk drive door open.",ebAbortRetryIgnore Or ebDefaultButton3)
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 310
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement).
ebDirectory (constant)
Description Bit position of a file attribute indicating that a file is a directory entry.
Example This example dimensions an array and fills it with directory names using the ebDirectory constant.
Sub Main()
Dim s$()
FileList s$,"c:\*",ebDirectory
a% = SelectBox("Directories", "Choose one:", s$)
If a% >= 0 Then
MsgBox "You selected directory: " & s(a%)
Else
MsgBox "No selection made."
End If
End Sub
See Also Dir, Dir$ (page 280) (functions); FileList (page 343) (statement); SetAttr (page 477)
(statement); GetAttr (page 357) (function); FileAttr (page 339) (function).
ebDos (constant)
ebDouble (constant)
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement); VarType
(page 516) (function); Variant (page 515) (data type).
ebEmpty (constant)
Example
Sub Main()
Dim MyVariant as Variant
If VarType(MyVariant) = ebEmpty Then
MsgBox "This variant has not been assigned a value yet!"
End If
End Sub
See Also VarType (page 516) (function); Variant (page 515) (data type).
ebError (constant)
See Also VarType (page 516) (function); Variant (page 515) (data type).
ebExclamation (constant)
Example This example displays a dialog box with an OK button and an exclamation icon.
Sub Main()
MsgBox "Out of memory saving to disk.",ebOKOnly Or ebExclamation
End Sub
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement).
ebHidden (constant)
Example This example dimensions an array and fills it with filenames using the ebHidden attribute.
Sub Main()
Dim s$()
FileList s$,"*",ebHidden
If ArrayDims(s$) = 0 Then
MsgBox "No hidden files found!"
End
End If
a% = SelectBox("Hidden Files","Choose one", s$)
If a% >= 0 Then
MsgBox "You selected hidden file " & s(a%)
Else
MsgBox "No selection made."
End If
End Sub
See Also Dir, Dir$ (page 280) (functions); FileList (page 343) (statement); SetAttr (page 477)
(statement); GetAttr (page 357) (function); FileAttr (page 339) (function).
ebIgnore (constant)
Description Returned by the MsgBox function when the Ignore button is chosen.
Example This example displays a critical error dialog box and sees what the user wants to do.
Sub Main()
rc% = MsgBox("Printer out of paper.",ebAbortRetryIgnore)
If rc% = ebIgnore Then
'Continue printing here.
End If
End Sub
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement).
ebInformation (constant)
Example This example displays a dialog box with the Information icon.
Sub Main()
MsgBox "You just deleted your file!",ebOKOnly Or ebInformation
End Sub
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement).
ebInteger (constant)
Example This example defines a function that returns True if a variant contains an Integer value (either a 16-bit or
32-bit Integer).
Function IsInteger(v As Variant) As Boolean
If VarType(v) = ebInteger Or VarType(v) = ebLong Then
IsInteger = True
Else
IsInteger = False
End If
End Function
Sub Main()
Dim i as Integer
i = 123
If IsInteger(i) then
Msgbox "i is an Integer."
End If
End Sub
See Also VarType (page 516) (function); Variant (page 515) (data type).
ebItalic (constant)
Description Used with the Text and TextBox statement to specify an italic
font.
Example
Sub Main()
Begin Dialog UserDialog 16,32,232,132,"Italic Font Demo"
Text 10,10,200,20,"Hello, world.",,"Helv",24,ebItalic
TextBox 10,35,200,20,.Edit,,"Times New Roman",16,ebItalic
OKButton 96,110,40,14
End Dialog
Dim a As UserDialog
Dialog a
End Sub
See Also Text (page 502) (statement), TextBox (page 503) (statement).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 314
ebLong (constant)
ebNo (constant)
Example This example asks a question and queries the user's response.
Sub Main()
rc% = MsgBox("Do you want to update the glossary?",ebYesNo)
If rc% = ebNo Then
MsgBox "The user clicked 'No'." 'Don't update glossary.
End If
End Sub
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement).
ebNone (constant)
Comments This value can be used with the Dir$ and FileList commands. These functions will return only files with
no attributes set when used with this constant. This constant is equal to 64.
Example This example dimensions an array and fills it with filenames with no attributes set.
Sub Main()
Dim s$()
FileList s$,"*",ebNone
If ArrayDims(s$) = 0 Then
MsgBox "No files found without attributes!"
End
End If
a% = SelectBox("No Attributes", "Choose one", s$)
If a% >= 0 Then
MsgBox "You selected file " & s(a%)
Else
MsgBox "No selection made."
End If
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 315
See Also Dir, Dir$ (page 280) (functions); FileList (page 343) (statement); SetAttr (page 477) (statement);
GetAttr (page 357) (function); FileAttr (page 339) (function).
ebNormal (constant)
Comments This value can be used with the Dir$ and FileList commands and will return files with the Archive,
Volume, ReadOnly, or no attributes set. It will not match files with Hidden, System, or Directory attributes.
This constant is equal to 0.
Example This example dimensions an array and fills it with filenames with Normal attributes.
Sub Main()
Dim s$()
FileList s$,"*", ebNormal
If ArrayDims(s$) = 0 Then
MsgBox "No filesfound!"
End
End If
a% = SelectBox("Normal Files", "Choose one", s$)
If a% >= 0 Then
MsgBox "You selected file " & s(a%)
Else
MsgBox "No selection made."
End If
End Sub
See Also Dir, Dir$ (page 280) (functions); FileList (page 343) (statement); SetAttr (page 477) (statement);
GetAttr (page 357) (function); FileAttr (page 339) (function).
ebNull (constant)
Example
Sub Main()
Dim MyVariant
MyVariant = Null
If VarType(MyVariant) = ebNull Then
MsgBox "This variant is Null"
End If
End Sub
ebObject (constant)
Description Number representing the type of an Object variant (an OLE automation
object).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 316
Example
Sub Main()
Dim MyVariant
If VarType(MyVariant) = ebObject Then
MsgBox MyVariant.Value
Else
MsgBox "'MyVariant' is not an object."
End If
End Sub
See Also VarType (page 516) (function); Variant (page 515) (data type).
ebOK (constant)
Example This example displays a dialog box that allows the user to cancel.
Sub Main()
rc% = MsgBox("Are you sure you want to exit Windows?",ebOKCancel)
If rc% = ebOK Then System.Exit
End Sub
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement).
ebOKCancel (constant)
Example This example displays a dialog box that allows the user to cancel.
Sub Main()
rc% = MsgBox("Are you sure you want to exit Windows?",ebOKCancel)
If rc% = ebOK Then System.Exit
End Sub
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement).
ebOKOnly (constant)
Example This example informs the user of what is going on (no options).
Sub Main()
MsgBox "The system has been reset.",ebOKOnly
End Sub
ebQuestion (constant)
Example This example displays a dialog box with OK and Cancel buttons and a question icon.
Sub Main()
rc% = MsgBox("OK to delete file?",ebOKCancel Or ebQuestion)
End Sub
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement)
ebReadOnly (constant)
Example This example dimensions an array and fills it with filenames with ReadOnly attributes.
Sub Main()
Dim s$()
FileList s$, "*", ebReadOnly
If ArrayDims(s$) = 0 Then
MsgBox "No read only files found!"
End
End If
a% = SelectBox("ReadOnly", "Choose one", s$)
If a% >= 0 Then
MsgBox "You selected file " & s(a%)
Else
MsgBox "No selection made."
End If
End Sub
See Also Dir, Dir$ (page 280) (functions); FileList (page 343) (statement); SetAttr (page 477)
(statement); GetAttr (page 357) (function); FileAttr (page 339) (function).
ebRegular (constant)
Description Used with the Text and TextBox statement to specify an normal-styled font (i.e., neither bold or
italic).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 318
Example
Sub Main()
Begin Dialog UserDialog 16,32,232,132,"Regular Font Demo"
Text 10,10,200,20,"Hello, world.",,"Helv",24,ebRegular
TextBox 10,35,200,20,.Edit,,"Times New Roman",16,ebRegular
OKButton 96,110,40,14
End Dialog
Dim a As UserDialog
Dialog a
End Sub
See Also Text (page 502) (statement), TextBox (page 503) (statement)
ebRetry (constant)
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement)
ebRetryCancel (constant)
Example This example invokes a dialog box with Retry and Cancel buttons.
Sub Main()
rc% = MsgBox("Unable to open file.",ebRetryCancel)
End Sub
ebSingle (constant)
Example This example defines a function that returns True if the passed variant is a Real number.
Function IsReal(v As Variant) As Boolean
If VarType(v) = ebSingle Or VarType(v) = ebDouble Then
IsReal = True
Else
IsReal = False
End If
End Function
Sub Main()
Dim i as Integer
i = 123
If IsReal(i) then
Msgbox "i is Real."
End If
End Sub
See Also VarType (page 516) (function); Variant (page 515) (data type).
ebString (constant)
Example
Sub Main()
Dim MyVariant as variant
MyVariant = "This is a test."
If VarType(MyVariant) = ebString Then
MsgBox "Variant is a string."
End If
End Sub
ebSystem (constant)
Description Bit position of a file attribute indicating that a file is a system file.
Example This example dimensions an array and fills it with filenames with System attributes.
Sub Main()
Dim s$()
FileList s$,"*",ebSystem
a% = SelectBox("System Files", "Choose one", s$)
If a% >= 0 Then
MsgBox "You selected file " & s(a%)
Else
MsgBox "No selection made."
End If
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 320
See Also Dir, Dir$ (page 280) (functions); FileList (page 343) (statement); SetAttr (page 477)
(statement); GetAttr (page 357) (function); FileAttr (page 339) (function).
ebSystemModal (constant)
Example
Sub Main()
MsgBox "All applications are halted!",ebSystemModal
End Sub
See Also ebApplicationModal (page 305) (constant); Constants (topic); MsgBox (page 409)
(function); MsgBox (page 411) (statement).
ebVariant (constant)
Comments Currently, it is not possible for variants to use this subtype. This constant is equal to 12.
See Also VarType (page 516) (function); Variant (page 515) (data type).
ebVolume (constant)
Description Bit position of a file attribute indicating that a file is the volume label.
Example This example dimensions an array and fills it with filenames with Volume attributes.
Sub Main()
Dim s$()
FileList s$, "*", ebVolume
If ArrayDims(s$) > 0 Then
MsgBox "The volume name is: " & s(1)
Else
MsgBox "No volumes found."
End If
End Sub
See Also Dir, Dir$ (page 280) (functions); FileList (page 343) (statement); SetAttr (page 477)
(statement); GetAttr (page 357) (function); FileAttr (page 339) (function).
ebYes (constant)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 321
ebYesNo (constant)
Example This example displays a dialog box with Yes and No buttons.
Sub Main()
rc% = MsgBox("Are you sure you want to remove all formatting?",ebYesNo)
End Sub
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement).
ebYesNoCancel (constant)
Example This example displays a dialog box with Yes, No, and Cancel buttons.
Sub Main()
rc% = MsgBox("Format drive C:?",ebYesNoCancel)
If rc% = ebYes Then
MsgBox "The user chose Yes."
End If
End Sub
See Also MsgBox (page 409) (function); MsgBox (page 411) (statement).
Empty (constant)
Comments The Empty value has special meaning indicating that a Variant is uninitialized. When Empty is
assigned to numbers, the value 0 is assigned. When Empty is assigned to a String , the string is
assigned a zero-length string.
Example
Sub Main()
Dim a As Variant
a = Empty
MsgBox "This string is" & a & "concatenated with Empty"
MsgBox "5 + Empty = " & (5 + a)
End Sub
See Also Null (page 421) (constant); Variant (page 515) (data type); VarType (page 516) (function).
End (statement)
Syntax End
Description Terminates execution of the current script, closing all open files.
See Also Close (page 248) (statement); Stop (page 491) (statement); Exit For (page 334) (statement); Exit Do
(page 334) (statement); Exit Function (page 335) (statement); Exit Sub (page 335) (function).
Syntax Begin Dialog (page 231) DialogName [x],[y],width,height,title$ [,[.DlgProc] [,[PicName$] [,style]]] Dialog
Statements End Dialog
Description Defines the end of the dialog box template for use with the Dialog statement and function.
See Also Begin Dialog (page 231) (statement), CancelButton (page 243) (statement); CheckBox (page 240)
(statement); ComboBox (page 249) (statement); Dialog (page 278) (function); Dialog (page 279)
(statement); DlgProc (page 289) (function); DropListBox (page 301) (statement); GroupBox (page
361) (statement); ListBox (page 394) (statement); OKButton (page 426) (statement); OptionButton
(page 434) (statement); OptionGroup (page 435) (statement); Picture (page 438) (statement;
PictureButton (page 439) (statement); PushButton (page 447) (statement); Text (page 502)
(statement); TextBox (page 503) (statement).
Note Within user dialog boxes, the default font is 8-point MS Sans Serif.
Comments Environ$ returns a String , whereas Environ returns a String variant. If variable$ is specified, then
this function looks for that variable$ in the environment. If the variable$ name cannot be found, then a
zero-length string is returned. If VariableNumber is specified, then this function looks for the Nth variable
within the environment (the first variable being number 1). If there is no such environment variable, then a
zero-length string is returned. Otherwise, the entire entry from the environment is returned in the following
format:
variable = value
Example This example looks for the DOS Comspec variable and displays the value in a dialog box.
Sub Main()
Dim a$(1)
a$(1) = Environ("SITE_Root")
MsgBox "My CIMPLICITY project directory is: " & a$(1)
End Sub
EOF (function)
Description Returns True if the end-of-file has been reached for the given file; returns False otherwise.
Comments The filenumber parameter is an Integer used by the Basic Control Engine to refer to the open file—the
number passed to the Open statement. With sequential files, EOF returns True when the end of the
file has been reached (i.e., the next file read command will result in a runtime error). With Random or
Binary files, EOF returns True after an attempt has been made to read beyond the end of the file.
Thus, EOF will only return True when Get was unable to read the entire record.
Example This example opens the autoexec.bat file and reads lines from the file until the end-of-file is reached.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
file$ = "c:\autoexec.bat"
Open file$ For Input As #1
Do While Not EOF(1)
Line Input #1,newline
Loop
Close
MsgBox "The last line of '" & file$ "' is:" & crlf & crlf & newline
End Sub
See Also Open (page 428) (statement); LOF (page 397) (function).
Eqv (operator)
Comments If both expressions are either Boolean , Boolean variants, or Null variants, then a logical equivalence
is performed as follows:
Binary Equivalence If the two expressions are Integer, then a binary equivalence is performed, returning
an Integer result. All other numeric types (including Empty variants) are converted to Long and a binary
equivalence is then performed, returning a Long result. Binary equivalence forms a new value based on
a bit-by-bit comparison of the binary representations of the two expressions, according to the following
table:
1 Eqv 1 = 1 Example
0 Eqv 1 = 0 5 01101001
1 Eqv 0 = 0 6 10101010
Example This example assigns False to A, performs some equivalent operations, and displays a dialog box with the
result. Since A is equivalent to False, and False is equivalent to 0, and by definition, A = 0, then the dialog
box will display "A is False."
Sub Main()
a = False
If ((a Eqv False) And (False Eqv 0) And (a = 0)) Then
MsgBox "a is False."
Else
MsgBox "a is True."
End If
End Sub
See Also Operator Precedence (page 431) (topic); Or (page 435) (operator); Xor (page 532) (operator); Imp
(page 371) (operator); And (page 204) (operator).
Erase (statement)
Comments For dynamic arrays, the elements are erased, and the array is redimensioned to have no dimensions
(and therefore no elements). For fixed arrays, only the elements are erased; the array dimensions are not
changed.
After a dynamic array is erased, the array will contain no elements and no dimensions. Thus, before the
array can be used by your program, the dimensions must be reestablished using the Redim statement.
Up to 32 parameters can be specified with the Erase statement.
The meaning of erasing an array element depends on the type of the element being erased:
String (variable-length) Frees the string, then sets the element to a zero-length string.
Object Decrements the reference count and sets the element to Nothing .
Example This example fills an array with a list of available disk drives, displays the list, erases the array and then
redisplays the list.
Sub Main()
Dim a$(10) 'Declare an array.
DiskDrives a 'Fill element 1 with a list of available disk drives.
r = SelectBox("Array Before Erase",,a)
Erase a$ 'Erase all elements in the array.
r = SelectBox("Array After Erase",,a)
End Sub
See Also Redim (page 459) (statement); Arrays (page 218) (topic).
Erl (function)
Syntax Erl[()]
Comments The first line of the script is 1, the second line is 2, and so on. The internal value of Erl is reset to 0 with
any of the following statements: Resume , Exit Sub , Exit Function . Thus, if you want to use this value
outside an error handler, you must assign it to a variable.
Example This example generates an error and then determines the line on which the error occurred.
Sub Main()
Dim i As Integer
On Error Goto Trap1
i = 32767 'Generate an error--overflow.
i = i + 1
Exit Sub
Trap1:
MsgBox "Error on line: " & Erl
Exit Sub 'Reset the error handler.
End Sub
See Also Err (page 326) (function); Error, Error$ (page 326) (functions); Error Handling (page 327) (topic).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 326
Err (function)
Err (statement)
Description Sets the value returned by the Err function to a specific Integer value.
Comments Only positive values less than or equal to 32767 can be used. Setting value to -1 has the side effect of
resetting the error state. This allows you to perform error trapping within an error handler. The ability to
reset the error handler while within an error trap is not standard Basic. Normally, the error handler is reset
only with the Resume , Exit Sub , or Exit Function statement.
Example This example forces error 10, with a subsequent transfer to the TestError label. TestError tests the error
and, if not error 55, resets Err to 999 (user-defined error) and returns to the Main subroutine.
Sub Main()
On Error Goto TestError
Error 10
MsgBox "The returned error is: '" & Err() & " - " & Error$ & "'"
Exit Sub
TestError:
If Err = 55 Then 'File already open.
MsgBox "Cannot copy an open file. Close it and try again."
Else
MsgBox "Error '" & Err & "' has occurred."
Err = 999
End If
Resume Next
End Sub
See Also Error (page 327) (statement); Error Handling (page 327) (topic).
Description Returns a String containing the text corresponding to the given error number or the most recent error.
Comments Error$ returns a String, whereas Error returns a String variant. The errornumber parameter is an
Integer containing the number of the error message to retrieve. If this parameter is omitted, then the
function returns the text corresponding to the most recent runtime error. If no runtime error has occurred,
then a zero-length string is returned. If the Error statement was used to generate a user-defined runtime
error, then this function will return a zero-length string ("").
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 327
Example This example forces error 10, with a subsequent transfer to the TestError label. TestError tests the error
and, if not error 55, resets Err to 999 (user-defined error) and returns to the Main subroutine.
Sub Main()
On Error Goto TestError
Error 10
MsgBox "The returned error is: '" & Err & " - " & Error & "'"
Exit Sub
TestError:
If Err = 55 Then 'File already open.
MsgBox "Cannot copy an open file. Close it and try again."
Else
MsgBox "Error '" & Err & "' has occurred."
Err = 999
End If
Resume Next
End Sub
See Also Erl (page 325) (function); Err (page 326) (function); Error Handling (page 327) (topic).
Error (statement)
Comments The errornumber parameter is any Integer containing either a built-in error number or a user-defined error
number. The Err function can be used within the error trap handler to determine the value of the error.
Example This example forces error 10, with a subsequent transfer to the TestError label. TestError tests the error
and, if not error 55, resets Err to 999 (user-defined error) and returns to the Main subroutine.
Sub Main()
On Error Goto TestError
Error 10
MsgBox "The returned error is: '" & Err() & " - " & Error$ & "'"
Exit Sub
TestError:
If Err = 55 Then 'File already open.
MsgBox "Cannot copy an open file. Close it and try again."
Else
MsgBox "Error '" & Err & "' has occurred."
Err = 999
End If
Resume Next
End Sub
See Also Err (page 326) (statement); Error Handling (page 327) (topic).
1. Visual Basic–compatible errors: These errors, numbered between 0 and 799, are numbered
and named according to the errors supported by Visual Basic.
2. Basic Control Engine script errors: These errors, numbered from 800 to 999, are unique to the
Basic Control Engine..
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 328
3. User-defined errors: These errors, equal to or greater than 1,000, are available for use by
extensions or by the script itself.
Err.Clear (method)
Syntax Err.Clear
Comments After this method has been called, the properties of the Err object will have the following values:
Property Value
Err.Description ""
Err.HelpContext 0
Err.HelpFile ""
Err.LastDLLError 0
Err.Number 0
Err.Source ""
The properties of the Err object are automatically reset when any of the following statements are
executed:
Example
'The following script gets input from the user using error
'checking.
Sub Main()
Dim x As Integer
On Error Resume Next
x = InputBox("Type in a number")
If Err.Number <> 0 Then
Err.Clear
x = 0
End If
MsgBox x
End Sub
See Also Error Handling (page 327) (topic), Err.Description (page 328) (property), Err.HelpContext (page 329)
(property), Err.HelpFile (page 330) (property), Err.LastDLLError (page 331) (property), Err.Number
(page 332) (property), Err.Source (page 333) (property)
Err.Description (property)
Comments For errors generated by BasicScript, the Err.Description property is automatically set. For user-defined
errors, you should set this property to be a description of your error. If you set the Err.Number property
to one of BasicScript’s internal error numbers and you don’t set the Err.Description property, then the
Err.Description property is automatically set when the error is generated (i.e., with Err.Raise).
Example
'The following script gets input from the user using error
'checking. When an error occurs, the Err.Description property
'is displayed to the user and execution continues with a default
'value.
Sub Main()
Dim x As Integer
On Error Resume Next
x = InputBox("Type in a number")
If Err.Number <> 0 Then
MsgBox "The following error occurred: "
& Err.Description
x = 0
End If
MsgBox x
End Sub
See Also Error Handling (page 327) (topic), Err.Clear (page 328) (method), Err.HelpContext (page 329)
(property), Err.HelpFile (page 330) (property), Err.LastDLLError (page 331) (property), Err.Number
(page 332) (property), Err.Source (page 333) (property)
Err.HelpContext (property)
Description Sets or retrieves the help context ID that identifies the help topic for information on the error.
Comments The Err.HelpContext property, together with the Err.HelpFile property, contain sufficient information to
display help for the error. When BasicScript generates an error, the Err.HelpContext property is set to
0 and the and the Err.HelpFile property is set to ""; the value of the Err.Number property is sufficient for
displaying help in this case. The exception is with errors generated by an OLE automation server; both the
Err.HelpFile and Err.HelpContext properties are set by the server to values appropriate for the generated
error. When generating your own user-define errors, you should set the Err.HelpContext property and the
Err.HelpFile property appropriately for your error. If these are not set, then BasicScript displays its own
help at an appropriate place.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 330
Example
'This example defines a replacement for InputBox that deals
'specifically with Integer values. If an error occurs, the
'function generates a user-defined error that can be trapped
'by the caller.
Function InputInteger(Prompt,Optional Title,Optional Def)
On Error Resume Next
Dim x As Integer
x = InputBox(Prompt,Title,Def)
If Err.Number Then
Err.HelpFile = "AZ.HLP"
Err.HelpContext = 2
Err.Description = "Integer value expected"
InputInteger = Null
Err.Raise 3000
End If
InputInteger = x
End Function
Sub Main
Dim x As Integer
Do
On Error Resume Next
x = InputInteger("Enter a number:")
If Err.Number = 3000 Then
Msgbox "Invalid number, press ""F1"" to invoke help" _
,,,Err.HelpFile,Err.HelpContext
End If
Loop Until Err.Number <> 3000
End Sub
See Also Error Handling (page 327) (topic), Err.Clear (page 328) (method), Err.Description (page 328)
(property), Err.HelpFile (page 330) (property), Err.LastDLLError (page 331) (property), Err.Number
(page 332) (property), Err.Source (page 333) (property)
Err.HelpFile (property)
Description Sets or retrieves the name of the help file associated with the error.
Comments The Err.HelpFile property, together with the Err.HelpContents property, contain sufficient information
to display help for the error. When BasicScript generates an error, the Err.HelpContents property is
set to 0 and the Err.HelpFile property is set to ""; the value of the Err.Number property is sufficient for
displaying help in this case. The exception is with errors generated by an OLE automation server; both the
Err.HelpFile and Err.HelpContext properties are set by the server to values appropriate for the generated
error. When generating your own user-define errors, you should set the Err.HelpContext property and the
Err.HelpFile property appropriately for your error. If these are not set, then BasicScript displays its own
help at an appropriate place.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 331
Example
'This example defines a replacement for InputBox that deals
'specifically with Integer values. If an error occurs, the
'function generates a user-defined error that can be trapped
'by the caller.
Function InputInteger(Prompt,Optional Title,Optional Def)
On Error Resume Next
Dim x As Integer
x = InputBox(Prompt,Title,Def)
If Err.Number Then
Err.HelpFile = "AZ.HLP"
Err.HelpContext = 2
Err.Description = "Integer value expected"
InputInteger = Null
Err.Raise 3000
End If
InputInteger = x
End Function
Sub Main
Dim x As Integer
Do
On Error Resume Next
x = InputInteger("Enter a number:")
If Err.Number = 3000 Then
MsgBox "Invalid number, press ""F1"" to invoke help" _
,,, Err.HelpFile,Err.HelpContext
End If
Loop Until Err.Number <> 3000
End Sub
See Also Error Handling (page 327) (topic)m Err.Clear (page 328) (method), Err.HelpContext (page 329)
(property), Err.Description ( (page 328)(property), Err.LastDLLError (page 331) (property), Err.Number
(page 332) (property), Err.Source (page 333) (property)
Note The Err.HelpFile property can be set to any valid Windows help file (i.e., a file with a .HLP extension
compatible with the WINHELP help engine).
Err.LastDLLError (property)
Syntax Err.LastDLLError
Description Returns the last error generated by an external call, i.e. a call to a routine declared with the Declare
statement that resides in an external module.
Comments The Err.LastDLLError property is automatically set when calling a routine defined in an external module. If
no error occurs within the external call this property will automatically be set to 0.
Example
'The following script calls the GetCurrentDirectoryA. If an
'error occurs, this Win32 function sets the Err.LastDLLError
'property which can be checked for.
Declare Sub GetCurrentDirectoryA Lib "kernel32" (ByVal DestLen _
As Integer,ByVal lpDest As String)
Sub Main()
Dim dest As String * 256
Err.Clear
GetCurrentDirectoryA len(dest),dest
If Err.LastDLLError <> 0 Then
MsgBox "Error " & Err.LastDLLError & " occurred."
Else
MsgBox "Current directory is " & dest
End If
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 332
See Also Error Handling (page 327) (topic), Err.Clear (page 328) (method), Err.HelpContext (page 329)
(property), Err.Description (page 328) (property), Err.HelpFile (page 330) (property), Err.Number
(page 332) (property), Err.Source (page 333) (property)
Note This property is set by DLL routines that set the last error using the Win32 function SetLastError().
BasicScript uses the Win32 function GetLastError() to retrieve the value of this property. The value 0 is
returned when calling DLL routines that do not set an error.
Err.Number (property)
Comments The Err.Number property is set automatically when an error occurs. This property can be used within an
error trap to determine which error occurred. You can set the Err.Number property to any Long value. The
Number property is the default property of the Err object. This allows you to use older style syntax such as
those shown below: Err = 6 If Err = 6 Then MsgBox "Overflow" The Err function can only be used while
within an error trap. The internal value of the Err.Number property is reset to 0 with any of the following
statements: Resume, Exit Sub, Exit Function. Thus, if you want to use this value outside an error handler,
you must assign it to a variable. Setting Err.Number to –1 has the side effect of resetting the error state.
This allows you to perform error trapping within an error handler. The ability to reset the error handler
while within an error trap is not standard Basic. Normally, the error handler is reset only with the Resume,
Exit Sub, Exit Function, End Function, or End Sub statements.
Example
'This example forces error 10, with a subsequent transfer to
'the TestError label. TestError tests the error and, if not
'error 55, resets Err to 999 (user-defined error) and returns
'to the Main subroutine.
Sub Main()
On Error Goto TestError
Error 10
MsgBox "The returned error is: '" & Err() & " - " & _
Error$ & "'"
Exit Sub
TestError:
If Err = 55 Then 'File already open.
MsgBox "Cannot copy an open file. Close it and try again."
Else
MsgBox "Error '" & Err & "' has occurred!"
Err = 999
End If
Resume Next
End Sub
Err.Raise (method)
Description Generates a runtime error, setting the specified properties of the Err object.
Parameter Description
number A Long value indicating the error number to be generated. This parameter is required.
Errors predefined by BasicScript are in the range between 0 and 1000.
source An optional String expression specifying the source of the error—i.e., the object or module
that generated the error. If omitted, then BasicScript uses the name of the currently
executing script.
description An optional String expression describing the error. If omitted and number maps to a
predefined BasicScript error number, then the corresponding predefined description is used.
Otherwise, the error "Application-defined or object-define error" is used.
helpfile An optional String expression specifying the name of the help file containing context-
sensitive help for this error. If omitted and number maps to a predefined BasicScript error
number, then the default help file is assumed.
helpcontext An optional Long value specifying the topic within helpfile containing context-sensitive help
for this error. If some arguments are omitted, then the current property values of the Err
object are used. This method can be used in place of the Error statement for generating
errors. Using the Err.Raise method gives you the opportunity to set the desired properties
of the Err object in one statement.
Example
'The following example uses the Err.Raise method to generate
'a user-defined error.
Sub Main()
Dim x As Variant
On Error Goto TRAP
x = InputBox("Enter a number:")
If Not IsNumber(x) Then
Err.Raise 3000,,"Invalid number specified","WIDGET.HLP",30
End If
MsgBox x
Exit Sub
TRAP:
MsgBox Err.Description
End Sub
See Also Error (page 327) (statement), Error Handling (page 327) (topic), Err.Clear (page 328) (method),
Err.HelpContext (page 329) (property), Err.Description (page 328) (property), Err.HelpFile (page
330) (property), Err.Number (page 332) (property), Err.Source (page 333) (property)
Err.Source (property)
Comments For OLE automation errors generated by the OLE server, the Err.Source property is set to the name of
the object that generated the error. For all other errors generated by BasicScript, the Err.Source property
is automatically set to be the name of the script that generated the error. For user-defined errors, the
Err.Source property can be set to any valid String expression indicating the source of the error. If the
Err.Source property is not explicitly set for user-defined errors, the BasicScript sets the value to be the
name of the script in which the error was generated.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 334
Example
'The following script generates an error, setting the source
'to the specific location where the error was generated.
Function InputInteger(Prompt,Optional Title,Optional Def)
On Error Resume Next
Dim x As Integer
x = InputBox(Prompt,Title,Def)
If Err.Number Then
Err.Source = "InputInteger"
Err.Description = "Integer value expected"
InputInteger = Null
Err.Raise 3000
End If
InputInteger = x
End Function
Sub Main
On Error Resume Next
x = InputInteger("Enter a number:")
If Err.Number Then MsgBox Err.Source & ":" & Err.Description
End Sub
See Also Error Handling (page 327) (topic), Err.Clear (page 328) (method), Err.HelpContext (page 329)
(property), Err.Description (page 328) (property), Err.HelpFile (page 330) (property), Err.Number
(page 332) (property), Err.LastDLLError (page 331) (property)
Exit Do (statement)
Syntax Exit Do
Description Causes execution to continue on the statement following the Loop clause.
Example This example will load an array with directory entries unless there are more than ten entries-in which
case, the Exit Do terminates the loop.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
Dim a$(5)
Do
i% = i% + 1
If i% = 1 Then
a(i%) = Dir("*")
Else
a(i%) = Dir
End If
If i% >= 5 Then Exit Do
Loop While (a(i%) <> "")
If i% = 5 Then
MsgBox i% & " directory entries processed!"
Else
MsgBox "Less than " & i% & " entries processed!"
End If
End Sub
See Also Stop (page 491) (statement); Exit For (page 334) (statement); Exit Function (page 335) (statement);
Exit Sub (page 335) (statement); End (page 322) (statement); Do...Loop (page 298) (statement).
Description Causes execution to exit the innermost For loop, continuing execution on the line following the Next
statement.
Example This example enters a large user-defined cycle, performs a calculation and exits the For...Next loop when
the result exceeds a certain value.
Const critical_level = 500
Sub Main()
num = InputBox("Please enter the number of cycles","Cycles")
For i = 1 To Val(num)
newpressure = i * 2
If newpressure >= critical_level Then Exit For
Next i
MsgBox "The valve pressure is: " & newpressure
End Sub
See Also Stop (page 491) (statement); Exit Do (page 334) (statement); Exit Function (page 335) (statement);
Exit Sub (page 335) (statement); End (page 322) (statement); Do...Loop (page 298) (statement).
Description Causes execution to exit the current function, continuing execution on the statement following the call to
this function.
Example This function displays a message and then terminates with Exit Function.
Function Test_Exit() As Integer
MsgBox "Testing function exit, returning to Main()."
Test_Exit = 0
Exit Function
MsgBox "This line should never execute."
End Function
Sub Main()
a% = Test_Exit()
MsgBox "This is the last line of Main()."
End Sub
See Also Stop (page 491) (statement); Exit For (page 334) (statement); Exit Do (page 334) (statement); Exit
Sub (page 335) (statement); End (page 322) (statement); Do...Loop (page 298) (statement).
Description Causes execution to exit the current subroutine, continuing execution on the statement following the call
to this subroutine.
Comments This statement can appear anywhere within a subroutine. It cannot appear within a function.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 336
Example This example displays a dialog box and then exits. The last line should never execute because of the Exit
Sub statement.
Sub Main()
MsgBox "Terminating Main()."
Exit Sub
MsgBox "Still here in Main()."
End Sub
See Also Stop (page 491) (statement); Exit For (page 334) (statement); Exit Function (page 335) (statement);
Exit Do (page 334) (statement); End (page 322) (statement); Do...Loop (page 298) (statement).
Exp (function)
A runtime error is generated if value is out of the range specified above. The value of e is 2.71828
.
Example This example assigns a to e raised to the 12.4 power and displays it in a dialog box.
Sub Main()
a# = Exp(12.4)
MsgBox "e to the 12.4 power is: " & a#
End Sub
Basic Control Engine scripts allows expressions to involve data of different types. When this occurs,
the two arguments are converted to be of the same type by promoting the less precise operand to
the same type as the more precise operand. For example, the Basic Control Engine will promote the
value of i% to a Double in the following expression:
result# = i% * d#
In some cases, the data type to which each operand is promoted is different than that of the most
precise operand. This is dependent on the operator and the data types of the two operands and is
noted in the description of each operator.
If an operation is performed between a numeric expression and a String expression, then the String
expression is usually converted to be of the same type as the numeric expression. For example,
the following expression converts the String expression to an Integer before performing the
multiplication:
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 337
There are exceptions to this rule as noted in the description of the individual operators.
Type Coercion
The Basic Control Engine performs numeric type conversion automatically. Automatic conversions
sometimes result in overflow errors, as shown in the following example:
d# = 45354
i% = d#
In this example, an overflow error is generated because the value contained in d# is larger than the
maximum size of an Integer.
Rounding
When floating-point values (Single or Double) are converted to integer values (Integer or Long), the
fractional part of the floating-point number is lost, rounding to the nearest integer value. The Basic
Control Engine uses Baker's rounding:
• If the fractional part is larger than .5, the number is rounded up.
• If the fractional part is smaller than .5, the number is rounded down.
• If the fractional part is equal to .5, then the number is rounded up if it is odd and down if it is
even.
The following table shows sample values before and after rounding:
Before Rounding After Rounding to Whole Number
2.1 2
4.6 5
2.5 2
3.5 4
Default Properties
When an OLE object variable or an Object variant is used with numerical operators such as addition
or subtraction, then the default property of that object is automatically retrieved. For example,
consider the following:
The above example displays This application is Microsoft Excel in a dialog box. When the variable
Excel is used within the expression, the default property is automatically retrieved, which, in this
case, is the string Microsoft Excel. Considering that the default property of the Excel object is
.Value, then the following two statements are equivalent:
False (constant)
FileAttr (function)
FileCopy (statement)
FileDateTime (function)
FileDirs (statement)
FileExists (function)
FileLen (function)
FileList (statement)
FileParse$ (function)
Fix (function)
For...Next (statement)
FreeFile (function)
False (constant)
Example This example assigns False to a, performs some equivalent operations, and displays a dialog box with the
result. Since a is equivalent to False, and False is equivalent to 0, and by definition, a = 0, then the dialog
box will display "a is False."
Sub Main()
a = False
If ((a = False) And (False Eqv 0) And (a = 0)) Then
MsgBox "a is False."
Else
MsgBox "a is True."
End If
End Sub
See Also True (page 507) (constant); Constants (topic); Boolean (page 233) (data type).
FileAttr (function)
Description Returns an Integer specifying the file mode (if attribute is 1) or the operating system file handle (if
attribute is 2).
Parameter Description
Filenumber Integer value used by Basic Control Engine to refer to the open file; the
number passed to the Open statement.
1 Input
2 Output
4 Random
8 Append
32 Binary
Example This example opens a file for input, reads the file attributes, and determines the file mode for which it was
opened. The result is displayed in a dialog box.
Sub Main()
Open "c:\autoexec.bat" For Input As #1
a% = FileAttr(1,1)
Select Case a%
Case 1
MsgBox "Opened for input."
Case 2
MsgBox "Opened for output."
Case 4
MsgBox "Opened for random."
Case 8
MsgBox "Opened for append."
Case 32
MsgBox "Opened for binary."
Case Else
MsgBox "Unknown file mode."
End Select
a% = FileAttr(1,2)
MsgBox "File handle is: " & a%
Close
End Sub
See Also FileLen (page 342) (function); GetAttr (page 357) (function); FileExists (page 342) (function); Open
(page 428) (statement); SetAttr (page 477) (statement).
FileCopy (statement)
Parameter Description
source$ String containing the name of a single file to copy. The source$ parameter cannot contain
wildcards ( ? or * ) but may contain path information.
destination String containing a single, unique destination file, which may contain a drive and path
$ specification.
The file will be copied and renamed if the source$ and destination$ filenames are not the same. Some
platforms do not support drive letters and may not support dots to indicate current and parent directories.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 341
Example This example copies the autoexec.bat file to "autoexec.sav", then opens the copied file and tries to copy it
again--which generates an error.
Sub Main()
On Error Goto ErrHandler
FileCopy "c:\autoexec.bat","c:\autoexec.sav"
Open "c:\autoexec.sav" For Input As # 1
FileCopy "c:\autoexec.sav","c:\autoexec.sv2"
Close
Exit Sub
ErrHandler:
If Err = 55 Then 'File already open.
MsgBox "Cannot copy an open file. Close it and try again."
Else
MsgBox "An unspecified file copy error has occurred."
End If
Resume Next
End Sub
See Also Kill (page 385) (statement); Name (page 412) (statement).
FileDateTime (function)
Description Returns a Date variant representing the date and time of the last modification of a file.
Comments This function retrieves the date and time of the last modification of the file specified by filename$
(wildcards are not allowed). A runtime error results if the file does not exist. The value returned can be
used with the date/time functions (i.e., Year , Month , Day , Weekday , Minute , Second , Hour ) to
extract the individual elements.
Example This example gets the file date/time of the autoexec.bat file and displays it in a dialog box.
Sub Main()
If FileExists("c:\autoexec.bat") Then
a# = FileDateTime("c:\autoexec.bat")
MsgBox "The date/time information for the file is: " & Year(a#) & "-" & Month(a#) & "-" &
Day(a#)
Else
MsgBox "The file does not exist."
End If
End Sub
See Also FileLen (page 342) (function); GetAttr (page 357) (function); FileAttr (page 339) (function); FileExists
(page 342) (function).
Notes: The Win32 operating system stores the file creation date, last modification date, and the date the file was
last written to. The FileDateTime function only returns the last modification date.
FileDirs (statement)
Description Fills a String or Variant array with directory names from disk.
Parameter Description
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 342
Array() Either a zero- or a one-dimensioned array of strings or variants. The array can be either
dynamic or fixed. If array() is dynamic, then it will be redimensioned to exactly hold the
new number of elements. If there are no elements, then the array will be redimensioned
to contain no dimensions. You can use the LBound, UBound, and ArrayDims functions to
determine the number and size of the new array's dimensions. If the array is fixed, each
array element is first erased, then the new elements are placed into the array. If there are
fewer elements than will fit in the array, then the remaining elements are initialized to zero-
length strings (for String arrays) or Empty (for Variant arrays). A runtime error results if
the array is too small to hold the new elements.
t*. c:\*
If this parameter is omitted, then * is used, which fills the array with all the subdirectory
names within the current directory.
Example This example fills an array with directory entries and displays the first one.
Sub Main()
Dim a$()
FileDirs a$,"c:\*"
MsgBox "The first directory is: " & a$(0)
End Sub
See Also FileList (page 343) (statement); Dir, Dir$ (page 280) (functions); CurDir, CurDir$ (page 259)
(functions); ChDir (page 239) (statement).
FileExists (function)
Comments This function determines whether a given filename$ is valid. This function will return False if filename$
specifies a subdirectory.
Example This example checks to see whether there is an autoexec.bat file in the root directory of the C drive, then
displays either its creation date and time or the fact that it does not exist.
Sub Main()
If FileExists("c:\autoexec.bat") Then
Msgbox "This file exists!"
Else
MsgBox "File does not exist."
End If
End Sub
See Also FileLen (page 342) (function); GetAttr (page 357) (function); FileAttr (page 339) (function); FileParse
$ (page 344) (function).
FileLen (function)
Comments This function is used in place of the LOF function to retrieve the length of a file without first opening the
file. A runtime error results if the file does not exist.
Example This example checks to see whether there is a c:\autoexec.bat file and, if there is, displays the length of
the file.
Sub Main()
file$ = "c:\autoexec.bat"
If FileExists(file$) And FileLen(file$) <> 0) Then
b% = FileLen(file$)
MsgBox "'" & file$ & "' is " & b% & " bytes."
Else
MsgBox "'" & file$ & "' does not exist."
End If
End Sub
See Also GetAttr (page 357) (function); FileAttr (page 339) (function); FileParse$ (page 344) (function);
FileExists (page 342) (function); Loc (page 395) (function).
FileList (statement)
Parameter Description
Array() Either a zero- or a one-dimensioned array of strings or variants. The array can be either
dynamic or fixed. If array() is dynamic, then it will be redimensioned to exactly hold the
new number of elements. If there are no elements, then the array will be redimensioned to
contain no dimensions. You can use the LBound , UBound , and ArrayDims functions
to determine the number and size of the new array's dimensions. If the array is fixed, each
array element is first erased, then the new elements are placed into the array. If there are
fewer elements than will fit in the array, then the remaining elements are initialized to zero-
length strings (for String arrays) or Empty (for Variant arrays). A runtime error results
if the array is too small to hold the new elements.
Filespec$ String specifying which filenames are to be included in the list. The filespec$ parameter
can include wildcards, such as * and ? . If this parameter is omitted, then * is used.
Include_attr Integer specifying attributes of files you want included in the list. It can be any combination
of the attributes listed below. If this parameter is omitted, then the value 97 is used (
ebReadOnly Or ebArchive Or ebNone ).
Exclude_attr Integer specifying attributes of files you want excluded from the list. It can be any
combination of the attributes listed below. If this parameter is omitted, then the value 18
is used ( ebHidden Or ebDirectory ). In other words, hidden files and subdirectories are
excluded from the list.
Wildcards The * character matches any sequence of zero or more characters, whereas the ? character
matches any single character. Multiple *'s and ?'s can appear within the expression to form complete
searching patterns. The following table shows some examples:
(All files)
*
Example This example fills an array a with the directory of the current drive for all files that have normal or no
attributes and excludes those with system attributes. The dialog box displays four filenames from the
array.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
Dim a$()
FileList a$,"*.*",(ebNormal + ebNone),ebSystem
If ArrayDims(a$) > 0 Then
r = SelectBox("FileList","The files you filtered are:",a$)
Else
MsgBox "No files found."
End If
End Sub
See Also FileDirs (page 341) (statement); Dir, Dir$ (page 280) (functions).
FileParse$ (function)
Description Returns a String containing a portion of filename$ such as the path, drive, or file extension.
Comments The filename$ parameter can specify any valid filename (it does not have to exist). For example:
..\test.dat
c:\sheets\test.dat
test.dat
A runtime error is generated if filename$ is a zero-length string. The optional operation parameter is an
Integer specifying which portion of the filename$ to extract. It can be any of the following values.
1 Drive c
2 Path c:\sheets
3 Name test.dat
4 Root test
5 Extension dat
If operation is not specified, then the full name is returned. A runtime error will result if operation is not one
of the above values. A runtime error results if filename$ is empty.
Example This example parses the file string c:\temp\autoexec.bat into its component parts and displays them in
a dialog box.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
Dim a$(5)
file$ = "c:\temp\autoexec.bat"
For i = 1 To 5
a$(i) = FileParse$(file$,i)
Next i
msg1 = "The breakdown of '" & file$ & "' is:" & crlf & crlf
msg1 = msg & a$(1) & crlf & a$(2) & crlf & a$(3) & crlf & a$(4) & crlf & a$(5)
MsgBox msg1
End Sub
See Also FileLen (page 342) (function); GetAttr (page 357) (function); FileAttr (page 339) (function); FileExists
(page 342) (function).
Note The backslash and forward slash can be used interchangeably. For example, c:\test.dat is the same as c:/
test.dat.
Fix (function)
Comments This function returns the integer part of the given value by removing the fractional part. The sign is
preserved. The Fix function returns the same type as number, with the following exceptions:
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 346
Example This example returns the fixed part of a number and assigns it to b, then displays the result in a dialog
box.
Sub Main()
a# = -19923.45
b% = Fix(a#)
MsgBox "The fixed portion of -19923.45 is: " & b%
End Sub
See Also Int (page 376) (function); CInt (page 243) (function).
Syntax For Each member in group [statements] [Exit For] [statements] Next [member]
Parameter Description
member Name of the variable used for each iteration of the loop. If group is an array, then member
must be a Variant variable. If group is a collection, then member must be an Object variable,
an explicit OLE automation object, or a Variant.
BasicScript supports iteration through the elements of OLE collections or arrays, unless the arrays
contain user-defined types or fixed-length strings. The iteration variable is a copy of the collection or array
element in the sense that change to the value of member within the loop has no effect on the collection
or array. The For Each...Next statement traverses array elements in the same order the elements are
stored in memory. For example, the array elements contained in the array defined by the statement
Dim a(1 To 2,3 To 4) are traversed in the following order: (1,3), (1,4), (2,3), (2,4). The order in which the
elements are traversed should not be relevant to the correct operation of the script. The For Each...Next
statement continues executing until there are no more elements in group or until an Exit For statement
is encountered. For Each...Next statements can be nested. In such a case, the Next [member] statement
applies to the innermost For Each...Next or For...Next statement. Each member variable of nested For
Each...Next statements must be unique. A Next statement appearing by itself (with no member variable)
matches the innermost For Each...Next or For...Next loop.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 347
Example
’The following subroutine iterates through the elements
’of an array using For Each...Next.
Sub Main()
Dim a(3 To 10) As Single
Dim i As Variant
Dim s As String
For i = 3 To 10
a(i) = Rnd()
Next i
For Each i In a
i = i + 1
Next i
s = ""
For Each i In a
If s <> "" Then s = s & ","
s = s & i
Next i
MsgBox s
End Sub
’The following subroutine displays the names of each worksheet
’in an Excel workbook.
Sub Main()
Dim Excel As Object
Dim Sheets As Object
Set Excel = CreateObject("Excel.Application")
Excel.Visible = 1
Excel.Workbooks.Add
Set Sheets = Excel.Worksheets
For Each a In Sheets
MsgBox a.Name
Next a
End Sub
See Also Do...Loop (page 298) (statement), While...Wend (page 522) (statement), For...Next (page 347)
(statement)
Note Due to errors in program logic, you can inadvertently create infinite loops in your code. Under Windows
and Win32, you can break out of infinite loops using Ctrl+Break.
For...Next (statement)
Syntax For counter = start To end [Step increment] [statements] [Exit For] [statements] Next [counter
[,nextcounter]... ]
Description Repeats a block of statements a specified number of times, incrementing a loop counter by a given
increment each time through the loop.
Parameter Description
counter Name of a numeric variable. Variables of the following types can be used: Integer, Long,
Single, Double, Variant.
start Initial value for counter. The first time through the loop, counter is assigned this value.
end Final value for counter. The statements will continue executing until counter is equal to end.
increment Amount added to counter each time through the loop. If end is greater than start, then
increment must be positive. If end is less than start, then increment must be negative.
If increment is not specified, then 1 is assumed. The expression given as increment is
evaluated only once. Changing the step during execution of the loop will have no effect.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 348
The For...Next statement continues executing until an Exit For statement is encountered when
counter is greater than end. For...Next statements can be nested. In such a case, the Next [ counter
] statement applies to the innermost For...Next . The Next clause can be optimized for nested next
loops by separating each counter with a comma. The ordering of the counters must be consistent with the
nesting order (innermost counter appearing before outermost counter). The following example shows two
equivalent For statements:
For i = 1 To 10 For i = 1 To 10
For j = 1 To 10 For j = 1 To 10
Next j Next j,i
Next I
A Next clause appearing by itself (with no counter variable) matches the innermost For loop. The
counter variable can be changed within the loop but will have no effect on the number of times the loop
will execute.
Example
Sub Main()
'This example constructs a truth table for the OR statement 'using nested For...Next loops.
Msg1 = "Logic table for Or:" & crlf & crlf
For x = -1 To 0
For y = -1 To 0
z = x Or y
msg1 = msg1 & CBool(x) & " Or "
msg1 = msg1 & CBool(y) & " = "
msg1 = msg1 & CBool(z) & Basic.Eoln$
Next y
Next x
MsgBox msg1
End Sub
See Also Do...Loop (page 298) (statement); While...Wend (page 522) (statement).
Notes Due to errors in program logic, you can inadvertently create infinite loops in your code. You can use Ctrl
+Break to break out of infinite loops.
Comments Format$ returns a String , whereas Format returns a String variant. The Format$/Format
functions take the following parameters:
Parameter Description
Userformat Format expression that can be either one of the built-in Basic Control Engine formats or
$ a user-defined format consisting of characters that specify how the expression should be
displayed. String, numeric, and date/time formats cannot be mixed in a single Userformat$
expression.
If Userformat$ is omitted and the expression is numeric, then these functions perform the same function
as the Str$ or Str statements, except that they do not preserve a leading space for positive values. If
expression is Null , then a zero-length string is returned.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 349
Built-In Formats To format numeric expressions, you can specify one of the built-in formats. There are two
categories of built-in formats: one deals with numeric expressions and the other with date/time values.
The following tables list the built-in numeric and date/time format strings, followed by an explanation of
what each does.
Numeric Formats
Format Description
Currency Displays the numeric expression as currency, with thousands separator if necessary.
Fixed Displays at least one digit to the left of the decimal separator and two digits to the right.
Standard Displays the numeric expression with thousands separator if necessary. Displays at least
one digit to the left of the decimal separator and two digits to the right.
Percent Displays the numeric expression multiplied by 100. A percent sign (%) will appear at the
right of the formatted output. Two digits are displayed to the right of the decimal separator.
Scientific Displays the number using scientific notation. One digit appears before the decimal
separator and two after.
Yes/No Displays No if the numeric expression is 0. Displays Yes for all other values.
True/False Displays False if the numeric expression is 0. Displays True for all other values.
On/Off Displays Off if the numeric expression is 0. Displays On for all other values.
Date/Time Formats
Format Description
General Displays the date and time. If there is no fractional part in the numeric expression, then only
date the date is displayed. If there is no integral part in the numeric expression, then only the time
is displayed. Output is in the following form: 1/1/95 01:00:00 AM.
Medium Displays a medium date—prints out only the abbreviated name of the month.
date
Long time Displays the long time. The default is: h:mm:ss.
Medium Displays the time using a 12-hour clock. Hours and minutes are displayed, and the AM/PM
time designator is at the end.
Short time Displays the time using a 24-hour clock. Hours and minutes are displayed.
User-Defined Formats In addition to the built-in formats, you can specify a user-defined format by using
characters that have special meaning when used in a format expression. The following tables list the
characters you can use for numeric, string, and date/time formats and explain their functions.
Numeric Formats
Character Meaning
Displays a number or a 0. If a number exists in the numeric expression in the position where
the 0 appears, the number will be displayed. Otherwise, a 0 will be displayed. If there are
more 0s in the format string than there are digits, the leading and trailing 0s are displayed
without modification.
Displays a number or nothing. If a number exists in the numeric expression in the position
where the number sign appears, the number will be displayed. Otherwise, nothing will be
displayed. Leading and trailing 0s are not displayed.
Designates the number of digits to the left of the decimal and the number of digits to the
right. The character used in the formatted string depends on the decimal placeholder, as
specified by your locale.
The numeric expression is multiplied by 100, and the percent character is inserted in the
same position as it appears in the user-defined format string.
The common use for the thousands separator is to separate thousands from hundreds.
To specify this use, the thousands separator must be surrounded by digit placeholders.
Commas appearing before any digit placeholders are specified are just displayed. Adjacent
commas with no digit placeholders specified between them and the decimal mean that
the number should be divided by 1,000 for each adjacent comma in the format string. A
comma immediately to the left of the decimal has the same function. The actual thousands
separator character used depends on the character specified by your locale.
:E- E+ e- e These are the scientific notation operators, which display the number in scientific notation.
+ At least one digit placeholder must exist to the left of E- , E+ , e- , or e+ . Any digit
placeholders displayed to the left of E- , E+ , e- , or e+ determine the number of digits
displayed in the exponent. Using E+ or e+ places a + in front of positive exponents and a
– in front of negative exponents. Using E- or e- places a – in front of negative exponents
and nothing in front of positive exponents.
Separates hours, minutes, and seconds when time values are being formatted. The actual
character used depends on the character specified by your locale.
Separates months, days, and years when date values are being formatted. The actual
character used depends on the character specified by your locale.
:- + $ ( ) These are the literal characters you can display. To display any other character, you should
space precede it with a backslash or enclose it in quotes.
To display characters, precede them with a backslash. To display a backslash, use two
backslashes. Double quotation marks can also be used to display characters. Numeric
formatting characters, date/time formatting characters, and string formatting characters
cannot be displayed without a preceding backslash.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 351
:"ABC" Displays the text between the quotation marks, but not the quotation marks. To designate a
double quotation mark within a format string, use two adjacent double quotation marks.
Any empty space in a field will be filled with the specified fill character.
Numeric formats can contain one to three parts. Each part is separated by a semicolon. If you specify
one format, it applies to all values. If you specify two formats, the first applies to positive values and the
second to negative values. If you specify three formats, the first applies to positive values, the second to
negative values, and the third to 0s. If you include semicolons with no format between them, the format for
positive values is used.
String Formats
Character Meaning
@ This is a character placeholder. Displays a character if one exists in the expression in the
same position; otherwise, displays a space. Placeholders are filled from right to left unless
the format string specifies left to right.
& This is a character placeholder. Displays a character if one exists in the expression in the
same position; otherwise, displays nothing. Placeholders are filled from right to left unless
the format string specifies left to right.
< This character forces lowercase. Displays all characters in the expression in lowercase.
> This character forces uppercase. Displays all characters in the expression in uppercase.
! This character forces placeholders to be filled from left to right. The default is right to left.
Date/Time Formats
Character Meaning
c Displays the date as ddddd and the time as ttttt . Only the date is displayed if no
fractional part exists in the numeric expression. Only the time is displayed if no integral
portion exists in the numeric expression.
w Displays the number of the day of the week (1–7). Sunday is 1; Saturday is 7.
m Displays the month without a leading 0 (1–12). If m immediately follows h or hh, m is treated
as minutes (0–59).
AM/PM Displays the time using a 12-hour clock. Displays an uppercase AM for time values before
12 noon. Displays an uppercase PM for time values after 12 noon and before 12 midnight.
am/pm Displays the time using a 12-hour clock. Displays a lowercase am or pm at the end.
A/P Displays the time using a 12-hour clock. Displays an uppercase A or P at the end.
a/p Displays the time using a 12-hour clock. Displays a lowercase a or p at the end.
AMPM Displays the time using a 12-hour clock. Displays the string s1159 for values before 12
noon and s2359 for values after 12 noon and before 12 midnight.
Example
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
a# = 1199.234
msg1 = "Some general formats for '" & a# & "' are:" & crlf & crlf
msg1 = msg1 & Format(a#,"General Number") & crlf
msg1 = msg1 & Format(a#,"Currency") & crlf
msg1 = msg1 & Format(a#,"Standard") & crlf
msg1 = msg1 & Format(a#,"Fixed") & crlf
msg1 = msg1 & Format(a#,"Percent") & crlf
msg1 = msg1 & Format(a#,"Scientific") & crlf
g1 = msg1 & Format(True,"Yes/No") & crlf
msg1 = msg1 & Format(True,"True/False") & crlf
msg1 = msg1 & Format(True,"On/Off") & crlf
msg1 = msg1 & Format(a#,"0,0.00") & crlf
msg1 = msg1 & Format(a#,"##,###,###.###") & crlf
MsgBox msg1
da$ = Date$
msg1 = "Some date formats for '" & da$ & "' are:" & crlf & crlf
msg1 = msg1 & Format(da$,"General Date") & crlf
msg1 = msg1 & Format(da$,"Long Date") & crlf
msg1 = msg1 & Format(da$,"Medium Date") & crlf
msg1 = msg1 & Format(da$,"Short Date") & crlf
MsgBox msg1
ti$ = Time$
msg1 = "Some time formats for '" & ti$ & "' are:" & crlf & crlf
msg1 = msg1 & Format(ti$,"Long Time") & crlf
msg1 = msg1 & Format(ti$,"Medium Time") & crlf
msg1 = msg1 & Format(ti$,"Short Time") & crlf
MsgBox msg1
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 353
See Also Str, Str$ (page 495) (functions); CStr (page 258) (function).
Note The default date/time formats are read from the [Intl] section of the win.ini file.
FreeFile (function)
Syntax FreeFile[()]
Comments The number returned is suitable for use in the Open statement and will always be between 1 and 255
inclusive.
Example This example assigns A to the next free file number and displays it in a dialog box.
Sub Main()
a = FreeFile
MsgBox "The next free file number is: " & a
End Sub
See Also FileAttr (page 339) (function); Open (page 428) (statement).
2. May contain letters, digits, and the underscore character ( _ ). Punctuation and type-declaration
characters are not allowed.
The exclamation point ( ! ) can appear within the name as long as it is not the last character, in
which case it is interpreted as a type-declaration character.
4. The call cannot end with a comma. For instance, using the above example, the following is not
valid:
a = Test(1,,)
5. The call must contain the minimum number of parameters as required by the called function.
For instance, using the above example, the following are invalid:
a = Test(,1) 'Only passes two out of three required parameters.
a = Test(1,2) 'Only passes two out of three required parameters.
Fv (function)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 354
Description Calculates the future value of an annuity based on periodic fixed payments and a constant rate of interest.
Comments An annuity is a series of fixed payments made to an insurance company or other investment company
over a period of time. Examples of annuities are mortgages and monthly savings plans. The Fv function
requires the following parameters:
Parameter Description
Rate Double representing the interest rate per period. Make sure that annual rates are normalized
for monthly periods (divided by 12).
NPer Double representing the total number of payments (periods) in the annuity.
Pmt Double representing the amount of each payment per period. Payments are entered as
negative values, whereas receipts are entered as positive values.
Pv Double representing the present value of your annuity. In the case of a loan, the present
value would be the amount of the loan, whereas in the case of a retirement annuity, the
present value would be the amount of the fund.
Due Integer indicating when payments are due for each payment period. A 0 specifies payment
at the end of each period, whereas a 1 indicates payment at the start of each period.
Rate and NPer values must be expressed in the same units. If Rate is expressed as a percentage per
month, then NPer must also be expressed in months. If Rate is an annual rate, then the NPer must also
be given in years. Positive numbers represent cash received, whereas negative numbers represent cash
paid out.
Example This example calculates the future value of 100 dollars paid periodically for a period of 10 years (120
months) at a rate of 10% per year (or .10/12 per month) with payments made on the first of the month.
The value is displayed in a dialog box. Note that payments are negative values.
Sub Main()
a# = Fv((.10/12),120,-100.00,0,1)
MsgBox "Future value is: " & Format(a#,"Currency")
End Sub
See Also IRR (page 378) (function); MIRR (page 404) (function); Npv (page 420) (function); Pv (page 450)
(function).
Get (statement)
GetAllSettings (function)
GetAttr (function)
GetObject (function)
GetSetting (function)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 355
Global (statement)
GoSub (statement)
Goto (statement)
GroupBox (statement)
Get (statement)
Description Retrieves data from a random or binary file and stores that data into the specified variable.
Parameter Description
filenumber Integer used by the Basic Control Engine to identify the file. This is the same number
passed to the Open statement.
recordnumber Long specifying which record is to be read from the file. For binary files, this number
represents the first byte to be read starting with the beginning of the file (the first byte
is 1). For random files, this number represents the record number starting with the
beginning of the file (the first record is 1). This value ranges from 1 to 2147483647. If the
recordnumber parameter is omitted, the next record is read from the file (if no records
have been read yet, then the first record in the file is read). When this parameter is
omitted, the commas must still appear, as in the following example:
Get #1,,recvar
variable Variable into which data will be read. The type of the variable determines how the data is
read from the file, as described below.
With random files, a runtime error will occur if the length of the data being read exceeds the reclen
parameter specified with the Open statement. If the length of the data being read is less than the record
length, the file pointer is advanced to the start of the next record. With binary files, the data elements
being read are contiguous¾ the file pointer is never advanced.
Variable Types The type of the variable parameter determines how data will be read from the file. It can
be any of the following types:
String (variable-length) In binary files, variable-length strings are read by first determining the
specified string variable's length and then reading that many bytes from the
file. For example, to read a string of eight characters:
String (fixed-length) Fixed-length strings are read by reading a fixed number of characters from
the file equal to the string's declared length.
Date 8 bytes are read from the file (IEEE double format).
Boolean 2 bytes are read from the file. Nonzero values are True, and zero values
are False .
Variant A 2-byte VarType is read from the file, which determines the format
of the data that follows. Once the VarType is known, the data is read
individually, as described above. With user-defined errors, after the 2-byte
VarType , a 2-byte unsigned integer is read and assigned as the value of
the user-defined error, followed by 2 additional bytes of information about
the error. The exception is with strings, which are always preceded by a 2-
byte string length.
User-defined types Each member of a user-defined data type is read individually In binary files,
variable-length strings within user-defined types are read by first reading
a 2-byte length followed by the string's content. This storage is different
from variable-length strings outside of user-defined types. When reading
user-defined types, the record length must be greater than or equal to the
combined size of each element within the data type.
Arrays Arrays cannot be read from a file using the Get statement.
Objects Object variables cannot be read from a file using the Get statement.
Example This example opens a file for random write, then writes ten records into the file with the values 10...50.
Then the file is closed and reopened in random mode for read, and the records are read with the Get
statement. The result is displayed in a message box.
Sub Main()
Open "test.dat" For Random Access Write As #1
For x = 1 to 10
y = x * 10
Put #1,x,y
Next x
Close
Open "test.dat" For Random Access Read As #1
msg1 = ""
For y = 1 to 5
Get #1,y,x
msg1 = msg1 & "Record " & y & ": " & x & Basic.Eoln$
Next y
Close
MsgBox msg1
End Sub
See Also Open (page 428) (statement); Put (page 448) (statement); Input# (page 372) (statement); Line
Input# (page 392) (statement); Input, Input$ (page 373) (functions)
GetAllSettings (function)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 357
Description Returns all of the keys within the specified section, or all of the sections within the specified application
from the system registry.
Parameter Description
appname A String expression specifying the name of the application from which settings or keys will be
returned.
section A String expression specifying the name of the section from which keys will be returned. If
omitted, then all of the section names within appname will be returned.
Example
Sub Main()
Dim NewAppSettings() As Variant
SaveSetting appname := "NewApp", section := "Startup", _
key := "Height", setting := 200
SaveSetting appname := "NewApp", section := "Startup _
", key := "Width", setting := 320
GetAllSettings appname := "NewApp", _
section := "Startup ", resultarray := NewAppSettings
For i = LBound(NewAppSettings) To UBound(NewAppSettings)
NewAppSettings(i) = NewAppSettings(i) & "=" & _
GetSetting("NewApp", "Startup", NewAppSettings(i))
Next i
r = SelectBox("Registry Settings","", NewAppSettings)
End Sub
See Also GetSetting (page 359) (function), DeleteSetting (page 277) (statement), SaveSetting (page 468)
(statement)
Notes Under Win32, this statement operates on the system registry. All settings are read from the following entry
in the system registry: HKEY_CURRENT_USER\Software\BasicScript Program Settings\appname\section
GetAttr (function)
Comments The attribute value returned is the sum of the attributes set for the file. The value of each attribute is as
follows:
EbNormal 0 Read-only files, archive files, subdirectories, and files with no attributes.
To determine whether a particular attribute is set, you can And the values shown above with the value
returned by GetAttr . If the result is True , the attribute is set, as shown below:
Sub Main()
Dim w As Integer
w = GetAttr("sample.txt")
If w And ebReadOnly Then MsgBox "This file is read-only."
End Sub
Example This example tests to see whether the file test.dat exists. If it does not, then it creates the file. The file
attributes are then retrieved with the GetAttr function, and the result is displayed.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
Dim a()
FileList a,"*.*"
Again:
msg1 = ""
r = SelectBox("Attribute Checker","Select File:",a)
If r = -1 Then
End
Else
y% = GetAttr(a(r))
End If
If y% = 0 Then msg1 = msg1 & "This file has no special attributes." & crlf
If y% And ebReadOnly Then msg1 = msg1 & "The read-only bit is set." & crlf
If y% And ebHidden Then msg1 = msg1 & "The hidden bit is set." & crlf
If y% And ebSystem Then msg1 = msg1 & "The system bit is set." & crlf
If y% And ebVolume Then msg1 = msg1 & "The volume bit is set." & crlf
If y% And ebDirectory Then msg1 = msg1 & "The directory bit is set." & crlf
If y% And ebArchive Then msg1 = msg1 & "The archive bit is set."
MsgBox msg1
Goto Again
End Sub
See Also SetAttr (page 477) (statement); FileAttr (page 339) (function).
GetObject (function)
Description Returns the object specified by filename$ or returns a previously instantiated object of the given class$.
Comments This function is used to retrieve an existing OLE automation object, either one that comes from a file or
one that has previously been instantiated.
The filename$ argument specifies the full pathname of the file containing the object to be activated. The
application associated with the file is determined by OLE at runtime. For example, suppose that a file
called c:\docs\resume.doc was created by a word processor called wordproc.exe . The following
statement would invoke wordproc.exe , load the file called c:\docs\resume.doc , and assign that object
to a variable:
Dim doc As Object
Set doc = GetObject("c:\docs\resume.doc")
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 359
To activate a part of an object, add an exclamation point to the filename followed by a string representing
the part of the object that you want to activate. For example, to activate the first three pages of the
document in the previous example:
Dim doc As Object
Set doc = GetObject("c:\docs\resume.doc!P1-P3")
The GetObject function behaves differently depending on whether the first parameter is omitted. The
following table summarizes the different behaviors of GetObject :
Omitted Specified Reference to an existing instance of the specified object. A runtime error results if
the object is not already loaded.
"" Specified Reference to a new object (as specified by class$). A runtime error occurs if an
object of the specified class cannot be found. This is the same as CreateObject .
Specified Omitted Default object from filename$. The application to activate is determined by OLE
based on the given filename.
Specified Specified Object given by class$ from the file given by filename$. A runtime error occurs if
an object of the given class cannot be found in the given file.
This second example loads the OLE server associated with a document.
Dim MyObject As Object
Set MyObject = GetObject("c:\documents\resume.doc")
End Sub
See Also CreateObject (page 245) (function); Object (page 422) (data type).
GetSetting (function)
Parameter Description
appname String expression specifying the name of the application from which the setting will be read.
section String expression specifying the name of the section within appname to be read.
key String expression specifying the name of the key within section to be read.
default An optional String expression specifying the default value to be returned if the desired key
does not exist in the system registry. If omitted, then an empty string is returned if the key
doesn’t exist.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 360
Example
Sub Main()
SaveSetting appname := "NewApp", section := "Startup", _
key := "Height", setting := 200
SaveSetting appname := "NewApp", section := "Startup", _
key := "Width", setting := 320
MsgBox GetSetting(appname := "NewApp", section := "Startup", _
key := "Height", default := "50")
DeleteSetting "NewApp" ' Delete the NewApp key
End Sub
See Also GetAllSettings (page 356) (function), DeleteSetting (page 277) (statement), SaveSetting (page 468)
(statement)
Note Under Win32, this statement operates on the system registry. All settings are read from the following entry
in the system registry: HKEY_CURRENT_USER\Software\BasicScript Program Settings\appname\section\key
On this platform, the appname parameter is not optional.
Global (statement)
GoSub (statement)
Comments Execution can later be returned to the statement following the GoSub by using the Return statement.
The label parameter must be a label within the current function or subroutine. GoSub outside the context
of the current function or subroutine is not allowed.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 361
Example This example gets a name from the user and then branches to a subroutine to check the input. If the user
clicks Cancel or enters a blank name, the program terminates; otherwise, the name is set to MICHAEL,
and a message is displayed.
Sub Main()
uname$ = Ucase$(InputBox$("Enter your name:","Enter Name"))
GoSub CheckName
MsgBox "I'm looking for MICHAEL, not " & uname$
Exit Sub
CheckName:
If (uname$ = "") Then
GoSub BlankName
ElseIf uname$ = "MICHAEL" Then
GoSub RightName
Else
GoSub OtherName
End If
Return
BlankName:
MsgBox "No name? Clicked Cancel? I'm shutting down."
Exit Sub
RightName:
Msgbox "Hey, MIKE where have you been?"
End
OtherName:
Return
End Sub
See Also Goto (page 361) (statement); Return (page 461) (statement).
Goto (statement)
The compiler will produce an error if label does not exist.The label must appear within the same
subroutine or function as the Goto .Labels are identifiers that follow these rules:
GroupBox (statement)
Comments This statement can only appear within a dialog box template (that is., between the Begin Dialog and
End Dialog statements). The group box control is used for static display only¾the user cannot interact
with a group box control. Separator lines can be created using group box controls. This is accomplished
by creating a group box that is wider than the width of the dialog box and extends below the bottom of the
dialog box; three sides of the group box are not visible.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 362
If title$ is a zero-length string, then the group box is drawn as a solid rectangle with no title. The GroupBox
statement requires the following parameters:
Parameter Description
X, Y Integer coordinates specifying the position of the control (in dialog units) static to the upper
left corner of the dialog box.
width, Integer coordinates specifying the dimensions of the control in dialog units.
height
title$ String containing the label of the group box. If title$ is a zero-length string, then no title will
appear.
.Identifier Optional parameter that specifies the name by which this control can be referenced by
statements in a dialog function (such as DlgFocus and DlgEnable ). If omitted, then the
first two words of title$ are used.
Example This example shows the GroupBox statement being used both for grouping and as a separator line.
Sub Main()
Begin Dialog OptionsTemplate 16,32,128,84,"Options"
GroupBox 4,4,116,40,"Window Options"
CheckBox 12,16,60,8,"Show &Toolbar",.ShowToolbar
CheckBox 12,28,68,8,"Show &Status Bar",.ShowStatusBar
GroupBox -12,52,152,48," ",.SeparatorLine
OKButton 16,64,40,14,.OK
CancelButton 68,64,40,14,.Cancel
End Dialog
Dim OptionsDialog As OptionsTemplate
Dialog OptionsDialog
End Sub
See Also CancelButton (page 243) (statement); CheckBox (page 240) (statement); ComboBox (page 249)
(statement); Dialog (page 278) (function); Dialog (page 279) (statement); DropListBox (page 301)
(statement); ListBox (page 394) (statement); OKButton (page 426) (statement); OptionButton (page
434) (statement); OptionGroup (page 435) (statement); Picture (page 438) (statement); PushButton
(page 447) (statement); Text (page 502) (statement); TextBox (page 503) (statement); Begin (page
231) Dialog (page 231) (statement), PictureButton (page 439) (statement).
HelpButton (statement)
HLine (statement)
Hour (function)
HPage (statement)
HScroll (statement)
HWND (object)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 363
HWND.Value (property)
HelpButton (statement)
Comments This statement can only appear within a dialog box template (i.e., between the Begin Dialog and End
Dialog statements). The HelpButton statement takes the following parameters:
Parameter Description
x,y Integer position of the control (in dialog units) static to the upper left corner of the dialog
box.
HelpFileName String expression specifying the name of the help file to be invoked when the button is
$ selected.
HelpContext Long expression specifying the ID of the topic within HelpFileName$ containing context-
sensitive help.
.Identifier Name by which this control can be referenced by statements in a dialog function (such as
DlgFocus and DlgEnable).
When the user selects a help button, the associated help file is located at the indicated topic. Selecting
a help button does not remove the dialog. Similarly, no actions are sent to the dialog procedure when a
help button is selected. When a help button is present within a dialog, it can be automatically selected by
pressing the help key (F1 on most platforms).
Example
Sub Main()
Begin Dialog HelpDialogTemplate ,,180,96,"Untitled"
OKButton 132,8,40,14
CancelButton 132,28,40,14
HelpButton 132,48,40,14,"", 10
Text 16,12,88,12,"Please click ""Help"".",.Text1
End Dialog
Dim HelpDialog As HelpDialogTemplate
Dialog HelpDialog
End Sub
See Also CancelButton (page 243) (statement), CheckBox (page 240) (statement), ComboBox (page 249)
(statement), Dialog (page 278) (function), Dialog (page 279) (statement), DropListBox (page 301)
(statement), GroupBox (page 361) (statement), ListBox (page 394) (statement), OKButton (page
426) (statement), OptionButton (page 434) (statement), OptionGroup (page 435) (statement),
Picture (page 438) (statement), PushButton (page 447) (statement), Text (page 502) (statement),
Begin Dialog (page 231) (statement), PictureButton (page 439) (statement)
Comments Hex$ returns a String , whereas Hex returns a String variant. The returned string contains only the
number of hexadecimal digits necessary to represent the number, up to a maximum of eight.
The number parameter can be any type but is rounded to the nearest whole number before converting to
hex. If the passed number is an integer, then a maximum of four digits are returned; otherwise, up to eight
digits can be returned. The number parameter can be any expression convertible to a number. If number
is Null , then Null is returned. Empty is treated as 0.
Example This example accepts a number and displays the decimal and hexadecimal equivalent until the input
number is 0 or invalid.
Sub Main()
Do
xs$ = InputBox("Enter a number to convert:","Hex Convert")
x = Val(xs$)
If x <> 0 Then
MsgBox "Decimal: " & x & " Hex: " & Hex(x)
Else
MsgBox "Goodbye."
End If
Loop While x <> 0
End Sub
HLine (statement)
Description Scrolls the window with the focus left or right by the specified number of lines.
Comments The lines parameter is an Integer specifying the number of lines to scroll. If this parameter is omitted,
then the window is scrolled right by one line.
Example This example scrolls the Notepad window to the left by three "amounts." Each "amount" is equivalent to
clicking the right arrow of the horizontal scroll bar once.
Sub Main()
AppActivate "Notepad"
HLine 3 'Move 3 lines in.
End Sub
See Also HPage (page 365) (statement); HScroll (page 365) (statement).
Hour (function)
Description Returns the hour of the day encoded in the specified time parameter.
Comments The value returned is as an Integer between 0 and 23 inclusive. The time parameter is any expression
that converts to a Date .
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 365
Example This example takes the current time; extracts the hour, minute, and second; and displays them as the
current time.
Sub Main()
Msgbox "It is now hour " & Hour(Time) & " of today."
End Sub
See Also Day (page 269) (function); Minute (page 404) (function); Second (page 471) (function); Month (page
406) (function); Year (page 533) (function); Weekday (page 521) (function); DatePart (page 267)
(function).
HPage (statement)
Description Scrolls the window with the focus left or right by the specified number of pages.
Comments The pages parameter is an Integer specifying the number of pages to scroll. If this parameter is omitted,
then the window is scrolled right by one page.
Example This example scrolls the Notepad window to the left by three "amounts." Each "amount" is equivalent to
clicking within the horizontal scroll bar on the right side of the thumb mark.
Sub Main()
AppActivate "Notepad"
HPage 3 'Move 3 pages down.
End Sub
See Also HLine (page 364) (statement); HScroll (page 365) (statement).
HScroll (statement)
Description Sets the thumb mark on the horizontal scroll bar attached to the current window.
Comments The position is given as a percentage of the total range associated with that scroll bar. For example, if the
percentage parameter is 50, then the thumb mark is positioned in the middle of the scroll bar.
Example This example centers the thumb mark on the horizontal scroll bar of the Notepad window.
Sub Main()
AppActivate "Notepad"
HScroll 50 'Jump to the middle of the document.
End Sub
See Also HLine (page 364) (statement); HPage (page 365) (statement).
HWND (object)
Comments This data type is used to hold references to physical windows in the operating environment. The following
commands operate on HWND objects:
WinSize
The above language elements support both string and HWND window specifications.
Example This example activates the "Main" MDI window within Program Manager.
Sub Main()
Dim ProgramManager As HWND
Dim ProgramManagerMain As HWND
Set ProgramManager = WinFind("Program Manager")
If ProgramManager Is Not Nothing Then
WinActivate ProgramManager
WinMaximize ProgramManager
Set ProgramManagerMain = WinFind("Program Manager|Main")
If ProgramManagerMain Is Not Nothing Then
WinActivate ProgramManagerMain
WinRestore ProgramManagerMain
Else
MsgBox "Your Program Manager doesn't have a Main group."
End If
Else
MsgBox "Program Manager is not running."
End If
End Sub
See Also HWND.Value (page 366) (property); WinFind (page 525) (function); WinActivate (page 523)
(statement).
HWND.Value (property)
Description The default property of an HWND object that returns a Variant containing a HANDLE to the physical
window of an HWND object variable.
Comments The .Value property is used to retrieve the operating environment–specific value of a given HWND
object. The size of this value depends on the operating environment in which the script is executing and
thus should always be placed into a Variant variable. This property is read-only.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 367
Example This example displays a dialog box containing the class name of Program Manager's Main window. It
does so using the .Value property, passing it directly to a Windows external routine.
Declare Sub GetClassName Lib "user" (ByVal Win%,ByVal ClsName$,
ByVal ClsNameLen%)
Sub Main()
Dim ProgramManager As HWND
Set ProgramManager = WinFind("Program Manager")
ClassName$ = Space(40)
GetClassName ProgramManager.Value,ClassName$,Len(ClassName$)
MsgBox "The program classname is: " & ClassName$
End Sub
If...Then...Else (statement)
IIf (function)
IMEStatus (function)
Imp (operator)
Input# (statement)
Int (function)
IPmt (function)
IRR (function)
Is (operator)
IsDate (function)
IsEmpty (function)
IsError (function)
IsMissing (function)
IsNull (function)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 368
IsNumeric (function)
IsObject (function)
IsWebSpaceSession (function)
Item$ (function)
ItemCount (function)
If...Then...Else (statement)
Comments The single-line conditional statement (syntax 1) has the following parameters:
Parameter Description
statements One or more statements separated with colons. This group of statements is executed
when condition is TRUE.
else_statements One or more statements separated with colons. This group of statements is executed
when condition is FALSE.
Parameter Description
elseif_statements One or more statements to be executed when condition is False and else_condition
is True .
else_statements One or more statements to be executed when both condition and else_condition are
False .
Example This example inputs a name from the user and checks to see whether it is MICHAEL or MIKE using three
forms of the If...Then...Else statement. It then branches to a statement that displays a welcome message
depending on the user's name.
Sub Main()
uname$ = UCase(InputBox("Enter your name:","Enter Name"))
If uname$ = "MICHAEL" Then GoSub MikeName
If uname$ = "MIKE" Then
GoSub MikeName
Exit Sub
End If
If uname$ = "" Then
MsgBox "Since you don't have a name, I'll call you MIKE!"
uname$ = "MIKE"
GoSub MikeName
ElseIf uname$ = "MICHAEL" Then
GoSub MikeName
Else
GoSub OtherName
End If
Exit Sub
MikeName:
MsgBox "Hello, MICHAEL!"
Return
OtherName:
MsgBox "Hello, " & uname$ & "!"
Return
End Sub
See Also Choose (page 241) (function); Switch (page 496) (function); IIf (page 369) (function); Select...Case
(page 472) (statement).
IIf (function)
Comments Both expressions are calculated before IIf returns. The IIf function is shorthand for the following
construct:
If condition Then
variable = TrueExpression
Else
variable = FalseExpression
End If
Example
Sub Main()
s$ = "Car"
MsgBox "You have a " & IIf(s$ = "Car","nice car.","nice non-car.")
End Sub
See Also Choose (page 241) (function); Switch (page 496) (function); If...Then...Else (page 368) (statement);
Select...Case (page 472) (statement).
IMEStatus (function)
Syntax IMEStatus[()]
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 370
Comments The IMEStatus function returns one of the following constants for Japanese locales:
ebIMEDisabled 3 disabled
For Korean locales, this function returns a value with the first 5 bits having the following meaning:
Note: You can test for the different bits using the And operator as follows:
a = IMEStatus() If a And 1 Then ... 'Test for bit 0 If a And 2 Then ... 'Test for bit 1 If a And 4 Then ... 'Test
for bit 2 If a And 8 Then ... 'Test for bit 3 If a And 16 Then ... ’Test for bit 4
Example
'This example retrieves the IMEStatus and displays the results.
Sub Main()
a = IMEStatus()
Select case a
Case 0
MsgBox "IME not installed."
Case 1
MsgBox "IME on."
Case 2
Msgbox "IME off."
End Select
End Sub
Imp (operator)
Comments If both expressions are either Boolean, Boolean variants, or Null variants, then a logical implication is
performed as follows:
Binary Implication If the two expressions are Integer, then a binary implication is performed, returning
an Integer result. All other numeric types (including Empty variants) are converted to Long and a binary
implication is then performed, returning a Long result. Binary implication forms a new value based on
a bit-by-bit comparison of the binary representations of the two expressions, according to the following
table:
1 Imp 1 = 1 Example
0 Imp 1 = 1 5 01101001
1 Imp 0 = 0 6 10101010
Example This example compares the result of two expressions to determine whether one implies the other.
Sub Main()
a = 10 : b = 20 : c = 30 : d = 40
If (a < b) Imp (c < d) Then
MsgBox "a is less than b implies that c is less than d."
Else
MsgBox "a is less than b does not imply that c is less than d."
End If
If (a < b) Imp (c > d) Then
MsgBox "a is less than b implies that c is greater than d."
Else
MsgBox "a is less than b does not imply that c is greater than d."
End If
End Sub
See Also Operator Precedence (page 431) (topic); Or (page 435) (operator); Xor (page 532) (operator); Eqv
(page 323) (operator); And (operator). (page 204)
Input# (statement)
Each variable must be type-matched to the data in the file. For example, a String variable must be
matched to a string in the file.The following parsing rules are observed while reading each variable in
the variable list:
2. When reading String variables, if the first character on the line is a quotation mark, then
characters are read up to the next quotation mark or the end of the line, whichever comes first.
Blank lines are read as empty strings. If the first character read is not a quotation mark, then
characters are read up to the first comma or the end of the line, whichever comes first. String
delimiters (quotes, comma, end-of-line) are not included in the returned string.
3. When reading numeric variables, scanning of the number stops when the first nonnumber
character (such as a comma, a letter, or any other unexpected character) is encountered.
Numeric errors are ignored while reading numbers from a file. The resultant number is
automatically converted to the same type as the variable into which the value will be placed. If
there is an error in conversion, then 0 is stored into the variable.
octaldigits [!|#|%|&|@] After reading the number, input is skipped up to the next
delimiter—a comma, an end-of-line, or an end-of-file.Numbers must adhere to any of the
following syntaxes: [-|+]digits[.digits ][E[-|+]digits][!|#|%|&|@] &Hhexdigits[!|#|%|
&] &[O]
4. When reading Boolean variables, the first character must be #; otherwise, a runtime error
occurs. If the first character is #, then input is scanned up to the next delimiter (a comma, an
end-of-line, or an end-of-file). If the input matches #FALSE#, then FALSE is stored in the
Boolean ; otherwise TRUE is stored.
5. When reading Date variables, the first character must be #; otherwise, a runtime error occurs.
If the first character is #, then the input is scanned up to the next delimiter (a comma, an end-
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 373
of-line, or an end-of-file). If the input ends in a # and the text between the #'s can be correctly
interpreted as a date, then the date is stored; otherwise, December 31, 1899, is stored.
Normally, dates that follow the universal date format are input from sequential files. These
dates use this syntax: #YYYY-MM-DD HH:MM:SS#where YYYY is a year between 100 and
9999, MM is a month between 1 and 12, DD is a day between 1 and 31, HH is an hour between
0 and 23, MM is a minute between 0 and 59, and SS is a second between 0 and 59.
6. When reading Variant variables, if the data begins with a quotation mark, then a string is read
consisting of the characters between the opening quotation mark and the closing quotation mark,
end-of-line, or end-of-file.
If the input does not begin with a quotation mark, then input is scanned up to the next comma,
end-of-line, or end-of-file and a determination is made as to what data is being represented. If
the data cannot be represented as a number, Date , Error , Boolean , or Null , then it is read
as a string.The following table describes how special data is interpreted as variants:
7. End-of-line is interpreted as either a single line feed, a single carriage return, or a carriage-
return/line-feed pair. Thus, text files from any platform can be interpreted using this command.
The filenumber parameter is a number that is used by The Basic Control Engine to refer to
the open file, the number passed to the Open statement.The filenumber must reference a file
opened in Input mode. It is good practice to use the Write statement to write date elements
to files read with the Input statement to ensure that the variable list is consistent between the
input and output routines.
Description Returns a specified number of characters or bytes read from a given sequential file.
Functions Return
Parameter Description
numchars Integer containing the number of characters to be read from the file.
numbytes Integer containing the number of bytes to be read from the file.
filenumber Integer referencing a file opened in either Input or Binary mode. This is the same number
passed to the Open statement.
Input and Input All characters, including spaces and end-of-lines. Null characters are ignored.
$
Example
'This example opens the autoexec.bat file and displays it in a
'dialog box.
Const crlf = Chr$(13) & Chr$(10)
Sub Main()
x& = FileLen("c:\autoexec.bat")
If x& > 0 Then
Open "c:\autoexec.bat" For Input As #1
Else
MsgBox "File not found or empty."
Exit Sub
End If
If x& > 80 Then
ins = Input(80,#1)
Else
ins = Input(x,#1)
End If
Close
MsgBox "File length: " & x& & crlf & ins
End Sub
See Also Open (page 428) (statement); Get (page 355) (statement); Input# (page 372) (statement); Line
Input# (page 392) (statement).
Description Displays a dialog box with a text box into which the user can type.
Comments The content of the text box is returned as a String (in the case of InputBox$) or as a String variant (in
the case of InputBox). A zero-length string is returned if the user selects Cancel. The InputBox/InputBox$
functions take the following named parameters:
Parameter Description
prompt Text to be displayed above the text box. The prompt parameter can contain multiple lines,
each separated with an end-of-line (a carriage return, line feed, or carriage-return/line-feed
pair). A runtime error is generated if prompt is Null.
title Caption of the dialog box. If this parameter is omitted, then no title appears as the dialog
box's caption. A runtime error is generated if title is Null.
default Default response. This string is initially displayed in the text box. A runtime error is generated
if default is Null.
xpos, Integer coordinates, given in twips (twentieths of a point), specifying the upper left corner of
ypos the dialog box static to the upper left corner of the screen. If the position is omitted, then the
dialog box is positioned on or near the application executing the script.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 375
helpfile Name of the file containing context-sensitive help for this dialog. If this parameter is
specified, then context must also be specified.
context Number specifying the ID of the topic within helpfile for this dialog's help. If this parameter is
specified, then helpfile must also be specified.
You can type a maximum of 255 characters into InputBox. If both the helpfile and context parameters
are specified, then a Help button is added in addition to the OK and Cancel buttons. Context-sensitive
help can be invoked by selecting this button or using the help key (F1 on most platforms). Invoking help
does not remove the dialog. When Cancel is selected, an empty string is returned. An empty string is
also returned when the user selects the OK button with no text in the input box. Thus, it is not possible
to determine the difference between these two situations. If you need to determine the difference, you
should create a user-defined dialog or use the AskBox function.
Example
Sub Main()
s$ = InputBox$("File to copy:","Copy","sample.txt")
End Sub
See Also MsgBox (page 411) (statement), AskBox, AskBox$ (page 221) (functions), AskPassword,
AskPassword$ (page 222) (functions), OpenFileName$ (page 429) (function), SaveFileName$ (page
467) (function), SelectBox (page 473) (function), AnswerBox (page 205) (function)
Description Returns the first character position of string find within string search.
Parameter Description
start Integer specifying the character position where searching begins. The start parameter must
be between 1 and 32767. If this parameter is omitted, then the search starts at the beginning
(start = 1).
find Text for which to search. This can be any expression convertible to a String.
If this parameter is omitted, then string comparisons use the current Option Compare
setting. If no Option Compare statement has been encountered, then Binary is used (i.e.,
string comparisons are case-sensitive).
If the string is found, then its character position within search is returned, with 1 being the character
position of the first character.
The InStr and InStrB functions observe the following additional rules:
The InStr and InStrB functions operate on character and byte data respectively. The Instr function
interprets the start parameter as a character, performs a textual comparisons, and returns a character
position. The InStrB function, on the other hand, interprets the start parameter as a byte position,
performs binary comparisons, and returns a byte position. On SBCS platforms, the InStr and InStrB
functions are identical.
Example This example checks to see whether one string is in another and, if it is, then it copies the string to a
variable and displays the result.
Sub Main()
a$ = "This string contains the name Stuart and other characters."
x% = InStr(1, a$,"Stuart",1)
If x% <> 0 Then
b$ = Mid(a$,x%,6)
MsgBox b$ & " was found."
Exit Sub
Else
MsgBox "Stuart not found."
End If
End Sub
See Also Mid, Mid$ (page 402) (functions); Option Compare (page 432) (statement); Item$ (page 383)
(function); Word$ (page 529) (function); Line$ (page 392) (function).
Int (function)
Comments This function returns the integer part of a given value by returning the first integer less than the number.
The sign is preserved. The Int function returns the same type as number, with the following exceptions:
See Also Fix (page 345) (function); CInt (page 243) (function).
Syntax Integer
Description A data type used to declare whole numbers with up to four digits of precision.
Comments Integer variables are used to hold numbers within the following range:
–32768 <= integer <= 32767
Internally, integers are 2-byte short values. Thus, when appearing within a structure, integers require 2
bytes of storage. When used with binary or random files, 2 bytes of storage are required. When passed to
external routines, Integer values are sign-extended to the size of an integer on that platform (either 16 or
32 bits) before pushing onto the stack. The type-declaration character for Integer is % .
See Also Currency (page 259) (data type); Date (page 263) (data type); Double (page 300) (data type); Long
(page 398) (data type), Object (page 422) (data type), Single (page 479) (data type), String (page
494) (data type), Variant (page 515) (data type), Boolean (page 233) (data type), DefType (page
276) (statement), CInt (page 243) (function).
IPmt (function)
Description Returns the interest payment for a given period of an annuity based on periodic, fixed payments and a
fixed interest rate.
Comments An annuity is a series of fixed payments made to an insurance company or other investment company
over a period of time. Examples of annuities are mortgages, monthly savings plans, and retirement plans.
The following table describes the different parameters:
Parameter Description
Rate Double representing the interest rate per period. If the payment periods are monthly, be sure
to divide the annual interest rate by 12 to get the monthly rate.
Per Double representing the payment period for which you are calculating the interest payment.
If you want to know the interest paid or received during period 20 of an annuity, this value
would be 20.
Nper Double representing the total number of payments in the annuity. This is usually expressed
in months, and you should be sure that the interest rate given above is for the same period
that you enter here.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 378
Pv Double representing the present value of your annuity. In the case of a loan, the present
value would be the amount of the loan because that is the amount of cash you have in the
present. In the case of a retirement plan, this value would be the current value of the fund
because you have a set amount of principal in the plan.
Fv Double representing the future value of your annuity. In the case of a loan, the future value
would be zero because you will have paid it off. In the case of a savings plan, the future
value would be the balance of the account after all payments are made.
Due Integer indicating when payments are due. If this parameter is 0, then payments are due at
the end of each period (usually, the end of the month). If this value is 1, then payments are
due at the start of each period (the beginning of the month).
Rate and Nper must be in expressed in the same units. If Rate is expressed in percentage paid per
month, then Nper must also be expressed in months. If Rate is an annual rate, then the period given
in Nper should also be in years or the annual Rate should be divided by 12 to obtain a monthly rate. If
the function returns a negative value, it represents interest you are paying out, whereas a positive value
represents interest paid to you.
Example This example calculates the amount of interest paid on a $1,000.00 loan financed over 36 months with an
annual interest rate of 10%. Payments are due at the beginning of the month. The interest paid during the
first 10 months is displayed in a table.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
msg1 = ""
For x = 1 to 10
ipm# = IPmt((.10/12),x,36,1000,0,1)
msg1 = msg1 & Format(x,"00") & " : " & Format(ipm#," 0,0.00") & crlf
Next x
MsgBox msg1
End Sub
See Also NPer (page 420) (function); Pmt (page 440) (function); PPmt (page 441) (function); Rate (page
453) (function).
IRR (function)
Description Returns the internal rate of return for a series of periodic payments and receipts.
Comments The internal rate of return is the equivalent rate of interest for an investment consisting of a series of
positive and/or negative cash flows over a period of regular intervals. It is usually used to project the rate
of return on a business investment that requires a capital investment up front and a series of investments
and returns on investment over time. The IRR function requires the following parameters:
Parameter Description
ValueArray() Array of Double numbers that represent payments and receipts. Positive values are
payments, and negative values are receipts. There must be at least one positive and one
negative value to indicate the initial investment (negative value) and the amount earned by
the investment (positive value).
Guess Double containing your guess as to the value that the IRR function will return. The most
common guess is .1 (10 percent).
The value of IRR is found by iteration. It starts with the value of Guess and cycles through the calculation
adjusting Guess until the result is accurate within 0.00001 percent. After 20 tries, if a result cannot be
found, IRR fails, and the user must pick a better guess.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 379
Example This example illustrates the purchase of a lemonade stand for $800 and a series of incomes from the sale
of lemonade over 12 months. The projected incomes for this example are generated in two For...Next
Loops, and then the internal rate of return is calculated and displayed. (Not a bad investment!)
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
Dim valu#(12)
valu(1) = -800 'Initial investment
msg1 = valu#(1) & ", "
See Also Fv (page 353) (function); MIRR (page 404) (function); Npv (page 420) (function); Pv (page 450)
(function).
Is (operator)
Description Returns True if the two operands refer to the same object; returns False otherwise.
Comments This operator is used to determine whether two object variables refer to the same object. Both operands
must be object variables of the same type (i.e., the same data object type or both of type Object ). The
Nothing constant can be used to determine whether an object variable is uninitialized:
If MyObject Is Nothing Then MsgBox "MyObject is uninitialized."
Example This function inserts the date into a Microsoft Word document.
Sub InsertDate(ByVal WinWord As Object)
If WinWord Is Nothing Then
MsgBox "Object variant is not set."
Else
WinWord.Insert Date$
End If
End Sub
Sub Main()
Dim WinWord As Object
On Error Resume Next
WinWord = CreateObject("word.basic")
InsertDate WinWord
End Sub
See Also Operator Precedence (page 431) (topic); Like (page 391) (operator).
Platform(s) All.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 380
Notes When comparing OLE automation objects, the Is operator will only return True if the operands
reference the same OLE automation object. This is different from data objects. For example, the following
use of Is (using the object class called excel.application ) returns True :
Dim a As Object
Dim b As Object
a = CreateObject("excel.application")
b = a
If a Is b Then Beep
The following use of Is will return False , even though the actual objects may be the same:
Dim a As Object
Dim b As Object
a = CreateObject("excel.application")
b = GetObject(,"excel.application")
If a Is b Then Beep
The Is operator may return False in the above case because, even though a and b reference the
same object, they may be treated as different objects by OLE 2.0 (this is dependent on the OLE 2.0
server application).
IsDate (function)
Description Returns True if expression can be legally converted to a date; returns False otherwise.
Example
Sub Main()
Dim a As Variant
Retry:
a = InputBox("Enter a date.","Enter Date")
If IsDate(a) Then
MsgBox Format(a,"long date")
Else
Msgbox "Not quite, please try again!"
Goto Retry
End If
End Sub
See Also Variant (page 515) (data type); IsEmpty (page 380) (function); IsError (page 381) (function); IsObject
(page 383) (function); VarType (page 516) (function); IsNull (page 382) (function).
IsEmpty (function)
Description Returns True if expression is a Variant variable that has never been initialized; returns False
otherwise.
Example
Sub Main()
Dim a As Variant
If IsEmpty(a) Then
a = 1.0# 'Give uninitialized data a Double value 0.0.
MsgBox "The variable has been initialized to: " & a
Else
MsgBox "The variable was already initialized!"
End If
End Sub
See Also Variant (page 515) (data type); IsDate (page 380) (function); IsError (page 381) (function); IsObject
(page 383) (function); VarType (page 516) (function); IsNull (page 382) (function).
IsError (function)
Description Returns True if expression is a user-defined error value; returns False otherwise.
Example This example creates a function that divides two numbers. If there is an error dividing the numbers, then
a variant of type "error" is returned. Otherwise, the function returns the result of the division. The IsError
function is used to determine whether the function encountered an error.
Function Div(ByVal a,ByVal b) As Variant
If b = 0 Then
Div = CVErr(2112) 'Return a special error value.
Else
Div = a / b 'Return the division.
End If
End Function
Sub Main()
Dim a As Variant
a = Div(10,12)
If IsError(a) Then
MsgBox "The following error occurred: " & CStr(a)
Else
MsgBox "The result of the division is: " & a
End If
End Sub
See Also Variant (page 515) (data type); IsEmpty (page 380) (function); IsDate (page 380) (function); IsObject
(page 383) (function); VarType (page 516) (function); IsNull (page 382) (function).
IsMissing (function)
Description Returns True if variable was passed to the current subroutine or function; returns False if omitted.
Comments The IsMissing is used with variant variables passed as optional parameters (using the Optional
keyword) to the current subroutine or function. For non-variant variables or variables that were not
declared with the Optional keyword, IsMissing will always return True .
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 382
Example The following function runs an application and optionally minimizes it. If the optional isMinimize parameter
is not specified by the caller, then the application is not minimized.
Sub Test(AppName As String,Optional isMinimize As Variant)
app = Shell(AppName)
If Not IsMissing(isMinimize) Then
AppMinimize app
Else
AppMaximize app
End If
End Sub
Sub Main
Test "notepad.exe" 'Maximize this application
Test "notepad.exe",True 'Minimize this application
End Sub
See Also Declare (page 276) (statement), Sub...End Sub (page 496) (statement), Function...End Function
(statement) (page 353)
IsNull (function)
Description Returns True if expression is a Variant variable that contains no valid data; returns False otherwise.
Example
Sub Main()
Dim a As Variant 'Initialized as Empty
If IsNull(a) Then MsgBox "The variable contains no valid data."
a = Empty * Null
If IsNull(a) Then MsgBox "Null propagated through the expression."
End Sub
See Also Empty (page 321) (constant); Variant (page 515) (data type); IsEmpty (page 380) (function); IsDate
(page 380) (function); IsError (page 381) (function); IsObject (page 383) (function); VarType (page
516) (function).
IsNumeric (function)
Description Returns True if expression can be converted to a number; returns False otherwise.
Comments If passed a number or a variant containing a number, then IsNumeric always returns True . If a String
or String variant is passed, then IsNumeric will return True only if the string can be converted to a
number. The following syntaxes are recognized as valid numbers:
&Hhexdigits[&|%|!|#|@]
&[O]octaldigits[&|%|!|#|@]
[-|+]digits[.[digits]][E[-|+]digits][!|%|&|#|@]
If an Object variant is passed, then the default property of that object is retrieved and one of the above
rules is applied. IsNumeric returns False if expression is a Date .
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 383
Example
Sub Main()
Dim s$ As String
s$ = InputBox("Enter a number.","Enter Number")
If IsNumeric(s$) Then
MsgBox "You did good!"
Else
MsgBox "You didn't do so good!"
End If
End Sub
See Also Variant (page 515) (data type); IsEmpty (page 380) (function); IsDate (page 380) (function); IsError
(page 381) (function); IsObject (page 383) (function); VarType (page 516) (function); IsNull (page
382) (function).
IsObject (function)
Description Returns True if expression is a Variant variable containing an Object ; returns False otherwise.
Example This example will attempt to find a running copy of Excel and create 'a Excel object that can be referenced
as any other object in the Basic Control Engine.
Sub Main()
Dim v As Variant
On Error Resume Next
Set v = GetObject(,"Excel.Application")
If IsObject(v) Then
MsgBox "The default object value is: " & v = v.Value 'Access value property of the
object.
Else
MsgBox "Excel not loaded."
End If
End Sub
See Also Variant (page 515) (data type); IsEmpty (page 380) (function); IsDate (page 380) (function); IsError
(page 381) (function); VarType (page 516) (function); IsNull (page 382) (function).
IsWebSpaceSession (function)
Syntax IsWebSpaceSession
Example
Sub Main()
End Sub
Item$ (function)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 384
Description Returns all the items between first and last within the specified formatted text list.
Parameter Description
text$ String containing the text from which a range of items is returned.
first Integer containing the index of the first item to be returned. If first is greater than the number
of items in text$, then a zero-length string is returned.
last Integer containing the index of the last item to be returned. All of the items between first and
last are returned. If last is greater than the number of items in text$, then all items from first
to the end of text are returned.
delimiters String containing different item delimiters. By default, items are separated by commas
$ and end-of-lines. This can be changed by specifying different delimiters in the delimiters$
parameter.
Example This example creates two delimited lists and extracts a range from each, then displays the result in a
dialog box.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
ilist$ = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15"
slist$ = "1/2/3/4/5/6/7/8/9/10/11/12/13/14/15"
list1$ = Item$(ilist$,5,12)
list2$ = Item$(slist$,2,9,"/")
MsgBox "The returned lists are: " & crlf & list1$ & crlf & list2$
End Sub
See Also ItemCount (page 384) (function); Line$ (page 392) (function); LineCount (page 393) (function); Word
$ (page 529) (function); WordCount (page 530) (function).
ItemCount (function)
Description Returns an Integer containing the number of items in the specified delimited text.
Comments Items are substrings of a delimited text string. Items, by default, are separated by commas and/or end-of-
lines. This can be changed by specifying different delimiters in the delimiters$ parameter. For example, to
parse items using a backslash:
n = ItemCount(text$,"\")
Example This example creates two delimited lists and then counts the number of items in each. The counts are
displayed in a dialog box.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
ilist$ = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15"
slist$ = "1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16/17/18/19"
l1% = ItemCount(ilist$)
l2% = ItemCount(slist$,"/")
msg1 = "The first lists contains: " & l1% & " items." & crlf
msg1 = msg1 & "The second list contains: " & l2% & " items."
MsgBox msg1
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 385
See Also Item$ (page 383) (function); Line$ (page 392) (function); LineCount (page 393) (function); Word$
(page 529) (function); WordCount (page 530) (function).
Keywords (topic)
Kill (statement)
Keywords (topic)
A keyword is any word or symbol recognized by the Basic Control Engine as part of the language. All of the following
are keywords:
Restrictions All keywords are reserved by the Basic Control Engine , in that you cannot create a variable, function,
constant, or subroutine with the same name as a keyword. However, you are free to use all keywords as the names of
structure members.
Kill (statement)
Comments The filespec$ argument can include wildcards, such as * and ? . The * character matches any
sequence of zero or more characters, whereas the ? character matches any single character. Multiple
* 's and ? 's can appear within the expression to form complex searching patterns. The following table
shows some examples.
* (All files)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 386
Example This example looks to see whether file test1.dat exists. If it does not, then it creates both test1.dat and
test2.dat. The existence of the files is tested again; if they exist, a message is generated, and then they
are deleted. The final test looks to see whether they are still there and displays the result.
Sub Main()
If Not FileExists("test1.dat") Then
Open "test1.dat" For Output As #1
Open "test2.dat" For Output As #2
Close
End If
If FileExists ("test1.dat") Then
MsgBox "File test1.dat exists."
Kill "test?.dat"
End If
If FileExists ("test1.dat") Then
MsgBox "File test1.dat still exists."
Else
MsgBox "test?.dat successfully deleted."
End If
End Sub
LBound (function)
Len (function)
Let (statement)
Like (operator)
Line$ (function)
LineCount (function)
ListBox (statement)
Literals (topic)
Loc (function)
Lock (statement)
Lof (function)
Log (function)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 387
LSet (statement)
LBound (function)
Description Returns an Integer containing the lower bound of the specified dimension of the specified array variable.
Comments The dimension parameter is an integer specifying the desired dimension. If this parameter is not specified,
then the lower bound of the first dimension is returned. The LBound function can be used to find the
lower bound of a dimension of an array returned by an OLE automation method or property:
LBound(object.property [,dimension])
LBound(object.method [,dimension])
Examples
Sub Main()
'This example dimensions two arrays and displays their lower bounds.
Dim a(5 To 12)
Dim b(2 To 100,9 To 20)
lba = LBound(a)
lbb = LBound(b,2)
MsgBox "The lower bound of a is: " & lba & " The lower bound of b is: " & lbb
See Also UBound (page 510) (function); ArrayDims (page 217) (function); Arrays (page 218) (topic).
Comments LCase$ returns a String , whereas LCase returns a String variant. Null is returned if text is Null .
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 388
Example This example shows the LCase function used to change uppercase names to lowercase with an
uppercase first letter.
Sub Main()
lname$ = "WILLIAMS"
fl$ = Left(lname$,1)
rest$ = Mid(lname$,2,Len(lname$))
lname$ = fl$ & LCase(rest$)
MsgBox "The converted name is: " & lname$
End Sub
Function Returns
Left$ String
The length parameter is an Integer value specifying the number of characters to return as
follows.
Length is Returns
0 Zero-length string
Functions Return
LeftB and LeftB$ Sequence of bytes from a string containing byte data.
Length is Returns
Comments Left$ returns a String , whereas Left returns a String variant. NumChars is an Integer value
specifying the number of character to return. If NumChars is 0, then a zero-length string is returned. If
NumChars is greater than or equal to the number of characters in the specified string, then the entire
string is returned. NULL is returned if text is NULL.
Example This example shows the Left$ function used to change uppercase names to lowercase with an uppercase
first letter.
Sub Main()
lname$ = "WILLIAMS"
fl$ = Left(lname$,1)
rest$ = Mid(lname$,2,Len(lname$))
lname$ = fl$ & LCase(rest$)
MsgBox "The converted name is: " & lname$
End Sub
Len (function)
Description Returns the number of characters in expression or the number of bytes required to store the specified
variable.
Comments If expression evaluates to a string, then Len returns the number of characters in a given string or 0 if
the string is empty. When used with a Variant variable, the length of the variant when converted to a
String is returned. If expression is a Null , then Len returns a Null variant. If used with a non-String
or non- Variant variable, the function returns the number of bytes occupied by that data element. When
used with user-defined data types, the function returns the combined size of each member within the
structure. Since variable-length strings are stored elsewhere, the size of each variable-length string within
a structure is 2 bytes. The following table describes the sizes of the individual data elements:
Data Size
Element
Integer 2 bytes
Long 4 bytes
Float 4 bytes
Double 8 bytes.
Currency 8 bytes
Objects 0 bytes. Both data object variables and variables of type Object are always returned as 0
size.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 390
User- Combined size of each structure member. Variable-length strings within structures require
defined 2 bytes of storage. Arrays within structures are fixed in their dimensions. The elements for
type fixed arrays are stored within the structure and therefore require the number of bytes for each
array element multiplied by the size of each array dimension: element_size * dimension1 *
dimension2...
The Len function always returns 0 with object variables or any data object variable.
Let (statement)
Comments The use of the word Let is supported for compatibility with other implementations of the Basic
Control Engine. Normally, this word is dropped. When assigning expressions to variables, internal type
conversions are performed automatically between any two numeric quantities. Thus, you can freely
assign numeric quantities without regard to type conversions. However, it is possible for an overflow
error to occur when converting from larger to smaller types. This happens when the larger type contains
a numeric quantity that cannot be represented by the smaller type. For example, the following code will
produce a runtime error:
Dim amount As Long
im quantity As Integer
amount = 400123 'Assign a value out of range for int.
quantity = amount 'Attempt to assign to Integer.
Example
Sub Main()
Let a$ = "This is a string."
Let b% = 100
Let c# = 1213.3443
End Sub
See Also = (page 202) (keyword); Expression Evaluation (page 336) (topic).
Like (operator)
Description Compares two strings and returns TRUE if the expression matches the given pattern; returns FALSE
otherwise.
Comments Case sensitivity is controlled by the Option Compare setting. The pattern expression can contain
special characters that allow more flexible matching:
Character Evaluates to
[!range] Matches if the character in question is not within the specified range.
A range specifies a grouping of characters. To specify a match of any of a group of characters, use the
syntax [ABCDE] . To specify a range of characters, use the syntax [A-Z] . Special characters must
appear within brackets, such as []*?# . If expression or pattern is not a string, then both expression and
pattern are converted to String variants and compared, returning a Boolean variant. If either variant is
Null , then Null is returned. The following table shows some examples:
See Also Operator Precedence (page 431) (topic); Is (page 379) (operator); Option Compare (page 432)
(statement).
Comments The filenumber parameter is a number that is used to refer to the open file¾the number passed to the
Open statement. The filenumber must reference a file opened in Input mode. The file is read up to the
next end-of-line, but the end-of-line character(s) is (are) not returned in the string. The file pointer is
positioned after the terminating end-of-line.
The variable parameter is any string or variant variable reference. This statement will automatically
declare the variable if the specified variable has not yet been used or dimensioned. This statement
recognizes either a single line feed or a carriage-return/line-feed pair as the end-of-line delimiter.
Example This example reads five lines of the autoexec.bat file and displays them in a dialog box.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
file$ = "c:\autoexec.bat"
Open file$ For Input As #1
msg1 = ""
For x = 1 To 5
Line Input #1,lin$
msg1 = msg1 & lin$ & crlf
Next x
MsgBox "The first 5 lines of '" & file$ & "' are:" & crlf & crlf & msg1
End Sub
See Also Open (page 428) (statement); Get (page 355) (statement); Input# (page 372) (statement); Input,
Input$ (page 373) (functions).
Line$ (function)
Syntax Line$(text$,first[,last])
Description Returns a String containing a single line or a group of lines between first and last.
Comments Lines are delimited by carriage return, line feed, or carriage-return/line-feed pairs. The Line$ function
takes the following parameters:
Parameter Description
text$ String containing the text from which the lines will be extracted.
first Integer representing the index of the first line to return. If last is omitted, then this line will
be returned. If first is greater than the number of lines in text$, then a zero-length string is
returned.
Example This example reads five lines of the autoexec.bat file, extracts the third and fourth lines with the Line$
function, and displays them in a dialog box.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
file$ = "c:\autoexec.bat"
Open file$ For Input As #1
txt = ""
For x = 1 To 5
Line Input #1,lin$
txt = txt & lin$ & crlf
Next x
lines$ = Line$(txt,3,4)
MsgBox "The 3rd and 4th lines of '" & file$ & "' are:" & crlf_
& crlf & lines$
End Sub
See Also Item$ (page 383) (function); ItemCount (page 384) (function); LineCount (page 393) (function); Word
$ (page 529) (function); WordCount (page 530) (function).
LineCount (function)
Example This example reads your autoexec.bat file into a variable and then determines how many lines it is
comprised of.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
file$ = "c:\autoexec.bat"
Open file$ For Input As #1
txt = ""
Do Until Eof(1)
Line Input #1,lin$
txt = txt & lin$ & crlf
Loop
lines! = LineCount(txt)
MsgBox "'" & file$ & "' is " & lines! & " lines long!" & crlf_
& crlf & txt
End Sub
See Also Item$ (page 383) (function); ItemCount (page 384) (function); Line$ (page 392) (function); Word$
(page 529) (function); WordCount (page 530) (function).
Line numbers are not supported by the Basic Control Engine. As an alternative to line numbers, you can use
meaningful labels as targets for absolute jumps, as shown below:
Sub Main()
Dim i As Integer
On Error Goto MyErrorTrap
i = 0
LoopTop:
i = i + 1
If i < 10 Then Goto LoopTop
MyErrorTrap:
MsgBox "An error occurred."
End Sub
ListBox (statement)
Comments When the dialog box is invoked, the list box will be filled with the elements contained in ArrayVariable.
This statement can only appear within a dialog box template (that is, between the Begin Dialog and
End Dialog statements). The ListBox statement requires the following parameters:
Parameter Description
X, Y Integer coordinates specifying the position of the control (in dialog units) static to the
upper left corner of the dialog box.
width, height Integer coordinates specifying the dimensions of the control in dialog units.
ArrayVariable Specifies a single-dimensioned array of strings used to initialize the elements of the
list box. If this array has no dimensions, then the list box will be initialized with no
elements. A runtime error results if the specified array contains more than one dimension.
ArrayVariable can specify an array of any fundamental data type (structures are not
allowed). Null and Empty values are treated as zero-length strings.
Identifier Name by which this control can be referenced by statements in a dialog function (such
as DlgFocus and DlgEnable ). This parameter also creates an integer variable
whose value corresponds to the index of the list box's selection (0 is the first item, 1
is the second, and so on). This variable can be accessed using the following syntax:
DialogVariable . Identifier
Example This example creates a dialog box with two list boxes, one containing files and the other containing
directories.
Sub Main()
Dim files() As String
Dim dirs() As String
Begin Dialog ListBoxTemplate 16,32,184,96,"Sample"
Text 8,4,24,8,"&Files:"
ListBox 8,16,60,72,files$,.Files
Text 76,4,21,8,"&Dirs:"
ListBox 76,16,56,72,dirs$,.Dirs
OKButton 140,4,40,14
CancelButton 140,24,40,14
End Dialog
FileList files
FileDirs dirs
See Also CancelButton (page 243) (statement); CheckBox (page 240) (statement); ComboBox (page 249)
(statement); Dialog (page 278) (function); Dialog (page 279) (statement); DropListBox (page 301)
(statement); GroupBox (page 361) (statement); OKButton (page 426) (statement); OptionButton (page
434) (statement); OptionGroup (page 435) (statement); Picture (page 438) (statement); PushButton
(page 439) (statement); Text (page 502) (statement); TextBox (page 503) (statement); Begin (page
231) Dialog (page 231) (statement), PictureButton (page 439) (statement).
Literals (topic)
Literals are values of a specific type. The following table shows the different types of literals
supported by the Basic Control Engine:
Literal Description
5# Double whose value is 5.0. A number's type can be explicitly set using any of the following type-declaration
characters:
% Integer
& Long
# Double
! Single
5.5 Double Value is 5.5. Any number with decimal point is considered a double.
"""hello""" String Of seven characters: "hello". Quotation marks can be embedded within strings by using two
consecutive quotation marks.
#1/1/1994# Date value whose internal representation is 34335.0. Any valid date can appear with #'s. Date literals are
interpreted at execution time using the locale settings of the host environment. To ensure that date literals
are correctly interpreted for all locales, use the international date format: #YYYY-MM-DD HH:MM:SS#
Constant Folding The Basic Control Engine supports constant folding where constant expressions are
calculated by the compiler at compile time. For example, the expression i% = 10 + 12 is the same as: i
% = 22 Similarly, with strings, the expression s$ = "Hello," + " there" + (46) is the same as: s$ = "Hello,
there."
Loc (function)
Description Returns a Long representing the position of the file pointer in the given file.
Comments The filenumber parameter is an Integer used by the Basic Control Engine to refer to the number
passed by the Open statement to the Basic Control Engine . The Loc function returns different values
depending on the mode in which the file was opened:
Example This example reads 5 lines of the autoexec.bat file, determines the current location of the file pointer, and
displays it in a dialog box.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
file$ = "c:\autoexec.bat"
Open file$ For Input As #1
For x = 1 To 5
If Not EOF(1) Then Line Input #1,lin$
Next x
lc% = Loc(1)
Close
MsgBox "The file byte location is: " & lc%
End Sub
See Also Seek (page 471) (function); Seek (page 472) (statement); FileLen (page 342) (function).
Lock (statement)
Description Locks a section of the specified file, preventing other processes from accessing that section of the file until
the Unlock statement is issued.
Parameter Description
filenumber Integer used by the Basic Control Engine to refer to the open file—the number passed to
the Open statement.
For sequential files, the record, start, and end parameters are ignored. The entire file is locked. The
section of the file is specified using one of the following:
Syntax Description
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 397
record Locks the specified record number (for Random files) or byte (for Binary files).
to end Locks from the beginning of the file to the specified record (for Random files) or byte (for
Binary files).
start to end Locks the specified range of records (for Random files) or bytes (for Binary files).
The lock range must be the same as that used to subsequently unlock the file range, and all locked
ranges must be unlocked before the file is closed. Ranges within files are not unlocked automatically by
the Basic Control Engine when your script terminates, which can cause file access problems for other
processes. It is a good idea to group the Lock and Unlock statements close together in the code, both
for readability and so subsequent readers can see that the lock and unlock are performed on the same
range. This practice also reduces errors in file locks.
Example This example creates test.dat and fills it with ten string variable records. These are displayed in a dialog
box. The file is then reopened for read/write, and each record is locked, modified, rewritten, and unlocked.
The new records are then displayed in a dialog box.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
a$ = "This is record number: "
b$ = "0"
rec$ = ""
msg1 = ""
Open "test.dat" For Random Access Write Shared As #1
For x = 1 To 10
rec$ = a$ & x
Lock #1,x
Put #1,,rec$
Unlock #1,x
msg1 = msg1 & rec$ & crlf
Next x
Close
MsgBox "The records are:" & crlf & msg1
msg1 = ""
Open "test.dat" For Random Access Read Write Shared As #1
For x = 1 To 10
rec$ = Mid(rec$,1,23) & (11 - x)
Lock #1,x
Put #1,x,rec$
Unlock #1,x
msg1 = msg1 & rec$ & crlf
Next x
MsgBox "The records are: " & crlf & msg1
Close
Kill "test.dat"
End Sub
See Also Unlock (page 511) (statement); Open (page 428) (statement).
Lof (function)
Description Returns a Long representing the number of bytes in the given file.
Comments The filenumber parameter is an Integer used by the Basic Control Engine to refer to the open file, the
number passed to the Open statement. The file must currently be open.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 398
Example This example creates a test file, writes ten records into it, then finds the length of the file and displays it in
a message box.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
a$ = "This is record number: "
See Also Loc (page 395) (function); Open (page 428) (statement); FileLen (page 342) (function).
Log (function)
Comments The value of number must be a Double greater than 0. The value of e is
2.71828.
Example This example calculates the natural log of 100 and displays it in a message box.
Sub Main()
x# = Log(100)
MsgBox "The natural logarithm of 100 is: " & x#
End Sub
Syntax Long
Description Long variables are used to hold numbers (with up to ten digits of precision) within the following range:
–2,147,483,648 <= Long <= 2,147,483,647
Internally, longs are 4-byte values. Thus, when appearing within a structure, longs require 4 bytes of
storage. When used with binary or random files, 4 bytes of storage are required. The type-declaration
character for Long is & .
See Also Currency (page 259) (data type); Date (page 263) (data type); Double (page 300) (data type);
Integer (page 377) (data type); Object (page 422) (data type); Single (page 479) (data type); String
(page 494) (data type); Variant (page 515) (data type); Boolean (page 233) (data type); DefType
(page 276) (statement); CLng (page 248) (function).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 399
LSet (statement)
Syntax 1
LSet dest = source
Syntax 2
LSet dest_variable = source_variable
Description Left-aligns the source string in the destination string or copies one user-defined type to another.
Comments Syntax 1 The LSet statement copies the source string source into the destination string dest. The
dest parameter must be the name of either a String or Variant variable. The source parameter is any
expression convertible to a string. If source is shorter in length than dest, then the string is left-aligned
within dest, and the remaining characters are padded with spaces. If source$ is longer in length than
dest, then source is truncated, copying only the leftmost number of characters that will fit in dest. The
destvariable parameter specifies a String or Variant variable. If destvariable is a Variant containing
Empty, then no characters are copied. If destvariable is not convertible to a String, then a runtime error
occurs. A runtime error results if destvariable is Null . Syntax 2 The source structure is copied byte for
byte into the destination structure. This is useful for copying structures of different types. Only the number
of bytes of the smaller of the two structures is copied. Neither the source structure nor the destination
structure can contain strings.
Example This example replaces a 40-character string of asterisks (*) with an RSet and LSet string and then
displays the result.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
Dim msg,tmpstr$
tmpstr$ = String(40,"*")
msg1 = "Here are two strings that have been right-" + crlf
msg1 = msg1 & "and left-justified in a 40-character string."
Msg1 = msg1 & crlf & crlf
Rset tmpstr$ = "Right|"
msg1 = msg1 & tmpstr$ & crlf
LSet tmpstr$ = "|Left"
msg1 = msg1 & tmpstr$ & crlf
MsgBox msg1
End Sub
Syntax
LTrim[$](text)
Comments LTrim$ returns a String , whereas LTrim returns a String variant. Null is returned if text is
Null .
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 400
Example This example displays a right-justified string and its LTrim result. Const crlf = Chr$(13) + Chr$(10)
Sub Main()
txt$ = " This is text "
tr$ = LTrim(txt$)
MsgBox "Original ->" & txt$ & "<-" & crlf & "Left Trimmed ->" & tr$ & "<-"
End Sub
See Also RTrim, RTrim$ (page 464) (functions); Trim, Trim$ (page 506) (functions).
Main (statement)
MCI (function)
Minute (function)
MIRR (function)
MkDir (statement)
Mod (operator)
Month (function)
Msg.Close (method)
Msg.Open (method)
Msg.Text (property)
Msg.Thermometer (property)
MsgBox (function)
MsgBox (statement)
Main (statement)
Syntax
Sub Main()
End Sub
Example
Sub Main()
MsgBox "This is the Main() subroutine and entry point."
End Sub
MCI (function)
Description Executes an Mci command, returning an Integer indicating whether the command was successful.
Parameter Description
result$ String variable into which the result is placed. If the command doesn't return anything, then
a zero-length string is returned. To ignore the returned string, pass a zero-length string, such
as. r% = Mci("open chimes.wav type waveaudio","")
error$ Optional String variable into which an error string will be placed. A zero-length string will be
returned if the function is successful.
Example 1 This first example plays a wave file. The wave file is played to completion before execution can continue.
Sub Main()
Dim result As String
Dim ErrorMessage As String
Dim Filename As String
Dim rc As Integer
'Establish name of file in the Windows directory.
Filename = FileParse$(System.WindowsDirectory$ + "\" + "chimes.wav")
'Open the file and driver.
rc = Mci("open " & Filename & " type waveaudio alias CoolSound","",ErrorMessage)
If (rc) Then
'Error occurred--display error message to user.
MsgBox ErrorMessage
Exit Sub
End If
rc = Mci("play CoolSound wait","","") 'Wait for sound to finish.
rc = Mci("close CoolSound","","") 'Close driver and file.
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 402
Example 2 This next example shows how to query an Mci device and play an MIDI file in the background.
Sub Main()
Dim result As String
Dim ErrMsg As String
Dim Filename As String
Dim rc As Integer
'Check to see whether MIDI device can play for us.
rc = Mci("capability sequencer can play",result,ErrorMessage)
'Check for error.
If rc Then
MsgBox ErrorMessage
Exit Sub
End If
'Can it play?
If result <> "true" Then
MsgBox "MIDI device is not capable of playing."
Exit Sub
End If
'Assemble a filename from the Windows directory.
Filename = FileParse$(System.WindowsDirectory$ & "\" & "canyon.mid")
Description Returns a sub-string of the specified string, beginning with start, for length characters (for Mid and Mid$) or
bytes (for MidB and MidB$).
Mid and Sub-string starting at character position start and will be length characters long
Mid$
MidB and Sub-string starting at byte position start and will be length bytes long.
MidB$
Functions Return
The returned sub-string starts at character position start and will be length characters long. Mid$
returns a String , whereas Mid returns a String variant. The Mid/Mid$ functions take the following
parameters:
Parameter Description
string Any String expression containing the text from which data is returned.
start Integer specifying the position where the sub-string begins. If start is greater than the length
of string, then a zero-length string is returned.
length Integer specifying the number of characters or bytes to return. If this parameter is omitted,
then the entire string is returned, starting at start.
The Mid function will return Null text is Null . The MidB and MidB$ functions are used to return a sub-
string of bytes from a string containing byte data.
Example
'This example displays a substring from the middle of a
'string variable using the Mid$ function and replaces the
'first four characters with "NEW " using the Mid$ statement.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
a$ = "This is the Main string containing text."
b$ = Mid$(a$,13,Len(a$))
Mid$ (b$,1) = NEW "
MsgBox a$ & crlf & b$
End Sub
See Also InStr, InStrB (page 375) (functions), Option Compare (page 432) (statement), Mid, Mid$, MidB, MidB$
(page 403) (statements)
Parameter Description
start Integer specifying the character position (for Mid and Mid$) or byte position (for MidB and MidB
$) within variable where replacement begins. If start is greater than the length of variable,
then variable remains unchanged.
length Integer specifying the number of characters or bytes to change. If this parameter is omitted,
then the entire string is changed, starting at start.
newvalue Expression used as the replacement. This expression must be convertible to a String.
The resultant string is never longer than the original length of variable. With Mid and MidB, variable must
be a Variant variable convertible to a String, and newvalue is any expression convertible to a string. A
runtime error is generated if either variant is NULL. Statements are used to replace the following.
Statement Replaces
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 404
Example
'This example displays a substring from the middle of a
'string variable using the Mid$ function, replacing the
'first four characters with "NEW " using the Mid$ statement.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
a$ = "This is the Main string containing text."
b$ = Mid$(a$,13,Len(a$))
Mid$(b$,1) = "NEW " End Sub
See Also Mid, Mid$, MidB, MidB$ (page 402) (functions), Option Compare (page 432) (statement)
Minute (function)
Description Returns the minute of the day encoded in the specified time parameter.
Comments The value returned is as an Integer between 0 and 59 inclusive. The time parameter is any expression
that converts to a Date .
Example This example takes the current time; extracts the hour, minute, and second; and displays them as the
current time.
Sub Main()
Msgbox "It is now minute " & Minute(Time) & " of the hour."
End Sub
See Also Day (page 269) (function); Second (page 471) (function); Month (page 406) (function); Year (page
533) (function); Hour (page 364) (function); Weekday (page 521) (function); DatePart (page 267)
(function).
MIRR (function)
Description Returns a Double representing the modified internal rate of return for a series of periodic payments and
receipts.
Comments The modified internal rate of return is the equivalent rate of return on an investment in which payments
and receipts are financed at different rates. The interest cost of investment and the rate of interest
received on the returns on investment are both factors in the calculations. The MIRR function requires
the following parameters:
Parameter Description
ValueArray() Array of Double numbers representing the payments and receipts. Positive values are
payments (invested capital), and negative values are receipts (returns on investment).
There must be at least one positive (investment) value and one negative (return) value.
FinanceRate Double representing the interest rate paid on invested monies (paid out).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 405
ReinvestRate Double representing the rate of interest received on incomes from the investment
(receipts).
FinanceRate and ReinvestRate should be expressed as percentages. For example, 11 percent should be
expressed as 0.11. To return the correct value, be sure to order your payments and receipts in the correct
sequence.
Example This example illustrates the purchase of a lemonade stand for $800 financed with money borrowed at
10%. The returns are estimated to accelerate as the stand gains popularity. The proceeds are placed in
a bank at 9 percent interest. The incomes are estimated (generated) over 12 months. This program first
generates the income stream array in two For...Next loops, and then the modified internal rate of return is
calculated and displayed. Notice that the annual rates are normalized to monthly rates by dividing them by
12.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
Dim valu#(12)
valu(1) = -800 'Initial investment
msg1 = valu(1) & ", "
For x = 2 To 5
valu(x) = 100 + (x * 2) 'Incomes months 2-5
msg1 = msg1 & valu(x) & ", "
Next x
For x = 6 To 12
valu(x) = 100 + (x * 10) 'Incomes months 6-12
msg1 = msg1 & valu(x) & ", "
Next x
retrn# = MIRR(valu,.1/12,.09/12) 'Note: normalized annual rates
msg1 = "The values: " & crlf & msg1 & crlf & crlf
MsgBox msg1 & "Modified rate: " & Format(retrn#,"Percent")
End Sub
See Also Fv (page 353) (function); IRR (page 378) (function); Npv (page 420) (function); Pv (page 450)
(function).
MkDir (statement)
Example This example creates a new directory on the default drive. If this causes an error, then the error is
displayed and the program terminates. If no error is generated, the directory is removed with the RmDir
statement.
Sub Main()
On Error Resume Next
MkDir "testdir"
If Err <> 0 Then
MsgBox "The following error occurred: " & Error(Err)
Else
MsgBox "Directory 'testdir' was created and is about to be removed."
RmDir "testdir"
End If
End Sub
See Also ChDir (page 239) (statement); ChDrive (page 239) (statement); CurDir, CurDir$ (page 259)
(functions); Dir, Dir$ (page 280) (functions); RmDir (page 463) (statement).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 406
Mod (operator)
Comments If both expressions are integers, then the result is an integer. Otherwise, each expression is converted to
a Long before performing the operation, returning a Long . A runtime error occurs if the result overflows
the range of a Long . If either expression is Null , then Null is returned. Empty is treated as 0.
Example This example uses the Mod operator to determine the value of a randomly selected card where card 1
is the ace (1) of clubs and card 52 is the king (13) of spades. Since the values recur in a sequence of 13
cards within 4 suits, we can use the Mod function to determine the value of any given card number.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
cval$ = "Ace,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten,Jack,Queen,King"
Randomize
card% = Random(1,52)
value = card% Mod 13
If value = 0 Then value = 13
CardNum$ = Item$(cval,value)
If card% < 53 Then suit$ = "Spades"
If card% < 40 Then suit$ = "Hearts"
If card% < 27 Then suit$ = "Diamonds"
If card% < 14 Then suit$ = "Clubs"
msg1 = "Card number " & card% & " is the "
msg1 = msg 1& CardNum & " of " & suit$
MsgBox msg1
End Sub
Month (function)
Description Returns the month of the date encoded in the specified date parameter.
Comments The value returned is as an Integer between 1 and 12 inclusive. The date parameter is any expression
that converts to a Date .
See Also Day (page 269) (function) Minute (page 404) (function); Second (page 471) (function); Year (page
533) (function); Hour (page 364) (function); Weekday (page 521) (function); DatePart (page 267)
(function).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 407
Msg.Close (method)
Syntax Msg.Close
Example
Sub Main()
Msg.Open "Printing. Please wait...",0,True,True
Sleep 3000
Msg.Close
End Sub
See Also Msg.Open (page 407) (method); Msg.Thermometer (page 408) (property); Msg.Text (page
408) (property).
Msg.Open (method)
Description Displays a message in a dialog box with an optional Cancel button and thermometer.
Parameter Description
prompt String containing the text to be displayed. The text can be changed using the Msg.Text
property.
timeout Integer specifying the number of seconds before the dialog box is automatically removed.
The timeout parameter has no effect if its value is 0.
cancel Boolean controlling whether or not a Cancel button appears within the dialog box beneath
the displayed message. If this parameter is True, then a Cancel button appears. If it is not
specified or False, then no Cancel button is created. If a user chooses the Cancel button
at runtime, a trappable runtime error is generated (error number 18). In this manner, a
message dialog box can be displayed and processing can continue as normal, aborting
only when the user cancels the process by choosing the Cancel button.
thermometer Boolean controlling whether the dialog box contains a thermometer. If this parameter
is True, then a thermometer is created between the text and the optional Cancel
button. The thermometer initially indicates 0% complete and can be changed using the
Msg.Thermometer property.
XPos, YPos Integer coordinates specifying the location of the upper left corner of the message box,
in twips (twentieths of a point). If these parameters are not specified, then the window is
centered on top of the application.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 408
Unlike other dialog boxes, a message dialog box remains open until the user selects Cancel, the timeout
has expired, or the Msg.Close method is executed (this is sometimes referred to as modeless). Only a
single message window can be opened at any one time. The message window is removed automatically
when a script terminates. The Cancel button, if present, can be selected using either the mouse or
keyboard. However, these events will never reach the message dialog unless you periodically call
DoEvents from within your script.
See Also Msg.Close (page 407) (method); Msg.Thermometer (page 408) (property); Msg.Text (page 408)
(property).
Msg.Text (property)
Description Changes the text within an open message dialog box (one that was previously opened with the
Msg.Open method).
Comments The message dialog box is not resized to accommodate the new text. A runtime error will result if a
message dialog box is not currently open (using Msg.Open ).
Example This example creates a modeless message box, leaving room in the message text for the record number.
This box contains a Cancel button.
Sub Main()
Msg.Open "Reading Record",0,True,False
For i = 1 To 100
'Read a record here.
'Update the modeless message box.
Sleep 100
Msg.Text ="Reading record " & i
Next i
Msg.Close
End Sub
See Also Msg.Close (page 407) (method); Msg.Open (page 407) (method); Msg.Thermometer (page 408)
(property).
Msg.Thermometer (property)
Description Changes the percentage filled indicated within the thermometer of a message dialog box (one that was
previously opened with the Msg.Open method).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 409
Comments A runtime error will result if a message box is not currently open (using Msg.Open ) or if the value of
percentage is not between 0 and 100 inclusive.
Example This example create a modeless message box with a thermometer and a Cancel button. This example
also shows how to process the clicking of the Cancel button.
Sub Main()
On Error Goto ErrorTrap
Msg.Open "Reading records from file...",0,True,True
For i = 1 To 100 'Read a record here.
'Update the modeless message box.
Msg.Thermometer =i
DoEvents
Sleep 50
Next i
Msg.Close
On Error Goto 0 'Turn error trap off.
Exit Sub
ErrorTrap:
If Err = 809 Then
MsgBox "Cancel was pressed!"
Exit Sub 'Reset error handler.
End If
End Sub
See Also Msg.Close (page 407) (method); Msg.Open (page 407) (method); Msg.Text (page 408) (property).
MsgBox (function)
Description Displays a message in a dialog box with a set of predefined buttons, returning an Integer representing
which button was selected.
Comments
Important: The message box has an approximate maximum allowed number of characters.
The:
It is estimated that on a 1280x800 resolution approximately 128 characters fit in the message box. The
estimation is based on the fact that some letters/numbers/symbols require more than one character space
(e.g. M); some less (e.g. i). Therefore the exact allowed number of characters depends on what numbers/
letters/symbols are used in the message.
Parameter Description
title Caption of the dialog box. This parameter is any expression convertible to a String. If it
is omitted, then the script is used. A runtime error is generated if title is Null .
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 410
ebOK 1 OK
ebCancel 2 Cancel
ebAbort 3 Abort
ebRetry 4 Retry
ebIgnore 5 Ignore
ebYes 6 Yes
ebNo 7 No
ebOKOnly 0 OK button
The default value for type is 0 (display only the OK button, making it the default). Breaking Text across
Lines The msg parameter can contain end-of-line characters, forcing the text that follows to start on a new
line. The following example shows how to display a string on two lines:
MsgBox "This is on" + Chr(13) + Chr(10) + "two lines."
r = MsgBox("Hello, World")
Example
Sub Main()
MsgBox "This is a simple message box."
MsgBox "This is a message box with a title and an icon.",_
ebExclamation,"Simple"
MsgBox "This message box has OK and Cancel buttons.",_
ebOkCancel,"MsgBox"
MsgBox "This message box has Abort, Retry, and Ignore buttons.",_
ebAbortRetryIgnore,"MsgBox"
MsgBox "This message box has Yes, No, and Cancel buttons.",_
ebYesNoCancel Or ebDefaultButton2,"MsgBox"
MsgBox "This message box has Yes and No buttons.",ebYesNo,"MsgBox"
MsgBox "This message box has Retry and Cancel buttons.",_
ebRetryCancel,"MsgBox"
MsgBox "This message box is system modal!",ebSystemModal
End Sub
See Also AskBox$ (page 221) (function); AskPassword$ (page 222) (function); InputBox, InputBox$ (page
374) (functions); OpenFilename$ (page 429) (function); SaveFilename$ (page 467) (function);
SelectBox (page 473) (function); AnswerBox (page 205) (function).
Note MsgBox displays all text in its dialog box in 8-point MS Sans Serif.
MsgBox (statement)
Description This command is the same as the MsgBox function, except that the statement form does not return a
value. See MsgBox (function).
Example
Sub Main()
MsgBox "This is text displayed in a message box." 'Display text.
MsgBox "The result is: " & (10 * 45) 'Display a number.
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 412
See Also AskBox$ (page 221) (function); AskPassword$ (page 222) (function); Input, Input$, InputB, InputB$
(page 373) (functions); OpenFilename$ (page 429) (function); SaveFilename$ (page 467) (function);
SelectBox (page 473) (function); AnswerBox (page 205) (function).
Name (statement)
Net.AddCon (method)
Net.Browse$ (method)
Net.CancelCon (method)
Net.GetCaps (method)
Net.GetCon$ (method)
Net.User$ (property)
New (keyword)
Not (operator)
Nothing (constant)
Now (function)
NPer (function)
Npv (function)
Null (constant)
Name (statement)
Comments Each parameter must specify a single filename. Wildcard characters such as * and ? are not allowed.
Some platforms allow naming of files to different directories on the same physical disk volume. For
example, the following rename will work under Windows:
Name "c:\samples\mydoc.txt" As "c:\backup\doc\mydoc.bak"
You cannot rename files across physical disk volumes. For example, the following will error under
Windows:
Name "c:\samples\mydoc.txt" As "a:\mydoc.bak" 'This will error!
To rename a file to a different physical disk, you must first copy the file, then erase the original:
FileCopy "c:\samples\mydoc.txt","a:\mydoc.bak" 'Make a copy
Kill "c:\samples\mydoc.txt" 'Delete the original
Example This example creates a file called test.dat and then renames it to test2.dat.
Sub Main()
oldfile$ = "test.dat"
newfile$ = "test2.dat"
On Error Resume Next
If FileExists(oldfile$) Then
Name oldfile$ As newfile$
If Err <> 0 Then
msg1 = "The following error occurred: " & Error(Err)
Else
msg1 = "'" & oldfile$ & "' was renamed to '" & newfile$ & "'"
End If
Else
Open oldfile$ For Output As #1
Close
Name oldfile$ As newfile$
If Err <> 0 Then
msg1 = "'" & oldfile$ & "' not created. The following error occurred: " & Error(Err)
Else
msg1 = "'" & oldfile$ & "' was created and renamed to '" & newfile$ & "'"
End If
End If
MsgBox msg1
End Sub
See Also Kill (page 385) (statement), FileCopy (page 340) (statement).
Many language elements in BasicScript support named parameters. Named parameters allow you to
specify parameters to a function or subroutine by name rather than in adherence to a predetermined
order. The following table contains examples showing various calls to MsgBox both using parameter
by both name and position.
By Name MsgBox Prompt:= "Hello, world."
Using named parameter makes your code easier to read, while at the same time removes you from
knowing the order of parameter. With function that require many parameters, most of which are
optional (such as MsgBox), code becomes significantly easier to write and maintain.
When supported, the names of the named parameter appear in the description of that language
element.
When using named parameter, you must observe the following rules:
• Named parameter must use the parameter name as specified in the description of that language
element. Unrecognized parameter names cause compiler errors.
• All parameters, whether named or positional, are separated by commas.
• The parameter name and its associated value are separated with :=
• If one parameter is named, then all subsequent parameter must also be named as shown below:
Net.AddCon (method)
Description Redirects a local device (a disk drive or printer queue) to the specified shared device or remote server.
The new syntax does not affect previously compiled code. If Password is not specified, then the
default password is used. If empty, then no password is used. If LocalName is not specified, then the
a connection is made to the network resource without redirecting the local device. The UserName
parameter specifies the name of the user making the connection. If UserName is not specified, then the
default user for that process is used. The isPermanent parameter specifies whether the connection should
be restored during subsequent logon operations. Only a successful connection will persist in this manner.
Parameter Description
netpath$ String containing the name of the shared device or the name of a remote server. This
parameter can contain the name of a shared printer queue (such as that returned by
Net.Browse[1] ) or the name of a network path (such as that returned by Net.Browse[0] ).
password String containing the password for the given device or server. This parameter is mainly used
$ to specify the password on a remote server.
localname String containing the name of the local device being redirected, such as "LPT1" or "D:".
$
Example This example sets N: so that it refers to the network path SYS:\PUBLIC.
Sub Main()
Net.AddCon "SYS:\PUBLIC","","N:"
End Sub
See Also Net.CancelCon (page 415) (method); Net.GetCon$ (page 417) (method)
Net.Browse$ (method)
Description Calls the currently installed network's browse dialog box, requesting a particular type of information.
Comments The type parameter is an Integer specifying the type of dialog box to display:
Type Description
0 If type is 0, then this method displays a dialog box that allows the user to browse network volumes
and directories. Choosing OK returns the completed pathname as a String.
1 If type is 1, then this function displays a dialog box that allows the user to browse the network's
printer queues. Choosing OK returns the complete name of that printer queue as a String. This
string is the same format as required by the Net.AddCon method.
This dialog box differs depending on the type of network installed. A runtime error will result if no network
is present.
Net.CancelCon (method)
Description The isForce parameter is True if missing or omitted. The isPermanent parameter indicates if the
disconnection should persist to subsequent logon operations. On all platforms, the Connection parameter
specifies what is to be disconnected. If Connection specifies a local device, then only that device is
disconnected. If Connection specifies a remote device, then all local devices attached to that remote
device are disconnected. Cancels a network connection.
Parameter Description
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 416
connection String containing the name of the device to cancel, such as "LPT1" or "D:".
$
isForce Boolean specifying whether to force the cancellation of the connection if there are open files
or open print jobs.
• If this parameter is True, then this method will close all open files and open print jobs
before the connection is closed.
• If this parameter is False, this the method will issue a runtime error if there are any open
files or open print jobs.
Example This example deletes the drive mapping associated with drive N:.
Sub Main()
Net.CancelCon "N:"
End Sub
See Also Net.AddCon (page 414) (method); Net.GetCon$ (page 417) (method).
Net.GetCaps (method)
Description Returns an Integer specifying information about the network and its capabilities.
Parameter Description
type Integer specifying what type of information to retrieve. This parameter is different from
platform to platform.
localname String specifying the name of the local device to which is attached to the network device to
$ be queried. If this parameter is missing, then information about the first network device is
returned.
Value Description
1 Always returns 0.
2 Network type:
0 No network is installed.
1 Microsoft Network
3 Novell NetWare.
4 Banyan Vines
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 417
5 10Net
6 Locus
7 SunSoft PC NFS.
8 LanStep
9 9 Titles.
10 Articom Lantastic
11 IBM AS/400
13 DEC Pathworks
Version of the network with the major version in the high byte and the minor version in the low byte: Major
= Net.GetCaps(2) \ 256 Minor = Net.GetCaps(2) And &H00FF
Example
Sub Main()
'This example checks the type of network.
If Net.GetCaps(2) = 768 Then _
MsgBox "This is a Novell network."
'This checks whether the net supports retrieval of the
'user name.
If Net.GetCaps(4) And 1 Then _
MsgBox "User name is: " & Net.User$
'This checks whether this net supports the Browse dialog
'boxes.
If Net.GetCaps(6) And &H0010 Then MsgBox Net.Browse$(1)
End Sub
Net.GetCon$ (method)
Description Returns the name of the network resource associated with the specified redirected local device.
Comments The localname$ parameter specifies the name of the local device, such as "LPT1" or "D:". The function
returns a zero-length string if the specified local device is not redirected. A runtime error will result if no
network is present.
See Also Net.CancelCon (page 415) (method); Net.AddCon (page 414) (method).
Net.User$ (property)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 418
Comments A runtime error is generated if the network is not installed. The LocalName parameter is the name of the
local device that the user has made a connection to. If this parameter is omitted, then the name of the
current user of the process is used. If Localname is a network name and the user is connected to that
resource using different names, the network provider may not be able to resolve which user name to
return. In this case, the provider may make an arbitrary choice from the possible user names.
Example
Sub Main()
'This example tells the user who he or she is.
MsgBox "You are " & Net.User$
'This example makes sure this capability is supported.
If Net.GetCaps(4) And 1 Then MsgBox "You are " & _
Net.User$
End Sub
New (keyword)
Description Creates a new instance of the specified object type, assigning it to the specified object variable.
Comments The New keyword is used to declare a new instance of the specified data object. This keyword can
only be used with data object types. At runtime, the application or extension that defines that object
type is notified that a new object is being defined. The application responds by creating a new physical
object (within the appropriate context) and returning a reference to that object, which is immediately
assigned to the variable being declared. When that variable goes out of scope (that is, the Sub or
Function procedure in which the variable is declared ends), the application is notified. The application
then performs some appropriate action, such as destroying the physical object.
See Also Dim (page 279) (statement); Set (page 476) (statement).
Not (operator)
TRUE FALSE
FALSE TRUE
NULL NULL
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 419
Any A binary negation of the number. If the number is an Integer, then an Integer is returned.
numeric Otherwise, the expression is first converted to a Long, then a binary negation is performed,
type returning a Long.
Example This example demonstrates the use of the Not operator in comparing logical expressions and for
switching a True/False toggle variable.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
a = False
b = True
If (Not a and b) Then msg1 = "a = False, b = True" & crlf
toggle% = True
msg1 = msg1 & "toggle% is now " & CBool(toggle%) & crlf
toggle% = Not toggle%
msg1 = msg1 & "toggle% is now " & CBool(toggle%) & crlf
toggle% = Not toggle%
msg1 = msg1 & "toggle% is now " & CBool(toggle%)
MsgBox msg1
End Sub
See Also Boolean (page 233) (data type); Comparison Operators (page 250) (topic).
Nothing (constant)
Description A value indicating that an object variable no longer references a valid object.
Example
Sub Main()
Dim a As Object
If a Is Nothing Then
MsgBox "The object variable references no object."
Else
MsgBox "The object variable references: " & a.Value
End If
End Sub
See Also Set (page 476) (statement); Object (page 422) (data type).
Now (function)
Syntax Now[()]
Description Returns a Date variant representing the current date and time.
Example This example shows how the Now function can be used as an elapsed-time counter.
Sub Main()
t1# = Now
MsgBox "Wait a while and click OK."
t2# = Now
t3# = Second(t2#) - Second(t1#)
MsgBox "Elapsed time was: " & t3# & " seconds."
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 420
See Also Date, Date$ (page 263) (functions); Time, Time$ (page 504) (functions).
NPer (function)
Description Returns the number of periods for an annuity based on periodic fixed payments and a constant rate of
interest.
Comments An annuity is a series of fixed payments paid to or received from an investment over a period of time.
Examples of annuities are mortgages, retirement plans, monthly savings plans, and term loans. The
NPer function requires the following parameters:
Parameter Description
Rate Double representing the interest rate per period. If the periods are monthly, be sure to
normalize annual rates by dividing them by 12.
Pmt Double representing the amount of each payment or income. Income is represented by
positive values, whereas payments are represented by negative values.
Pv Double representing the present value of your annuity. In the case of a loan, the present
value would be the amount of the loan, and the future value (see below) would be zero.
Fv Double representing the future value of your annuity. In the case of a loan, the future value
would be zero, and the present value would be the amount of the loan.
Due Integer indicating when payments are due for each payment period. A 0 specifies payment
at the end of each period, whereas a 1 indicates payment at the start of each period.
Positive numbers represent cash received, whereas negative numbers represent cash paid out.
Example This example calculates the number of $100.00 monthly payments necessary to accumulate $10,000.00
at an annual rate of 10%. Payments are made at the beginning of the month.
Sub Main()
ag# = NPer((.10/12),100,0,10000,1)
MsgBox "The number of monthly periods is: " & Format(ag#,"Standard")
End Sub
See Also IPmt (page 377) (function); Pmt (page 440) (function); PPmt (page 441) (function); Rate (page
453) (function).
Npv (function)
Description Returns the net present value of an annuity based on periodic payments and receipts, and a discount
rate.
Parameter Description
Rate Double that represents the interest rate over the length of the period. If the values are
monthly, annual rates must be divided by 12 to normalize them to monthly rates.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 421
ValueArray() Array of Double numbers representing the payments and receipts. Positive values are
payments, and negative values are receipts. There must be at least one positive and one
negative value.
Positive numbers represent cash received, whereas negative numbers represent cash paid out. For
accurate results, be sure to enter your payments and receipts in the correct order because Npv uses the
order of the array values to interpret the order of the payments and receipts. If your first cash flow occurs
at the beginning of the first period, that value must be added to the return value of the Npv function. It
should not be included in the array of cash flows. Npv differs from the Pv function in that the payments
are due at the end of the period and the cash flows are variable. Pv 's cash flows are constant, and
payment may be made at either the beginning or end of the period.
Example This example illustrates the purchase of a lemonade stand for $800 financed with money borrowed at
10%. The returns are estimated to accelerate as the stand gains popularity. The incomes are estimated
(generated) over 12 months. This program first generates the income stream array in two For...Next
loops, and then the net present value (Npv) is calculated and displayed. Note normalization of the annual
10% rate.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
Dim valu#(12)
valu(1) = -800 'Initial investment
msg1 = valu(1) & ", "
For x = 2 To 5 'Months 2-5
valu(x) = 100 + (x * 2)
msg1 = msg1 1& valu(x) & ", "
Next x
For x = 6 To 12 'Months 6-12
valu(x) = 100 + (x * 10) 'Accelerated income
msg1 = msg1 & valu(x) & ", "
Next x
NetVal# = NPV((.10/12),valu)
msg1 = "The values:" & crlf & msg1 & crlf & crlf
MsgBox msg1 & "Net present value: " & Format(NetVal#,"Currency")
End Sub
See Also Fv (page 353) (function); IRR (page 378) (function); MIRR (page 404) (function); Pv (page 450)
(function).
Null (constant)
Comments The Null value has special meaning indicating that a variable contains no data. Most numeric operators
return Null when either of the arguments is Null . This "propagation" of Null makes it especially useful
for returning error values through a complex expression. For example, you can write functions that return
Null when an error occurs, then call this function within an expression. You can then use the IsNull
function to test the final result to see whether an error occurred during calculation. Since variants are
Empty by default, the only way for Null to appear within a variant is for you to explicitly place it there.
Only a few functions return this value.
Example
Sub Main()
Dim a As Variant
a = Null
If IsNull(a) Then MsgBox "The variable is Null."
MsgBox "The VarType of a is: " & VarType(a) 'Should display 1.
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 422
Objects (topic)
OKButton (statement)
On Error (statement)
Open (statement)
OpenFilename$ (function)
Operator Precision(topic)
OptionButton (statement)
OptionGroup (statement)
Or (operator)
Syntax Object
Comments The Object type is used to declare variables that reference objects within an application using OLE
automation. Each object is a 4-byte (32-bit) value that references the object internally. The value 0 (or
Nothing ) indicates that the variable does not reference a valid object, as is the case when the object
has not yet been given a value. Accessing properties or methods of such Object variables generates a
runtime error.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 423
Using Objects Object variables are declared using the Dim, Public, or Private statement:
Dim MyApp As Object
Object variables can be assigned values (thereby referencing a real physical object) using the Set
statement:
Set MyApp = CreateObject("phantom.application")
Set MyApp = Nothing
Methods of an Object are also accessed using the dot (.) separator:
MyApp.Open "sample.txt"
isSuccess = MyApp.Save("new.txt",15)
Automatic Destruction The Basic Control Engine keeps track of the number of variables that reference a
given object so that the object can be destroyed when there are no longer any references to it:
Sub Main() 'Number of references to object
Dim a As Object '0
Dim b As Object '0
Set a = CreateObject("phantom.application) '1
Set b = a '2
Set a = Nothing '1
End Sub '0 (object destroyed)
Note An OLE automation object is instructed by the Basic Control Engine to destroy itself when no
variables reference that object. However, it is the responsibility of the OLE automation server to destroy it.
Some servers do not destroy their objects—usually when the objects have a visual component and can be
destroyed manually by the user.
See Also Currency (page 259) (data type); Date (page 263) (data type); Double (page 300) (data type);
Integer (page 377) (data type); Long (page 398) (data type); Single (page 479) (data type); String
(page 494) (data type); Variant (page 515) (data type); Boolean (page 233) (data type); DefType
(page 276) (statement).
Objects (topic)
The Basic Control Engine defines two types of objects: data objects and OLE automation objects.
What Is an Object
An object in the Basic Control Engine is an encapsulation of data and routines into a single unit. The
use of objects in the Basic Control Engine has the effect of grouping together a set of functions and
data items that apply only to a specific object type.
Objects expose data items for programmability called properties. For example, a sheet object may
expose an integer called NumColumns. Usually, properties can be both retrieved (get) and modified
(set).
Objects also expose internal routines for programmability called methods. In the Basic Control
Engine, an object method can take the form of a function or a subroutine. For example, a OLE
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 424
automation object called MyApp may contain a method subroutine called Open that takes a single
argument (a filename), as shown below:
MyApp.Open "c:\files\sample.txt"
Initially, objects are given the value 0 (or Nothing). Before an object can be accessed, it must be
associated with a physical object.
MyApp.BackgroundColor = 10
i% = MyApp.DocumentCount
Properties are set using the Basic Control Engine normal assignment statement:
MyApp.BackgroundColor = 10
i% = MyApp.DocumentCount + 10
MsgBox "Number of documents = " & MyApp.DocumentCount
MyApp.Open "c:\files\sample.txt",True,15
Object methods that return a value behave like function calls in the Basic Control Engine. Any
arguments must be enclosed in parentheses:
There is no syntactic difference between calling a method function and retrieving a property value, as
shown below:
• Objects can be compared to each other to determine whether they refer to the same object.
• Objects can be compared with Nothing to determine whether the object variable refers to a valid
object.
Collections
A collection is a set of related object variables. Each element in the set is called a member and is
accessed via an index, either numeric or text, as shown below:
MyApp.Toolbar.Buttons(0)
MyApp.Toolbar.Buttons("Tuesday")
The collection itself contains properties that provide you with information about the collection and
methods that allow navigation within that collection:
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 426
Predefined Objects
The Basic Control Engine predefines a few objects for use in all scripts. These are:
Description Returns a String containing the octal equivalent of the specified number.
Comments Oct$ returns a String , whereas Oct returns a String variant. The returned string contains only
the number of octal digits necessary to represent the number. The number parameter is any numeric
expression. If this parameter is Null , then Null is returned. Empty is treated as 0. The number
parameter is rounded to the nearest whole number before converting to the octal equivalent.
Example This example accepts a number and displays the decimal and octal 'equivalent until the input number is 0
or invalid.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
Do
xs$ = InputBox("Enter a number to convert:","Octal Convert")
x = Val(xs$)
If x <> 0 Then
MsgBox "Decimal: " & x & " Octal: " & Oct(x)
Else
MsgBox "Goodbye."
End If
Loop While x <> 0
End Sub
OKButton (statement)
Comments This statement can only appear within a dialog box template (that is, between the Begin Dialog and
End Dialog statements). The OKButton statement accepts the following parameters:
Parameter Description
X, Y Integer coordinates specifying the position of the control (in dialog units) static to the upper
left corner of the dialog box.
width, Integer coordinates specifying the dimensions of the control in dialog units.
height
Identifier Name by which this control can be referenced by statements in a dialog function (such as
DlgFocus and DlgEnable ).
If the DefaultButton parameter is not specified in the Dialog statement, the OK button will be used as the
default button. In this case, the OK button can be selected by pressing Enter on a nonbutton control. A
dialog box template must contain at least one OKButton , CancelButton , or PushButton statement
(otherwise, the dialog box cannot be dismissed).
Example This example shows how to use the OK and Cancel buttons within a dialog box template and how to
detect which one closed the dialog box.
Sub Main()
Begin Dialog QuitDialogTemplate 16,32,116,64,"Quit"
Text 4,8,108,8,"Are you sure you want to exit?"
CheckBox 32,24,63,8,"Save Changes",.SaveChanges
OKButton 12,40,40,14
CancelButton 60,40,40,14
End Dialog
Dim QuitDialog As QuitDialogTemplate
rc% = Dialog(QuitDialog)
Select Case rc%
Case -1
MsgBox "OK was pressed!"
Case 1
MsgBox "Cancel was pressed!"
End Select
End Sub
See Also CancelButton (page 243) (statement); CheckBox (page 240) (statement); ComboBox (page 249)
(statement); Dialog (page 278) (function); Dialog (page 279) (statement); DropListBox (page 301)
(statement); GroupBox (page 361) (statement); ListBox (page 394) (statement); OptionButton (page
434) (statement); OptionGroup (page 435) (statement); Picture (page 438) (statement); PushButton
(page 447) (statement); Text (page 502) (statement); TextBox (page 503) (statement); Begin (page
231) Dialog (page 231) (statement), PictureButton (page 439) (statement).
On Error (statement)
Description Defines the action taken when a trappable runtime error occurs.
Comments The form O n Error Goto label causes execution to transfer to the specified label when a runtime error
occurs. The form On Error Resume Next causes execution to continue on the line following the line that
caused the error. The form On Error Goto 0 causes any existing error trap to be removed. If an error
trap is in effect when the script ends, then an error will be generated. An error trap is only active within
the subroutine or function in which it appears. Once an error trap has gained control, appropriate action
should be taken, and then control should be resumed using the Resume statement. The Resume
statement resets the error handler and continues execution. If a procedure ends while an error is pending,
then an error will be generated. (The Exit Sub or E xit Function statement also resets the error
handler, allowing a procedure to end without displaying an error message.)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 428
Errors within an Error Handler If an error occurs within the error handler, then the error handler of the
caller (or any procedure in the call stack) will be invoked. If there is no such error handler, then the error
is fatal, causing the script to stop executing. The following statements reset the error state (that is, these
statements turn off the fact that an error occurred):
Resume
Err=-1
The Resume statement forces execution to continue either on the same line or on the line following the
line that generated the error. The Err=-1 statement allows explicit resetting of the error state so that the
script can continue normal execution without resuming at the statement that caused the error condition.
The On Error statement will not reset the error. Thus, if an On Error statement occurs within an error
handler, it has the effect of changing the location of a new error handler for any new errors that may occur
once the error has been reset.
Example This example will demonstrate three types of error handling. The first case simply by-passes an expected
error and continues with program operation. The second case creates an error branch that jumps to
a common error handling routine that processes incoming errors, clears the error (with the Resume
statement) and resumes program execution. The third case clears all internal error handling so that
execution will stop when the next error is encountered.
Sub Main()
Dim x%
a = 10000
b = 10000
Pass:
Err = -1 'Clear error status.
MsgBox "Cleared error status and continued."
On Error Goto Overflow 'Branch to new error routine on any
x% = 1000 'subsequent errors.
x% = a * b
x% = a / 0
See Also Error Handling (page 327) (topic); Error (page 327) (statement); Resume (page 461) (statement).
Open (statement)
1. Read Write
2. Write
3. Read
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 429
Description Sets the default data type of variables and function return values when not otherwise specified.
Comments By default, the type of implicitly defined variables and function return values is Variant. This statement
is used for backward compatibility with earlier versions of BasicScript where the default data type was
Integer. This statement must appear outside the scope of all functions and subroutines. Currently, type
can only be set to Integer.
Example
'This script sets the default data type to Integer. This fact
'is used to declare the function AddIntegers which returns an
'Integer data type.
Option Default Integer
Function AddIntegers(a As Integer,b As Integer)
Foo = a + b
End Function
Sub Main
Dim a,b,result
a = InputBox("Enter an integer:")
b = InputBox("Enter an integer:")
result = AddIntegers(a,b)
End Sub
Comments By default, BasicScript implicitly declares variables that are used but have not been explicitly declared
with Dim, Public, or Private. To avoid typing errors, you may want to use Option Explicit to prevent
this behavior. The Option Explicit statement also enforces explicit declaration of all externally called
procedures. Once specified, all externally called procedures must be explicitly declared with the Declare
statement.
See Also Const (page 252) (statement), Dim (page 279) (statement), Public (page 446) (statement), Private
(page 445) (statement), ReDim (page 459) (statement), Declare (page 276) (statement)
OpenFilename$ (function)
Description Displays a dialog box that prompts the user to select from a list of files, returning the full pathname of the
file the user selects or a zero-length string if the user selects Cancel.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 430
Comments This function displays the standard file open dialog box, which allows the user to select a file. It takes the
following parameters:
Parameter Description
Title$ String specifying the title that appears in the dialog box's title bar. If this parameter is
omitted, then "Open" is used.
Extension$ String specifying the available file types. If this parameter is omitted, then all files are
displayed.
e$ = "All Files:*.BMP,*.WMF;Bitmaps:*.BMP;Metafiles:*.WMF"
f$ = OpenFilename$("Open Picture",e$)
Example This example asks the user for the name of a file, then proceeds to read the first line from that file.
Sub Main
Dim f As String,s As String
f$ = OpenFilename$("Open Picture","Text Files:*.TXT")
If f$ <> "" Then
Open f$ For Input As #1
Line Input #1,s$
Close #1
MsgBox "First line from " & f$ & " is " & s$
End If
End Sub
See Also MsgBox (page 411) (statement); AskBox$ (page 221) (function); AskPassword$ (page 222)
(function); InputBox, InputBox$ (page 374) (functions); SaveFilename$ (page 467) (function);
SelectBox (page 473) (function); AnswerBox (page 205) (function).
Placeholder Description
type Specifies the name of the grouping of files, such as All Files .
The following table shows the precedence of the operators supported by the Basic Control Engine.
Operations involving operators of higher precedence occur before operations involving operators of
lower precedence. When operators of equal precedence occur together, they are evaluated from left
to right.
Operator Description Precedence Order
() Parentheses Highest
^ Exponentiation
- Unary minus
\ Integer division
Mod Modulo
When numeric, binary, logical or comparison operators are used, the data type of the result is generally the same as the
data type of the more precise operand. For example, adding an Integer and a Long first converts the Integer operand
to a Long, then performs a long addition, overflowing only if the result cannot be contained with a Long. The order of
precision is shown in the following table: Empty Least precise BooleanIntegerLongSingleDateDoubleCurrency Most
precise
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 432
There are exceptions noted in the descriptions of each operator. The rules for operand conversion are further
complicated when an operator is used with variant data. In many cases, an overflow causes automatic promotion of
the result to the next highest precise data type. For example, adding two Integer variants results in an Integer variant
unless it overflows, in which case the result is automatically promoted to a Long variant.
Comments By default, the lower bound used for all array declarations is 0. This statement must appear outside of any
functions or subroutines.
Example
Option Base 1
Sub Main()
Dim a(10) 'Contains 10 elements (not 11).
a(1) = "Hello"
MsgBox "The first element of the array is: " & a(1)
End Sub
See Also Dim (page 279) (statement); Public (page 446) (statement); Private (page 445) (statement).
Comments When Option Compare is set to Binary, then string comparisons are case-sensitive (for example, "A"
does not equal "a"). When it is set to Text, string comparisons are case-insensitive (for example, "A" is
equal to "a"). The default value for Option Compare is Binary. The Option Compare statement affects
all string comparisons in any statements that follow the Option Compare statement. Additionally, the
setting affects the default behavior of Instr, StrComp, and the Like operator. The following table shows
the types of string comparisons affected by this setting: > < <> <= >= Instr StrComp Like The Option
Compare statement must appear outside the scope of all subroutines and functions. In other words, it
cannot appear within a Sub or Function block.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 433
See Also Like (page 391) (operator); InStr (page 375) (function); StrComp (page 492) (function); Comparison
Operators (page 250) (topic).
Description Turns on or off the ability to use C-style escape sequences within strings.
Comments When Option CStrings On is in effect, the compiler treats the backslash character as an escape
character when it appears within strings. An escape character is simply a special character that cannot
otherwise be ordinarily typed by the computer keyboard.
\a Bell Chr$(7)
\b Backspace Chr$(8)
\t Tab Chr$(9)
\0 Null Chr$(0)
\\ Backslash Chr$(92)
\? Question mark ?
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 434
With hexadecimal values, the Basic Control Engine stops scanning for digits when it encounters a
nonhexadecimal digit or two digits, whichever comes first. Similarly, with octal values, the Basic Control
Engine stops scanning when it encounters a nonoctal digit or three digits, whichever comes first. When
Option CStrings Off is in effect, then the backslash character has no special meaning. This is the
default.
Example
Option CStrings On
Sub Main()
MsgBox "They said, \"Watch out for that clump of grass!\""
MsgBox "First line.\r\nSecond line."
MsgBox "Char A: \x41 \r\n Char B: \x42"
End Sub
OptionButton (statement)
Comments This statement can only appear within a dialog box template (that is, between the Begin Dialog and
End Dialog statements). The OptionButton statement accepts the following parameters:
Parameter Description
X, Y Integer coordinates specifying the position of the control (in dialog units) static to the upper
left corner of the dialog box.
width, Integer coordinates specifying the dimensions of the control in dialog units.
height
title$ String containing text that appears within the option button. This text may contain an
ampersand character to denote an accelerator letter, such as "&Portrait" for Portrait ,
which can be selected by pressing the P accelerator.
.Identifier Name by which this control can be referenced by statements in a dialog function (such as
DlgFocus and DlgEnable ).
See Also CancelButton (page 243) (statement); CheckBox (page 240) (statement); ComboBox (page 249)
(statement); Dialog (page 278) (function); Dialog (page 279) (statement); DropListBox (page 301)
(statement); GroupBox (page 361) (statement); ListBox (page 394) (statement); OKButton (page
426) (statement); OptionGroup (page 435) (statement); Picture (page 438) (statement); PushButton
(page 447) (statement); Text (page 502) (statement); TextBox (page 503) (statement); Begin (page
231) Dialog (page 231) (statement), PictureButton (page 439) (statement).
Note Accelerators are underlined, and the accelerator combination Alt+letter is used.
OptionGroup (statement)
Description Specifies the start of a group of option buttons within a dialog box template.
Comments The .Identifier parameter specifies the name by which the group of option buttons can be referenced by
statements in a dialog function (such as DlgFocus and DlgEnable ). This parameter also creates an
integer variable whose value corresponds to the index of the selected option button within the group (0 is
the first option button, 1 is the second option button, and so on). This variable can be accessed using the
following syntax: DialogVariable.Identifier. This statement can only appear within a dialog box template
(that is, between the Begin Dialog and End Dialog statements). When the dialog box is created, the
option button specified by .Identifier will be on; all other option buttons in the group will be off. When the
dialog box is dismissed, the .Identifier will contain the selected option button.
See Also CancelButton (page 243) (statement); CheckBox (page 240) (statement); ComboBox (page 249)
(statement); Dialog (page 278) (function); Dialog (page 279) (statement); DropListBox (page 301)
(statement); GroupBox (page 361) (statement); ListBox (page 394) (statement); OKButton (page
426) (statement); OptionButton (page 434) (statement); Picture (page 438) (statement); PushButton
(page 447) (statement); Text (page 502) (statement); TextBox (page 503) (statement); Begin Dialog
(page 231) (statement), PictureButton (page 439) (statement).
Or (operator)
Comments If both expressions are either Boolean , Boolean variants, or Null variants, then a logical disjunction is
performed as follows:
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 436
If the first expresionn and the second expression then: the result is
is is
Binary Disjunction If the two expressions are Integer, then a binary disjunction is performed, returning
an Integer result. All other numeric types (including Empty variants) are converted to Long and a binary
disjunction is then performed, returning a Long result. Binary disjunction forms a new value based on a
bit-by-bit comparison of the binary representations of the two expressions according to the following table:
1 Or 1 = 1 Example
0 Or 1 = 1 5 10101001
1 Or 0 = 1 6 01101010
0 Or 0 = 0 Or 11101011
See Also Operator Precedence (page 431) (topic); Xor (page 532) (operator); Eqv (page 323) (operator); Imp
(page 371) (operator); And (page 204) (operator).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 437
Pi (constant)
Picture (statement)
PictureButton (statement)
Pmt (function)
PointSetMultiple (function)
PointSetMultipleEX (function)
PopupMenu (function)
PPmt (function)
Print (statement)
Print# (statement)
Private (statement)
Public (statement)
PushButton (statement)
Put (statement)
Pv (function)
Pi (constant)
Syntax Pi
See Also Tan (page 501) (function); Atn (page 223) (function); Cos (page 257)
(function); Sin (page 479) (function).
Picture (statement)
Comments Picture controls are used for the display of graphics images only. The user cannot interact with these
controls. The Picture statement accepts the following parameters:
Parameter Description
X, Y Integer coordinates specifying the position of the control (in dialog units) static to the
upper left corner of the dialog box.
width, height Integer coordinates specifying the dimensions of the control in dialog units.
PictureName String containing the name of the picture. If PictureType is 0, then this name specifies the
$ name of the file containing the image. If PictureType is 10, then PictureName$ specifies
the name of the image within the resource of the picture library. If PictureName$ is empty,
then no picture will be associated with the control. A picture can later be placed into the
picture control using the DlgSetPicture statement.
PictureType Integer specifying the source for the image. The following sources are supported:
.Identifier Name by which this control can be referenced by statements in a dialog function (such
as DlgFocus and DlgEnable ). If omitted, then the first two words of PictureName$ are
used.
style Specifies whether the picture is drawn within a 3D frame. It can be any of the following
values:
The picture control extracts the actual image from either a disk file or a picture library. In the case of
bitmaps, both 2- and 16-color bitmaps are supported. In the case of WMFs, the Basic Control Engine
supports the Placeable Windows Metafile. If PictureName$ is a zero-length string, then the picture is
removed from the picture control, freeing any memory associated with that picture.
Example 1 This first example shows how to use a picture from a file.
Sub Main()
Begin Dialog LogoDialogTemplate 16,32,288,76,"Introduction"
OKButton 240,8,40,14
Picture 8,8,224,64,"c:\bitmaps\logo.bmp",0,.Logo
End Dialog
Dim LogoDialog As LogoDialogTemplate
Dialog LogoDialog
End Sub
Example 2 This second example shows how to use a picture from a picture library with a 3D frame.
Sub Main()
Begin Dialog LogoDialogTemplate 16,31,288,76,"Introduction",,"pictures.dll"
OKButton 240,8,40,14
Picture 8,8,224,64,"CompanyLogo",10,.Logo,1
End Dialog
Dim LogoDialog As LogoDialogTemplate
Dialog LogoDialog
End Sub
See Also CancelButton (page 243) (statement); CheckBox (page 240) (statement); ComboBox (page 249)
(statement); Dialog (page 278) (function); Dialog (page 279) (statement); DropListBox (page 301)
(statement); GroupBox (page 361) (statement); ListBox (page 394) (statement); OptionButton (page
434) (statement); OptionGroup (page 435) (statement); PushButton (page 447) (statement); Text
(page 502) (statement); TextBox (page 503) (statement); Begin (page 231) Dialog (page 231)
(statement), PictureButton (page 439) (statement); DlgSetPicture (page 291) (statement).
Notes Picture controls can contain either a bitmap or a WMF (Windows metafile). When extracting images from
a picture library, the Basic Control Engine assumes that the resource type for metafiles is 256. Picture
libraries are implemented as DLLs on the Windows and Win32 platforms.
PictureButton (statement)
Comments Picture button controls behave very much like a push button controls. Visually, picture buttons are
different than push buttons in that they contain a graphic image imported either from a file or from a
picture library. The PictureButton statement accepts the following parameters:
Parameter Description
X, Y Integer coordinates specifying the position of the control (in dialog units) static to the
upper left corner of the dialog box.
width, height Integer coordinates specifying the dimensions of the control in dialog units.
PictureName String containing the name of the picture. If PictureType is 0, then this name specifies the
$ name of the file containing the image. If PictureType is 10, then PictureName$ specifies
the name of the image within the resource of the picture library. If PictureName$ is empty,
then no picture will be associated with the control. A picture can later be placed into the
picture control using the DlgSetPicture statement.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 440
PictureType Integer specifying the source for the image. The following sources are supported:
.Identifier Name by which this control can be referenced by statements in a dialog function (such as
DlgFocus and DlgEnable ).
The picture button control extracts the actual image from either a disk file or a picture library, depending
on the value of PictureType. The supported picture formats vary from platform to platform. If PictureName
$ is a zero-length string, then the picture is removed from the picture button control, freeing any memory
associated with that picture.
Example 1 This first example shows how to use a picture from a file.
Sub Main()
Begin Dialog LogoDialogTemplate 16,32,288,76,"Introduction"
OKButton 240,8,40,14
PictureButton 8,4,224,64,"c:\bitmaps\logo.bmp",0,.Logo
End Dialog
Dim LogoDialog As LogoDialogTemplate
Dialog LogoDialog
End Sub
Example 2 This second example shows how to use a picture from a picture library.
Sub Main()
Begin Dialog LogoDialogTemplate 16,31,288,76,"Introduction",,"pictures.dll"
OKButton 240,8,40,14
PictureButton 8,4,224,64,"CompanyLogo",10,.Logo
End Dialog
Dim LogoDialog As LogoDialogTemplate
Dialog LogoDialog
End Sub
See Also CancelButton (page 243) (statement); CheckBox (page 240) (statement); ComboBox (page 249)
(statement); Dialog (page 278) (function); Dialog (page 279) (statement); DropListBox (page 301)
(statement); GroupBox (page 361) (statement); ListBox (page 394) (statement); OKButton (page
426) (statement); OptionButton (page 434) (statement); OptionGroup (page 435) (statement);
PushButton (page 447) (statement); Text (page 502) (statement); TextBox (page 503) (statement);
Begin (page 231) Dialog (page 231) (statement), Picture (page 438) (statement); DlgSetPicture
(page 291) (statement).
Notes Picture controls can contain either a bitmap or a WMF (Windows metafile). When extracting images from
a picture library, the Basic Control Engine assumes that the resource type for metafiles is 256. Picture
libraries are implemented as DLLs on the Win32 platforms. Picture controls can contain either bitmaps or
Windows metafiles.
Pmt (function)
Description Returns the payment for an annuity based on periodic fixed payments and a constant rate of interest.
Comments An annuity is a series of fixed payments made to an insurance company or other investment company
over a period of time. Examples of annuities are mortgages and monthly savings plans. The Pmt
function requires the following parameters:
Parameter Description
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 441
Rate Double representing the interest rate per period. If the periods are given in months, be sure
to normalize annual rates by dividing them by 12.
Pv Double representing the present value of your annuity. In the case of a loan, the present
value would be the amount of the loan.
Fv Double representing the future value of your annuity. In the case of a loan, the future value
would be 0.
Due Integer indicating when payments are due for each payment period. A 0 specifies payment
at the end of each period, whereas a 1 specifies payment at the start of each period.
Rate and NPer must be expressed in the same units. If Rate is expressed in months, then NPer must also
be expressed in months. Positive numbers represent cash received, whereas negative numbers represent
cash paid out.
Example This example calculates the payment necessary to repay a $1,000.00 loan over 36 months at an annual
rate of 10%. Payments are due at the beginning of the period.
Sub Main()
x = Pmt((.1/12),36,1000.00,0,1)
msg1 = "The payment to amortize $1,000 over 36 months @ 10% is: "
MsgBox msg1 & Format(x,"Currency")
End Sub
See Also IPmt (page 377) (function); NPer (page 420) (function); PPmt (page 441) (function); Rate (page
453) (function).
PopupMenu (function)
Description Displays a pop-up menu containing the specified items, returning an Integer representing the index of
the selected item.
Comments If no item is selected (that is, the pop-up menu is canceled), then a value of 1 less than the lower bound
is returned (normally, –1). This function creates a pop-up menu using the string elements in the given
array. Each array element is used as a menu item. A zero-length string results in a separator bar in the
menu. The pop-up menu is created with the upper left corner at the current mouse position. A runtime
error results if MenuItems$ is not a single-dimension array. Only one pop-up menu can be displayed at a
time. An error will result if another script executes this function while a pop-up menu is visible.
Example
Sub Main()
Dim a$()
AppList a$
w% = PopupMenu(a$)
End Sub
PPmt (function)
Description Calculates the principal payment for a given period of an annuity based on periodic, fixed payments and a
fixed interest rate.
Comments An annuity is a series of fixed payments made to an insurance company or other investment company
over a period of time. Examples of annuities are mortgages and monthly savings plans. The PPmt
function requires the following parameters:
Parameter Description
Per Double representing the number of payment periods. Per can be no less than 1 and no
greater than NPer.
Pv Double representing the present value of your annuity. In the case of a loan, the present
value would be the amount of the loan.
Fv Double representing the future value of your annuity. In the case of a loan, the future value
would be 0 .
Due Integer indicating when payments are due. If this parameter is 0 , then payments are due at
the end of each period; if it is 1 , then payments are due at the start of each period.
Rate and NPer must be in the same units to calculate correctly. If Rate is expressed in months, then
NPer must also be expressed in months. Negative values represent payments paid out, whereas positive
values represent payments received.
Example This example calculates the principal paid during each year on a loan of $1,000.00 with an annual rate
of 10% for a period of 10 years. The result is displayed as a table containing the following information:
payment, principal payment, principal balance.
Const crlf = Chr$(13) + Chr$(10)
pay = Pmt(.1,10,1000.00,0,1)
msg1 = "Amortization table for 1,000" & crlf & "at 10% annually for"
msg1 = msg1 & " 10 years: " & crlf & crlf
bal = 1000.00
For per = 1 to 10
prn = PPmt(.1,per,10,1000,0,0)
bal = bal + prn
msg1 = msg1 & Format(pay,"Currency") & " " & Format$(Prn,"Currency")
msg1 = msg1 & " " & Format(bal,"Currency") & crlf
Next per
MsgBox msg1
End Sub
See Also IPmt (page 377) (function); NPer (page 420) (function); PPmt (page 441) (function); Rate (page
453) (function).
Print (statement)
Comments The actual output device depends on the platform on which the Basic Control Engine is running. The
following table describes how data of different types is written:
Data Description
Type
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 443
Any Printed with an initial space reserved for the sign (space = positive). Additionally, there is a
numeric space following each number.
type
Date Printed using the short date format. If either the date or time component is missing, only the
provided portion is printed (this is consistent with the "general date" format understood by the
Format/Format$ functions).
User- Printed as "Error code", where code is the value of the user-defined error. The word "Error" is
defined not translated.
errors
Each expression in expressionlist is separated with either a comma (,) or a semicolon (;). A comma
means that the next expression is output in the next print zone. A semicolon means that the next
expression is output immediately after the current expression. Print zones are defined every 14 spaces. If
the last expression in the list is not followed by a comma or a semicolon, then a carriage return is printed
to the file. If the last expression ends with a semicolon, no carriage return is printed¾the next Print
statement will output information immediately following the expression. If the last expression in the list
ends with a comma, the file pointer is positioned at the start of the next print zone on the current line.
The Tab and Spc functions provide additional control over the column position. The Tab function
moves the file position to the specified column, whereas the Spc function outputs the specified number
of spaces.
Example
Sub Main()
i% = 10
s$ = "This is a test."
Print "The value of i=";i%,"the value of s=";s$
'This example prints the value of i% in print zone 1 and s$ in print
'zone 3.
Print i%,,s$
'This example prints the value of i% and s$ separated by 10 spaces.
Print i%;Spc(10);s$
'This example prints the value of i in column 1 and s$ in column 30.
Print i%;Tab(30);s$
'This example prints the value of i% and s$.
Print i%;s$,
Print 67
End Sub
Print# (statement)
Comments The filenumber parameter is a number that is used by the Basic Control Engine to refer to the open file,
the number passed to the Open statement. The following table describes how data of different types is
written:
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 444
Data Description
Type
Any Printed with an initial space reserved for the sign (space = positive). Additionally, there is a
numeric space following each number.
type
Date Printed using the short date format. If either the date or time component is missing, only the
provided portion is printed (this is consistent with the "general date" format understood by the
Format/Format$ functions).
User- Printed to files as "Error code", where code is the value of the user-defined error. The word
defined "Error" is not translated.
errors
Each expression in expressionlist is separated with either a comma (,) or a semicolon (;). A comma
means that the next expression is output in the next print zone. A semicolon means that the next
expression is output immediately after the current expression. Print zones are defined every 14 spaces. If
the last expression in the list is not followed by a comma or a semicolon, then an end-of-line is printed to
the file. If the last expression ends with a semicolon, no end-of-line is printed¾the next Print statement
will output information immediately following the expression. If the last expression in the list ends with a
comma, the file pointer is positioned at the start of the next print zone on the current line.
The Write statement always outputs information ending with an end-of-line. Thus, if a Print statement
is followed by a Write statement, the file pointer is positioned on a new line. The Print statement can
only be used with files that are opened in Output or Append mode. The Tab and Spc functions
provide additional control over the file position. The Tab function moves the file position to the specified
column, whereas the Spc function outputs the specified number of spaces. In order to correctly read the
data using the Input# statement, you should write the data using the Write statement.
Example
Sub Main()
'This example opens a file and prints some data.
Open "test.dat" For Output As #1
i% = 10
s$ = "This is a test."
Print #1,"The value of i=";i%,"the value of s=";s$
'This example prints the value of i% in print zone 1 and s$ in
'print zone 3.
Print #1,i%,,s$
'This example prints the value of i% and s$ separated by ten spaces.
Print #1,i%;Spc(10);s$
'This example prints the value of i in column 1 and s$ in column 30.
Print #1,i%;Tab(30);s$
'This example prints the value of i% and s$.
Print #1,i%;s$,
Print #1,67
Close #1
Kill "test.dat"
End Sub
See Also Open (page 428) (statement); Put (page 448) (statement); Write# (page 530) (statement).
Note The end-of-line character can be either the carriage-return/line-feed pair, or the line-feed character.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 445
If you want it to go to a file you need the # otherwise it goes to standard out and uses the first
variable (in thise case f) as the first item to output to standard out. So that print line should be
Private (statement)
Description Declares a list of private variables and their corresponding types and sizes.
Comments Private variables are global to every Sub and Function within the currently executing script. If a type-
declaration character is used when specifying name (such as % , @ , & , $ , or ! ), the optional [As
type ] expression is not allowed. For example, the following are allowed: Private foo As Integer Private
foo% The subscripts parameter allows the declaration of arrays. This parameter uses the following
syntax: [lower To ] upper [,[lower To ] upper]... The lower and upper parameters are integers specifying
the lower and upper bounds of the array. If lower is not specified, then the lower bound as specified
by Option Base is used (or 1 if no Option Base statement has been encountered). Up to 60 array
dimensions are allowed.
The total size of an array (not counting space for strings) is limited to 64K. Dynamic arrays are declared
by not specifying any bounds: Private a() The type parameter specifies the type of the data item being
declared. It can be any of the following data types: String, Integer, Long, Single, Double, Currency
, Object, data object, built-in data type, or any user-defined data type. If a variable is seen that has not
been explicitly declared with either Dim , Public , or Private , then it will be implicitly declared local to
the routine in which it is used. Fixed-Length Strings Fixed-length strings are declared by adding a length
to the String type-declaration character: Private name As String * length where length is a literal number
specifying the string's length. Initial Values All declared variables are given initial values, as described in
the following table:
Integer 0
Long 0
Double 0.0
Single 0.0
Currency 0.0
Object Nothing
Boolean False
Variant Empty
User-defined type Each element of the structure is given a default value, as described above.
Arrays Each element of the array is given a default value, as described above.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 446
Example This example sets the value of variable x# in two separate routines to show the behavior of private
variables.
Private x#
Sub Area()
x# = 10 'Set this copy of x# to 10 and display
MsgBox x#
End Sub
Sub Main()
x# = 100 'Set this copy of x# to 100 and display after calling the Area subroutine
Area
MsgBox x#
End Sub
See Also Dim (page 279) (statement); Redim (page 459) (statement); Public (page 446) (statement); Option
Base (page 432) (statement).
Public (statement)
Description Declares a list of public variables and their corresponding types and sizes.
Comments Public variables are global to all Sub s and Function s in all scripts. If a type-declaration character is
used when specifying name (such as % , @ , & , $ , or ! ), the optional [ As type ] expression is
not allowed. For example, the following are allowed: Public foo As Integer Public foo% The subscripts
parameter allows the declaration of arrays. This parameter uses the following syntax: [lower To] upper [,
[lower To] upper]... The lower and upper parameters are integers specifying the lower and upper bounds
of the array. If lower is not specified, then the lower bound as specified by Option Base is used (or 1 if no
Option Base statement has been encountered). Up to 60 array dimensions are allowed.
The total size of an array (not counting space for strings) is limited to 64K. Dynamic arrays are declared
by not specifying any bounds: Public a() The type parameter specifies the type of the data item being
declared. It can be any of the following data types: String, Integer, Long, Single, Double, Currency,
Object, data object, built-in data type, or any user-defined data type. If a variable is seen that has not
been explicitly declared with either Dim , Public , or Private , then it will be implicitly declared local
to the routine in which it is used. For compatibility, the keyword Global is also supported. It has the
same meaning as Public . Fixed-Length Strings Fixed-length strings are declared by adding a length to
the String type-declaration character: Public name As String * length where length is a literal number
specifying the string's length. Initial Values All declared variables are given initial values, as described in
the following table:
Parameter Description
Integer 0
Long 0
Double 0.0
Single 0.0
Currency 0.0
Object Nothing
Boolean False
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 447
Variant Empty
User-defined type Each element of the structure is given a default value, as described above.
Arrays Each element of the array is given a default value, as described above.
Sharing Variables When sharing variables, you must ensure that the declarations of the shared variables
are the same in each script that uses those variables. If the public variable being shared is a user-defined
structure, then the structure definitions must be exactly the same.
Example This example uses a subroutine to calculate the area of ten circles and displays the result in a dialog box.
The variables R and Ar are declared as Public variables so that they can be used in both Main and Area.
Const crlf = Chr$(13) + Chr$(10)
Public x#,ar#
Sub Area()
ar# = (x# ^ 2) * Pi
End Sub
Sub Main()
msg1 = "The area of the ten circles are:" & crlf & crlf
For x# = 1 To 10
Area
msg1 = msg1 & x# & ": " & Format(ar#,"fixed") & Basic.Eoln$
Next x#
MsgBox msg1
End Sub
See Also Dim (page 279) (statement); Redim (page 459) (statement); Option Base (page 432) (statement).
PushButton (statement)
Comments Choosing a push button causes the dialog box to close (unless the dialog function redefines this
behavior). This statement can only appear within a dialog box template (that is, between the Begin Dialog
and End Dialog statements). The PushButton statement accepts the following parameters:
Parameter Description
X, Y Integer coordinates specifying the position of the control (in dialog units) static to the upper
left corner of the dialog box.
width, Integer coordinates specifying the dimensions of the control in dialog units.
height
title$ String containing the text that appears within the push button. This text may contain an
ampersand character to denote an accelerator letter, such as " &Save " for Save .
.Identifier Name by which this control can be referenced by statements in a dialog function (such as
DlgFocus and DlgEnable ).
If a push button is the default button, it can be selected by pressing Enter on a nonbutton control. A
dialog box template must contain at least one OKButton , CancelButton , or PushButton statement
(otherwise, the dialog box cannot be dismissed).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 448
Example This example creates a bunch of push buttons and displays which button was pushed.
Sub Main()
Begin Dialog ButtonTemplate 17,33,104,84,"Buttons"
OKButton 8,4,40,14,.OK
CancelButton 8,24,40,14,.Cancel
PushButton 8,44,40,14,"1",.Button1
PushButton 8,64,40,14,"2",.Button2
PushButton 56,4,40,14,"3",.Button3
PushButton 56,24,40,14,"4",.Button4
PushButton 56,44,40,14,"5",.Button5
PushButton 56,64,40,14,"6",.Button6
End Dialog
Dim ButtonDialog As ButtonTemplate
WhichButton% = Dialog(ButtonDialog)
MsgBox "You pushed button " & WhichButton%
End Sub
See Also CancelButton (page 243) (statement); CheckBox (page 240) (statement); ComboBox (page 249)
(statement); Dialog (page 278) (function); Dialog (page 279) (statement); DropListBox (page 301)
(statement); GroupBox (page 361) (statement); ListBox (page 394) (statement); OKButton (page
426) (statement); OptionButton (page 434) (statement); OptionGroup (page 435) (statement);
Picture (page 438) (statement); Text (page 502) (statement); TextBox (page 503) (statement); Begin
(page 231) Dialog (page 231) (statement), PictureButton (page 439) (statement); DlgSetPicture
(page 291) (statement).
Note Accelerators are underlined, and the accelerator combination Alt+ letter is used.
Put (statement)
Description Writes data from the specified variable to a Random or Binary file.
Parameter Description
filenumber Integer representing the file to be written to. This is the same value as returned by the
Open statement.
recordnumber Long specifying which record is to be written to the file. For Binary files, this number
represents the first byte to be written starting with the beginning of the file (the first byte
is 1). For Random files, this number represents the record number starting with the
beginning of the file (the first record is 1). This value ranges from 1 to 2147483647. If the
recordnumber parameter is omitted, the next record is written to the file (if no records
have been written yet, then the first record in the file is written). When recordnumber is
omitted, the commas must still appear, as in the following example: Put #1,,recvar If
recordlength is specified, it overrides any previous change in file position specified with
the Seek statement.
The variable parameter is the name of any variable of any of the following types:
String (variable-length In Binary files, variable-length strings are written by first determining the
specified string variable's length, then writing that many bytes to the file. In
Random files, variable-length strings are written by first writing a 2-byte
length, then writing that many characters to the file.
String (fixed-length) Fixed-length strings are written to Random and Binary files in the same
way: the number of characters equal to the string's declared length are
written.
Boolean 2 bytes are written to the file (either –1 for TRUE or 0 for FALSE).
Variant A 2-byte VarType is written to the file followed by the data as described
above. With variants of type 10 (user-defined errors), the 2-byte VarType
is followed by a 2-byte unsigned integer (the error value), which is then
followed by 2 additional bytes of information. The exception is with strings,
which are always preceded by a 2-byte string length.
User-defined types Each member of a user-defined data type is written individually. In Binary
files, variable-length strings within user-defined types are written by first
writing a 2-byte length followed by the string's content. This storage is
different than variable-length strings outside of user-defined types. When
writing user-defined types, the record length must be greater than or equal
to the combined size of each element within the data type.
Objects Object variables cannot be written to a file using the Put statement.
With Random files, a runtime error will occur if the length of the data being written exceeds the
record length (specified as the reclen parameter with the Open statement). If the length of the data
being written is less than the record length, the entire record is written along with padding (whatever
data happens to be in the I/O buffer at that time). With Binary files, the data elements are written
contiguously: they are never separated with padding.
Example This example opens a file for random write, then writes ten records into the file with the values 10-50.
Then the file is closed and reopened in random mode for read, and the records are read with the Get
statement. The result is displayed in a dialog box.
Sub Main()
Open "test.dat" For Random Access Write As #1
For x = 1 To 10
r% = x * 10
Put #1,x,r%
Next x
Close
Open "test.dat" For Random Access Read As #1
For x = 1 To 10
Get #1,x,r%
msg1 = "Record " & x & " is: " & r% & Basic.Eoln$
Next x
MsgBox msg1
Close
Kill "test.dat"
End Sub
See Also Open (page 428) (statement); Put (page 448) (statement); Write# (page 530) (statement); Print#
(page 443) (statement).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 450
Pv (function)
Syntax Pv (Rate,NPer,Pmt,Fv,Due)
Description Calculates the present value of an annuity based on future periodic fixed payments and a constant rate of
interest.
Parameter Description
Rate Double representing the interest rate per period. When used with monthly payments, be
sure to normalize annual percentage rates by dividing them by 12.
Fv Double representing the future value of the annuity after the last payment has been made. In
the case of a loan, the future value would be 0.
Due Integer indicating when the payments are due for each payment period. A 0 specifies
payment at the end of each period, whereas a 1 specifies payment at the start of each
period.
Rate and NPer must be expressed in the same units. If Rate is expressed in months, then NPer must also
be expressed in months. Positive numbers represent cash received, whereas negative numbers represent
cash paid out.
Example This example demonstrates the present value (the amount you'd have to pay now) for a $100,000 annuity
that pays an annual income of $5,000 over 20 years at an annual interest rate of 10%.
Sub Main()
pval = Pv(.1,20,-5000,100000,1)
MsgBox "The present value is: " & Format(pval,"Currency")
End Sub
See Also Fv (page 353) (function); IRR (page 378) (function); MIRR (page 404) (function); Npv (page 420)
(function).
QueEmpty (statement)
Syntax QueEmpty
Example
'This code begins a new queue,
then drags a selection over a
'range of characters in Notepad.
Sub Main()
AppActivate "Notepad"
QueEmpty 'Make sure the queue
is empty.
QueMouseDn
ebLeftButton,1440,1393
QueMouseUp
ebLeftButton,4147,2363
QueFlush True
End Sub
Random (function)
Randomize (statement)
Rate (function)
RCPDownload (statement)
RCPDownloadEx (function
RCPGroupExport (statement)
RCPGroupExportEx (function)
RCPGroupImport (statement)
RCPGroupImportEx (function)
RCPUpload (statement)
RCPUploadEx (function)
ReadIn$ (function)
ReadInSection (statement)
Redim (statement)
Rem (statement)
Reset (statement)
Resume (statement)
Return (statement)
RmDir (statement)
Rnd (function)
RSet (statement)
Random (function)
Description Returns a Long value greater than or equal to min and less than or equal to max.
Comments Both the min and max parameters are rounded to Long . A runtime error is generated if min is greater
than max.
Example This example sets the randomize seed then generates six random numbers between 1 and 54 for the
lottery.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
Dim a%(5)
Randomize
For x = 0 To 5
temp = Random(1,54)
'Elimininate duplicate numbers.
For y = 0 To 5
If a(y) = temp Then found = true
Next
If found = false Then a(x) = temp Else x = x - 1
found = false
Next
ArraySort a
msg1 = ""
For x = 0 To 5
msg1 = msg1 & a(x) & crlf
Next x
MsgBox "Today's winning lottery numbers are: " & crlf & crlf & msg1
End Sub
See Also Randomize (page 452) (statement); Rnd (page 463) (function).
Randomize (statement)
Comments If seed is not specified, then the current value of the system clock is used.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 453
Example This example sets the randomize seed then generates six random numbers between 1 and 54 for the
lottery.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
Dim a%(5)
Randomize 'This sets the random seed.
'Omitting this line will cause the random numbers to be
'identical each time the sample is run.
For x = 0 To 5
temp = Rnd(1) * 54 + 1
'Elimininate duplicate numbers.
For y = 0 To 5
If a(y) = temp Then found = true
Next
If found = false Then a(x) = temp Else x = x - 1
found = false
Next
ArraySort a
msg1 = ""
For x = 0 To 5
msg1 = msg1 & a(x) & crlf
Next x
MsgBox "Today's winning lottery numbers are: " & crlf & crlf & msg1
End Sub
See Also Random (page 452) (function); Rnd (page 463) (function).
Rate (function)
Comments An annuity is a series of fixed payments made to an insurance company or other investment company
over a period of time. Examples of annuities are mortgages and monthly savings plans. The Rate
function requires the following parameters:
Parameter Description
Pv Double representing the present value of your annuity. In a loan situation, the present value
would be the amount of the loan.
Fv Double representing the future value of the annuity after the last payment has been made. In
the case of a loan, the future value would be zero.
Due Integer specifying when the payments are due for each payment period. A 0 indicates
payment at the end of each period, whereas a 1 indicates payment at the start of each
period.
Guess Double specifying a guess as to the value the Rate function will return. The most common
guess is .1 (10 percent).
Positive numbers represent cash received, whereas negative values represent cash paid out. The value
of Rate is found by iteration. It starts with the value of Guess and cycles through the calculation adjusting
Guess until the result is accurate within 0.00001 percent. After 20 tries, if a result cannot be found, Rate
fails, and the user must pick a better guess.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 454
Example This example calculates the rate of interest necessary to save $8,000 by paying $200 each year for 48
years. The guess rate is 10%.
Sub Main()
r# = Rate(48,-200,8000,0,1,.1)
MsgBox "The rate required is: " & Format(r#,"Percent")
End Sub
See Also IPmt (page 377) (function); NPer (page 420) (function); Pmt (page 440) (function); PPmt (page
441) (function).
RCPDownload (statement)
Description Downloads the specified Recipe from the specified Recipe Group using the specified Map.
Parameter Description
filename$ Required string containing the name of the Recipe Group file where the Recipe is located.
The Recipe Group file must exist
mapname$ Optional string containing the name of the Map to be used when Downloading the Recipe.
pointorval$ Optional string containing the Batch Point or Batch ID to be used when Downloading the
Recipe.
Example
RCPDownload "D:\Bread.rgp", "White", "Line1", "Batch of White Bread", 0
RCPDownloadEx (function)
Description Downloads the specified Recipe from the specified Recipe Group using the specified Map.
Parameter Description
filename$ Required string containing the name of the Recipe Group file where the
Recipe is located. The Recipe Group file must exist
mapname$ Optional string containing the name of the Map to be used when
Downloading the Recipe.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 455
pointorval$ Optional string containing the Batch Point or Batch ID to be used when
Downloading the Recipe.
Example
RCPDownload ("D:\Bread.rgp", "White", "Line1", "Batch of White Bread", 0)
RCPGroupExport (statement)
Parameter Description
groupname Required string containing the name of the Recipe Group file. The Recipe Group file must
$ exist.
Example
RCPGroupExport "D:\Bread.rgp"
RCPGroupExportEx (function)
Parameter Description
groupname$ Required string containing the name of the Recipe Group file. The
Recipe Group file must exist.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 456
Example
RCPGroupExport ("D:\Bread.rgp")
RCPGroupImport (statement)
Parameter Description
groupname$ Required string containing the name of the Recipe Group file.
Example
RCPGroupExport "D:\Bread.rgp", "Bread2.csv"
RCPGroupImportEx (function)
Parameter Description
groupname$ Required string containing the name of the Recipe Group file.
Example
RCPGroupExport ("D:\Bread.rgp", "Bread2.csv")
RCPUpload (statement)
Description Uploads the specified Recipe to the specified Recipe Group using the specified Map.
Parameter Description
filename$ Required string containing the name of the Recipe Group file where the Recipe is located.
The Recipe Group file must exist.
mapname$ Optional string containing the name of the Map to be used when Uploading the Recipe.
newname$ Optional string containing the name of the Recipe to be uploaded. You may use a new or
existing Recipe name.
Example
RCPUpload "D:\Bread.rgp", "White", "Line1", "NewWhite"
RCPUploadEx (function)
Description Uploads the specified Recipe to the specified Recipe Group using the specified Map.
Parameter Description
filename$ Required string containing the name of the Recipe Group file where the
Recipe is located. The Recipe Group file must exist.
mapname$ Optional string containing the name of the Map to be used when
Uploading the Recipe.
newname$ Optional string containing the name of the Recipe to be uploaded. You
may use a new or existing Recipe name.
Example
RCPUpload ("D:\Bread.rgp", "White", "Line1", "NewWhite")
ReadIni$ (function)
Description Returns a String containing the specified item from an ini file.
Parameter Description
Section$ String specifying the section that contains the desired variable, such as "windows". Section
names are specified without the enclosing brackets.
See Also WriteIni (page 531) (statement); ReadIniSection (page 458) (statement)
Notes If the name of the ini file is not specified, then win.ini is assumed. If the filename$ parameter does not
include a path, then this statement looks for ini files in the Windows directory.
ReadIniSection (statement)
Description Fills an array with the item names from a given section of the specified ini file.
Parameter Description
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 459
Section$ String specifying the section that contains the desired variables, such as "windows".
Section names are specified without the enclosing brackets.
ArrayOfItems() Specifies either a zero- or a one-dimensioned array of strings or variants. The array can
be either dynamic or fixed. If ArrayOfItems() is dynamic, then it will be redimensioned to
exactly hold the new number of elements. If there are no elements, then the array will be
redimensioned to contain no dimensions. You can use the LBound, UBound, and ArrayDims
functions to determine the number and size of the new array's dimensions. If the array
is fixed, each array element is first erased, then the new elements are placed into the
array. If there are fewer elements than will fit in the array, then the remaining elements
are initialized to zero-length strings (for String arrays) or Empty (for Variant arrays).
A runtime error results if the array is too small to hold the new elements.
On return, the ArrayOfItems() parameter will contain one array element for each variable in the specified
ini section.
Example
Sub Main()
Dim items() As String
ReadIniSection "Windows",items$
r% = SelectBox("INI Items",,items$)
End Sub
See Also ReadIni$ (page 458) (function); WriteIni (page 531) (statement)
Note If the name of the ini file is not specified, then win.ini is assumed. If the filename$ parameter does not
include a path, then this statement looks for .ini files in the Windows directory.
Redim (statement)
Description Redimensions an array, specifying a new upper and lower bound for each dimension of the array.
Comments The variablename parameter specifies the name of an existing array (previously declared using the Dim
statement) or the name of a new array variable. If the array variable already exists, then it must previously
have been declared with the Dim statement with no dimensions, as shown in the following example:
Dim a$() 'Dynamic array of strings (no dimensions yet)
Dynamic arrays can be redimensioned any number of times. The subscriptRange parameter specifies the
new upper and lower bounds for each dimension of the array using the following syntax:
[lower To] upper [,[lower To] upper]...
If lower is not specified, then 0 is used (or the value set using the Option Base statement). A runtime
error is generated if lower is less than upper. Array dimensions must be within the following range:
–32768 <= lower <= upper <= 32767
The type parameter can be used to specify the array element type. Arrays can be declared using any
fundamental data type, user-defined data types, and objects. Re-dimensioning an array erases all
elements of that array unless the Preserve keyword is specified. When this keyword is specified,
existing data in the array is preserved where possible. If the number of elements in an array dimension is
increased, the new elements are initialized to 0 (or empty string). If the number of elements in an array
dimension is decreased, then the extra elements will be deleted. If the Preserve keyword is specified,
then the number of dimensions of the array being re-dimensioned must either be zero or the same as the
new number of dimensions.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 460
Example This example uses the FileList statement to re-dim an array and fill it with filename strings. A new array
is then re-dimmed to hold the number of elements found by FileList, and the FileList array is copied into it
and partially displayed.
Sub Main()
Dim fl$()
FileList fl$,"*.*"
count = Ubound(fl$)
Redim nl$(Lbound(fl$) To Ubound(fl$))
For x = 1 to count
nl$(x) = fl(x)
Next x
MsgBox "The last element of the new array is: " & nl$(count)
End Sub
See Also Dim (page 279) (statement); Public (page 446) (statement); Private (page 445) (statement);
ArrayDims (page 217) (function); LBound (page 387) (function); UBound (page 510) (function).
Rem (statement)
Example
Sub Main()
em This is a line of comments that serves to illustrate the
Rem workings of the code. You can insert comments to make it more
Rem readable and maintainable in the future.
End Sub
See Also ' (page 192) (keyword); Comments (page 260) (topic).
Reset (statement)
Syntax Reset
Description Closes all open files, writing out all I/O buffers.
Example This example opens a file for output, closes it with the Reset statement, then deletes it with the Kill
statement.
Sub Main()
Open "test.dat" for Output Access Write as # 1
Reset
Kill "test.dat"
If FileExists("test.dat") Then
MsgBox "The file was not deleted."
Else
MsgBox "The file was deleted."
End If
End Sub
See Also Close (page 248) (statement); Open (page 428) (statement).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 461
Resume (statement)
Comments The form Resume 0 (or simply Resume by itself) causes execution to continue with the statement that
caused the error. The form Resume Next causes execution to continue with the statement following the
statement that caused the error.
The form Resume label causes execution to continue at the specified label. The Resume statement
resets the error state. This means that, after executing this statement, new errors can be generated and
trapped as normal.
Example This example accepts two integers from the user and attempts to multiply the numbers together. If either
number is larger than an integer, the program processes an error routine and then continues program
execution at a specific section using 'Resume <label>'. Another error trap is then set using 'Resume Next'.
The new error trap will clear any previous error branching and also 'tell' the program to continue execution
of the program even if an error is encountered.
Sub Main()
Dim a%,b%,x%
Again:
On Error Goto Overflow
a% = InputBox("Enter 1st integer to multiply","Enter Number")
b% = InputBox("Enter 2nd integer to multiply","Enter Number")
See Also Error Handling (page 327) (topic); On Error (page 427) (statement).
Return (statement)
Syntax Return
Description Transfers execution control to the statement following the most recent GoSub .
Comments A runtime error results if a Return statement is encountered without a corresponding GoSub
statement.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 462
Example This example calls a subroutine and then returns execution to the Main routine by the Return statement.
Sub Main()
GoSub SubTrue
MsgBox "The Main routine continues here."
Exit Sub
SubTrue:
MsgBox "This message is generated in the subroutine."
Return
Exit Sub
End Sub
Functions Return
Parameter Description
string String from which characters are returned. A runtime error is generated if string is
NULL.
Length is Returns
The RightB and RightB$ functions are used to return byte data from strings containing
byte data.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 463
Example
'This example shows the Right$ function used in a routine to
'change uppercase names to lowercase with an uppercase first
'letter.
Sub Main()
lname$ = "WILLIAMS"
x = Len(lname$)
rest$ = Right$(lname$,x - 1)
fl$ = Left$(lname$,1)
lname$ = fl$ & LCase$(rest$)
MsgBox "The converted name is: " & lname$
End Sub
RmDir (statement)
Example This routine creates a directory and then deletes it with RmDir.
Sub Main()
On Error Goto ErrMake
MkDir("test01")
On Error Goto ErrRemove
RmDir("test01")
ErrMake:
MsgBox "The directory could not be created."
Exit Sub
ErrRemove:
MsgBox "The directory could not be removed."
Exit Sub
End Sub
See Also ChDir (page 239) (statement); ChDrive (page 239) (statement); CurDir, CurDir$ (page 259)
(functions); Dir, Dir$ (page 280) (functions); MkDir (page 405) (statement).
Rnd (function)
Comments If number is omitted, the next random number is returned. Otherwise, the number parameter has the
following meaning:
If Then
Example This example sets the randomize seed then generates six random numbers between 1 and 54 for the
lottery.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
Dim a%(5)
Randomize
For x = 0 To 5
temp = Rnd(1) * 54 + 1
Elimininate duplicate numbers.
or y = 0 To 5
If a(y) = temp Then found = true
Next
If found = false Then a(x) = temp Else x = x - 1
found = false
Next
ArraySort a
msg1 = ""
For x = 0 To 5
msg1 = msg1 & a(x) & crlf
Next x
MsgBox "Today's winning lottery numbers are: " & crlf & crlf & msg1
End Sub
See Also Randomize (page 452) (statement); Random (page 452) (function)
RSet (statement)
Description Copies the source string source into the destination string destvariable.
Comments If source is shorter in length than destvariable, then the string is right-aligned within destvariable and the
remaining characters are padded with spaces. If source is longer in length than destvariable, then source
is truncated, copying only the leftmost number of characters that will fit in destvariable. A runtime error
is generated if source is Null . The destvariable parameter specifies a String or Variant variable.
If destvariable is a Variant containing Empty , then no characters are copied. If destvariable is not
convertible to a String , then a runtime error occurs. A runtime error results if destvariable is Null .
Example This example replaces a 40-character string of asterisks (*) with an RSet and LSet string and then
displays the result.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
Dim msg1,tmpstr$
tmpstr$ = String(40,"*")
msg1 = "Here are two strings that have been right-" + crlf
msg1 = msg1 & "and left-justified in a 40-character string."
msg1 = msg1 & crlf & crlf
RSet tmpstr$ = "Right|"
msg1 = msg1 & tmpstr$ & crlf
LSet tmpstr$ = "|Left"
msg1 = msg1 & tmpstr$ & crlf
MsgBox msg1
End Sub
Comments RTrim$ returns a String , whereas RTrim returns a String variant. Null is returned if text
is Null .
Example This example displays a left-justified string and its RTrim result.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
txt$ = " This is text "
tr$ = RTrim(txt$)
MsgBox "Original ->" & txt$ & "<-" & crlf & "Right Trimmed ->" & tr$ & "<-"
End Sub
See Also LTrim, LTrim$ (page 399) (functions); Trim, Trim$ (page 506) (functions).
SaveFilename$ (function)
SaveSetting (statement)
Screen.DlgBaseUnitsX (property)
Screen.DlgBaseUnitsY (property)
Screen.Height (property)
Screen.TwipsPerPixelX (property)
Screen.TwipsPerPixelY (property)
Screen.Width (property)
Second (function)
Seek (function)
Seek (statement)
Select...Case (statement)
SelectBox (function)
SendKeys (statement)
Set (statement)
SetAttr (statement)
Sgn (function)
Shell (function)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 466
Sin (function)
Sleep (statement)
Sln (function)
Spc (function)
SQLBind (function)
SQLClose (function)
SQLError (function)
SQLExecQuery (function)
SQLGetSchema (function)
SQLOpen (function)
SQLQueryTimeout (statement)
SQLRequest (function)
SQLRetrieve (function)
SQLRetrieveToFile (function)
Sqr (function)
Stop (statement)
StrComp (function)
StrConv (function)
Switch (function)
SYD (function)
System.Exit (method)
System.FreeMemory (property)
System.FreeResources (property)
System.MouseTrails (method)
System.Restart (method)
System.TotalMemory (property)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 467
System.WindowsDirectory$ (property)
System.WindowsVersion$ (property)
SaveFilename$ (function)
Description Displays a dialog box that prompts the user to select from a list of files and returns a String containing the
full path of the selected file.
Parameter Description
title$ String containing the title that appears on the dialog box's caption. If this string is omitted,
then "Save As" is used.
extensions String containing the available file types. Its format depends on the platform on which the
$ Basic Control Engine is running. If this string is omitted, then all files are used.
The SaveFilename$ function returns a full pathname of the file that the user selects. A zero-length string
is returned if the user selects Cancel. If the file already exists, then the user is prompted to overwrite it.
e$ = "All Files:*.BMP,*.WMF;Bitmaps:*.BMP;Metafiles:*.WMF"
f$ = SaveFilename$("Save Picture",e$)
Example This example creates a save dialog box, giving the user the ability to save to several different file types.
Sub Main()
e$ = "All Files:*.BMP,*.WMF;Bitmaps:*.BMP;Metafiles:*.WMF"
f$ = SaveFilename$("Save Picture",e$)
If Not f$ = "" Then
Msgbox "User choose to save file as: " + f$
Else
Msgbox "User canceled."
End IF
End Sub
See Also MsgBox (page 411) (statement); AskBox (page 409) (function); AskPassword$ (page 222)
(function); InputBox, InputBox$ (page 374) (functions); OpenFilename$ (page 429) (function);
SelectBox (page 473) (function); AnswerBox (page 205) (function).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 468
Placeholder Description
description Specifies the grouping of files for the user, such as All Files .
SaveSetting (statement)
Description Saves the value of the specified key in the system registry. The following table describes the named
parameters to the SaveSetting statement:
Parameter Description
appname String expression indicating the name of the application whose setting will be modified.
section String expression indicating the name of the section whose setting will be modified.
Example
'The following example adds two entries to the Windows registry
'if run under Win32 or to NEWAPP.INI on other platforms,
'using the SaveSetting statement. It then uses DeleteSetting
'to remove these entries.
Sub Main()
SaveSetting appname := "NewApp", section := "Startup", _
key := "Height", setting := 200
SaveSetting appname := "NewApp", section := "Startup", _
key := "Width", setting := 320
DeleteSetting "NewApp" 'Remove NewApp key from registry
End Sub
See Also GetAllSettings (page 356) (function), DeleteSetting (page 277) (statement), GetSetting (page 359)
(function)
Note Under Win32, this statement operates on the system registry. All settings are saved to the following entry
in the system registry: HKEY_CURRENT_USER\Software\BasicScript Program Settings\appname\section\key
On this platform, the appname parameter is not optional.
Screen.DlgBaseUnitsX (property)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 469
Syntax Screen.DlgBaseUnitsX
Description Returns an Integer used to convert horizontal pixels to and from dialog units.
Comments The number returned depends on the name and size of the font used to display dialog boxes. To convert
from pixels to dialog units in the horizontal direction: ((XPixels * 4) + (Screen.DlgBaseUnitsX - 1)) /
Screen.DlgBaseUnitsX To convert from dialog units to pixels in the horizontal direction: (XDlgUnits *
Screen.DlgBaseUnitsX) / 4
Example This example converts the screen width from pixels to dialog units.
Sub Main()
XPixels = Screen.Width
conv% = Screen.DlgBaseUnitsX
XDlgUnits = (XPixels * 4) + (conv% -1) / conv%
MsgBox "The screen width is " & XDlgUnits & " dialog units."
End Sub
Screen.DlgBaseUnitsY (property)
Syntax Screen.DlgBaseUnitsY
Description Returns an Integer used to convert vertical pixels to and from dialog units.
Comments The number returned depends on the name and size of the font used to display dialog boxes. To convert
from pixels to dialog units in the vertical direction: (YPixels * 8) + (Screen.DlgBaseUnitsY - 1) /
Screen.DlgBaseUnitsY To convert from dialog units to pixels in the vertical direction: (YDlgUnits *
Screen.DlgBaseUnitsY) / 8
Example This example converts the screen width from pixels to dialog units.
Sub Main()
YPixels = Screen.Height
conv% = Screen.DlgBaseUnitsY
YDlgUnits = (YPixels * 8) + (conv% -1) / conv%
MsgBox "The screen width is " & YDlgUnits & " dialog units."
End Sub
Screen.Height (property)
Syntax Screen.Height
Comments This property is used to retrieve the height of the screen in pixels. This value will differ depending on the
display resolution. This property is read-only.
Screen.TwipsPerPixelX (property)
Syntax Screen.TwipsPerPixelX
Description Returns an Integer representing the number of twips per pixel in the horizontal direction of the installed
display driver.
Example This example displays the number of twips across the screen horizontally.
Sub Main()
XScreenTwips = Screen.Width * Screen.TwipsPerPixelX
MsgBox "Total horizontal screen twips = " & XScreenTwips
End Sub
Screen.TwipsPerPixelY (property)
Syntax Screen.TwipsPerPixelY
Description Returns an Integer representing the number of twips per pixel in the vertical direction of the installed
display driver.
Example This example displays the number of twips across the screen vertically.
Sub Main()
YScreenTwips = Screen.Height * Screen.TwipsPerPixelY
MsgBox "Total vertical screen twips = " & YScreenTwips
End Sub
Screen.Width (property)
Syntax Screen.Width
Comments This property is used to retrieve the width of the screen in pixels. This value will differ depending on the
display resolution. This property is read-only.
Second (function)
Description Returns the second of the day encoded in the specified time parameter.
Comments The value returned is an Integer between 0 and 59 inclusive. The time parameter is any expression that
converts to a Date .
Example This example fires an event every 10 seconds based on the system clock.
Sub Main()
trigger = 10
Do
xs% = Second(Now)
If (xs% Mod trigger = 0) Then
Beep
End 'Remove this line to trigger the loop continuously.
Sleep 1000
End If
DoEvents
Loop
End Sub
See Also Day (page 269) (function); M (page 404) inute (page 404) (function); Month (page 406) (function);
Year (page 533) (function); Hour (page 364) (function); Weekday (page 521) (function); DatePart
(page 267) (function).
Seek (function)
Description Returns the position of the file pointer in a file static to the beginning of the file.
Comments The filenumber parameter is a number that the Basic Control Engine uses to refer to the open file—the
number passed to the Open statement. The value returned depends on the mode in which the file was
opened:
The value returned is a Long between 1 and 2147483647, where the first byte (or first record) in the file
is 1.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 472
Example This example opens a file for random write, then writes ten records into the file using the PUT statement.
The file position is displayed using the Seek Function, and the file is closed.
Sub Main()
Open "test.dat" For Random Access Write As #1
For x = 1 To 10
r% = x * 10
Put #1,x,r%
Next x
y = Seek(1)
MsgBox "The current file position is: " & y
Close
End Sub
See Also Seek (page 472) (statement); Loc (page 395) (function).
Seek (statement)
Description Sets the position of the file pointer within a given file such that the next read or write operation will occur at
the specified position.
Parameter Description
filenumber Integer used by the Basic Control Engine to refer to the open file—the number passed to the
Open statement.
position Long that specifies the location within the file at which to position the file pointer. The value
must be between 1 and 2147483647, where the first byte (or record number) in the file is
1. For files opened in either Binary, Output, Input, or Append mode, position is the byte
position within the file. For Random files, position is the record number.
A file can be extended by seeking beyond the end of the file and writing data there.
Example This example opens a file for random write, then writes ten records into the file using the PUT statement.
The file is then reopened for read, and the ninth record is read using the Seek and Get functions.
Sub Main()
Open "test.dat" For Random Access Write As #1
For x = 1 To 10
rec$ = "Record#: " & x
Put #1,x,rec$
Next x
Close
Open "test.dat" For Random Access Read As #1
Seek #1,9
Get #1,,rec$
MsgBox "The ninth record = " & x
Close
Kill "test.dat"
End Sub
See Also Seek (page 471) (function); Loc (page 395) (function)
Select...Case (statement)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 473
Syntax
Select Case testexpression
[Case expressionlist
[statement_block]]
[Case expressionlist
[statement_block]]
.
.
[Case Else
[statement_block]]
End Select
Description Used to execute a block of the Basic Control Engine statements depending on the value of a given
expression.
Part Description
statement_block Any group of the Basic Control Engine statements. If the testexpression matches
any of the expressions contained in expressionlist, then this statement block will be
executed.
Multiple expression ranges can be used within a single Case clause. For example:
Case 1 to 10,12,15 Is > 40
Only the statement_block associated with the first matching expression will be executed. If no matching
statement_block is found, then the statements following the Case Else will be executed. A Select...End
Select expression can also be represented with the If...Then expression. The use of the Select
statement, however, may be more readable.
Example This example uses the Select...Case statement to output the current operating system.
Sub Main()
OpSystem% = Basic.OS
Select Case OpSystem%
Case 0,2
s = "Microsoft Windows"
Case 1
s = "DOS"
Case 3 to 8,12
s = "UNIX"
Case 10
s = "IBM OS/2"
Case Else
s = "Other"
End Select
MsgBox "This version of the Basic Control Engine is running on: " & s
End Sub
See Also Choose (page 241) (function); Switch (page 496) (function); IIf (page 369) (function); If...Then...Else
(page 368) (statement)
SelectBox (function)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 474
Syntax SelectBox(title,prompt,ArrayOfItems)
Description Displays a dialog box that allows the user to select from a list of choices and returns an Integer containing
the index of the item that was selected.
Parameter Description
title Title of the dialog box. This can be an expression convertible to a String. A runtime error is
generated if title is Null.
prompt Text to appear immediately above the list box containing the items. This can be an
expression convertible to a String. A runtime error is generated if prompt is Null.
ArrayOfItems Single-dimensioned array. Each item from the array will occupy a single entry in the
list box. A runtime error is generated if ArrayOfItems is not a single-dimensioned array.
ArrayOfItems can specify an array of any fundamental data type (structures are not
allowed). Null and Empty values are treated as zero-length strings.
The value returned is an Integer representing the index of the item in the list box that was selected, with 0
being the first item. If the user selects Cancel, –1 is returned.
result% = SelectBox("Picker","Pick an application:",a$)
Example This example gets the current apps running, puts them in to an array and then asks the user to select one
from a list.
Sub Main()
Dim a$()
AppList a$
result% = SelectBox("Picker","Pick an application:",a$)
If Not result% = -1 then
Msgbox "User selected: " & a$(result%)
Else
Msgbox "User canceled"
End If
End Sub
See Also MsgBox (page 411) (statement); AskBox$ (page 221) (function); AskPassword$ (page 222)
(function); InputBox, InputBox$ (page 374) (functions); OpenFilename$ (page 429) (function);
SaveFilename$ (page 467) (function); AnswerBox (page 205) (function)
Note The SelectBox displays all text in its dialog box in 8-point MS Sans Serif.
SendKeys (statement)
Description Sends the specified keys to the active application, optionally waiting for the keys to be processed before
continuing.
Parameter
Description
KeyStringString containing the keys to be sent. The format for KeyString$ is described below.
$
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 475
isWait Boolean value. If TRUE, then the Basic Control Engine waits for the keys to be completely
processed before continuing. If you are using SendKeys in a CimEdit/CimView script, you must
set this flag to TRUE. If you do not, when a user tries to execute the SendKeys statement, the
CimView screen freezes and processing will not continue. If FALSE (or not specified), then the
BasicScript continues script execution before the active application receives all keys from the
SendKeys statement.
time Integer specifying the number of milliseconds devoted for the output of the entire KeyString$
parameter. It must be within the following range:
0 <= time <= 32767
For example, if time is 5000 (5 seconds) and the KeyString$ parameter contains ten keys, then a
key will be output every 1/2 second. If unspecified (or 0), the keys will play back at full speed.
Specifying Keys To specify any key on the keyboard, simply use that key, such as "a" for lowercase a,
or "A" for uppercase a . Sequences of keys are specified by appending them together: "abc" or "dir /w".
Some keys have special meaning and are therefore specified in a special way, by enclosing them within
braces. For example, to specify the percent sign, use "{%}" . the following table shows the special keys:
Keys that are not displayed when you press them are also specified within braces, such as {Enter} or
{Up}. A list of these keys follows:
Keys can be combined with Shift, Ctrl, and Alt using the reserved keys " + ", " ^ ", and " % " respectively:
For Key Combination Use Shift+Enter "+{Enter}" Ctrl+C "^c" Alt+F2 "%{F2}"
To specify a modifier key combined with a sequence of consecutive keys, group the key sequence within
parentheses, as in the following example: For Key Combination Use Shift+A, Shift+B "+(abc)" Ctrl+F1, Ctrl
+F2 "^({F1}{F2})"
Use " ~ " as a shortcut for embedding Enter within a key sequence: For Key Combination Use a, b, Enter, d,
e "ab~de" Enter, Enter "~~"
To embed quotation marks, use two quotation marks in a row: For Key Combination Use "Hello" ""Hello""
a"b"c "a""b""c"
Key sequences can be repeated using a repeat count within braces: For Key Combination Use Ten "a"
keys "{a 10}" Two Enter keys "{Enter 2}"
Example This example runs Notepad, writes to Notepad, and saves the new file using the SendKeys statement.
Sub Main()
Dim id As Variant
id = Shell ("notepad.exe") 'Run Notepad minimized
AppActivate id 'Now activate Notepad
AppMaximize 'Open and maximize the Notepad window
SendKeys "Hello Notepad", 1 'Write text with time to avoid burst
Sleep 2000
SendKeys "%fs", 1 'Save file (Simulate Alt+F,S keys)
Sleep 2000
SendKeys "name.txt{ENTER}", 1 'Enter name of file to save
AppClose
End Sub
Set (statement)
Comments Syntax 1 The first syntax assigns the result of an expression to an object variable. This statement does
not duplicate the object being assigned but rather copies a reference of an existing object to an object
variable. The object_expression is any expression that evaluates to an object of the same type as the
object_var. With data objects, Set performs additional processing. When the Set is performed, the object
is notified that a reference to it is being made and destroyed. For example, the following statement deletes
a reference to object A , then adds a new reference to B .
Set a = b
Syntax 2 In the second syntax, the object variable is being assigned to a new instance of an existing
object type. This syntax is valid only for data objects. When an object created using the New keyword
goes out of scope (that is, the Sub or Function in which the variable is declared ends), the object is
destroyed.
Syntax 3 The reserved keyword Nothing is used to make an object variable reference no object. At a
later time, the object variable can be compared to Nothing to test whether the object variable has been
instantiated:
Set a = Nothing
:
If a Is Nothing Then Beep
Example This example creates two objects and sets their values.
Sub Main()
Dim document As Object
Dim page As Object
Set document = GetObject("c:\resume.doc")
Set page = Document.ActivePage
MsgBox page.name
End Sub
See Also = (page 202) (statement); Let (page 390) (statement); CreateObject (page 245) (function);
GetObject (page 358) (function); Nothing (page 419) (constant).
SetAttr (statement)
Description Changes the attribute filename$ to the given attribute. A runtime error results if the file cannot be found.
Parameter Description
The attribute parameter can contain any combination of the following values:
The attributes can be combined using the + operator or the binary Or operator.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 478
Example This example creates a file and sets its attributes to Read-Only and System.
Sub Main()
Open "test.dat" For Output As #1
Close #1
MsgBox "The current file attribute is: " & GetAttr("test.dat")
SetAttr "test.dat",ebReadOnly + ebSystem
MsgBox "The file attribute was set to: " & GetAttr("test.dat")
SetAttr "test.dat",ebNormal
Kill "test.dat"
End Sub
See Also GetAttr (page 357) (function); FileAttr (page 339) (function).
Sgn (function)
Description Returns an Integer indicating whether a number is less than, greater than, or equal to 0.
Comments Returns 1 if number is greater than 0. Returns 0 if number is equal to 0. Returns –1 if number is less than
0. The number parameter is a numeric expression of any type. If number is Null , then a runtime error is
generated. Empty is treated as 0.
Example This example tests the product of two numbers and displays a message based on the sign of the result.
Sub Main()
a% = -100
b% = 100
c% = a% * b%
Select Case Sgn(c%)
Case -1
MsgBox "The product is negative " & Sgn(c%)
Case 0
MsgBox "The product is 0 " & Sgn(c%)
Case 1
MsgBox "The product is positive " & Sgn(c%)
End Select
End Sub
Shell (function)
Parameter Description
command$ String containing the name of the application and any parameters.
WindowStyle Optional Integer specifying the state of the application window after execution. It can be
any of the following values:
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 479
An error is generated if unsuccessful running command$. The Shell command runs programs
asynchronously: the statement following the Shell statement will execute before the child application
has exited. On some platforms, the next statement will run before the child application has finished
loading. The Shell function returns a value suitable for activating the application using the AppActivate
statement. It is important that this value be placed into a Variant , as its type depends on the platform.
Example This example displays the Windows Clock, delays awhile, then closes it.
Sub Main()
id = Shell("clock.exe",1)
AppActivate "Clock"
Sleep(2000)
AppClose "Clock"
End Sub
See Also SendKeys (page 474) (statement); AppActivate (page 207) (statement)
Note This function returns a global process ID that can be used to identify the new process.
Important CIMPLICITY runs as a service. Programs started from the Event Manager run as part of the service.
Services, by default, do not interact with the desktop. Therefore, shelling of a program such as CimView,
will cause the program to run, but with no interface.
Sin (function)
Example This example displays the sine of pi/4 radians (45 degrees).
Sub Main()
c# = Sin(Pi / 4)
MsgBox "The sine of 45 degrees is: " & c#
End Sub
See Also Tan (page 501) (function); Cos (page 257) (function); Atn
(page 223) (function).
Syntax Single
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 480
Description A data type used to declare variables capable of holding real numbers with up to seven digits of precision.
Comments Single variables are used to hold numbers within the following ranges: Sign Range Negative
-3.402823E38 <= single <= -1.401298E-45 Positive 1.401298E-45 <= single <= 3.402823E38 The
type-declaration character for Single is ! .
Storage Internally, singles are stored as 4-byte (32-bit) IEEE values. Thus, when appearing within a
structure, singles require 4 bytes of storage. When used with binary or random files, 4 bytes of storage is
required. Each single consists of the following
• A 1-bit sign
• An 8-bit exponent
• A 24-bit mantissa
See Also Currency (page 259) (data type); Date (page 263) (data type); Double (page 300) (data type);
Integer (page 377) (data type); Long (page 398) (data type); Object (page 422) (data type); String
(page 494) (data type); Variant (page 515) (data type); Boolean (page 233) (data type); DefType
(page 276) (statement); CSng (page 258) (function).
Sleep (statement)
Sln (function)
Description Returns the straight-line depreciation of an asset assuming constant benefit from the asset.
Comments The Sln of an asset is found by taking an estimate of its useful life in years, assigning values to each
year, and adding up all the numbers. The formula used to find the Sln of an asset is as follows:
(Cost - Salvage Value) / Useful Life
Parameter Description
Salvage Double representing the estimated value of the asset at the end of its useful life.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 481
The unit of time used to express the useful life of the asset is the same as the unit of time used to express
the period for which the depreciation is returned.
Example This example calculates the straight-line depreciation of an asset that cost $10,000.00 and has a salvage
value of $500.00 as scrap after 10 years of service life.
Sub Main()
dep# = Sln(10000.00,500.00,10)
MsgBox "The annual depreciation is: " & Format(dep#,"Currency")
End Sub
See Also SYD (page 497) (function); DDB (page 269) (function).
Comments Space$ returns a String , whereas Space returns a String variant. NumSpaces is an Integer
between 0 and 32767.
Example This example returns a string of ten spaces and displays it.
Sub Main()
ln$ = Space(10)
MsgBox "Hello" & ln$ & "over there."
End Sub
See Also String, String$ (page 495) (functions); Spc (page 481) (function).
Spc (function)
Description Prints out the specified number of spaces. This function can only be used with the Print and Print#
statements.
Comments The numspaces parameter is an Integer specifying the number of spaces to be printed. It can be any
value between 0 and 32767. If a line width has been specified (using the Width statement), then the
number of spaces is adjusted as follows:
numspaces = numspaces Mod width
If the resultant number of spaces is greater than width - print_position , then the number of spaces is
recalculated as follows:
numspaces = numspaces – (width – print_position)
These calculations have the effect of never allowing the spaces to overflow the line length. Furthermore,
with a large value for column and a small line width, the file pointer will never advance more than one
line.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 482
See Also Tab (page 501) (function); Print (page 442) (statement); Print# (page 443) (statement).
SQLBind (function)
Description Specifies which fields are returned when results are requested using the SQLRetrieve or
SQLRetrieveToFile function.
Comments The following table describes the parameters to the SQLBind function:
Parameter Description
array Any array of variants. Each call to SQLBind adds a new column number (an Integer) in the
appropriate slot in the array. Thus, as you bind additional columns, the array parameter
grows, accumulating a sorted list (in ascending order) of bound columns. If array is fixed,
then it must be a one-dimensional variant array with sufficient space to hold all the bound
column numbers. A runtime error is generated if array is too small. If array is dynamic, then it
will be resized to exactly hold all the bound column numbers.
column Optional Long parameter that specifies the column to which to bind data. If this parameter is
omitted, all bindings for the connection are dropped.
This function returns the number of bound columns on the connection. If no columns are bound, then 0 is
returned. If there are no pending queries, then calling SQLBind will cause an error (queries are initiated
using the SQLExecQuery function). If supported by the driver, row numbers can be returned by binding
column 0. The Basic Control Engine generates a runtime error that can be trapped if SQLBind fails.
Additional error information can then be retrieved using the SQLError function.
See Also SQLRetrieve (page 489) (function); SQLRetrieveToFile (page 490) (function).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 483
SQLClose (function)
Comments The unique connection ID (connectionID) is a Long value representing a valid connection as returned
by SQLOpen . After SQLClose is called, any subsequent calls made with the connectionID will
generate runtime errors. The SQLClose function returns 0 if successful; otherwise, it returns the passed
connection ID and generates a trappable runtime error. Additional error information can then be retrieved
using the SQLError function.
The Basic Control Engine automatically closes all open SQL connections when either the script or the
application terminates. You should use the SQLClose function rather than relying on the application to
automatically close connections in order to ensure that your connections are closed at the proper time.
SQLError (function)
Description Retrieves driver-specific error information for the most recent SQL functions that failed.
Comments This function is called after any other SQL function fails. Error information is returned in a two-dimensional
array (ErrArray). The following table describes the parameters to the SQLError function:
Parameter Description
ErrArray Two-dimensional Variant array, which can be dynamic or fixed. If the array is fixed, it must
be (x,3), where x is the number of errors you want returned. If x is too small to hold all the
errors, then the extra error information is discarded. If x is greater than the number of errors
available, all errors are returned, and the empty array elements are set to Empty. If the array
is dynamic, it will be resized to hold the exact number of errors.
ID Optional Long parameter specifying a connection ID. If this parameter is omitted, error
information is returned for the most recent SQL function call.
Each array entry in the ErrArray parameter describes one error. The three elements in each array entry
contain the following information:
Element Value
( entry ,0) The ODBC error state, indicated by a Long containing the error class and subclass.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 484
( entry ,2) The text error message returned by the driver. This field is String type.
For example, to retrieve the ODBC text error message of the first returned error, the array is referenced
as:
ErrArray(0,2)
The SQLError function returns the number of errors found. The Basic Control Engine generates
a runtime error if SQLError fails. (You cannot use the SQLError function to gather additional error
information in this case.)
Example This example forces a connection error and traps it for use with the SQLError function.
Sub Main()
Dim a() As Variant
On Error Goto Trap
id& = SQLOpen("",,4)
id& = SQLClose(id&)
Exit Sub
Trap:
rc% = SQLError(a)
If (rc%) Then
For x = 0 To (rc% - 1)
MsgBox "The SQL state returned was: " & a(x,0)
MsgBox "The native error code returned was: " & a(x,1)
MsgBox a(x,2)
Next x
End If
End Sub
SQLExecQuery (function)
Comments This function is called after a connection to a data source is established using the SQLOpen function.
The SQLExecQuery function may be called multiple times with the same connection ID, each time
replacing all results. The following table describes the parameters to the SQLExecQuery function:
Parameter Description
ID Long identifying a valid connected data source. This parameter is returned by the
SQLOpen function.
query$ String specifying an SQL query statement. The SQL syntax of the string must strictly
follow that of the driver.
The return value of this function depends on the result returned by the SQL statement:
SQL Value
Statement
SELECT...FROM The value returned is the number of columns returned by the SQL statement.
DELETE,INSERT,UPDATE
The value returned is the number of rows affected by the SQL statement.
The Basic Control Engine generates a runtime error if SQLExecQuery fails. Additional error information
can then be retrieved using the SQLError function.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 485
See Also SQLOpen (page 487) (function); SQLClose (page 483) (function); SQLRetrieve (page 489)
(function); SQLRetrieveToFil (page 490) (function)
SQLGetSchema (function)
Description Returns information about the data source associated with the specified connection.
Comments The following table describes the parameters to the SQLGetSchema function:
Parameter Description
ID Long parameter identifying a valid connected data source. This parameter is returned by the
SQLOpen function.
action Integer parameter specifying the results to be returned. The following table lists values for
this parameter:
Value Meaning
4 Returns a one-dimensional array of table names for a specified owner and database
associated with the current connection. The array is returned in the array parameter.
(0,0) Zeroth column name (0,1) ODBC SQL data type ( Integer ) (1,0) First
column name (1,1) ODBC SQL data type ( Integer ) : : (n-1,0) Nth column
name (n-1,1) ODBC SQL data type ( Integer )
7 Returns a string containing the name (either the directory name or the database
name, depending on the driver) of the current database.
8 Returns a string containing the name of the data source on the current connection.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 486
9 Returns a string containing the name of the DBMS of the data source on the current
connection (for example, "FoxPro 2.5" or "Excel Files").
10 Returns a string containing the name of the server for the data source.
11 Returns a string containing the owner qualifier used by the data source (for
example, "owner," "Authorization ID," "Schema").
12 Returns a string containing the table qualifier used by the data source (for example,
"table," "file").
13 Returns a string containing the database qualifier used by the data source (for
example, "database," "directory").
14 Returns a string containing the procedure qualifier used by the data source (for
example, "database procedure," "stored procedure," "procedure").
array Optional Variant array parameter. This parameter is only required for action values 1,
2, 3, 4, and 5. The returned information is put into this array. If array is fixed and it is not
the correct size necessary to hold the requested information, then SQLGetSchema will
fail. If the array is larger than required, then any additional elements are erased. If array is
dynamic, then it will be redimensioned to hold the exact number of elements requested.
qualifier Optional String parameter required for actions 3, 4, or 5. The values are listed in the
following table:
Action Qualifier
3 The qualifier parameter must be the name of the database represented by ID.
4 The qualifier parameter specifies a database name and an owner name. The syntax
for this string is: DatabaseName.OwnerName
5 The qualifier parameter specifies the name of a table on the current connection.
The Basic Control Engine generates a runtime error if SQLGetSchema fails. Additional error information
can then be retrieved using the SQLError function. If you want to retrieve the available data sources
(where action = 1) before establishing a connection, you can pass 0 as the ID parameter. This is the only
action that will execute successfully without a valid connection.
This function calls the ODBC functions SQLGetInfo and SQLTables in order to retrieve the
requested information. Some database drivers do not support these calls and will therefore cause the
SQLGetSchema function to fail.
SQLOpen (function)
Description Establishes a connection to the specified data source, returning a Long representing the unique
connection ID.
Comments This function connects to a data source using a login string (login$) and optionally sets the completed
login string (completed$) that was used by the driver. The following table describes the parameters to the
SQLOpen function:
Parameter Description
login$ String expression containing information required by the driver to connect to the requested
data source. The syntax must strictly follow the driver's SQL syntax.
completed Optional String variable that will receive a completed connection string returned by the
$ driver. If this parameter is missing, then no connection string will be returned.
Value Meaning
2 The driver's dialog box is only displayed if the connection string does not contain
enough information to make the connection. This is the default behavior.
3 The driver's dialog box is only displayed if the connection string does not contain
enough information to make the connection. Dialog box options that were passed as
valid parameters are dimmed and unavailable.
The SQLOpen function will never return an invalid connection ID. The following example establishes a
connection using the driver's login dialog box:
id& = SQLOpen("",,1)
The Basic Control Engine returns 0 and generates a trappable runtime error if SQLOpen fails. Additional
error information can then be retrieved using the SQLError function. Before you can use any SQL
statements, you must set up a data source and relate an existing database to it. This is accomplished
using the odbcadm.exe program.
Example This example connects the data source called "sample," returning the completed connection string, and
then displays it.
Sub Main()
Dim s As String
id& = SQLOpen("dsn=SAMPLE",s$,3)
MsgBox "The completed connection string is: " & s$
id& = SQLClose(id&)
End Sub
SQLQueryTimeout (statement)
Description Specifies the timeout, in seconds, for ODBC queries. If you do not set SQLQueryTimeout , the default
timeout is 60 seconds (1 minute).
Parameter Description
Example The following example sets the timeout for ODBC queries to 120 seconds (2 minutes).
Sub Main()
SQLQueryTimeout 120
End Sub
SQLRequest (function)
Description Opens a connection, runs a query, and returns the results as an array.
Parameter Description
connection String specifying the connection information required to connect to the data source.
query String specifying the query to execute. The syntax of this string must strictly follow the
syntax of the ODBC driver.
array Array of variants to be filled with the results of the query. The array parameter must be
dynamic: it will be resized to hold the exact number of records and fields.
output Optional String to receive the completed connection string as returned by the driver.
prompt Optional Integer specifying the behavior of the driver's dialog box.
isColumnNames Optional Boolean specifying whether the column names are returned as the first row
of results. The default is False .
The Basic Control Engine generates a runtime error if SQLRequest fails. Additional error information
can then be retrieved using the SQLError function. The SQLRequest function performs one of the
following actions, depending on the type of query being performed:
SELECT The SQLRequest function fills array with the results of the query, returning a Long
containing the number of results placed in the array. The array is filled as follows
(assuming an x by y query):
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 489
(record 1,field 1)
(record 1,field 2)
:
(record 1,field y)
(record 2,field 1)
(record 2,field 2)
:
(record 2,field y)
:
:
(record x,field 1)
(record x,field 2)
:
(record x,field y)
INSERT, DELETE, The SQLRequest function erases array and returns a Long containing the
UPDATE number of affected rows.
Example This example opens a data source, runs a select query on it, and then displays all the data found in the
result set.
Sub Main()
Dim a() As Variant
l& = SQLRequest("dsn=SAMPLE;","Select * From c:\sample.dbf",a,,3,True)
For x = 0 To Ubound(a)
For y = 0 To l - 1
MsgBox a(x,y)
Next y
Next x
End Sub
SQLRetrieve (function)
Comments This function is called after a connection to a data source is established, a query is executed, and the
desired columns are bound. The following table describes the parameters to the SQLRetrieve function:
Parameter Description
ID Long identifying a valid connected data source with pending query results.
array Two-dimensional array of variants to receive the results. The array has x rows by y
columns. The number of columns is determined by the number of bindings on the
connection.
maxrows Optional Integer specifying the maximum number of rows to be returned. If maxrows
is greater than the number of rows available, all results are returned, and additional
rows are set to empty. If maxrows is less than the number of rows available, the
array is filled, and additional results are placed in memory for subsequent calls to
SQLRetrieve.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 490
isColumnNames Optional Boolean specifying whether column names should be returned as the first
row of results. The default is FALSE.
isFetchFirst Optional Boolean expression specifying whether results are retrieved from the
beginning of the result set. The default is False .
Before you can retrieve the results from a query, you must (1) initiate a query by calling the
SQLExecQuery function and (2) specify the fields to retrieve by calling the SQLBind function. This
function returns a Long specifying the number of rows available in the array. The Basic Control Engine
generates a runtime error if SQLRetrieve fails. Additional error information is placed in memory.
Example This example executes a query on the connected data source, binds columns, and retrieves them.
Sub Main()
Dim b() As Variant
Dim c() As Variant
id& = SQLOpen("DSN=SAMPLE",,3)
qry& = SQLExecQuery(id&,"Select * From c:\sample.dbf")
i% = SQLBind(id&,b,3)
i% = SQLBind(id&,b,1)
i% = SQLBind(id&,b,2)
i% = SQLBind(id&,b,6)
l& = SQLRetrieve(id&,c)
For x = 0 To Ubound(c)
For y = 0 To Ubound(b)
MsgBox c(x,y)
Next y
Next x
id& = SQLClose(id&)
End Sub
See Also SQLOpen (page 487) (function); SQLExecQuery (page 484) (function); SQLClose (page 483)
(function); SQLBind (page 482) (function); SQLRetrieveToFile (page 490) (function).
SQLRetrieveToFile (function)
Description Retrieves the results of a query and writes them to the specified file.
Comments The following table describes the parameters to the SQLRetrieveToFile function:
Parameter Description
destination String specifying the file where the results are written.
isColumnNames Optional Boolean specifying whether the first row of results returned are the bound
column names. By default, the column names are not returned.
delimiter Optional String specifying the column separator. A tab ( Chr$(9) ) is used as the
default.
Before you can retrieve the results from a query, you must (1) initiate a query by calling the
SQLExecQuery function and (2) specify the fields to retrieve by calling the SQLBind function. This
function returns the number of rows written to the file. A runtime error is generated if there are no pending
results or if the Basic Control Engine is unable to open the specified file. The Basic Control Engine
generates a runtime error if SQLRetrieveToFile fails. Additional error information may be placed in
memory for later use with the SQLError function.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 491
Example This example opens a connection, runs a query, binds columns, and writes the results to a file.
Sub Main()
Dim b() As Variant
id& = SQLOpen("DSN=SAMPLE;UID=RICH",,4)
t& = SQLExecQuery(id&,"Select * From c:\sample.dbf")
i% = SQLBind(id&,b,3)
i% = SQLBind(id&,b,1)
i% = SQLBind(id&,b,2)
i% = SQLBind(id&,b,6)
l& = SQLRetrieveToFile(id&,"c:\results.txt",True,",")
id& = SQLClose(id&)
End Sub
See Also SQLOpen (page 487) (function); SQLExecQuery (page 484) (function); SQLClose (page 483)
(function); SQLBind (page 482) (function); SQLRetrieve (page 489) (function).
Sqr (function)
Example This example calculates the square root of the numbers from 1 to 10 and displays them.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
msg1 = ""
For x = 1 To 10
sx# = Sqr(x)
msg1 = msg1 & "The square root of " & x & " is " &_
Format(sx#,"Fixed") & crlf
Next x
MsgBox msg1
End Sub
Stop (statement)
Syntax Stop
Description Suspends execution of the current script, returning control to a debugger if one is present. If a debugger is
not present, this command will have the same effect as End .
Example The Stop statement can be used for debugging. In this example, it is used to stop execution when Z is
randomly set to 0.
Sub Main()
For x = 1 To 10
z = Random(0,10)
If z = 0 Then Stop
y = x / z
Next x
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 492
See Also Exit For (page 334) (statement); Exit Do (page 334) (statement); Exit Function (page 335)
(statement); Exit Sub (page 335) (statement); End (page 322) (statement).
Comments The number parameter is any numeric expression or expression convertible to a number. If number
is negative, then the returned string will contain a leading minus sign. If number is positive, then the
returned string will contain a leading space. Singles are printed using only 7 significant digits. Doubles are
printed using 15–16 significant digits. These functions recognize the decimal separator and thousands
separators as specified in the Regional Settings in the Control Panel. If the regional settings are changed,
these functions will recognize it and act accordingly. The CStr , Format , and Format$ functions also
determine their separators based on the regional settings.
Example In this example, the Str$ function is used to display the value of a numeric variable.
Sub Main()
x# = 100.22
MsgBox "The string value is: " + Str(x#)
End Sub
See Also Format, Format$ (page 348) (functions); CStr (page 258) (function).
StrComp (function)
Description Returns an Integer indicating the result of comparing the two string arguments.
0 string1 = string2
Parameter Description
string1 First string to be compared, which can be any expression convertible to a String.
string2 Second string to be compared, which can be any expression convertible to a String.
compare Optional Integer specifying how the comparison is to be performed. It can be either of the
following values:
0 Case-sensitive comparison
1 Case-insensitive comparison
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 493
If compare is not specified, then the current Option Compare setting is used. If no Option Compare
statement has been encountered, then Binary is used (that is, string comparison is case-sensitive).
Example This example compares two strings and displays the results. It illustrates that the function compares two
strings to the length of the shorter string in determining equivalency.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
Dim abc As Integer
Dim abi As Integer
Dim cdc As Integer
Dim cdi As Integer
a$ = "This string is UPPERCASE and lowercase"
b$ = "This string is uppercase and lowercase"
c$ = "This string"
d$ = "This string is uppercase and lowercase characters"
msg1 = "a = " & a & crlf
msg1 = msg1 & "b = " & b & crlf
msg1 = msg1 & "c = " & c & crlf
msg1 = msg1 & "d = " & d & crlf & crlf
abc = StrComp(a$,b$,1)
msg1 = msg1 & "a and c (insensitive) : " & abc & crlf
abi = StrComp(a$,b$,0)
msg1 = msg1 & "a and c (sensitive): " & abi & crlf
cdc = StrComp(c$,d$,1)
msg1 = msg1 & "c and d (insensitive): " & cdc & crlf
cdi = StrComp(c$,d$,0)
msg1 = msg1 & "c and d (sensitive) : " & cdi & crlf
MsgBox msg1
End Sub
See Also Comparison Operators (page 250) (topic); Like (page 391) (operator); Option Compare (page 432)
(statement).
StrConv (function)
Parameter Description
ebProperCase 3 Capitalizes the first letter of each word and lower-cases all the letters. This
constant is supported on all platforms.
ebUnicode 64 Converts string from MBCS to UNICODE. (This constant can only be used on
platforms supporting UNICODE.)
ebFromUnicode128 Converts string from UNICODE to MBCS. (This constant can only be used on
platforms supporting UNICODE.)
A runtime error is generated when a conversion is requested that is not supported on the current platform.
For example, the ebWide and ebNarrow constants can only be used on an MBCS platform. (You can
determine platform capabilities using the Basic.Capabilities method.) The following groupings of
constants are mutually exclusive and therefore cannot be specified at the same time:
ebUpperCase, ebLowerCase, ebProperCase
ebWide, ebNarrow
ebUnicode, ebFromUnicode
Many of the constants can be combined. For example, ebLowerCase Or ebNarrow. When converting to
proper case (i.e., the ebProperCase constant), the following are seen as word delimiters: tab, linefeed,
carriage-return, formfeed, vertical tab, space, null.
Example
Sub Main()
a = InputBox("Type any string:")
MsgBox "Upper case: " & StrConv(a,ebUpperCase)
MsgBox "Lower case: " & StrConv(a,ebLowerCase)
MsgBox "Proper case: " & StrConv(a,ebProperCase)
If Basic.Capability(10) And Basic.OS = ebWin16 Then
'This is an MBCS locale
MsgBox "Narrow: " & StrConv(a,ebNarrow)
MsgBox "Wide: " & StrConv(a,ebWide)
MsgBox "Katakana: " & StrConv(a,ebKatakana)
MsgBox "Hiragana: " & StrConv(a,ebHiragana)
End If
End Sub
See Also UCase, UCase$ (page 511) (functions), LCase, LCase$ (page 387) (functions), Basic.Capability
(page 224) (method)
Syntax String
Comments Strings are used to hold sequences of characters, each character having a value between 0 and 255.
Strings can be any length up to a maximum length of 32767 characters. Strings can contain embedded
nulls, as shown in the following example: s$ = "Hello" + Chr$(0) + "there" 'String with embedded null
The length of a string can be determined using the Len function. This function returns the number of
characters that have been stored in the string, including unprintable characters. The type-declaration
character for String is $ .
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 495
String variables that have not yet been assigned are set to zero-length by default.
Strings are normally declared as variable-length, meaning that the memory required for storage of the
string depends on the size of its content. The following script statements declare a variable-length string
and assign it a value of length 5:
Dim s As String
s = "Hello" 'String has length 5.
Fixed-length strings are given a length in their declaration: Dim s As String * 20 s = "Hello" 'String has
length 20 (internally pads with spaces).
When a string expression is assigned to a fixed-length string, the following rules apply:
• If the string expression is less than the length of the fixed-length string, then the fixed-length string is
padded with spaces up to its declared length.
• If the string expression is greater than the length of the fixed-length string, then the string expression
is truncated to the length of the fixed-length string.
Fixed-length strings are useful within structures when a fixed size is required, such as when passing
structures to external routines.
The storage for a fixed-length string depends on where the string is declared, as described in the following
table:
In In the same data area as that of the structure. Local structures are on the stack; public
structures structures are stored in the public data space; and private structures are stored in the private
data space. Local structures should be used sparingly as stack space is limited.
In arrays In the global string space along with all the other array elements.
Local On the stack. The stack is limited in size, so local fixed-length strings should be used
routines sparingly.
See Also Currency (page 259) (data type);Date (page 263) (data type); Double (page 300) (data type); Integer
(page 377) (data type); Long (page 398) (data type); Object (page 422) (data type); Single (page
479) (data type); Variant (page 515) (data type); Boolean (page 233) (data type); DefType (page
276) (statement); CStr (page 258) (function).
Description Returns a string of length number consisting of a repetition of the specified filler character.
Comments String$ returns a String, whereas String returns a String variant. These functions take the following
parameters:
Parameter Description
CharCode Integer specifying the character code to be used as the filler character. If CharCode is
greater than 255 (the largest character value), then the Basic Control Engine converts it to a
valid character using the following formula: CharCode Mod 256
text$ Any String expression, the first character of which is used as the filler character.
Example This example uses the String function to create a line of "=" signs the length of another string and then
displays the character string underlined with the generated string.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
a$ = "This string will appear underlined."
b$ = String(Len(a$),"_")
MsgBox a$ & crlf & b$
End Sub
2. May contain letters, digits, and the underscore character ( _ ). Punctuation and type-declaration
characters are not allowed. The exclamation point ( ! ) can appear within the name as long as it
is not the last character.
4. The call cannot end with a comma. For instance, using the above example, the following is not
valid:
Test 1,,
5. The call must contain the minimum number of parameters as required by the called subroutine.
For instance, using the above example, the following are invalid:
Switch (function)
Comments The Switch function evaluates each condition and expression, returning the expression that corresponds
to the first condition (starting from the left) that evaluates to True . Up to seven condition/expression
pairs can be specified. A runtime error is generated it there is an odd number of parameters (that is, there
is a condition without a corresponding expression). The Switch function returns Null if no condition
evaluates to True .
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 497
Example The following code fragment displays the current operating platform. If the platform is unknown, then the
word "Unknown" is displayed.
Sub Main()
Dim a As Variant
a = Switch(Basic.OS = 0,"Windows XP",Basic.OS = 2,"Win32",Basic.OS = 11,"OS/2")
MsgBox "The current platform is: " & IIf(IsNull(a),"Unknown",a)
End Sub
See Also Choose (page 241) (function); IIf (page 369) (function); If...Then...Else (page 368) (statement);
Select...Case (page 472) (statement).
SYD (function)
Description Returns the sum of years' digits depreciation of an asset over a specific period of time.
Comments The SYD of an asset is found by taking an estimate of its useful life in years, assigning values to each
year, and adding up all the numbers. The formula used to find the SYD of an asset is as follows:
(Cost – Salvage_Value) * Remaining_Useful_Life / SYD
Parameter Description
Salvage Double representing the estimated value of the asset at the end of its useful life.
Period Double representing the period for which the depreciation is to be calculated. It cannot
exceed the life of the asset.
To receive accurate results, the parameters Life and Period must be expressed in the same units. If Life is
expressed in terms of months, for example, then Period must also be expressed in terms of months.
Example In this example, an asset that cost $1,000.00 is depreciated over ten years. The salvage value is $100.00,
and the sum of the years' digits depreciation is shown for each year.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
msg1 = ""
For x = 1 To 10
dep# = SYD(1000,100,10,x)
msg1 = msg1 & "Year: " & x & " Dep: " & Format(dep#,"Currency") & crlf
Next x
MsgBox msg1
End Sub
See Also Sln (page 480) (function); DDB (page 269) (function)
System.Exit (method)
Syntax System.Exit
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 498
Example This example asks whether the user would like to restart Windows after exiting.
Sub Main
message$="Restart Windows on exit?",ebYesNo,"Exit Windows"
button = MsgBox message$
If button = ebYes Then System.Restart 'Yes button selected.
If button = ebNo Then System.Exit 'No button selected.
End Sub
System.FreeMemory (property)
Syntax System.FreeMemory
Example The following example gets the free memory and converts it to kilobytes.
Sub Main()
FreeMem& = System.FreeMemory
FreeKBytes$ = Format(FreeMem& / 1000,"##,###")
MsgBox FreeKbytes$ & " Kbytes of free memory"
End Sub
See Also System.TotalMemory (page 499) (property); System.FreeResources (page 498) (property);
Basic.FreeMemory (page 226) (property).
System.FreeResources (property)
Syntax System.FreeResources
See Also System.TotalMemory (page 499) (property); System.FreeMemory (page 498) (property);
Basic.FreeMemory (page 226) (property).
System.MouseTrails (method)
Comments If isOn is True , then mouse trails are turned on; otherwise, mouse trails are turned off. A runtime error is
generated if mouse trails is not supported on your system.
System.Restart (method)
Syntax System.Restart
Example This example asks whether the user would like to restart Windows after exiting.
Sub Main
button = MsgBox ("Restart Windows on exit?",ebYesNo, _
"Exit Windows")
If button = ebYes Then System.Restart 'Yes button selected.
If button = ebNo Then System.Exit 'No button selected.
End Sub
System.TotalMemory (property)
Syntax System.TotalMemory
Description Returns a Long representing the number of bytes of available free memory in Windows.
See Also System.FreeMemory (page 498) (property); System.FreeResources (page 498) (property);
Basic.FreeMemory (page 226) (property).
System.WindowsDirectory$ (property)
Syntax System.WindowsDirectory$
System.WindowsVersion$ (property)
Syntax System.WindowsVersion$
Comments
Example This example sets the UseWin31 variable to True if the Windows version is greater than or equal to 3.1;
otherwise, it sets the UseWin31 variable to False.
Sub Main()
If Val(System.WindowsVersion$) >= 5 Then
MsgBox "You are running a Windows version 5 or later"
Else
MsgBox "You are running Windows version earlier than 5"
End If
End Sub
Tab (function)
Tan (function)
Text (statement)
TextBox (statement)
Timer (function)
TimeSerial (function)
TimeValue (function)
True (constant)
Type (statement)
TypeName (function)
TypeOf (function)
Tab (function)
Description Prints the number of spaces necessary to reach a given column position.
Comments This function can only be used with the Print and Print# statements. The column parameter is an
Integer specifying the desired column position to which to advance. It can be any value between 0 and
32767 inclusive. Rule 1: If the current print position is less than or equal to column, then the number of
spaces is calculated as:
column – print_position
Rule 2: If the current print position is greater than column, then column – 1 spaces are printed on the
next line. If a line width is specified (using the Width statement), then the column position is adjusted as
follows before applying the above two rules:
column = column Mod width
The Tab function is useful for making sure that output begins at a given column position, regardless of
the length of the data already printed on that line.
Example This example prints three column headers and three numbers aligned below the column headers.
Sub Main()
Print "Column1";Tab(10);"Column2";Tab(20);"Column3"
Print Tab(3);"1";Tab(14);"2";Tab(24);"3"
Sleep(10000) 'Wait 10 seconds.
End Sub
See Also Spc (page 481) (function); Print (page 442) (statement); Print# (page 443) (statement).
Tan (function)
Example This example computes the tangent of pi/4 radians (45 degrees).
Sub Main()
c# = Tan(Pi / 4)
MsgBox "The tangent of 45 degrees is: " & c#
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 502
See Also Sin (page 479) (function); Cos (page 257) (function); Atn
(page 223) (function).
Text (statement)
Description Defines a text control within a dialog box template. The text control only displays text; the user cannot set
the focus to a text control or otherwise interact with it.
Comments The text within a text control word-wraps. Text controls can be used to display up to 32K of text. The Text
statement accepts the following parameters:
Parameter Description
x, y Integer positions of the control (in dialog units) static to the upper left corner of the dialog
box.
title$ String containing the text that appears within the text control. This text may contain an
ampersand character to denote an accelerator letter, such as "&Save" for Save . Pressing
this accelerator letter sets the focus to the control following the Text statement in the dialog
box template.
Identifier Name by which this control can be referenced by statements in a dialog function (such as
DlgFocus and DlgEnable). If omitted, then the first two words from title$ are used.
FontName Name of the font used for display of the text within the text control. If omitted, then the default
$ font for the dialog is used.
size Size of the font used for display of the text within the text control. If omitted, then the default
size for the default font of the dialog is used.
style Style of the font used for display of the text within the text control. This can be any of the
following values:
Example
Sub Main()
Begin Dialog UserDialog 81,64,128,60,"Untitled"
CancelButton 80,32,40,14
OKButton 80,8,40,14
Text 4,8,68,44,"This text is displayed in the dialog box."
End Dialog
Dim d As UserDialog
Dialog d
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 503
See Also CancelButton (page 243) (statement); CheckBox (page 240) (statement); ComboBox (page 249)
(statement); Dialog (page 278) (function); Dialog (page 279) (statement); DropListBox (page 301)
(statement); GroupBox (page 361) (statement); ListBox (page 394) (statement); OKButton (page
426) (statement); OptionButton (page 434) (statement); OptionGroup (page 435) (statement);
Picture (page 438) (statement); PushButton (page 447) (statement); TextBox (page 503)
(statement); Begin Dialog (page 231) (statement), PictureButton (page 439) (statement).
Note Accelerators are underlined, and the Alt+letter accelerator combination is used. 8-point MS Sans Serif is
the default font used within user dialogs.
TextBox (statement)
Description Defines a single or multiline text-entry field within a dialog box template.
Comments If isMultiline is 1, the TextBox statement creates a multiline text-entry field. When the user types into
a multiline field, pressing the Enter key creates a new line rather than selecting the default button. This
statement can only appear within a dialog box template (that is, between the Begin Dialog and End
Dialog statements). The TextBox statement requires the following parameters:
Parameter Description
x, y Integer position of the control (in dialog units) static to the upper left corner of the
dialog box.
Identifier Name by which this control can be referenced by statements in a dialog function
(such as DlgFocus and DlgEnable ). This parameter also creates a string
variable whose value corresponds to the content of the text box. This variable can
be accessed using the syntax:
DialogVariable
.
Identifier
isMultiline Specifies whether the text box can contain more than a single line (0 = single-line;
1 = multiline).
FontName$ Name of the font used for display of the text within the text box control. If omitted,
then the default font for the dialog is used.
size Size of the font used for display of the text within the text box control. If omitted,
then the default size for the default font of the dialog is used.
style Style of the font used for display of the text within the text box control. This can be
any of the following values:
When the dialog box is created, the Identifier variable is used to set the initial content of the text box.
When the dialog box is dismissed, the variable will contain the new content of the text box. A single-line
text box can contain up to 256 characters. The length of text in a multiline text box is not limited by the
Basic Control Engine; the default memory limit specified by the given platform is used instead.
Example
Sub Main()
Begin Dialog UserDialog 81,64,128,60,"Untitled"
CancelButton 80,32,40,14
OKButton 80,8,40,14
TextBox 4,8,68,44,.TextBox1,1
End Dialog
Dim d As UserDialog
d.TextBox1 = "Enter text before invoking" 'Display text in the Textbox by setting the
default value of the TextBox before showing it.
Dialog d
End Sub
See Also CancelButton (page 243) (statement); CheckBox (page 240) (statement); ComboBox (page 249)
(statement); Dialog (page 278) (function); Dialog (page 279) (statement); DropListBox (page 301)
(statement); GroupBox (page 361) (statement); ListBox (page 394) (statement); OKButton (page
426) (statement); OptionButton (page 434) (statement); OptionGroup (page 435) (statement);
Picture (page 438) (statement); PushButton (page 447) (statement); Text (page 502) (statement);
Begin Dialog (page 231) (statement), PictureButton (page 439) (statement).
Note 8-point MS Sans Serif is the default font used within user dialogs.
Syntax Time[$][()]
Comments The Time$ function returns a String contains the time in 24-hour time format, whereas Time returns a
Date variant. To set the time, use the Time/Time$ statements.
Example This example returns the system time and displays it in a dialog box.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
oldtime$ = Time
msg1 = "Time was: " & oldtime$ & crlf
Time = "10:30:54"
msg1 = msg1 & "Time set to: " & Time & crlf
Time = oldtime$
msg1 = msg1 & "Time restored to: " & Time
MsgBox msg1
End Sub
See Also Time, Time$ (page 504) (statements); Date, Date$ (page 263) (functions); Date, Date$ (page 264)
(statements); Now (page 419) (function).
Description Sets the system time to the time contained in the specified string.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 505
Comments The Time$ statement requires a string variable in one of the following formats: HH HH:MM
HH:MM:SS where HH is between 0 and 23, MM is between 0 and 59, and SS is between 0 and 59. The
Time statement converts any valid expression to a time, including string and numeric values. Unlike the
Time$ statement, Time recognizes many different time formats, including 12-hour times.
Example This example returns the system time and displays it in a dialog box.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
oldtime$ = Time
msg1 = "Time was: " & oldtime$ & crlf
Time = "10:30:54"
msg1 = msg1 & "Time set to: " & Time & crlf
Time = oldtime$
msg1 = msg1 & "Time restored to: " & Time
MsgBox msg1
End Sub
See Also Time, Time$ (page 504) (statements); Date, Date$ (page 263) (functions); Date, Date$ (page 264)
(statements); Now (page 419) (function).
Note: If you do not have permission to change the time, a runtime error 70 will be generated.
Timer (function)
Syntax Timer
Description Returns a Single representing the number of seconds that have elapsed since midnight.
Example This example displays the elapsed time between execution start and the time you clicked the OK button
on the first message.
Sub Main()
start& = Timer
MsgBox "Click the OK button, please."
total& = Timer - start&
MsgBox "The elapsed time was: " & total& & " seconds."
End Sub
See Also Time, Time$ (page 504) (functions); Now (page 419) (function).
TimeSerial (function)
Syntax TimeSerial(hour,minute,second)
Description Returns a Date variant representing the given time with a date of
zero.
Parameter Description
Example
Sub Main()
start# = TimeSerial(10,22,30)
finish# = TimeSerial(10,35,27)
dif# = Abs(start# - finish#)
MsgBox "The time difference is: " & Format(dif#,"hh:mm:ss")
End Sub
See Also DateValue (page 268) (function); TimeValue (page 506) (function);
DateSerial (page 268) (function).
TimeValue (function)
Description Returns a Date variant representing the time contained in the specified string argument.
Comments This function interprets the passed time_string$ parameter looking for a valid time specification. The
time_string$ parameter can contain valid time items separated by time separators such as colon (:) or
period (.).
Time strings can contain an optional date specification, but this is not used in the formation of the returned
value. If a particular time item is missing, then it is set to 0. For example, the string "10 pm" would be
interpreted as "22:00:00."
Example This example calculates the TimeValue of the current time and displays it in a dialog box.
Sub Main()
t1$ = "10:15"
t2# = TimeValue(t1$)
MsgBox "The TimeValue of " & t1$ & " is: " & t2#
End Sub
See Also DateValue (page 268) (function); TimeSerial (page 505) (function); DateSerial (page 268) (function).
Function Returns
Trim Copy of the passed string expression (string) with both the leading and trailing
spaces removed.
Comments Trim$ returns a String , whereas Trim returns a String variant. Null is returned if text is Null .
Example 1
'This first example uses the Trim$ function to extract the
'nonblank part of a string and display it.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
text$ = " This is text "
tr$ = Trim$(text$)
MsgBox "Original =>" & text$ & "<=" & crlf & _
"Trimmed =>" & tr$ & "<="
End Sub
Example 2
'This second example displays a right-justified string and its
'LTrim result.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
a$ = " <= This is a right-justified string"
b$ = LTrim$(a$)
MsgBox a$ & crlf & b$
End Sub
Example 3
'This third example displays a left-justified string and its
'RTrim result.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
a$ = "This is a left-justified string. "
b$ = RTrim$(a$)
MsgBox a$ & "<=" & crlf & b$ & "<="
End Sub
See Also LTrim, LTrim$ (page 399) (functions); RTrim, RTrim$ (page 464) (functions).
True (constant)
Example This example sets variable a to True and then tests to see whether (1) A is True; (2) the True constant =
-1; and (3) A is equal to -1 (True).
Sub Main()
a = True
If ((a = True) and (True = -1) and (a = -1)) then
MsgBox "a is True."
Else
MsgBox "a is False."
End If
End Sub
See Also False (page 338) (constant); Constants (topic); Boolean (page 233) (data type).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 508
Type (statement)
Syntax
Type username
variable As type
variable As type
variable As type
:
End Type
Description The Type statement creates a structure definition that can then be used with the Dim statement to
declare variables of that type. The username field specifies the name of the structure that is used later
with the Dim statement.
where variable is the name of a field of the structure, and type is the data type for that variable. Any
fundamental data type or previously declared user-defined data type can be used within the structure
definition (structures within structures are allowed). Only fixed arrays can appear within structure
definitions. The Type statement can only appear outside of subroutine and function declarations.
When declaring strings within fixed-size types, it is useful to declare the strings as fixed-length. Fixed-
length strings are stored within the structure itself rather than in the string space. For example, the
following structure will always require 62 bytes of storage:
Type Person
FirstName As String * 20
LastName As String * 40
Age As Integer
End Type
Note: Fixed-length strings within structures are size-adjusted upward to an even byte boundary. Thus, a
fixed-length string of length 5 will occupy 6 bytes of storage within the structure.
Example This example displays the use of the Type statement to create a structure representing the parts of a
circle and assign values to them.
Type Circ
msg As String
rad As Integer
dia As Integer
are As Double
cir As Double
End Type
Sub Main()
Dim circle As Circ
circle.rad = 5
circle.dia = circle.rad * 2
circle.are = (circle.rad ^ 2) * Pi
circle.cir = circle.dia * Pi
circle.msg = "The area of this circle is: " & circle.are
MsgBox circle.msg
End Sub
See Also Dim (page 279) (statement); Public (page 446) (statement); Private (page 445) (statement).
TypeOf (function)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 509
Comments This function is used within the If...Then statement to determine if a variable is of a particular type. This
function is particularily useful for determining the type of OLE automation objects.
Example
Sub Main()
Dim a As Object
Set a = CreateObject("Excel.Application")
If TypeOf a Is "Application" Then
MsgBox "We have an Application object."
End If
End Sub
TypeName (function)
"String" A String.
objecttype A data object variable. In this case, objecttype is the name of the specific object type.
"Integer" An integer.
"Long" A long.
"Single" A single.
"Double" A double
class A specific type of OLE automation object. In this case, class is the name of the object as
known to OLE.
If then
Varname
is an
array the returned string can be any of the above strings follows by a empty parenthesis. For
example, "Integer()" would be returned for an array of integers.
expression the expression is evaluated and a String representing the resultant data type is returned.
Example
'The following example defines a subroutine that only accepts
'Integer variables. If not passed an Integer, it will inform
'the user that there was an error, displaying the actual type
'of variable that was passed.
Sub Foo(a As Variant)
If VarType(a) <> ebInteger Then
MsgBox "Foo does not support " & TypeName(a) & " variables"
End If
End Sub
UBound (function)
Unlock (statement)
UBound (function)
Description Returns an Integer containing the upper bound of the specified dimension of the specified array variable.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 511
Comments The dimension parameter is an integer that specifies the desired dimension. If not specified, then the
upper bound of the first dimension is returned. The UBound function can be used to find the upper
bound of a dimension of an array returned by an OLE automation method or property:
UBound(object.property [,dimension])
UBound(object.method [,dimension])
Example This example dimensions two arrays and displays their upper bounds.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
Dim a(5 To 12)
Dim b(2 To 100,9 To 20)
uba = UBound(a)
ubb = UBound(b,2)
MsgBox "The upper bound of a is: " & uba & crlf & " The upper bound of b is: " & ubb
This example uses Lbound and Ubound to dimension a dynamic array to hold a copy of an array
redimmed by the FileList statement.
Dim fl$()
FileList fl$,"*"
count = Ubound(fl$)
If ArrayDims(a) Then
Redim nl$(Lbound(fl$) To Ubound(fl$))
For x = 1 To count
nl$(x) = fl$(x)
Next x
MsgBox "The last element of the new array is: " & nl$(count)
End If
End Sub
See Also LBound (page 387) (function); ArrayDims (page 217) (function); Arrays (page 218) (topic).
Comments UCase$ returns a String , whereas UCase returns a String variant. Null is returned if text
is Null .
Example This example uses the UCase$ function to change a string from lowercase to uppercase.
Sub Main()
a1$ = "this string was lowercase, but was converted."
a2$ = UCase(a1$)
MsgBox a2$
End Sub
Unlock (statement)
Description Unlocks a section of the specified file, allowing other processes access to that section of the file.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 512
Parameter Description
filenumber Integer used by the Basic Control Script to refer to the open file—the number passed to the
Open statement.
For sequential files, the record, start, and end parameters are ignored: the entire file is unlocked. The
section of the file is specified using one of the following:
Syntax Description
record Unlock the specified record number (for Random files) or byte (for Binary files).
to end Unlock from the beginning of the file to the specified record (for Random files) or byte
(for Binary files).
start to end Unlock the specified range of records (for Random files) or bytes (for Binary files).
The unlock range must be the same as that used by the Lock statement.
Example This example creates a file named test.dat and fills it with ten string variable records. These are displayed
in a dialog box. The file is then reopened for read/write, and each record is locked, modified, rewritten,
and unlocked. The new records are then displayed in a dialog box.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
a$ = "This is record number: "
b$ = "0"
rec$ = ""
msg1 = ""
Open "test.dat" For Random Access Write Shared As #1
For x = 1 To 10
rec$ = a$ & x
Lock #1,x
Put #1,,rec$
Unlock #1,x
msg1 = msg1 & rec$ & crlf
Next x
Close
MsgBox "The records are: " & crlf & msg1
msg1 = ""
Open "test.dat" For Random Access Read Write Shared As #1
For x = 1 to 10
rec$ = Mid(rec$,1,23) & (11 - x)
Lock #1,x 'Lock it for our use.
Put #1,x,rec$ 'Nobody's changed it.
UnLock #1,x
msg1 = msg1 & rec$ & crlf
Next x
MsgBox "The records are: " & crlf & msg1
Close
Kill "test.dat"
End Sub
See Also Lock (page 396) (statement); Open (page 428) (statement).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 513
User-defined types (UDTs) are structure definitions created using the Type statement. UDTs are equivalent to C
language structures.
Declaring Structures The Type statement is used to create a structure definition. Type declarations must appear
outside the body of all subroutines and functions within a script and are therefore global to an entire script. Once
defined, a UDT can be used to declare variables of that type using the Dim, Public, or Private statement. The following
example defines a rectangle structure:
Type Rect
left As Integer
top As Integer
right As Integer
bottom As Integer
End Type
:
Sub Main()
Dim r As Rect
:
r.left = 10
End Sub
Any fundamental data type can be used as a structure member, including other user-defined types. Only fixed arrays
can be used within structures.
Copying Structures UDTs of the same type can be assigned to each other, copying the contents. No other standard
operators can be applied to UDTs.
Dim r1 As Rect
Dim r2 As Rect
:
r1 = r2
When copying structures of the same type, all strings in the source UDT are duplicated and references are placed into
the target UDT. The LSet statement can be used to copy a UDT variable of one type to another:
LSet variable1 = variable2
LSet cannot be used with UDTs containing variable-length strings. The smaller of the two structures determines how
many bytes get copied.
Passing Structures UDTs can be passed both to user-defined routines and to external routines, and they can be
assigned. UDTs are always passed by reference. Since structures are always passed by reference, the ByVal keyword
cannot be used when defining structure arguments passed to external routines (using Declare). The ByVal keyword
can only be used with fundamental data types such as Integer and String. Passing structures to external routines
actually passes a far pointer to the data structure.
Size of Structures The Len function can be used to determine the number of bytes occupied by a UDT:
Len(udt_variable_name)
Since strings are stored in the Basic Control Engine's data space, only a reference (currently, 2 bytes) is stored within a
structure. Thus, the Len function may seem to return incorrect information for structures containing strings.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 514
Val (function)
VarType (function)
Viewport.Clear (method)
Viewport.Close (method)
Viewport.Open (method)
VLine (statement)
VPage (statement)
VScroll (statement)
Val (function)
Spaces, tabs, and line feeds are ignored. If number does not contain a number, then 0 is returned.
The Val function continues to read characters from the string up to the first nonnumeric character. The
Val function always returns a double-precision floating-point value. This value is forced to the data type of
the assigned variable.
Example This example inputs a number string from an InputBox and converts it to a number variable.
Sub Main()
a$ = InputBox("Enter anything containing a number","Enter Number")
b# = Val(a$)
MsgBox "The value is: " & b#
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 515
'The following table shows valid strings and their numeric equivalents:
' "1 2 3" 123
' "12.3" 12.3
' "&HFFFF" -1
' "&O77" 63
' "12.345E-02" .12345
See Also CDbl (page 237) (function); Str, Str$ (page 495) (functions).
Assigning to VariantsBefore a Variant has been assigned a value, it is considered empty. Thus,
immediately after declaration, the VarType function will return ebEmpty. An uninitialized
variant is 0 when used in numeric expressions and is a zero-length string when used within string
expressions.A Variant is Empty only after declaration and before assigning it a value. The
only way for a Variant to become Empty after having received a value is for that variant to be
assigned to another Variant containing Empty , for it to be assigned explicitly to the constant
Empty , or for it to be erased using the Erase statement.When a variant is assigned a value, it is
also assigned that value's type. Thus, in all subsequent operations involving that variant, the variant
will behave like the type of data it contains.Operations on VariantsNormally, a Variant behaves
just like the data it contains. One exception to this rule is that, in arithmetic operations, variants are
automatically promoted when an overflow occurs. Consider the following statements:
Dim a As Integer,b As Integer,c As Integer
Dim x As Variant,y As Variant,z As Variant
a% = 32767
b% = 1
c% = a% + b% 'This will overflow.
x = 32767
y = 1
z = x + y 'z becomes a Long because of Integer overflow.
In the above example, the addition involving Integer variables overflows because the result
(32768) overflows the legal range for integers. With Variant variables, on the other hand, the
addition operator recognizes the overflow and automatically promotes the result to a Long .Adding
VariantsThe + operator is defined as performing two functions: when passed strings, it concatenates
them; when passed numbers, it adds the numbers.With variants, the rules are complicated because
the types of the variants are not known until execution time. If you use +, you may unintentionally
perform the wrong operation.It is recommended that you use the & operator if you intend to
concatenate two String variants. This guarantees that string concatenation will be performed and
not addition.Variants That Contain No DataA Variant can be set to a special value indicating that
it contains no valid data by assigning the Variant to Null:
Dim a As Variant
a = Null
The only way that a Variant becomes Null is if you assign it as shown above.The Null
value can be useful for catching errors since its value propagates through an expression.Variant
StorageVariants require 16 bytes of storage internally:
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 516
• A 2-byte type
• A 2-byte extended type for data objects
• Bytes of padding for alignment
• An 8-byte value
Unlike other data types, writing variants to Binary or Random files does not write 16
bytes. With variants, a 2-byte type is written, followed by the data (2 bytes for Integer and so
on).Disadvantages of VariantsThe following list describes some disadvantages of variants:
1. Using variants is slower than using the other fundamental data types (that is, Integer, Long,
Single, Double, Date, Object , String, Currency, and Boolean). Each operation involving a
Variant requires examination of the variant's type.
2. Variants require more storage than other data types (16 bytes as opposed to 8 bytes for a
Double, 2 bytes for an Integer, and so on).
3. Unpredictable behavior. You may write code to expect an Integer variant. At runtime, the
variant may be automatically promoted to a Long variant, causing your code to break.
Passing Nonvariant Data to Routines Taking VariantsPassing nonvariant data to a routine
that is declared to receive a variant by reference prevents that variant from changing type within
that routine. For example:
Sub Foo(v As Variant)
v = 50 'OK.
v = "Hello, world." 'Get a type-mismatch error here!
End Sub
Sub Main()
Dim i As Integer
Foo i 'Pass an integer by reference.
End Sub
In the above example, since an Integer is passed by reference (meaning that the caller can
change the original value of the Integer ), the caller must ensure that no attempt is made to
change the variant's type.Passing Variants to Routines Taking NonvariantsVariant variables
cannot be passed to routines that accept nonvariant data by reference, as demonstrated in the
following example:
Sub Foo(i As Integer)
End Sub
Sub Main()
Dim a As Variant
Foo a 'Compiler gives type-mismatch error here.
End Sub
VarType (function)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 517
Comments The variable parameter is the name of any Variant . The following table shows the different values that
can be returned by VarType :
0 ebEmpty Uninitialized
2 ebInteger Integer
3 ebLong Long
4 ebSingle Single
5 ebDouble Double
6 ebCurrency Currency
7 ebDate Date
8 ebString String
11 ebBoolean Boolean
Comments When passed an object, the VarType function returns the type of the default property of that object. If
the object has no default property, then either ebObject or ebDataObject is returned, depending on
the type of variable.
Example
Sub Main()
Dim v As Variant
v = 5& 'Set v to a Long.
If VarType(v) = ebInteger Then
Msgbox "v is an Integer."
ElseIf VarType(v) = ebLong Then
Msgbox "v is a Long."
End If
End Sub
See Also Empty (page 321) (constant); Null (page 421) (constant); Variant (page 515) (data type).
Viewport.Clear (method)
Syntax Viewport.Clear
Example
Sub Main()
Viewport.Open
Print "This will be
displayed in the viewport window."
Sleep 2000
Viewport.Clear
Print "This will replace
the previous text."
Sleep 2000
Viewport.Close
End Sub
Viewport.Close (method)
Syntax Viewport.Close
Example
Sub Main()
Viewport.Open
Print "This will be
displayed in the viewport window."
Sleep 2000
Viewport.Close
End Sub
Viewport.Open (method)
Description Opens a new viewport window or switches the focus to the existing viewport window.
Parameter Description
title Specifies a String containing the text to appear in the viewport's caption.
XPos, YPos Specifies Integer coordinates given in twips indicating the initial position of the upper left
corner of the viewport.
width,height Specifies Integer values indicating the initial width and height of the viewport.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 519
If a viewport window is already open, then it is given the focus. Otherwise, a new viewport window
is created. Combined with the Print statement, a viewport window is a convenient place to output
debugging information. The viewport window is closed when the BasicScript host application is
terminated. The following keys work within a viewport window:
Key Scrolls
Up Up by one line.
Only one viewport window can be open at any given time. Any scripts with Print statements will output
information into the same viewport window. When printing to viewports, the end-of-line character can
be any of the following: a carriage return, a line feed, or a carriage-return/line-feed pair. Embedded null
characters are printed as spaces.
Example
Sub Main()
Viewport.Open "BasicScript Viewport",100,100,500,500
Print "This will be displayed in the viewport window."
Sleep 2000
Viewport.Close
End Sub
VLine (statement)
Description Scrolls the window with the focus up or down by the specified number of lines.
Comments The lines parameter is an Integer specifying the number of lines to scroll. If this parameter is omitted,
then the window is scrolled down by one line.
Example This example prints a series of lines to the viewport, then scrolls back up the lines to the top using VLine.
Sub Main()
"BasicScript Viewport",100,100,500,200
For i = 1 to 50
Print "This will be displayed on line#: " & i
Next i
MsgBox "We will now go back 40 lines..."
VLine -40
MsgBox "...and here we are!"
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 520
See Also VPage (page 520) (statement); VScroll (page 520) (statement).
VPage (statement)
Description Scrolls the window with the focus up or down by the specified number of pages.
Comments The pages parameter is an Integer specifying the number of lines to scroll. If this parameter is omitted,
then the window is scrolled down by one page.
See Also VLine (page 519) (statement); VScroll (page 520) (statement).
VScroll (statement)
Description Sets the thumb mark on the vertical scroll bar attached to the current window.
Comments The position is given as a percentage of the total range associated with that scroll bar. For example, if the
percentage parameter is 50, then the thumb mark is positioned in the middle of the scroll bar.
Example This example prints a bunch of lines to the viewport, then scrolls back to the top using VScroll .
Sub Main()
"BasicScript Viewport",100,100,500,200
For i = 1 to 50
Print "This will be displayed on line#: " & i
Next i
Message$="We will now go to the the top "
MsgBox Message$
VScroll 0
VScroll 0
MsgBox " and here we are!"
End Sub
See Also VLine (page 519) (statement); VPage (page 520) (statement).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 521
Weekday (function)
While...Wend (statement)
Width# (statement)
WinActivate (statement)
WinClose (statement)
WinFind (function)
WinList (statement)
WinMaximize (statement)
WinMinimize (statement)
WinMove (statement)
WinRestore (statement)
WinSize (statement)
Word$ (function)
WordCount (function)
Write# (statement)
WriteIni (statement)
Weekday (function)
Description Returns an Integer value representing the day of the week given by date. Sunday is 1, Monday is 2, and
so on. The date parameter is any expression representing a valid date.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 522
Example This example gets a date in an input box and displays the day of the week and its name for the date
entered.
Sub Main()
Dim a$(7)
a$(1) = "Sunday"
a$(2) = "Monday"
a$(3) = "Tuesday"
a$(4) = "Wednesday"
a$(5) = "Thursday"
a$(6) = "Friday"
a$(7) = "Saturday"
Reprompt:
bd = InputBox("Please enter your birthday.","Enter Birthday")
If Not(IsDate(bd)) Then Goto Reprompt
dt = DateValue(bd)
dw = WeekDay(dt)
Msgbox "You were born on day " & dw & ", which was a " & a$(dw)
End Sub
See Also Day (page 269) (function);Minute (page 404) (function); Second (page 471) (function); Month (page
406) (function); Year (page 533) (function); Hour (page 364) (function); DatePart (page 267)
(function).
While...Wend (statement)
Comments The condition is initially and then checked at the top of each iteration through the loop.
Example This example executes a While loop until the random number generator returns a value of 1.
Sub Main()
x% = 0
count% = 0
While x% <> 1 And count% < 500
x% = Rnd(1)
If count% > 1000 Then
Exit Sub
Else
count% = count% + 1
End If
Wend
MsgBox "The loop executed " & count% & " times."
End Sub
See Also Do...Loop (page 298) (statement); For...Next (page 347) (statement).
Note: Due to errors in program logic, you can inadvertently create infinite loops in your code. You can break out
of infinite loops using Ctrl+Break.
Width# (statement)
Description Specifies the line width for sequential files opened in either Output or Append mode.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 523
Parameter Description
filenumber Integer used by the Basic Control Engine to refer to the open file—the number passed to the
Open statement.
newwidth Integer between 0 to 255 inclusive specifying the new width. If newwidth is 0, then no
maximum line length is used.
When a file is initially opened, there is no limit to line length. This command forces all subsequent output
to the specified file to use the specified value as the maximum line length. The Width statement affects
output in the following manner: if the column position is greater than 1 and the length of the text to be
written to the file causes the column position to exceed the current line width, then the data is written on
the next line. The Width statement also affects output of the Print command when used with the Tab
and Spc functions.
Example This statement sets the maximum line width for file number 1 to 80 columns.
Const crlf$ = Chr$(13) + Chr$(10)
Sub Main()
Dim i,msg1,newline$
Open "test.dat" For Output As #1 'Create data file.
For i = 0 To 9
Print #1,Chr(48 + i); 'Print 0-9 to test file all on same line.
Next i
Print #1,crlf 'New line.
Width #1,5 'Change line width to 5.
For i = 0 To 9 'Print 0-9 again. This time, five characters print before line wraps.
Print #1,Chr(48 + i);
Next I
Close #1
msg1 = "The effect of the Width statement is as shown below: " & crlf
Open "test.dat" For Input As #1 'Read new file.
Do While Not Eof(1)
Input #1,newline$
msg1 = msg1 & crlf$ & newline$
Loop
Close #1
msg1 = msg1 & crlf$ & crlf$ & "Choose OK to remove the test file."
MsgBox msg1 'Display effects of Width.
Kill "test.dat"
End Sub
See Also Print (page 442) (statement); Print# (page 443) (statement); Tab (page 501) (function); Spc (page
481) (function)
WinActivate (statement)
Description Activates the window with the given name or object value.
Parameter Description
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 524
window_name String containing the name that appears on the desired application's title bar. Optionally,
$ a partial name can be used, such as "Word" for "Microsoft Word." A hierarchy of
windows can be specified by separating each window name with a vertical bar (|), as in
the following example:
WinActivate "Notepad|Find"
In this example, the top-level windows are searched for a window whose title contains
the word "Notepad ." If found, the windows owned by the top level window are
searched for one whose title contains the string "Find ."
window_object HWND object specifying the exact window to activate. This can be used in place of the
window_name$ parameter to indicate a specific window to activate.
timeout Integer specifying the number of milliseconds for which to attempt activation of the
specified window. If not specified (or 0), then only one attempt will be made to activate
the window. This value is handy when you are not certain that the window you are
attempting to activate has been created.
Example This example runs the clock.exe program by activating the Run File dialog box from within Program
Manager.
Sub Main()
WinActivate "Program Manager"
Menu "File.Run"
WinActivate "Program Manager|Run"
SendKeys "clock.exe{ENTER}"
End Sub
WinClose (statement)
Parameter Description
window_name String containing the name that appears on the desired application's title bar. Optionally,
$ a partial name can be used, such as "Word" for "Microsoft Word." A hierarchy of
windows can be specified by separating each window name with a vertical bar (|), as in
the following example:
WinActivate "Notepad|Find"
In this example, the top-level windows are searched for a window whose title contains
the word "Notepad" . If found, the windows owned by the top level window are
searched for one whose title contains the string "Find" .
window_object HWND object specifying the exact window to activate. This can be used in place of the
window_name$ parameter to indicate a specific window to activate.
If window_name$ and window_object are omitted, then the window with the focus is closed. This
command differs from the AppClose command in that this command operates on the current window
rather than the current top-level window (or application).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 525
Example This example closes Microsoft Word if its object reference is found.
Sub Main()
Dim WordHandle As HWND
Set WordHandle = WinFind("Word")
If (WordHandle Is Not Nothing) Then WinClose WordHandle
End Sub
Note Under Windows, the current window can be an MDI child window, a pop-up window, or a top-level
window.
WinFind (function)
Description Returns an object variable referencing the window having the given name.
Comments The name$ parameter is specified using the same format as that used by the WinActivate statement.
Example This example closes Microsoft Word if its object reference is found.
Sub Main()
Dim WordHandle As HWND
Set WordHandle = WinFind("Word")
If (WordHandle Is Not Nothing) Then WinClose WordHandle
End Sub
WinList (statement)
Description Fills the passed array with references to all the top-level windows.
Comments The passed array must be declared as an array of HWND objects. The ArrayOfWindows parameter must
specify either a zero- or one-dimensioned dynamic array or a single-dimensioned fixed array. If the array
is dynamic, then it will be redimensioned to exactly hold the new number of elements. For fixed arrays,
each array element is first erased, then the new elements are placed into the array. If there are fewer
elements than will fit in the array, then the remaining elements are unused. A runtime error results if the
array is too small to hold the new elements. After calling this function, use the LBound and UBound
functions to determine the new size of the array.
WinMaximize (statement)
Parameter Description
window_name String containing the name that appears on the desired application's title bar. Optionally,
$ a partial name can be used, such as "Word" for "Microsoft Word." A hierarchy of
windows can be specified by separating each window name with a vertical bar (|), as in
the following example:
WinActivate "Notepad|Find"
In this example, the top-level windows are searched for a window whose title contains
the word "Notepad" . If found, the windows owned by the top level window are
searched for one whose title contains the string "Find" .
window_object HWND object specifying the exact window to activate. This can be used in place of the
window_name$ parameter to indicate a specific window to activate.
If window_name$ and window_object are omitted, then the window with the focus is maximized. This
command differs from the AppMaximize command in that this command operates on the current
window rather than the current top-level window.
See Also WinMinimize (page 526) (statement); WinRestore (page 528) (statement).
Note Under Windows, the current window can be an MDI child window, a pop-up window, or a top-level
window.
WinMinimize (statement)
Parameter Description
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 527
window_name String containing the name that appears on the desired application's title bar. Optionally,
$ a partial name can be used, such as "Word" for "Microsoft Word." A hierarchy of
windows can be specified by separating each window name with a vertical bar (|), as in
the following example:
WinActivate "Notepad|Find"
In this example, the top-level windows are searched for a window whose title contains
the word "Notepad" . If found, the windows owned by the top level window are
searched for one whose title contains the string "Find" .
window_object HWND object specifying the exact window to activate. This can be used in place of the
window_name$ parameter to indicate a specific window to activate.
If window_name$ and window_object are omitted, then the window with the focus is minimized. This
command differs from the AppMinimize command in that this command operates on the current window
rather than the current top-level window.
See Also WinMaximize (page 526) (statement); WinRestore (page 528) (statement).
Note Under Windows, the current window can be an MDI child window, a pop-up window, or a top-level
window.
WinMove (statement)
Parameter Description
x,y Integer coordinates given in twips that specify the new location for the window.
window_name String containing the name that appears on the desired application's title bar. Optionally,
$ a partial name can be used, such as "Word" for "Microsoft Word." A hierarchy of
windows can be specified by separating each window name with a vertical bar (|), as in
the following example:
WinActivate "Notepad|Find"
In this example, the top-level windows are searched for a window whose title contains
the word "Notepad". If found, the windows owned by the top level window are searched
for one whose title contains the string "Find".
window_object HWND object specifying the exact window to activate. This can be used in place of the
window_name$ parameter to indicate a specific window to activate.
If window_name$ and window_object are omitted, then the window with the focus is moved. This
command differs from the AppMove command in that this command operates on the current window rather
than the current top-level window. When moving child windows, remember that the x and y coordinates
are static to the client area of the parent window.
Example This example moves Program Manager to upper left corner of the screen.
WinMove 0,0,"Program Manager"
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 528
Note Under Windows, the current window can be an MDI child window, a pop-up window, or a top-level
window.
WinRestore (statement)
Comments Restoring a minimized window restores that window to its screen position before it was minimized.
Restoring a maximized window resizes the window to its size previous to maximizing. The WinRestore
statement requires the following parameters:
Parameter Description
window_name String containing the name that appears on the desired application's title bar. Optionally,
$ a partial name can be used, such as "Word" for "Microsoft Word." A hierarchy of
windows can be specified by separating each window name with a vertical bar (|), as in
the following example:
WinActivate "Notepad|Find"
In this example, the top-level windows are searched for a window whose title contains
the word "Notepad" . If found, the windows owned by the top level window are
searched for one whose title contains the string "Find" .
window_object HWND object specifying the exact window to activate. This can be used in place of the
window_name$ parameter to indicate a specific window to activate.
If window_name$ and window_object are omitted, then the window with the focus is restored. This
command differs from the AppRestore command in that this command operates on the current window
rather than the current top-level window.
Example This example minimizes all top-level windows except for Program Manager.
Sub Main()
Dim a() As HWND
WinList a
For i = 0 To UBound(a)
WinMinimize a(i)
Next I
WinRestore "Program Manager"
End Sub
See Also WinMaximize (page 526) (statement); WinMinimize (page 526) (statement)
Note Under Windows, the current window can be an MDI child window, a pop-up window, or a top-level
window.
WinSize (statement)
Description Resizes the given window to the specified width and height.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 529
Parameter Description
width,height Integer coordinates given in twips that specify the new size of the window.
window_name String containing the name that appears on the desired application's title bar. Optionally,
$ a partial name can be used, such as "Word" for "Microsoft Word." A hierarchy of
windows can be specified by separating each window name with a vertical bar (|), as in
the following example:
WinActivate "Notepad|Find"
In this example, the top-level windows are searched for a window whose title contains
the word "Notepad" . If found, the windows owned by the top level window are
searched for one whose title contains the string "Find" .
window_object HWND object specifying the exact window to activate. This can be used in place of the
window_name$ parameter to indicate a specific window to activate.
If window_name$ and window_object are omitted, then the window with the focus is resized. This
command differs from the AppSize command in that this command operates on the current window
rather than the current top-level window.
Note Under Windows, the current window can be an MDI child window, a pop-up window, or a top-level
window.
Word$ (function)
Description Returns a String containing a single word or sequence of words between first and last.
Parameter Description
first Integer specifying the index of the first word in the sequence to return. If last is not specified,
then only that word is returned.
last Integer specifying the index of the last word in the sequence to return. If last is specified,
then all words between first and last will be returned, including all spaces, tabs, and end-of-
lines that occur between those words.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 530
Words are separated by any non-alphanumeric characters such as spaces, tabs, end-of-lines, and
punctuation. If first is greater than the number of words in text$, then a zero-length string is returned.
If last is greater than the number of words in text$, then all words from first to the end of the text are
returned.
Example This example finds the name "Stuart" in a string and then extracts two words from the string.
Sub Main()
s$ = "My last name is Williams; Stuart is my surname."
c$ = Word$(s$,5,6)
MsgBox "The extracted name is: " & c$
End Sub
See Also Item$ (page 383) (function); ItemCount (page 384) (function); Line$ (page 392) (function);
LineCount (page 393) (function); WordCount (page 530) (function).
WordCount (function)
Description Returns an Integer representing the number of words in the specified text.
See Also Item$ (page 383) (function); ItemCount (page 384) (function); Line$ (page 392) (function);
LineCount (page 393) (function); Word$ (page 529) (function).
Write# (statement)
Comments The file referenced by filenumber must be opened in either Output or Append mode. The filenumber
parameter is an Integer used by the Basic Control Engine to refer to the open file—the number passed to
the Open statement. The following table summarizes how variables of different types are written:
Any numeric Written as text. There is no leading space, and the period is always used as the decimal
type separator.
User-defined Written as #ERROR ErrorNumber # , where ErrorNumber is the value of the user-defined
errors error. The word ERROR is not translated.
The Write statement outputs variables separated with commas. After writing each expression in the list,
Write outputs an end-of-line. The Write statement can only be used with files opened in Output or
Append mode.
Example This example opens a file for sequential write, then writes ten records into the file with the values 10...50.
Then the file is closed and reopened for read, and the records are read with the Input statement. The
results are displayed in a dialog box.
Sub Main()
Open "test.dat" For Output Access Write As #1
For x = 1 To 10
r% = x * 10
Write #1,x,r%
Next x
Close
msg1 = ""
Open "test.dat" For Input Access Read As #1
For x = 1 To 10
Input #1,a%,b%
msg1 = msg1 & "Record " & a% & ": " & b% & Basic.Eoln$
Next x
MsgBox msg1
Close
End Sub
See Also Open (page 428) (statement); Put (page 448) (statement); Print# (page 443) (statement).
WriteIni (statement)
Parameter Description
section$ String specifying the section that contains the desired variables, such as "windows." Section
names are specified without the enclosing brackets.
ItemName String specifying which item from within the given section you want to change. If ItemName$
$ is a zero-length string (""), then the entire section specified by section$ is deleted.
value$ String specifying the new value for the given item. If value$ is a zero-length string (""), then
the item specified by ItemName$ is deleted from the ini file.
Example This example sets the txt extension to be associated with Notepad.
Sub Main()
WriteIni "Extensions","txt","c:\windows\notepad.exe ^.txt","win.ini"
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 532
See Also ReadIni$ (page 458) (function); ReadIniSection (page 458) (statement)
Note If filename$ is not specified, the win.ini file is used. If the filename$ parameter does not include a path,
then this statement looks for ini files in the Windows directory.
X or (operator)
Comments If both expressions are either Boolean, Boolean variants, or NULL variants, then a logical exclusion is
performed as follows:
If the first expression is and the second expression is then the result is
If either expression is Null , then Null is returned. Binary Exclusion If the two expressions are Integer,
then a binary exclusion is performed, returning an Integer result. All other numeric types (including Empty
variants) are converted to Long, and a binary exclusion is then performed, returning a Long result. Binary
exclusion forms a new value based on a bit-by-bit comparison of the binary representations of the two
expressions according to the following table:
1 Xor 1 = 0 Example
0 Xor 1 = 1 5 01101001
1 Xor 0 = 1 6 10101010
Example This example builds a logic table for the XOR function and displays it.
Const crlf = Chr$(13) + Chr$(10)
Sub Main()
msg1 = "Logic table for Xor:" & crlf & crlf
For x = -1 To 0
For y = -1 To 0
z = x Xor y
msg1 = msg1 & CBool(x) & " Xor "
msg1 = msg1 & CBool(y) & " = "
msg1 = msg1 & CBool(z) & crlf
Next y
Next x
MsgBox msg1
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 533
See Also Operator Precedence (page 431) (topic); Or (page 435) (operator); Eqv (page 323) (operator); Imp
(page 371) (operator); And (page 204) (operator).
Year (function)
Description Returns the year of the date encoded in the specified date parameter. The value returned is between 100
and 9999 inclusive. The date parameter is any expression representing a valid date.
See Also Day (page 269) (function) Minute (page 404) (function); Second (page 471) (function); Month (page
406) (function); Hour (page 364) (function); Weekday (page 521) (function); DatePart (page 267)
(function).
CimEmAlarmEvent... (page
535)
CimEmEvent... (page
535)
CimEmPointEvent... (page
535)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 534
CimGetEMEvent... (page
536)
CimLogin/CimLogout...
(page 536)
CimProjectData... (page
536)
CimRemoveUnusedPoints...
(page 536)
IsTerminalServices... (page
537)
64-bit
Acquire...
Alarm...
Change...
CimChange...
CimEMAlarmEvent...
CimEMEvent...
CimEMPointEvent...
CimGetEMEvent...
CimIsMaster...
CimLogin/CimLogout...
CimProjectData...
CimRemoveUnusedPoints
Do...
Get...
IsTerminalServices
LogStatus
Point...
PointGet...
PointSet...
String...
Trace...
Acquire (function)
Description Acquire a Critical Section with a timeout. If the section is not acquired within the specified timeout, a value
of False is returned.
Critical Sections are used in multithreaded application to control reentrancy, protect access global data
structures, and provide synchronization. Only one thread of an application can be within a critical section
at a time. Since the Basic Control Engine is a multithreaded application, you may need to use critical
sections to prevent race type conditions.
Acquire and Release only work with the same process. In other words, two standalone executables
cannot protect against each other using this mechanism.
In the Basic Control Engine, when an event occurs, the script is started in parallel with any other currently
executing scripts. If two scripts compete for the same resource in your factory (e.g. controlling a pump)
you may need to use critical sections to control access.
Unlike a C application, access to public and private variables is controlled automatically by BASIC. That
is, if two threads are trying to set and get the value of a variable access to the variable is synchronous.
In other words, the thread, which is reading the value, won't get a value, which is half-written by the
other thread. However, if you are accessing more than one element of a global data structure and expect
another thread to be accessing the data, then you must protect the access with a critical section.
The Basic Control Engine automatically releases any critical sections held by the script when it
terminates. While the script is running, you can use the Acquire and Release commands to control when
a critical section is released. You must make a call to Release for each call you make to Acquire for a
critical section.
Comments
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 540
Parameter Description
Example Prevent reentry into the routine if the script is already in progress. If the script can't acquire the region
immediately, it will exit.
Sub Main()
if Acquire("DATETIME",0) = FALSE then
Exit Sub
end if
if Date$ <> LastDate then
LastDate = Date$
PointSet "DATE",LastDate
end if
PointSet "TIME",Time$
Release "DATETIME"
End Sub
Note: In the Basic Control Engine, when an event occurs, the script is started in parallel. If another
event triggers the same script before the script ends, two scripts will be running in parallel. The
Acquire and Release routines can be used to modify this behavior. Two options are available.
1. Serialize the processing. In this case, the second instance of the script waits until the first is
complete and then begins execution. This is accomplished by placing an acquire statement at the
start of the script.
2. Skip processing. In this case, the second instance of the script exits without performing any
processing. The example in Acquire (FUNCTION) illustrated this.
AlarmGenerate (statement)
Parameter Description
Alarm
Message Important: The following use of AlarmGenerate requires extra configuration for projects created before
Length CIMPLICITY version 6.1.
An alarm is triggered from a BCE script using AlarmGenerate. The alarm is a $CIMBASIC type. The alarm
message contains 80 characters. Example:
Sub Main()
AlarmGenerate "TEST_AMV","TEST_AMV_ALARM_SCRIPT","$SYSTEM","123456789012345678
90123456789012345678901234567890123456789012345678901234567890"
End Sub
Problem
If BASIC generates an alarm that is greater than 72 characters to a project that does not have the
following solution: The project will log an error indicating there were too many fields. The alarm will be
displayed with 72 characters.
Solution
Allow 80 characters in a BASIC alarm message. Idtpop the alarm_field record. Edit the alarm_field.idt file.
Change the field_len to 80 in the $CIMBASIC record. For projects created in CIMPLICITY version 6.1 and
later 80 characters are supported automatically.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 542
Example
Sub Main()
' Generate a single alarm with no reference Id.
AlarmGenerate "BCEDEMO","MY_ALARM_1","$SYSTEM",_
"Electrical Bus 1 Failure"
' Generate three of the same alarm for different resources.
AlarmGenerate "BCEDEMO","MY_ALARM_2","RESOURCE_1",_
"Multiple Instance for each resource"
AlarmGenerate "BCEDEMO","MY_ALARM_2","RESOURCE_2",_
"Multiple Instance for each resource"
AlarmGenerate "BCEDEMO","MY_ALARM_2","RESOURCE_3",_
"Multiple Instance for each resource"
' Generate three of the same alarm for the same resource
' but use a different reference id.
AlarmGenerate "BCEDEMO","MY_ALARM_3","RESOURCE_1",_
"Multiple Instances for RefId","","1"
AlarmGenerate "BCEDEMO","MY_ALARM_3","RESOURCE_1",_
"Multiple Instances for RefId","","2"
AlarmGenerate "BCEDEMO","MY_ALARM_3","RESOURCE_1",_
"Multiple Instances for RefId","","3"
End Sub
Notes The Alarm ID must have an Alarm Type of $CIMBASIC otherwise the alarm message may not be
displayed correctly.
A unique alarm in CIMPLICITY is defined by the Alarm ID, Resource ID and Reference ID combination.
Each unique alarm can be displayed as a distinct entry in the Alarm Viewer. Non-unique alarms are
stacked, so that the user only sees the most recent occurrence. In general, the Resource ID is used to
control the routing of alarms to users. The Reference ID is used by an application to distinguish between
different instances of the same alarm.
AlarmGenerateEx (statement)
Syntax AlarmGenerateEx Project$ , AlarmId$ , ResourceId$ , Message$, DateTime, IsUTC [ , UserId$ [ , RefId$ [
, Master]]]
Parameter Description
Project$ String. The project to generate the alarm on. An empty string ""
indicates the current project
AlarmId$ String. The ID of a non-point or point Alarm that is listed in the right-
pane of the Workbench>Alarms section.
Note:
ResourceId$ String. The Resource ID to generate the alarm against. Used to control
routing of the alarm.
Message$ (page 544) String. The generated alarm message to display. Note: This string
is substituted into the first variable field (page 544) of the alarm's
configured message.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 543
Note: If you do not use UTC time, you will be responsible for
making sure your system’s Time Zone settings, including DST, are
properly set.
CimBasic
'This example displays the syntax.
Example Sub Main()
1 theDate = Now()
AlarmGenerateEx "PROJECT01","ALARM501","$SYSTEM","Device 501 needs attention.", theDate,
FALSE
End Sub
.NET C#
//This example displays the syntax.
Example public void Main()
1 { DateTime dt = new DateTime(2012, 06, 18, 2, 5, 5);
Cimplicity.AlarmGenerateEx("TESTER","TESTALARMGEN","$SYSTEM","csAG Test",dt, true)}
Example
//This example displays time in microseconds.
2 public void Main()
{
DateTime dt = new DateTime(2012, 7, 1, 0,0,0,123);
// Add One extra millisecond + a few Nano100seconds (10000 milliseconds in a Nano100Seconds)
dt = dt.AddTicks(10100);
Cimplicity.AlarmGenerateEx("FORSHOW","MYALARM","$MAC_FR",".net", dt, false);
}
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 544
VB .NET
'This example displays the syntax.
Example Public Sub Main()
Dim DT1 As DateTime
DT1 = New DateTime(2012,7,1,15,30,22,123)
Cimplicity.AlarmGenerateEx("ALARMGENERATEUPDATE","CB1","$SYSTEM","Test VB alarm",
DT1, False)
End Sub
Note: Guidelines also apply to AlarmGenerate (page 540) and AlarmUpdate (page 545)
.
The message, which is a string, is substituted into the first variable field of the alarm's configured
message.
Message: User-defined alarm The substituted string will be the first %s in the Alarm Definition dialog box>Alarm
Message field.
Message : Point alarm ID The substituted string will be the first variable field (%VAL, %ID) in an Alarm Definition dialog
box (or Point Properties dialog box)>Alarm Message field. However, if a point alarm ID is used in an AlarmGenerateEx
or AlarmUpdateEx (page 547) script, because the alarm is not a $CIMBASIC alarm, the message will most likely not
display as you would expect. Examples The entry in the Alarm Message field includes text and more than one variable
POINT01 is %VAL : %STATE If the code:
Alarm message %s
However, like its point alarm counterpart, it also is not a $CIMBASIC alarm.
Each unique alarm can be displayed as a distinct entry in the Alarm Viewer.
If the actual point alarm is in alarm state and displays in the Alarm Viewer, using the same alarm ID
in:
Note: If only the generated alarm is listed AlarmUpdateEx (page 547) will acknowledge
and/or reset that alarm. Non-unique alarms are stacked, so that the user only sees the most recent
occurrence. In general, the Resource ID is used to control the routing of alarms to users. The
Reference ID is used by an application to distinguish between different instances of the same alarm.
AlarmUpdate (statement)
Description To update a currently generated alarm. The alarm being updated may be of any alarm type. However, if
the AlarmMessage$ is specified, it must be an alarm with an alarm type of $CIMBASIC.
Project$ String. The project to generate the alarm on, an empty string "" indicates the current
project
ResourceId$ String. The Resource ID to generate the alarm against. Used to control routing of the
alarm.
Action% Integer. Indicates whether to acknowledge or reset the alarm. Use the manifest
constants AM_ACKNOWLEDGED and AM_RESET to perform an acknowledgment and a reset.
By default, on a computer with Server Redundancy, alarm updates from the standby
computer's Event Manager are ignored. To acknowledge or reset an alarm on the
active computer from the standby computer, use AM_ACKNOWLEDGED_M or
AM_RESET_M to override the default behavior.
AlarmMessage String. (optional). The update alarm message to display. Note: This string is substituted
$ into the first variable field of the Alarm's message. For a user-defined alarm message,
this will be the first %s field in the message. For a point alarm message, it will be
the first variable field (%VAL, %ID, etc.) in the alarm message. For this reason, it is not
recommended that you use the AlarmMessage$ field when updating point alarms.
RefId$ String. A Reference ID used to distinguish between identical alarms. The Reference ID
needs to match the Reference ID of the generated alarm. If the alarm was generated
without a Reference ID, then this field can be omitted from the call.
Example
Sub Main()
a$ = time$
AlarmUpdate "BCEDEMO","MY_ALARM_1","$SYSTEM",x,_
"Electrical Bus 1 " & a$
AlarmUpdate "BCEDEMO","MY_ALARM_2","RESOURCE_1",x,_
"Multiple Instance for each resource " & a$
AlarmUpdate "BCEDEMO","MY_ALARM_2","RESOURCE_2",x,_
"Multiple Instance for each resource " & a$
AlarmUpdate "BCEDEMO","MY_ALARM_2","RESOURCE_3",x,_
"Multiple Instance for each resource " & a$
AlarmUpdate "BCEDEMO","MY_ALARM_3","RESOURCE_1",x,_
"Multiple Instances for RefIf " & a$,"","1"
AlarmUpdate "BCEDEMO","MY_ALARM_3","RESOURCE_1",x,_
"Multiple Instances for RefIf " & a$,"","2"
AlarmUpdate "BCEDEMO","MY_ALARM_3","RESOURCE_1",x,_
"Multiple Instances for RefIf " & a$,"","3"
End Sub
Note When updating an alarm, the AlarmId$, ResourceId$ and RefId$ must match exactly to the alarm to be
updated; if they do not match, the alarm will not be updated. When updating a point alarm, the RefId$ is
always the Point ID (which is also the Alarm ID).
AlarmUpdateCA (statement)
Syntax AlarmUpdate Project$, AlarmId$, ResourceId$, Action% ,caObj [, AlarmMessage$ [, UserId$ [,RefId
$]]]
Description To update a currently generated Change approval alarm. The alarm being updated may be of any alarm
type. However, if the AlarmMessage$ is specified, it must be an alarm with an alarm type of $CIMBASIC.
Project$ String. The project to generate the alarm on, an empty string "" indicates the current
project
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 547
ResourceId$ String. The Resource ID to generate the alarm against. Used to control routing of the
alarm.
Action% Integer. Indicates whether to acknowledge or reset the alarm. Use the manifest
constants AM_ACKNOWLEDGED and AM_RESET to perform an acknowledgment and a reset.
By default, on a computer with Server Redundancy, alarm updates from the standby
computer's Event Manager are ignored. To acknowledge or reset an alarm on the active
computer from the standby computer, use AM_ACKNOWLEDGED_M or AM_RESET_M to override
the default behavior.
AlarmMessage String. (optional). The update alarm message to display. Note: This string is substituted
$ into the first variable field of the Alarm's message. For a user-defined alarm message,
this will be the first %s field in the message. For a point alarm message, it will be
the first variable field (%VAL, %ID, etc.) in the alarm message. For this reason, it is not
recommended that you use the AlarmMessage$ field when updating point alarms.
RefId$ String. A Reference ID used to distinguish between identical alarms. The Reference ID
needs to match the Reference ID of the generated alarm. If the alarm was generated
without a Reference ID, then this field can be omitted from the call.
Example
Sub Main()
Dim obj As New CimAlmChangeApprovalData
obj.PerformerUserid = "OPERATOR"
obj.PerformerPassword = ""
obj.PerformerComment= "bool=1 from BCE"
obj.VerifierUserid = "MANAGER"
obj.VerifierPassword = ""
obj.VerifierComment= "bool=1 from BCE"
AlarmUpdateCA"ESIGDEMO","CA_TESTPOINT","$MAC_FR",AM_ACKNOWLEDGED,CAobj,
"CA_TESTPOINT","CA_TESTPOINT","CA_TESTPOINT"
End Sub
Note When updating an alarm, the AlarmId$, ResourceId$ and RefId$ must match exactly to the alarm to be
updated; if they do not match the alarm will not be updated. When updating a point alarm, the RefId$ is
always the Point ID (which is also the Alarm ID).
AlarmUpdateEx (statement)
Parameter Description
Project$ String. The project to update the alarm on. An empty string ""
indicates the current project.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 548
AlarmId$ String. The ID of a non-point or point Alarm that is listed in the right-
pane of the Workbench>Alarms section.
Note:
ResourceId$ String. The Resource ID to update the alarm against. Used to control
routing of the alarm.
Action Integer. Indicates whether to acknowledge or reset the alarm. Use the
following constants to perform an acknowledgment and a reset.
• AM_ACKNOWLEDGED
• AM_RESET
• AM_ACKNOWLEDGED_M
• AM_RESET_M
Note: If you do not use UTC time, you will be responsible for
making sure your system’s Time Zone settings, including DST, are
properly set.
Message$ (page 549) String. The update alarm message to display. Note: This string is
substituted into the first variable field (page 549) of the Alarm's
message.
CimBasic
'This example displays the syntax.
Example Sub Main()
theDate = Now()
AlarmUpdateEx "TESTER","ALARM501","$SYSTEM", AM_ACKNOWLEDGED, theDate, FALSE "Device 501:
Responded."
End Sub
.NET C#
//This example displays the syntax.
Example public void Main()
{ DateTime dt = new DateTime(2012, 06, 18, 2, 5, 5);
Cimplicity.AlarmUpdateEx("TESTER", "TESTALARMGEN", "$SYSTEM", Cimplicity.AM_ACKNOWLEDGED, dt,
true, "csAG Test")}
VB .NET
'This example displays the syntax.
Example Public Sub Main()
Dim DT2 As DateTime
DT2 = New DateTime (2012,7,10,20,20,30,789)
Cimplicity.AlarmUpdateEx("ALARMGENERATEUPDATE", "CB1", "$SYSTEM",
Cimplicity.AM_RESET + Cimplicity.AM_ACKNOWLEDGED, DT2, True, "Updated", "OPERATOR")
End Sub
Note: Guidelines also apply to AlarmGenerate (page 540) and AlarmUpdate (page 545)
.
The message, which is a string, is substituted into the first variable field of the alarm's configured
message.
Message: User-defined alarm The substituted string will be the first %s in the Alarm Definition dialog box>Alarm
Message field.
Message : Point alarm ID The substituted string will be the first variable field (%VAL, %ID) in an Alarm Definition dialog
box (or Point Properties dialog box)>Alarm Message field. However, if a point alarm ID is used in an AlarmGenerateEx
(page 542) or AlarmUpdateEx script, because the alarm is not a $CIMBASIC alarm, the message will most likely not
display as you would expect. Examples The entry in the Alarm Message field includes text and more than one variable
POINT01 is %VAL : %STATE If the code:
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 550
Alarm message %s
However, like its point alarm counterpart, it also is not a $CIMBASIC alarm.
Each unique alarm can be displayed as a distinct entry in the Alarm Viewer.
If the actual point alarm is in alarm state and displays in the Alarm Viewer, using the same alarm ID
in:
• AlarmGenerateEx (page 542) will generate a separate alarm from the point alarm.
• AlarmUpdateEx will acknowledge and/or reset the actual alarm depending on the command(s).
Note: If only the generated alarm is listed AlarmUpdateEx will acknowledge and/or reset that alarm.
• Non-unique alarms are stacked, so that the user only sees the most recent occurrence. In general,
the Resource ID is used to control the routing of alarms to users.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 551
ChangePassword (statement)
Project$ String. The project to change the password on. An empty string indicates the current
default project.
Example
Sub Main()
ChangePassword "CIMPDEMO", "OLDPASS", "NEWPASS"
End Sub
Note The user must be logged into the specified project or the function will fail.
CimChangeApprovalData (Object)
Overview The CimChangeApprovalData object contains information about Change Approval information (e.g.Performer
and Verifier User ID, Password and Comments for Point Operations).
Example
Dim obj As New CimAlmChangeApprovalData
obj.PerformerUserid = "OPERATOR"
obj.PerformerPassword = ""
obj.PerformerComment= "bool=1 from BCE"
obj.VerifierUserid = "MANAGER"
obj.VerifierPassword = ""
obj.VerifierComment= "bool=1 from BCE"
Syntax AlarmEvent.AlarmId
Description String. Returns the Alarm ID of the Alarm that triggered the event.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 552
Example
Sub Main()
Dim AlarmEvent as CimEmAlarmEvent
Set AlarmEvent = CimGetEMEvent().AlarmEvent()
PointSet "LAST_ALARM_ID", AlarmEvent.AlarmID
End if
End Sub
Syntax AlarmEvent.FinalState
Description Integer. Returns the final state of the alarm after the requested action. For example, if the user
acknowledged the alarm and the deletion requirements for the alarm only require acknowledgement then
the final state would be AM_DELETED.
• AM_GENERATED
• AM_ACKNOWLEDGED
• AM_RESET
• AM_DELETED
Example
Sub Main()
Dim AlarmEvent as CimEmAlarmEvent
Set AlarmEvent = CimGetEMEvent().AlarmEvent()
If AlarmEvent.FinalState = AM_ACKNOWLEDGED then
PointSet "ALARM_MESSAGE", "Alarm is Acknowledged"
End if
End Sub
Syntax AlarmEvent.GenTime
Description Date. Returns the day and time the alarm was generated.
Example
Sub Main()
Dim AlarmEvent as CimEmAlarmEvent
Set AlarmEvent = CimGetEMEvent().AlarmEvent()
PointSet "TEXT_ALARM_GEN_TIME", cstr(AlarmEvent.GenTime)
End if
End Sub
Syntax AlarmEvent.Message
Description String. Returns the text of the Alarm Message of the alarm that triggered the event.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 553
Example
Sub Main()
Dim AlarmEvent as CimEmAlarmEvent
Set AlarmEvent = CimGetEMEvent().AlarmEvent()
PointSet "LAST_ALARM_MESSAGE", AlarmEvent.Message
End if
End Sub
CimEMAlarmEvent (object)
Overview The CimEMAlarmEvent object provides information for scripts invoked from an alarm event.
Example
Dim alarmEvent As CimEmAlarmEvent
Set alarmEvent = CimGetEMEvent().AlarmEvent()
PointSet "ALARM_MESSAGE", alarmEvent.Message
Note CimEMAlarmEvent can only be used from the Event Manager. It is not valid in CimView/CimEdit.
Syntax AlarmEvent.PrevState
Description Integer. Returns the previous state of the alarm. Valid States are :
• AM_GENERATED
• AM_ACKNOWLEDGED
• AM_RESET
• AM_DELETED
Example
Sub Main()
Dim AlarmEvent as CimEmAlarmEvent
Set AlarmEvent = CimGetEMEvent().AlarmEvent()
If AlarmEvent.PrevState = AM_ACKNOWLEDGED then
PointSet "ALARM_PREVSTATE", "ACKNOWLEDGED"
End if
End Sub
Syntax AlarmEvent.RefID
Description String. Returns the Reference ID of the alarm that triggered the event.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 554
Example
Sub Main()
Dim AlarmEvent as CimEmAlarmEvent
Set AlarmEvent = CimGetEMEvent().AlarmEvent()
PointSet "LAST_ALARM_REF_ID", AlarmEvent.RefID
End if
End Sub
Syntax AlarmEvent.ReqAction
Description Integer. Returns the action requested on the alarm. For example, if the user had acknowledged the alarm
in the Alarm Viewer the requested action would be AM_ACKNOWLEDGED.
Example
Sub Main()
Dim AlarmEvent as CimEmAlarmEvent
Set AlarmEvent = CimGetEMEvent().AlarmEvent()
If AlarmEvent.ReqAction = AM_ACKNOWLEDGED then
PointSet "ALARM_MESSAGE", "Alarm has been Acknowledged"
End if
End Sub
Syntax AlarmEvent.ResourceID
Description String. Returns the Resource ID of the alarm that triggered the event.
Example
Sub Main()
Dim AlarmEvent as CimEmAlarmEvent
Set AlarmEvent = CimGetEMEvent().AlarmEvent()
PointSet "LAST_ALARM_RESOURCE_ID", AlarmEvent.ResourceID
End if
End Sub
Syntax Event.ActionID
Example
Sub Main()
Dim event as CimEMEvent
Set event = CsimGetEMEvent()
PointSet "LAST_ACTION_ID", event.ActionID
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 555
CimEMEvent.AlarmEvent (function)
Syntax Event.AlarmEvent
Description Returns CimEMAlarmEvent. Returns the Alarm Event object that triggered the action, or empty if action
was not triggered by an alarm.
Example
Sub Main()
Dim event as CimEMEvent
Set event = CimGetEMEvent()
If event.Type = EM_ALARM_GEN then
Dim alarmEvent as CimEMAlarmEvent
Set AlarmEvent = event.AlarmEvent()
' Process the alarm
End If
End Sub
Syntax Event.EventID
Example
Sub Main()
Dim event as CimEMEvent
Set event = CimGetEMEvent()
PointSet "LAST_EVENT_ID", event.EventId
End Sub
CimEMEvent (object)
Overview An object used by the Event Manager to hold information about the event that triggered the action.
Example
Sub Main()
Dim event as CimEMEvent
Set event = CimGetEMEvent()
PointSet "LAST_EVENT_ID", event.EventId
End Sub
Note CimEMEvent can only sbe used from the Event Manager. It is not valid in CimView/CimEdit.
Syntax Event.ObjectID
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 556
Description String. If the script is invoked from an object event, the Object ID invoking the action is returned. If the
script is invoked from a non-object event, an empty string is returned
Example
Sub Main()
Dim event as CimEMEvent
Set event = CimGetEMEvent()
PointSet "LAST_OBJECT_ID", event.ObjectID
End Sub
CimEMEvent.PointEvent
Syntax Event.PointEvent
Description Returns CimEMPointEvent. Returns the Point Event object that triggered the action, or empty if action
was not triggered by point event.
Example
Sub Main()
Dim event as CimEMEvent
Set event = CimGetEMEvent()
Dim pointEvent as CimEMPointEvent
Set pointEvent = event.PointEvent()
End Sub
Syntax Event.TimeStamp
Description Date. Returns the Time Stamp at which the event occurred.
Example
Sub Main()
Dim event as CimEMEvent
Set event = CimGetEMEvent()
PointSet "LAST_EVENT_TIME", cstr(eent.TimeStamp)
End Sub
Syntax Event.Type
Description Integer. Returns the type of event that triggered the action. Valid values are:
Example
Sub Main()
Dim event as CimEMEvent
Set event = CimGetEMEvent()
If event.Type = EM_ALARM_GEN then
Dim alarmEvent as CimEMAlarmEvent
Set AlarmEvent = event.AlarmEvent()
' Process the alarm
End If
End Sub
CimEMPointEvent.Id
Syntax PointEvent.Id
Description String. Returns the Point ID of the point that triggered the event.
Example
Sub Main()
Dim PointEvent as CimEmPointEvent
Set PointEvent = CimGetEMEvent().PointEvent()
' perform processing
' reset the event point to 0
PointSet PointEvent.Id, 0
End Sub
Note CimEMPointEvent can only be used from the Event Manager. It is not valid in CimView/CimEdit
CimEMPointEvent (object)
Overview An Event Manager Object used to contain information about a Point Event
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 558
Example
Sub Main()
Dim PointEvent as CimEmPointEvent
Set PointEvent = CimGetEMEvent().PointEvent()
' perform processing
' reset the event point to 0
PointSet PointEvent.Id, 0
End Sub
Syntax CimEMPointEvent.Quality
Description Long. Returns the 16-bit quality mask for the point that triggered the event.
Example
Sub Main()
Dim p as new CimEMPointEvent
Set p = CimGetEmEvent().PointEvent()
X = p.Quality
End Sub
Syntax CimEMPointEvent.QualityAlarmed
Description Boolean. Returns TRUE if the point that triggered the event is in alarm, FALSE otherwise.
Example
Sub Main()
Dim p as new CimEMPointEvent
Set p = CimGetEmEvent().PointEvent()
if p.QualityAlarmed then
DoSomething
End If
End Sub
Syntax CimEMPointEvent.QualityAlarms_Enabled
Description Boolean. Returns TRUE if alarming for the point that triggered the event is enabled, FALSE otherwise.
Example
Sub Main()
Dim p as new CimEMPointEvent
Set p = CimGetEmEvent().PointEvent()
if p.QualityAlarms_Enabled then
DoSomething
End If
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 559
Syntax CimEMPointEvent.QualityDisable_Write
Description Boolean. Returns TRUE if setpoints have been disabled for the point that triggered the event, FALSE
otherwise.
Example
Sub Main()
Dim p as new CimEMPointEvent
Set p = CimGetEmEvent().PointEvent()
if p.QualityDisable_Write Then
DoSomething
End If
End Sub
Syntax CimEMPointEvent.QualityLast_Upd_Man
Description Boolean. Returns TRUE if the value of the point that triggered the event came from a manual update
rather than a device read.
Example
Sub Main()
Dim p as new CimEMPointEvent
Set p = CimGetEmEvent().PointEvent()
If p.QualityLast_Upd_Man then
DoSomething
End If
End Sub
Syntax CimEMPointEvent.QualityManual_Mode
Description Boolean. Returns TRUE if the point that triggers the event was in Manual Mode, otherwise FALSE.
Example
Sub Main()
Dim p as new CimEMPointEvent
Set p = CimGetEmEvent().PointEvent()
if p.QualityManual_Mode then
ProcessManualMode
End if
End Sub
Syntax CimEMPointEvent.QualityIs_In_Range
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 560
Description Boolean. Returns TRUE if the value of the point that triggered the event is in range, FALSE if the point is
out of range. When a point is out of range its value is unavailable.
Example
Sub Main()
Dim p as new CimEMPointEvent
Set p = CimGetEmEvent().PointEvent()
if p.QualityIs_In_Range = FALSE then
DoSomething
End If
End Sub
Syntax CimEMPointEvent.QualityStale_Data
Description Boolean. Returns TRUE if the value of the point that triggered the event is stale, otherwise FALSE.
Example
Sub Main()
Dim p as new CimEMPointEvent
Set p = CimGetEmEvent().PointEvent()
if p.QualityStale_Data = TRUE
DoSomething
End If
End Sub
Syntax CimEMPointEvent.QualityIs_Available
Description Boolean. Returns TRUE if the value of the point that triggered the event is available, FALSE if the value is
unavailable.
Example
Sub Main()
Dim p as new CimEMPointEvent
Set p = CimGetEmEvent().PointEvent()
if p.QualityIs_Available = FALSE then
DoSomething
End If
End Sub
Syntax PointEvent.State
Description Integer. Returns the state of the point. Can be used to determine if the point is available. See Point.State
for a complete description of states.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 561
Example
Sub Main()
Dim PointEvent as CimEmPointEvent
Set PointEvent = CimGetEMEvent().PointEvent()
If PointEvent.State = CP_UNAVAILABLE THEN
LogStatus CIM_FAILURE,"Main()", _
"Point " & Point.Id & "is unavailable"
end
End if
End Sub
Syntax PointEvent.TimeStamp
Description Date. Returns the date and time of the point change that triggered the event.)
Example
Sub Main()
Dim PointEvent as CimEmPointEvent
Set PointEvent = CimGetEMEvent().PointEvent()
PointSet "LAST_EVENT_TIME", cstr(PointEvent.TimeStamp)
End Sub
Syntax CimEMPointEvent.UserFlags
Description Long. Returns the value of the 16-bit user defined flags for the point that triggered the event.
Example
Sub Main()
Dim p as new CimEMPointEvent
Set p = CimGetEmEvent().PointEvent()
X = p.UserFlags
End Sub
Syntax PointEvent.Value
Description Variant. Returns the value of the point that triggered the event.
Example
Sub Main()
Dim PointEvent as CimEmPointEvent
Set PointEvent = CimGetEMEvent().PointEvent()
PointSet "OUTPUT_POINT", PointEvent.Value + 100
End Sub
CimGetEMEvent (function)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 562
Syntax CimGetEMEvent()
Description Returns a CimEMEvent object. A function to return the event object that causes the action to run. Only
valid from Event Manager.
Example
Sub Main()
Dim event as CimEMEvent
Set event = CimGetEMEvent()
PointSet "LAST_EVENT_TIME", cstr(event.TimeStamp)
End Sub
Note CimGetEMEvent can only be used from the Event Manager. It is not valid in CimView/CimEdit.
CimIsMaster (function)
Syntax CimIsMaster
Description In a computer with Server Redundancy, to determine if the computer is operating in Active or Standby
mode. This function returns TRUE if the computer is currently the active computer. This function returns
FALSE if the computer is currently the standby.
Example
Sub Main()
If CimIsMaster then
MoveCrane
End if
End Sub
CimLogin (statement)
Description Initiates a login for the specified project. Similar in effect to selecting login from the Login Panel. Only
valid when the user is actively using points or viewing alarms from the project, otherwise it has no effect.
Initiating a login will cause the CIMPLICITY login box to be displayed.
Example
Sub Main()
CimLogin "CIMPDEMO"
End Sub
CimLogout (statement)
Description Logs the user out of the specified project. Similar in effect to selecting logout from the Login Panel.
When the user is logged out of the project, all points from the project will be unavailable and no alarm
information will be available. If the user is not logged into the project, the call has no effect.
Example
Sub Main()
CimLogout "CIMPDEMO"
End Sub
Syntax CimProjectData.Attributes
Description String. The list of attributes, separated by commas, of the entity to return for each item matching the
filter criteria. The Attribute IDs are case sensitive and must be entered in the case documented in
CimProjectData.Entity .
CimBasic
Dim d as new CimProjectData
Example d. Attributes = "POINT_ID,RESOURCE_ID,DESCRIPTION"
.Net
CimProjectData cpd = new CimProjectData();
Example cpd.Attributes = "POINT_ID,RESOURCE_ID";
Syntax CimProjectData.Filters
Description String. The filter set to be used to determine which items to return. Each filter contains an Attribute
ID and Value pair. You can use "*" and "?"as wildcard characters. The filters are documented in
CimProjectData.Entity . Filters must be in uppercase even when matching against lowercase data.
Example
Dim d as new CimProjectData
d.Filters = "POINT_ID=P*",DEVICE_ID=TESTP?C"
CimProjectData.GetNext (function)
Description This function returns the specified attributes for the next item that matches the filter criteria. If a record is
found, a value of TRUE is returned, otherwise a value of FALSE is returned. The function takes a variable
number (20 maximum) of string parameters. The values returned into the parameters are defined by the
attributes specified for the object.
: :
Example 1 The following sample script returns all the data items for the PID1 object.
Sub Main()
Dim browse as new CimProjectData
Browse.Project = "MY_PROJ"
Browse.Entity = "OBJECT_INF"
Browse.Attributes = DATA_ITEM"
Browse.Filters = "OBJECT_ID=PID1"
Dim dataItem as String
Top:
If Browse.GetNext(dataItem) = False then end
Msgbox dataitem
Goto top
End Sub
Example 2 The following sample script returns all points for a device:
Sub Main()
Dim browse as new CimProjectData
Browse.Project = "MY_PROJ"
Browse.Entity = "POINT"
Browse.Attributes = "POINT_ID,RESOURCE_ID"
Browse.Filters = "DEVICE_ID=PLC1"
Top:
If Browse.GetNext(p$,r$) = False then end
Msgbox "Point Id " & p$ & " Resource id " & r$
Goto top
End Sub
Syntax CimProjectData.Entity
Description String. The entity to obtain data for. Below is a list of the available entities and their attributes
Entity List
ACTION MEASSYSTEM PORT
GLB_PARMS
ACTION
Contains Action information
Attribute ID Filter Description
ALARM_BLK_GROUP
Contains Alarm Blocking Group Information.
Attribute ID Filter Description
PEER_BLOCK Yes Blocking Mode: If you select Peer Blocking mode, only the first alarm of a set of alarms
with equal priority displays for that group.
ALARM_CLASS
Contains Alarm Class information.
Attribute ID Filter Description
CLASS_ALARM_FG No The foreground color to use for points of this class that are in alarm state.
CLASS_ALARM_BG No The background color to use for points of this class that are in alarm state.
CLASS_NORMAL_FG No The foreground color to use for points of this class that are in normal state.
CLASS_NORMAL_BG No The background color to use for points of this class that are in normal state.
CLASS_ACK_FG No The foreground color to use for points of this class that are in acknowledged
state.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 566
CLASS_ACK_BG No The background color to use for points of this class that are in
acknowledged state.
CLASS_WAVE_FILE No The WAV file to play from the Alarm Sound Manager.
ALARM_DEF
Contains Alarm information.
Attribute ID Filter Description
Sample Script
AMLP
Contains Alarm Printer information.
Attribute ID Filter Description
CLASS
Contains Class information.
Attribute ID Filter Description
CLIENT
Contains Client information.
Attribute ID Filter Description
DEVICE
Contains Device information.
Attribute ID Filter Description
EVENT
Contains Event information.
Attribute ID Filter Description
SERVICE_ID No
EVENT_ACTION
Contains Event-Action information.
Attribute ID Filter Description
EA_SERVICE_ID Yes
GLB_PARMS
Contains Global Parameter information for the project.
Attribute ID Filter Description
MEASUNIT
Contains Measurement Unit information.
Attribute ID Filter Description
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 569
MEASSYSTEM
Contains Measurement System Information
Attribute ID Filter Description
OBJECT
Contains object information.
Attribute ID Filter Description
OBJECT_INF
This is a specialized entity used to extract information from a specified object. The filter for this
entity is OBJECT_ID=MY_OBJECT, where MY_OBJECT is replaced with the object name you
wish to read. Since the function returns specialized attribute information, only one of the attributes
may be used at a time.
This entity may not be used from the Event Manager or without a specified running project.
Attribute ID Filter Description
DATA_ITEM No Returns all data items for the object. Each data item returns by a GetNext call.
ATTRIBUTE, VALUE No Returns the attribute for the object. If VALUE is specified, it must be the second
attribute, and the value of the attribute will be returned
DEFAULT_GRAPHIC No Returns the name of the default graphic for the object's class. Must be specified with
GRAPHICS_FILE Example obj.Attributes= "GRAPHICS_FILE,DEFAULT_GRAPHIC"
POINT
Contains Point information.
Attribute ID Filter Description
DEVICE_ID Yes Device ID for the point, where the point data originates. If the point is a global point, the
device is "$GLOBAL". If the point is an equation point, the device is $DERIVED.
DISPLAY_LIMITS No Low and high display limits of the point separated by a hyphen.
MODIFIED No Data and time in string format that the point was last edited.
POINT_ALSTR
POINT_DISP
Contains Point Display information.
Attribute ID Filter Description
DISPLAY_LIM_LOW No The low limit for the point value display. Values below this limit will display as asterisks
(***).
DISPLAY_LIM_HIGH No The high limit for the point value display. Values above this limit will display as asterisks
(***).
POINT_ENUM
Contains Point Enumeration information.
Attribute ID Filter Description
POINT_ENUM_FLD
Contains Point Enumeration Field information.
Attribute ID Filter Description
SETPOINT_ALLOWED Yes Indicates if the point data field represented by this enumeration field can be set.
POINT_TYPE
Contains Point Type information.
Attribute ID Filter Description
DATA_TYPE No The numeric data type code for the point type.
PORT
Contains Port information.
Attribute ID Filter Description
PROJECTS
Contains information on Remote Projects.
Attribute ID Filter Description
RESOURCE _ID No For an Enterprise Server, the remote project's resource name.
PROTOCOL
Contains Protocol information.
Attribute ID Filter Description
RESOURCE
Contains Resource information.
Attribute ID Filter Description
ALARM_MGR_ID No The Alarm Manager process that receives alarms for this resource.
ROLE
Contains Role information.
Attribute ID Filter Description
SSPC
Contains Statistical Process Control Information.
Attribute ID Filter Description
SYS_PARMS
Contains global parameter information for the system.
Attribute ID Filter Description
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 574
UAFSETS
Valid Attribute Set Identifier
Attribute ID Filter Description
USER
Contains User Information.
Attribute ID Filter Description
USER_FIELDS
Contains Field Information for Point Attribute Sets.
Attribute ID Filter Description
UPD_DEVCOMM No Write to DevComm - Data will be sent to the associated devcom when this attribute is
set.
SAVE_WARMDATA No Preserve value - Indicates that this field should be saved on project shutdown.
CimProjectData (object)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 575
Overview The CimProjectData object provides the ability to search and return specific pieces of a project's
configuration. The underlying APIs used by the CimProjectData object are the same as those used to
browse point configuration on a remote project. In general, this object provides a convenient way to
retrieve a set of attributes based on specified filter criteria. This object provides a read-only capability. To
write configuration, please see the help file for the CIMPLICITY Configuration Object Model.
Example
Sub Main()
(CimBasic) ' This example retrieves all points beginning with A for Device MY_PLC
' in project MY_PROJECT and displays the point id and resource id of
' each matching item.
Dim d as new CimProjectData
d.Project = "MY_PROJECT"
d.Entity = "POINT"
d.Filters = "POINT_ID=A*,DEVICE_ID=MY_PLC"
d.Attributes = "POINT_ID,RESOURCE_ID"
Dim p as string
Dim r as String
top:
if d.GetNext(p,r) = TRUE then
MsgBox "Point Id = " & p & " Resource Id = " & r
goto top
End if
End Sub
Example
using System;
(.NET) using System.Collections.Generic;
using Proficy.CIMPLICITY;
public class CPD
{
public void Main()
{
try
{
CimProjectData cpd = new CimProjectData();
cpd.Project = "MY_PROJECT";
cpd.Entity = "POINT";
cpd.Attributes = "POINT_ID,RESOURCE_ID";
cpd.Filters = "POINT_ID=PGM*";
int count = 0;
count++;
}
Syntax CimProjectData.Project
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 576
Description String. Get/set the project to browse data from. Must be specified when used from CimView. For use in
the Event Manager, the project name should be empty to browse the local project.
Example
Dim d as new CimProjectData
d.project = "MY_PROJECT"
CimProjectData.Reset (method)
Syntax CimProjectData.Reset
Description Resets the list so that a new set of search criteria, attributes, or project may be specified.
Example
d.reset
CimRemoveUnusedPoints (method)
Syntax CimRemoveUnusedPoints
Description Removes unused points that have been created as a result of Variable assignments.
Comments The use of variables in expressions allows a user to assign points to animations at runtime. As the
program makes various variable assigns and adds new points to CimView, it leaves other points in a
state that no objects are using them. CimRemoveUnusedPoints can be used to remove these unused points
from the screen, which reduces the number of updates, CimView receives from PTMAP, thus improving
performance.
Example
Sub Cleanup
CimRemoveUnusedPoints
End Sub
DoQINTMath (function)
0 +
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 577
1 -
2 *
3 /
4 %
Example
Sub Main()
Dim qlowSrc1 as Double
Dim qhighSrc1 as Double
End Sub
DoUQINTMath (function)
0 +
1 -
2 *
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 578
3 /
4 %
Example
Sub Main()
Dim qlowSrc1 as Double
Dim qhighSrc1 as Double
End Sub
GetCurTimeHR (function)
Syntax GetCurTimeHR
Example
Sub Main()
Dim timestr as String
timestr = GetCurTimeHR
MsgBox "Current time = " & timestr
End Sub
GetKey (function)
Description To search for a keyword and returns its value. This is of use particularly from the Basic Control Engine to
extract the EVENT and ACTION, which caused the script to run. An empty string is returned if the key is
not found.
string$ String. The string to search for the keyword. The format of this string is keyword followed by
an equal sign and the value. A comma separates multiple keyword value combinations.
Example
Sub Main()
event_id$= GetKey("EVENT", command$)
action_id$ = GetKey("ACTION", command$)
' Name$ will contain PETE after this statement.
name$ = GetKey("NAME","NAME=PETE,LOCATION=ALBANY")
End Sub
GetMemoryInfoSymbolSpace (statement)
Description This statement obtains information on the memory usage for storing the names of the symbols for public
variables used in scripts at the module level.
Parameter Description
Example
Public testPublicLong As Long
Public testPublicString As String
Private pv_test As Long
Private pv_testString As String
Type ExampleRect
left As Integer
top As Integer
right As Integer
bottom As Integer
End Type
Public dd As ExampleRect
Sub OnMouseUp(x As Long, y As Long, flags As Long)
Dim ssUsed As Long
Dim ssFree As Long
Dim ssMax As Long
Dim psUsed As Long
Dim psFree As Long
Dim psMax As Long
Dim SymUsed As Long
Dim SymFree As Long
Dim SymMax As Long
Dim handlesUsed As Long
Dim handlesFree As Long
Dim handlesMax As Long
Dim memFlags As Long
testPublicLong = 1200
pv_testString = 1200
testPublicString = "constant string to show usage of string space by constants"
pv_testString = "More data, more data"
GetMemoryInfoStringSpaceHandles handlesUsed, handlesFree, handlesMax
GetMemoryInfoStringSpace ssUsed, ssFree, ssMax, memFlags
GetMemoryInfoPublicSpace psUsed, psFree, psMax
GetMemoryInfoSymbolSpace SymUsed, SymFree, SymMax
MsgBox "The current memory information: " + Chr$(13)_
+ "Handles Used = " + Format$(handlesUsed) + Chr$(13)_
+ "Handles Free = " + Format$(handlesFree) + Chr$(13)_
+ "Handles Max = " + Format$(handlesMax) + Chr$(13)_
+ "String Space Used = " + Format$(ssUsed) + Chr$(13)_
+ "String Space Free = " + Format$(ssFree) + Chr$(13)_
+ "String Space Max = " + Format$(ssMax) + Chr$(13)_
+ "Public Space Used = " + Format$(psUsed) + Chr$(13)_
+ "Public Space Free = " + Format$(psFree) + Chr$(13)_
+ "Public Space Max = " + Format$(psMax) + Chr$(13)_
+ "Symbol Space Used = " + Format$(SymUsed) + Chr$(13)_
+ "Symbol Space Free = " + Format$(SymFree) + Chr$(13)_
+ "Symbol Space Max = " + Format$(SymMax)
End Sub
GetMemoryInfoStringSpaceHandles (statement)
Description This statement obtains information on the handle usage for string space.
Parameter Description
Example
Option Explicit
Sub OnMouseUp(x As Long, y As Long, flags As Long)
Dim mymsg As String
Dim used As Long, free As Long, total As Long, outFlags As Long
Dim charCount
Dim i
Dim myarray(100) As String
mymsg = ""
mymsg = mymsg & Chr$(13) & "---- BEFORE ----"
GetMemoryInfoStringSpace used, free, total, outflags
mymsg = mymsg & Chr$(13) & "SPACE used:" & used & ", free:" & free & ", total:" & total
mymsg = mymsg & ", outFlags:" & outFlags
GetMemoryInfoStringSpaceHandles used, free, total
mymsg = mymsg & Chr$(13) & "HANDLES used:" & used & ", free:" & free & ", total:" & total
' Use up some string space and handles
charCount = 0
For i = LBound(myarray) To UBound(myarray) Step 1
myarray(i) = "ABCDEFGHIJKLMNOPQRSTUVWXYZ " & i & " ABCDEFGHIJKLMNOPQRSTUVWXYZ "
charCount = charCount + Len(myarray(i))
Next i
mymsg = mymsg & Chr$(13)
mymsg = mymsg & Chr$(13) & "---- AFTER populating, elements:" & (UBound(myarray) -
LBound(myarray)) _
& " char count:" & charCount & " ----"
GetMemoryInfoStringSpace used, free, total, outFlags
mymsg = mymsg & Chr$(13) & "SPACE used:" & used & ", free:" & free & ", total:" & total
mymsg = mymsg & ", outFlags:" & outFlags
GetMemoryInfoStringSpaceHandles used, free, total
mymsg = mymsg & Chr$(13) & "HANDLES used:" & used & ", free:" & free & ", total:" & total
MsgBox mymsg, ebOKOnly+ebInformation, "Memory Info"
End Sub
GetMemoryInfoStringSpace (statement)
Description This statement obtains information on the memory usage for string space.
Parameter Description
Example
Option Explicit
Sub OnMouseUp(x As Long, y As Long, flags As Long)
Dim mymsg As String
Dim used As Long, free As Long, total As Long, outFlags As Long
Dim charCount
Dim i
Dim myarray(100) As String
mymsg = ""
mymsg = mymsg & Chr$(13) & "---- BEFORE ----"
GetMemoryInfoStringSpace used, free, total, outflags
mymsg = mymsg & Chr$(13) & "SPACE used:" & used & ", free:" & free & ", total:" & total
mymsg = mymsg & ", outFlags:" & outFlags
GetMemoryInfoStringSpaceHandles used, free, total
mymsg = mymsg & Chr$(13) & "HANDLES used:" & used & ", free:" & free & ", total:" & total
' Use up some string space and handles
charCount = 0
For i = LBound(myarray) To UBound(myarray) Step 1
myarray(i) = "ABCDEFGHIJKLMNOPQRSTUVWXYZ " & i & " ABCDEFGHIJKLMNOPQRSTUVWXYZ "
charCount = charCount + Len(myarray(i))
Next i
mymsg = mymsg & Chr$(13)
mymsg = mymsg & Chr$(13) & "---- AFTER populating, elements:" & (UBound(myarray) -
LBound(myarray)) _
& " char count:" & charCount & " ----"
GetMemoryInfoStringSpace used, free, total, outFlags
mymsg = mymsg & Chr$(13) & "SPACE used:" & used & ", free:" & free & ", total:" & total
mymsg = mymsg & ", outFlags:" & outFlags
GetMemoryInfoStringSpaceHandles used, free, total
mymsg = mymsg & Chr$(13) & "HANDLES used:" & used & ", free:" & free & ", total:" & total
MsgBox mymsg, ebOKOnly+ebInformation, "Memory Info"
End Sub
Note The sum of the used and free parameter values will not be equal to the value of the total parameter. This
is because of the overhead that is used to manage the allocated blocks.
GetMemoryInfoPublicSpace (statement)
Description This statement obtains information on the memory usage for storing the values for public variables used in
scripts at the module level.
Parameter Description
Example
Public testPublicLong As Long
Public testPublicString As String
Private pv_test As Long
Private pv_testString As String
Type ExampleRect
left As Integer
top As Integer
right As Integer
bottom As Integer
End Type
Public dd As ExampleRect
Sub OnMouseUp(x As Long, y As Long, flags As Long)
Dim ssUsed As Long
Dim ssFree As Long
Dim ssMax As Long
Dim psUsed As Long
Dim psFree As Long
Dim psMax As Long
Dim SymUsed As Long
Dim SymFree As Long
Dim SymMax As Long
Dim handlesUsed As Long
Dim handlesFree As Long
Dim handlesMax As Long
Dim memFlags As Long
testPublicLong = 1200
pv_testString = 1200
testPublicString = "constant string to show usage of string space by constants"
pv_testString = "More data, more data"
GetMemoryInfoStringSpaceHandles handlesUsed, handlesFree, handlesMax
GetMemoryInfoStringSpace ssUsed, ssFree, ssMax, memFlags
GetMemoryInfoPublicSpace psUsed, psFree, psMax
GetMemoryInfoSymbolSpace SymUsed, SymFree, SymMax
MsgBox "The current memory information: " + Chr$(13)_
+ "Handles Used = " + Format$(handlesUsed) + Chr$(13)_
+ "Handles Free = " + Format$(handlesFree) + Chr$(13)_
+ "Handles Max = " + Format$(handlesMax) + Chr$(13)_
+ "String Space Used = " + Format$(ssUsed) + Chr$(13)_
+ "String Space Free = " + Format$(ssFree) + Chr$(13)_
+ "String Space Max = " + Format$(ssMax) + Chr$(13)_
+ "Public Space Used = " + Format$(psUsed) + Chr$(13)_
+ "Public Space Free = " + Format$(psFree) + Chr$(13)_
+ "Public Space Max = " + Format$(psMax) + Chr$(13)_
+ "Symbol Space Used = " + Format$(SymUsed) + Chr$(13)_
+ "Symbol Space Free = " + Format$(SymFree) + Chr$(13)_
+ "Symbol Space Max = " + Format$(SymMax)
End Sub
GetSystemWindowsDirectory (function)
Syntax
d$ = GetSystemWindowsDirectory
Description Returns the true Windows directory and not the per user Windows directory when running under Terminal
Services.
Example
Sub Main()
Direct$ = GetSystemWindowsDirectory
MsgBox "GetSystemWindowsDirectory = " & direct$
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 584
GetTimeComponentsHR (function)
Description Components of the time. Current time divided into time components of year, month, day, hour, min, sec
and nanoseconds.
Example
Sub Main()
Dim yy As Integer
Dim mm As Integer
Dim dd As Integer
Dim hh As Integer
Dim min As Integer
Dim sec As Integer
Dim nano As Long
localpoint.id = "\\$LOCAL\$LOCAL.DATETIME_VARUPDATE"
result = localpoint.GetQuadIntValue(qhigh,qlow)
GetTimeComponentsHR qhigh,qlow,yy,mm,dd,hh,min,sec,nano
End Sub
See also GetCurTimeHR (page 578) (function), SetTimecomponentsHR (page 622) (function)
GetTSSessionId (function)
Syntax
id& = GetTSSessionId
Description The Session ID of the Terminal Services client. This is 0 if running on the console or if Terminal Services
is not running.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 585
Example
Sub Main()
myid& = GetTSSessionId
MsgBox "Terminal Services Session Id = " & myid&
End Sub
IsTerminalServices (function)
Syntax
IsTerminalServices
Example
Sub Main()
MsgBox "Terminal Services = " & IsTerminalServices
End Sub
Description To provide the programmer with the ability to log errors to the CIMPLICITY Status Log. To view the errors,
use the CIMPLICITY Status Log Viewer.
Procedure$ String. The name of the Basic Procedure which logged the error.
error_reference Long. (optional). A user-defined error reference. Used to distinguish the difference
between two errors with the same error_code.
Example
Sub Main()
on error goto error_handler
....
..
Exit Sub
error_handler :
' error$, err, and erl are BASIC variables which contain the
' error text, error code and error line respectively.
LogStatus CIM_FAILURE, "main()", error$, err, erl
Exit Sub
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 586
Syntax Point.AlarmAck
Description Boolean. When used in combination with the Point.OnAlarmAck method, a Boolean is returned
indicating if the point's alarm is in an Acknowledged state.
Example
Sub Main()
Dim x as new Point
x.ID = "Some_point"
x.OnAlarmAck
top:
x.GetNext
Trace "Alarm Ack state is " & x.AlarmAck
End Sub
Point.Cancel (method)
Syntax Point.Cancel
Description To cancel the currently active OnChange , OnAlarm , OnTimed or OnAlarmAck request.
Example
Sub Main()
Dim t as new Point
t.Id = "TIME"
' Read the next two values of the point
t.OnChange
for i = 1 to 2
t.GetNext
next I
' Cancel the onchange request.
t.Cancel
' Get the point value every three seconds
t.OnTimed 3
for i = 1 to 2
t.GetNext
next I
End Sub
See Also Point.OnChange (page 598) (method), Point.OnTimed (page 598) (method), Point.OnAlarm (page
596) (method), Point.OnAlarmAck (page 597) (method)
Syntax Point.ChangeApproval = a
Description To set the Change Approval information for a point. Important: Change Approval must be set to an object
of type CimChangeApprovalData in order to perform set point operations on a point that requires change
approval..
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 587
Example
Sub Main()
Dim MyPoint As New Point
Dim obj As New CimChangeApprovalData
'Init Point
Set MyPoint.Id = "MYPOINT"
'Init CimChangeApprovalData with prompts
Select Case MyPoint.ChangeApprovalInfo
Case CP_CHANGEAPPROVALPERFORM
obj.PerformerUserid = AskBox("Performer Userid")
obj.PerformerPassword = AskPassword("Performer Password")
Case CP_CHANGEAPPROVALPERFORMVERIFY
obj.PerformerUserid = AskBox("Performer Userid")
obj.PerformerPassword = AskPassword("Performer Password")
obj.VerifierUserid = AskBox("Verifier Userid")
obj.VerifierPassword = AskPassword("Verifier Password")
Case CP_CHANGEAPPROVALNONE
End Select
'Copy our CimChangeApprovalData into the Point's ChangeApproval
Set MyPoint.ChangeApproval = obj
'Set the point
MyPoint.SetValue = InputBox("Setpoint")
End Sub
See also CimChangeApprovalData (page 551) (Object), AlarmUpdateCA (page 546) (Method),
PointChangeApprovalInfo (page 587) (property, read).
Syntax Point.ChangeApprovalInfo
Description Integer. To determine the level of change approval that is required to perform an operation.
Example
Sub OnMouseUp(x As Long, y As Long, flags As Long)
Dim MyPoint As New Point
'Init Point
Set MyPoint.Id = "MYPOINT"
'Check ChangeApprovalInfo to see what is required for approval
Select Case MyPoint.ChangeApprovalInfo
Case CP_CHANGEAPPROVALPERFORM
MsgBox "This Point requires a Performer for approval!"
Case CP_CHANGEAPPROVALPERFORMVERIFY
MsgBox "This Point requires a Performer and Verifier for approval!"
Case CP_CHANGEAPPROVALNONE
MsgBox "This Point does not require ChangeApproval!"
End Select
End Sub
See also AlarmUpdateCA (page 546) (Method), CimChangeApprovalData (page 551) (Object),
Point.ChangeApproval (page 586) (property, write)
Syntax Point.DataType
CP_UDINT An unsigned long (32-Bit) integer, returned as a double precision floating point number.
Example
if MyPoint.DataType = CP_STRING then
a$ = MyPoint.Value
else
a% = MyPoint.Value
end if
Syntax Point.DisplayFormat
Description String. To return a string containing the configured display format for the point.
Syntax Point.DownLoadPassword
Example
' Prompt the user for the download password if required to set
' the point.
Sub Main()
Dim p as new Point
p.Id = "CP_UINT"
p.Value = 10
if p.DownLoadPassword then
pass$ = AskPassword("DownLoad Password:")
p.Set pass$
else
p.Set
end if
End Sub
See also Point.SetPointPriv (page 606) (property, read); Point.InUserView (page 595) (property, read).
Syntax Point.Elements
Description Integer. To return the number of elements configured for the point. For array points this will be greater
than 1, for non-array points the value will be 1.
Example
Sub Main()
Dim MyPoint as new Point
MyPoint.Id = "ARRAY_POINT"
for x = 0 to MyPoint.Elements - 1
MyPoint.Value(x) = x
next x
MyPoint.Set
End sub
Point.EnableAlarm (method)
Description To enable or disable alarming on the point. Can be used to temporarily disable alarming on a point.
Enable Boolean. A value of TRUE enables alarming for the point and value of FALSE disables
alarming for the point.
Example
Sub Main()
Dim myPoint As New point
myPoint.Id = "ALARM_POINT"
' Disable alarm for point.
myPoint.EnableAlarm FALSE
End Sub
Syntax Point.Enabled
Description Boolean. To determine if the point is enabled to be collected from the PLC.
Syntax Point.EuLabel
Example
a$ = MyPoint.EuLabel
or
if MyPoint.EuLabel = "Litres" then
...
end if
Point.Get (statement)
Syntax Point.Get
Description To get the current value of the point from the CIMPLICITY Point Manager and store it in the object. You
may inspect the value through the Value and RawValue properties.
Example
Sub Main()
Dim MyPoint as new Point
MyPoint.Id = "\\PROJECT1\POINT1"
MyPoint.Get
MsgBox "The value is " & MyPoint.Value
End Sub
See also Point.Value (page 612) (method), Point.OnChange (page 598) (method), Point.OnTimed (page 598)
(method).
Point.GetArray (statement)
Description To retrieve an array point's values directly into a Basic array using Engineering Units Conversion if
applicable. There are several rules to keep in mind:
• If the array is undimensioned, the array will be re-dimensioned to the same size as the point.
• If the array is dimensioned smaller than the point, only that many elements will be copied into the
array.
• If the array is larger than the point, all elements of the point are copied, and the rest of the array is left
as is.
If the startElement is specified, the function will start copying data into the array at this element and will
continue until the end of the point is reached or the array is full whichever occurs first. If the endElement
is specified, the function will stop copying data into the array after populating this element or when the
end of the point is reached. If the fromElement is specified, the values copied into the array start at this
element in the point array and continue as described above. Note: You must get the point value using the
Get or GetNext method prior to using the GetArray method. The GetArray method does not retrieve
the current value from the Point Manager. Instead, it retrieves the current value in the Point Object, which
was generated during the last Get or GetNext . See the example below.
array Array. A dimensioned or un-dimensioned Basic Array to which the point data will be
copied.
startElement Integer. (optional) The first array element to which data will be copied.
endElement Integer. (optional) The last array element to which data will be copied.
fromElement Integer. (optional) The first point element from which data is to be copied.
Example
Sub Main()
Dim values() as integer
Dim p as new Point ' Declare the point object
p.Id = "ARRAY_POINT" ' Set the Id
p.Get ' Get value from CIMPLICITY
p.GetArray values ' Copy the object into values
End Sub
See Also Point.SetArray (page 604) (method); Point.GetRawArray (page 593) (method); Point.HasEuConv
(page 594) (property, read); Point.Value (page 612) (property, read/write); Point.RawValue (page
602) (property, read/write).
Point.GetNext (function)
Description Boolean. A function, to read the next value of a point with a specified timeout in milliseconds. Returns
True if the point was read, False if it timed out.
Example
Sub Main()
Dim MyPoint as new Point
MyPoint.Id = "TIME" ' Set the Id
MyPoint.OnChange ' Request the value on change
MyPoint.GetNext ' The current value is returned immediately.
if MyPoint.GetNext(1000) then ' Wait 1 second for the next value.
MsgBox MyPoint.Value ' Display the value.
Else
MsgBox "Timeout" ' Point didn't change in one second.
end if
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 592
See also Point.OnChange (page 598) (method); Point.OnTimed (page 598) (method); Point.OnAlarm (page
596) (method); Point.OnAlarmAck (page 597) (method); Point.Cancel (page 586) (method).
Point.GetNext (statement)
Syntax Point.GetNext
Description To wait for and get the next value of the point. This method returns when a point update is received for the
point, based on a previously submitted OnChange, OnAlarm, OnTimed or OnAlarmAck call. If the point
never changes, the call never returns. To wait with a timeout, see the GetNext(function.)
Example
' Calculate the average of the next two point values.
Sub Main()
Dim MyPoint as new Point
MyPoint.Id = "TANK_TEMPERATURE" ' Set the Id
MyPoint.OnChange ' Request point onchange
MyPoint.GetNext ' Retrieve the first value.
x = MyPoint.Value ' Record the value.
MyPoint.GetNext ' Wait for the next value.
x1 = MyPoint.Value ' Record the value
ave# = (x + x1 )/ 2 ' Calculate the average
MsgBox "The average was " & str$(ave)
End Sub
See Also Point.OnChange (page 598) (method); Point.OnAlarm (page 596) (method); Point.OnTimed (page
598) (method); Point.OnAlarmAck (page 597) (method)..
Point.GetQuadIntValue (function)
Description Will return the value of a 64-bit QINT or QUINT point in the form of two 32-bit double integers.
Example
Sub OnMouseUp(x As Long, y As Long, flags As Long)
'Declare variables
Dim qhigh As Double
Dim qlow As Double
Dim result As Boolean
Dim localpoint As New Point
'Initialize
localpoint.id = "\\$LOCAL\$LOCAL.DATETIME_VARUPDATE"
'Gets the value of a QuadInt and places it in our two 32 bit Basic doubles
result = localpoint.GetQuadIntValue(qhigh,qlow)
If result = True Then
MsgBox qhigh
Msgbox qlow
Else
MsgBox "Error!"
End If
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 593
Point.GetRawArray (statement)
Description To retrieve an array points value directly into a Basic array bypassing Engineering Units Conversion.
• If the array is undimensioned, the array will be re-dimensioned to the same size as the point.
• If the array is dimensioned smaller than the point, only that many elements will be copied into the
array.
• If the array is larger than the point, all elements of the point are copied, and the rest of the array is left
as is.
If the startElement is specified, the function will start copying data into the array at this element and will
continue until the end of the point is reached or the array is full whichever occurs first. If the endElement
is specified, the function will stop copying data into the array after populating this element or when the
end of the point is reached. If the fromElement is specified, the values copied into the array start at this
element in the point array and continue as described above.
Parameter Description
array Array. A dimensioned or un-dimensioned Basic Array to which the point data will be
copied.
startElement Integer. (optional) The first array element to which data will be copied.
endElement Integer. (optional) The last array element to which data will be copied.
fromElement Integer. (optional) The first point element from which data is to be copied.
Example
Sub Main()
Dim rawValues() as integer
Dim p as new Point ' Declare the point object
p.Id = "ARRAY_POINT" ' Set the Id
p.Get ' Get value from CIMPLICITY
p.GetRawArray rawValues ' Copy the object into values
End Sub
See Also Point.GetArray (page 590) (method); Point.SetRawArray (page 606) (method); Point.HasEuConv
(page 594) (property/read); Point.Value (page 612) (property, read/write); Point.RawValue (page
602) (property, read/write).
Point.GetTimeStampHR (statement)
Description Date. To retrieve the Microsecond timestamp into 2 double 32-bit values. The timestamp indicates the
time at which the point's value was read from the PLC.
Example
Sub Main()
Dim x as new Point
Dim qhigh as Double
Dim qlow as Double
a$ = InputBox$("Enter a point id")
x.Id = a$
x.GetTimeStampHR(qhigh,qlow)
End Sub
See also Point.QuadValueAsString (page 599) (property, read), Point.QuadValueAsString (page 599) (property,
write,) Point.SetQuadIntValue (page 606) (function), Point.TimeStampHR (page 593) (property, read),
GetTimeComponentsHR (page 584) (function), GetCurTimeHR (page 578) (function).
Syntax Point.GetValue
Description To get a snapshot of the point value from the Point Manager and return it. This operation combines the
Get Method and Value Property into a single command.
If the point is unavailable (due to the device being down, remote server unavailable, etc.) an error will
be generated if you attempt to access the value (since the value is unavailable.) See the Point.State
property if you need to determine if the point is available or not.
Example
Sub Main()
Dim MyPoint as new Point ' Declare the point object
MyPoint.Id = "TANK_LEVEL" ' Set the point id
x = MyPoint.GetValue ' Read and return the value.
End Sub
Syntax Point.HasEuConv
Description Boolean. To determine if the point has Engineering Units conversion configured.
Example
Sub Main()
Dim MyPoint as new Point
MyPoint.Id = "DEVICE_POINT_1"
if MyPoint.HasEuConv then
MsgBox "Has Eu Conversion"
else
MsgBox "No Eu Conversion"
end if
End Sub
See also Point.SetRawArray (page 606) (method); Point.SetArray (page 604) (method); Point.GetArray (page
590) (method); Point.GetRawArray (page 593) (method); Point.Value (page 612) (property, read/
write); Point.RawValue (page 602) (property, read/write).
Syntax Point.Id
Description String. To get or set the object's CIMPLICITY Point ID. The function generates an error if the point is not
configured or the remote server is not available.
Comments If an error is generated, one of the following error codes may be reported.
Err Description
Example
Sub Main()
Dim MyPoint as new Point
MyPoint.Id = "\\PROJECT1\POINT1" ' Set the id
End Sub
Syntax Point.InUserView
• If Resource Setpoint Security is checked in the Point Setup dialog box for the point's project and
the point's resource is not in the user's view, then FALSE is returned.
• If Level Setpoint Security is checked in the Point Setup dialog box and the point's level is greater
than the level of the user's role, then FALSE is returned.
• Otherwise, TRUE is returned.
• If the point is not in the user's view, a run time error will be generated if you try to set it.
Example
Sub Main()
Dim MyPoint as new Point
MyPoint.Id = "TEST_POINT"
if MyPoint.InUserView = TRUE
MyPoint.SetValue = 10
else
MsgBox "Point not in user view, setpoint not allowed"
end if
End Sub
See also Point.SetPointPriv (page 606) (property, read); Point.DownLoadPassword (page 588) (property, read).
Syntax Point.Length
Description Integer. To return the length in Bytes of the point value. This is valid only for character strings.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 596
Point (object)
Overview The Point object provides an object-oriented interface to CIMPLICITY real-time point data. Through the
object, you may set and read point values. Methods are supplied to receive the point value as it changes,
periodically, or when the alarm state changes.
Example 1
Dim MyPoint as new Point ' Creates a new empty point object
2
Dim ThisPoint as Point ' Creates a pointer to a point object
Set ThisPoint = MyPoint ' Now the two object are equal (BCE)
Notes In the above example, a point object is created two different ways.
1 Uses a new keyword; this is typically the method you will use. This constructs a point object, at which
time you can set the ID of the point and use it.
A runtime error will occur if you attempt to access methods of the object, since it is currently unassigned.
You can assign the reference to a particular object by using the SET command. In general, you will use this
with the PointGetNext function, which takes a list of point objects and returns the first one that changes.
Important: Point objects in .NET scripting must be explicitly disposed of by doing either of the
following:
Failing to do so will freeze the IDE (page 159) when the script is finished running.
Point.OnAlarm (statement)
Description To request the point's value when its alarm state changes. If no parameters
are specified, the value will be returned whenever the alarm state changes.
The four optional parameters can be used to restrict which alarm conditions will
be reported to the application.
Comments Call GetNext to obtain the next value of the point. Only one of the
OnChange , OnAlarm , OnTimed or OnAlarmAck requests may be active
at a time. Optional Parameters
Value Description
Example
Sub Main()
Dim MyPoint as new Point
MyPoint.Id = "TANK_LEVEL"
MyPoint.OnAlarm
Top:
MyPoint.GetNext
if MyPoint.State = CP_ALARM_HIGH then
MsgBox "Alarm High"
elseif MyPoint.State = CP_ALARM_LOW then
MsgBox "Alarm Low"
elseif MyPoint.State = CP_WARNING_HIGH then
MsgBox "Warning High"
elseif MyPoint.State = CP_WARNING_LOW then
MsgBox "Warning Low"
elseif MyPoint.State = CP_UNAVAILABLE then
MsgBox "Unavailable"
else
MsgBox "Normal"
end if
goto top
End Sub
See Also Point.GetNext (page 592) (method); Point.Cancel (page 586) (method);
Point.OnAlarmAck (page 597) (method).
Notes
The point value is sent when the point goes to warning or alarm state (based
on the selected value), and then point value is sent again when the point goes
back to normal state.
Due to a current limitation, selecting ALARM_HIGH and WARNING_LOW
, for example, will return the point for all alarm and warning states. In other
words, the High and Low end up applying to both the Alarm and Warning.
Point.OnAlarmAck (statement)
Syntax Point.OnAlarmAck
Description To receive the point's value when the alarm acknowledgment state changes.
Only one of the OnChange , OnAlarm , OnTimed or OnAlarmAck requests may be active at a
time.
See also Point.GetNext (page 592) (method); Point.Cancel (page 586) (method); Point.OnAlarm (page
596) (method).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 598
Point.OnChange (statement)
Syntax Point.OnChange
Description To request the point's value on change. The next value of the point may be received by calling the
GetNext method or function. The current value of the point is returned immediately. Any subsequent
GetNext call will block until the point's value changes.
Only one of the OnChange , OnAlarm , OnTimed or OnAlarmAck requests may be activate at a
time.
Sub Main()
Dim MyPoint as new Point ' Declare the point object
MyPoint.Id = "TANK_LEVEL" ' Set the Id
MyPoint.OnChange ' Request the value on change
top :
MyPoint. GetNext ' Get the value
Trace MyPoint.Value ' trace it to the output window
goto top ' repeat forever
End Sub
See also Point.GetNext (page 592) (method); Point.OnTimed (page 598) (method); Point.Cancel (page 586)
(method).
Point.OnTimed (statement)
Description To poll the points value periodically. A new value will be sent to the application every time_period
seconds. The application should call GetNext to retrieve the next value.
Comments Unlike the OnChange method, you may miss values of the point if it changes in between your polls.
Use the OnChange method to receive the point whenever it changes. OnTimed is useful if the point is
rapidly changing and you are only interested in its value in a periodic manner. Only one of the OnChange
, OnAlarm , OnTimed or OnAlarmAck requests may be active at a time.
Parameter Description
Example
Sub Main()
Dim MyPoint as new Point ' Declare the point object
MyPoint.Id = "TANK_LEVEL" ' Set the point Id
MyPoint.OnTimed 60 ' Request value every minute
Top :
MyPoint.GetNext ' Read the value
Trace MyPoint.Value ' Put it out to the trace buffer
goto top ' Repeat forever
End Sub
See Also Point.GetNext (page 592) (method); Point.OnChange (page 598) (method); Point.Cancel (page 586)
(method).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 599
Syntax Point.PointTypeId
Example
Sub Main()
Dim MyPoint as new Point
MyPoint.Id = "CP_DIGITAL"
if MyPoint.PointTypeId = "DIGITAL" then
MsgBox "It is a digital point"
else
MsgBox "Point Type ID is : " & MyPoint.PointTypeId
end If
End Sub
Syntax Point.QuadValueAsString
Description String. To return the string for the point values that are QINT,UQINT. Converts LONGLONG or
ULONGLONG values of datatypes QINT or UQINT into strings and returns them.
Example
Sub Main()
Dim p as new Point
Dim val as String
p.Id = "UQINT"
val = p.QuadValueAsString
MsgBox val
End Sub
See also Point.QuadValueAsString (page 599) (property, write), write,) Point.SetQuadIntValue (page 606)
(function), Point.TimeStampHR (page 593) (property, read).
Syntax Point.QuadValueAsString
Description Boolean. To take string of digits and convert them into 64-bit values and set the point values.
Example
Sub Main()
Dim p as new Point
Dim val as String
p.Id = "UQINT"
p.QuadValueAsString = "1234567899876543212" ‘Sets the
value of the point that has type UQINT.
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 600
See also Point.QuadValueAsString (page 599) (property, read),Point.SetQuadIntValue (page 606) (function),
Point.TimeStampHR (page 593) (property, read), GetTimeComponentsHR (page 584) (function),
GetCurTimeHR (page 578) (function).
Syntax Point.Quality
Description Long. Return the 16-bit quality mask for the point.
Example
Sub Main()
Dim p as new Point
p.Id = "VALVE_1"
p.Get
MsgBox cstr(p.Quality)
End Sub
Syntax Point.QualityAlarmed
Example
Sub Main()
Dim p as new Point
p.Id = "VALVE_1"
p.Get
if p.QualityAlarmed then
MsgBox "Point is in alarm"
End If
End Sub
Syntax Point.QualityAlarms_Enabled
Description Boolean. Returns TRUE if alarming for the point is enabled, FALSE otherwise.
Example
Sub Main()
Dim p as new Point
p.Id = "VALVE_1"
p.Get
if p.QualityAlarms_Enabled then
MsgBox "Alarming is enabled"
End If
End Sub
Syntax Point.QualityDisable_Write
Description Boolean. Returns TRUE if setpoints have been disabled for the point, FALSE otherwise.
Example
Sub Main()
Dim p as new Point
p.Id = "VALVE_1"
p.Get
if p.QualityDisable_Write Then
MsgBox "Writing disabled for point"
End If
End Sub
Syntax Point.QualityIs_Available
Description Boolean. Returns TRUE if the points value is available, FALSE if the value is unavailable.
Example
Sub Main()
Dim p as new Point
p.Id = "VALVE_1"
p.Get
if p.QualityIs_Available = FALSE then
MsgBox "Point is not available"
End If
End Sub
Syntax Point.QualityIs_In_Range
Description Boolean. Returns TRUE if the current value of the point is in range, FALSE if the point is out of range.
When a point is out of range its value is unavailable.
Example
Sub Main()
Dim p as new Point
p.Id = "VALVE_1"
p.Get
if p.QualityIs_In_Range = FALSE then
MsgBox "Point is out of range"
End If
End Sub
Syntax Point.QualityLast_Upd_Man
Description Boolean. Returns TRUE if the current value of the point came from a manual update rather than a device
read.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 602
Example
Sub Main()
Dim p as new Point
p.Id = "VALVE_1"
p.Get
if p.QualityLast_Upd_Man then
MsgBox "Last Update Manual"
End If
End Sub
Syntax Point.QualityManual_Mode
Description Boolean. Returns TRUE if the point has been placed into Manual Mode, otherwise FALSE.
Example
Sub Main()
Dim p as new Point
p.Id = "VALVE_1"
p.Get
if p.QualityManual_Mode then
PointSet "VALVE_1_STATE", "In Manual"
Else
PointSet "VALVE_1_STATE", ""
End If
End Sub
Syntax Point.QualityStale_Data
Description Boolean. Returns TRUE if the value of the point is stale, otherwise FALSE.
Example
Sub Main()
Dim p as new Point
p.Id = "VALVE_1"
p.Get
if p.QualityStale_Data = TRUE
MsgBox "Value is stale"
End If
End Sub
Description Same as Point.Value except bypasses Engineering Units conversion if configured for the point. Will
return into any type subject to some restrictions. All numeric types may be returned into any other numeric
type and into string types. String and BitString types can only be returned into string types. If the variable
being returned into does not have a type, the variable will be changed to the appropriate type, based on
the point type.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 603
Comments The option base determines if the first element of an array point will be zero or one. If you do not
explicitly set the option base , all arrays in Basic start at 0. If you set it to 1, all arrays in Basic start at 1.
See the example below.
.RawValue does not return the underlying numerical value for an enumerated point. If you want to obtain
the underlying numerical value.
Parameter Description
index Integer. (optional) The array element to access. Range depends on the option base
setting.
Example 2 'Access both the enumerated text and the underlying numerical 'value for a point.
Sub Main()
Dim p1 As New point
Dim p2 As New point
'get the enumerated value
p1.id = "ENUMERATEDPOINT"
p1.get
trace "enumerated text for " & p1.id & " is " & p1.value
'get the underlying numerical value
p2.id = "ENUMERATEDPOINT.$RAW_VALUE"
p2.get
'yes, we really mean p1.id, with p2.value!!!
trace "underlying numeric value for " & p1.id & " Is " & p2.value
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 604
Syntax Point.ReadOnly
Example
Sub Main()
Dim MyPoint as new Point ' Declare the point object
MyPoint.Id = "TANK_LEVEL" ' Set the Id
if MyPoint.ReadOnly then ' Is the point read-only?
MsgBox "Point cannot be set, point is read-only"
else
MyPoint.SetValue = 10 ' Set the value and write to CIMPLICITY.
end if
End Sub
Point.Set (statement)
Description To write the point's value out to the CIMPLICITY project. An optional download password can be supplied.
Comments The values set into the Point using the Value, RawValue, SetArray and SetRawArray methods are not written
out to the CIMPLICITY project until they are committed with a Set statement.
Parameter Description
Example
Sub Main()
Dim MyPoint as new Point ' Declare the point object
MyPoint.Id = "TANK_LEVEL" ' Set the Id
MyPoint.Value = 10 ' Set the value
MyPoint.Set ' Write the value out to CIMPLICITY
End Sub
See Also Point.SetValue (page 607) (property, read), PointSet (page 604) (method)
Note
Point.SetArray (statement)
• If the array is dimensioned smaller than the point, only that many elements will be copied into the
point.
• If the array is larger than the point, all elements of the array are copied, and the rest of the array is
ignored.
If the startElement is specified, the function will start copying data from the array at this element and will
continue until the end of the array is reached or the point is full whichever occurs first. If the endElement is
specified, the function will stop copying data from the array after copying this element or when the point is
full. If the fromElement is specified, the values copied from the array start at this element in the point array
and continue as described above.
Parameter Description
array Array. A dimensioned or undimensioned Basic Array from which the point data will be
copied.
startElement Integer. (optional) The first array element from which data will be copied.
endElement Integer. (optional) The last array element from which data will be copied.
fromElement Integer. (optional) The first point element to which data is to be copied.
Example
' Read an array point, sort the elements by value and write them
' out to CIMPLICITY sorted.
Sub Main()
Dim x() as integer 'Declare the value array
Dim MyPoint as new Point 'Declare the point object
MyPoint.id = "POINTNAME" 'Assign point to script
MyPoint.Get 'Get the point value
MyPoint.GetArray x 'Transfer point element into array
ArraySort x 'Sort the array
MyPoint.SetArray x 'Transfer to array into the point
MyPoint.Set 'Transfer the sorted data to CIMPLICITY.
End Sub
See Also Point.SetRawArray (page 606) (method); Point.Value (page 612) (property, read/write),
Point.GetArray (page 590) (method); Point.Set (page 604) (method).
Note The SetArray method only updates the internal value of the point object. The Set method must be
executed to write the value out to the CIMPLICITY project.
Point.SetElement (statement)
Example
'Set only the third element of an array
Sub Main()
Dim MyPoint As New Point 'Declare the point object
MyPoint.Id = "INT_ARRAY"
MyPoint.Value(3) = 10 'Assign the value of the third element
MyPoint.SetElement 3 'Write only the third element
End Sub
Syntax Point.SetpointPriv
Description Boolean. To determine if the user accessing the point has Setpoint privilege.
Example
Sub Main()
Dim MyPoint as new Point
MyPoint.Id = "TANK_LEVEL"
if MyPoint.SetpointPriv = FALSE then
MsgBox "You do not have the setpoint privilege"
else
MyPoint.SetValue = InputBox$("Setpoint Value:")
end if
End Sub
See also Point.DownloadPassword (page 588) (property, read); Point.InUserView (page 595) (property, read).
Point.SetQuadIntValue (function)
Syntax Point.SetQuadIntValue(qhigh,qlow)
Description To set the point's value in a CIMPLICITY project. This operation combines the Value and Set operations
into one command. The SetQuadIntValue function takes two double values to set the value of any 64 bit
data type QINT or UQINT.
Example
' To set the value of any point with data type QINT or UQINT
‘follow the example below.
Sub Main()
Dim qstr As String
Dim qhigh as Double
Dim qlow as Double
Dim MyPoint as new Point 'Declare the point object
MyPoint.Id = "QINT" 'Set the Id
qstr = "1000000899876543212"
QINTFromString qstr,qhigh,qlow
SetQuadIntValue (qhigh,qlow)
End Sub
See also Point.QuadValueAsString (page 599) (property, read),Point.QuadValueAsString (page 599) (property,
write), Point.SetQuadIntValue (page 606) (function), Point.TimeStampHR (page 593) (property,
read);Point.GetQuadIntValue (page 592) (function)
Point.SetRawArray (statement)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 607
Description To set an array point's values directly from a Basic array, bypassing Engineering Units Conversion.
• If the array is dimensioned smaller than the point, only that many elements will be copied into the
point.
• If the array is larger than the point, all elements of the point are set.
If the startElement is specified, the function will start copying data from the array at this element and will
continue until the end of the array is reached or the point is full whichever occurs first. If the endElement is
specified, the function will stop copying data from the array after copying this element or when the point is
full. If the fromElement is specified, the values copied from the array start at this element in the point array
and continue as described above.
Parameter Description
array Array. A dimensioned or undimensioned Basic Array from which the point data will be
copied.
startElement Integer. (optional) The first array element from which data will be copied.
endElement Integer. (optional) The last array element from which data will be copied.
fromElement Integer. (optional) The first point element to which data is to be copied.
Example
' Copy the log value of one array point to another array point.
Sub Main()
Dim source as new Point ' Declare source point
Dim dest as new Point ' Declare destination point
Dim x() as double ' Declare array
source.Id = "INPUT" ' Set the ID of the source point
source.Get ' Get the value of the source point
dest.Id = "OUTPUT" ' Set the ID of the destination point
source.GetRawArray x ' Transfer value to array
' Loop through array point, taking logarithm.
for I = 0 to source.Elements - 1
x(I) = log(x(I))
next I
dest.SetRawArray x ' Transfer value into destination object
dest.Set ' Set the value to CIMPLICITY
End Sub
See Also Point.SetArray (page 604) (method); Point.RawValue (page 602) (property, read/write);
Point.GetRawArray (page 593) (method).
Note The SetRawArray method only updates the internal value of the point object. The Set method must be
executed to write the value out to the CIMPLICITY project.
Syntax Point.SetValue = a
Description To set the point's value in a CIMPLICITY project. This operation combines the Value and Set
operations into one command. The SetValue method uses Engineering Units Conversion and cannot be
used to set elements of an array point.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 608
Example
' Ramp tank level from 0 to 100 in steps of five, with a delay
' on 100ms between each set.
Sub Main()
Dim MyPoint as new Point 'Declare the point object
MyPoint.Id = "TANK_LEVEL" 'Set the Id
for I = 0 to 100 step 5 'Loop in steps of 5
MyPoint.SetValue = I 'Set and write value to CIMPLICITY
Sleep 100 'Sleep 100ms
next I 'Loop
End Sub
Syntax Point.State
State Description
Example
' Increment the point value by one, if the point is unavailable,
' set it to 0.
Sub Main()
Dim MyPoint as new Point
MyPoint.Id = "TANK_LEVEL"
MyPoint.Get
if MyPoint.State = CP_UNAVAILABLE then
MyPoint.SetValue = 0
else
MyPoint.SetValue = MyPoint.Value + 1
end if
End Sub
See Also Point.Get (page 590) (method); Point.GetNext (page 592) (method)
Point (subject)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 609
Overview The values of CIMPLICITY points can be used in a variety of ways by a script. You can use scripts that
act on point values to define reactions to changing conditions in your process. Points are manipulated
by the PointSet statement and PointGet function or the point object. In general, PointSet and
PointGet are useful if you require the value of the point or wish to set the point. The point object
extends your capabilities by allowing you to receive point values as they change, access array points,
provide more information about the point's configuration; and improve performance when repeatedly
setting a point.
Security The CIMPLICITY extensions to Basic provide the same security which all your CIMPLICITY applications
use; Set Point Security, Set Point Privilege, Download Password and Set Point Audit trail. In order to
discuss security, first we will need to understand when security is imposed on your access to points.
There are two categories of processes running on your CIMPLICITY Server; User Applications and
Resident Processes. User Applications are applications run by the user, that usually provide a user
interface. Examples of such programs are CimView, CimEdit, Alarm Viewer and Program Editor. In
order for the application to access a point on the local CIMPLICITY project or a remote CIMPLICITY
project, a user login is required. The CIMPLICITY privileges defined for your User ID define your
capabilities. Resident Processes are processes that are started as part of your CIMPLICITY project.
Examples of resident processes are the Database Logger, Point Manager and scripts automatically
run by the Basic Control Engine. Since a resident process is a trusted part of your system, a resident
process is not required to obtain a login in order to access points in their project. If the resident process
wishes to access a point on a remote system, a remote project must be configured to supply the
resident process with the User ID and Password with which to log in to the remote system.
Performance The CIMPLICITY extensions to Basic provide a high performance mechanism to interact with your Point
Database. However, there are several considerations to keep in mind when designing your application
to obtain the highest performance possible. First, is the Set Point Audit Trail. For each CIMPLICITY role,
you may configure whether or not the user will generate an audit trail for each setpoint. The audit trail
is composed of a $DOWNLOAD event containing information on who set the point. This information is
sent to your event log and can provide a detailed audit trail of who and what was set. However, the audit
trail imposes significant overhead (20 times slower), since the record is logged to the database for each
setpoint. This is particularly noticeable when running setpoints in a loop in the Program Editor. However,
when the script is run from the Basic Control Engine, a $DOWNLOAD event will not be generated since
a resident process is trusted. If you do not require an audit trail is it recommended that you disable it
through role configuration (this is the default).
Second, is the difference between a PointSet statement and using the Point Object. With a Point
Object, you create the object once and initialize its point information once (data type, elements, etc.).
Subsequent operations on the Point are very fast, since the point characteristics are contained in the
object. Conversely, PointSet and PointRead must fetch the point information on each execution (in
benchmark testing this is 2 times slower.) Consider the following example :
The subroutine fast_set ramps the point ten times faster than the slow_set routine. While the second
example at first may appear more complex, you will find that the object interface provides much more
flexibility. As a rule, use PointGet and PointSet when you need to read or set the point's value once
within your script.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 610
Polling CIMPLICITY provides a high performance Point Interface. As a result, improperly written applications
can degrade the overall performance of a system. One common issue is polling a point to wait for it to
change. Consider the following example. Incorrect Code
Poll:
If PointGet("POLL_POINT") = 0 then
Sleep 100
Goto poll
End If
The sleep statement causes a 100ms delay between polls. However many extra polls are still being
performed. Correct and Most Efficient Code
Dim p as new point
p.Id = "POLL_POINT"
p.Onchange
Poll:
Wait_for
p.GetNext
if p.Value=0 then goto wait for
In this example, the script requests the value of the point as it changes. When the point changes, the
GetNext statement returns. When the point is not changing the script is waiting and using no system
resources.
Error Basic provides a flexible error handling capability with the On Error command. The CIMPLICITY
Handling extensions to Basic are designed to use the built in error handling capability. When an error occurs while
executing your CIMPLICITY command, a Basic Run Time error is generated. There are many ways you
can implement error handling. Among these are :
• No error handling. When an error occurs, the script's execution halts and the error is reported
(in the Program Editor, this is via a Message Box, and in the control engine by logging an error
message to the status log).
• Error Handler. When an error occurs, the script's execution moves to the defined error handler.
Within the error handler, the user can report the error or try to recover.
• In line error checking. When an error occurs, the script's execution continues on the next program
statement. The user can check the err variable to determine if an error occurred.
In the fast_set example above a run time error could be generated on the setting of the ID or the
setting of the value. Since the routine provides no error handling, when an error occurs, the routine exits
and returns to the calling routine. If no error handler is found as the program returns up the call stack,
a default error handler reports the run-time error. If you run the script from the Program Editor, a dialog
box opens, and if it is run from the Basic Control Engine, a Status Log message is created.
Sub inline_errorcheck()
' When an error occurs continue execution at the next statement
on error resume next
PointSet "BAD_POINT", 10
' Did an error occur?
If err <> 0 then
' clear the error
err = 0
Exit Sub
End if
PointSet "BAD_POINT1", 10
if err <> 0 then
err = 0
Exit Sub
end if
End Sub
sub outline_errorcheck()
' When an error occurs goto the error handler
on error goto error_handler
PointSet "BAD_POINT", 10
PointSet "BAD_POINT1", 10
Exit Sub
error_handler:
MsgBox "Error"
Exit Sub
End Sub
Syntax Point.TimeStamp
Description Date. To retrieve the timestamp into a Basic Date Object. The timestamp indicates the time at which the
point's value was read from the PLC.
Example
Sub Main()
Dim x as new Point
a$ = InputBox$("Enter a point id")
x.Id = a$
x.OnChange
top :
x.GetNext
Trace str$(x.TimeStamp) & " " & x.Value
goto top
End Sub
See also Point.Get (page 590) (method); Point.GetNext (page 592) (method).
Syntax Point.TimeStampHR
Description Date. To retrieve the Microsecond timestamp into a string object. The timestamp indicates the time at
which the point's value was read from the PLC.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 612
Example
Sub Main()
Dim x as new Point
a$ = InputBox$("Enter a point id")
x.Id = a$
x.OnChange
top :
x.GetNext
Trace str$(x.TimeStampHR) & " " & x.Value
goto top
End Sub
Syntax Point.UserFlags
Description Long. Returns the value of the 16-bit user defined flags for the point.
Example
Sub Main()
Dim p as new Point
p.Id = "VALVE_1"
p.Get
MsgBox cstr(p.UserFlags)
End Sub
Description To retrieve or set the value in the point object. The optional index may be supplied to access values of
an array point. The first element of the array is at the zero index. The value property uses Engineering
Units conversion if supplied by the point. To bypass Engineering Units conversion, use the RawValue
property.
Automatic conversion will be performed between data types as needed. The only exceptions are String
and BitString points, which can only be assigned from Strings.
Example
' This subroutine show automatic type conversion
Sub Main()
Dim MyPoint as new Point 'Declare the point object
MyPoint.Id = "INTEGER_POINT" 'Set the Id, Point Type is INTEGER
' The string value of "10" is automatically converted to a integer
' value of 10 and place in point object.
MyPoint.Value = "10"
MyPoint.Set ' Write the point
' The floating point value of 10.01 is truncated to 10 and place
' in the point
MyPoint.Value = 10.01
MyPoint.Set ' Write the point
End Sub
See also Point.RawValue (page 602) (property, read/write); Point.GetArray (page 590) (method);
Point.GetRawArray (page 593) (method).
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 613
Notes
• To retrieve the point value, the Point.Get method must be invoked first. Once the value has been
read, it can be accessed many times without having to retrieve it from the Point Manager on each
reference. If the point hasn't been read, an exception is generated.
• When setting a value, the value is not written to the device until the Set method is invoked.
PointGet (function)
Example
' Prompt user for point id, get the point value and display
' it into a message box.
Sub Main()
MsgBox "Value is " & PointGet(InputBox$("Enter Point Id") )
End Sub
Enclose CIMPLICITY Machine Edition array point names (that are passed through CIMPLICITY
Plant Edition Basic) in the the ASCII encoding for single quotes Chr$(39).
CIMPLICITY Machine Edition returns array points as single values using the form name[index].
• Is not enclosed in Chr$(39), BASIC will parse this out as a reference to an array element. You
will receive an error indicating a bad point name.
• Is enclosed in Chr$(39) the point will not be parsed in the PointSet and PointGet BASIC
procedures. The name will be passed straight through to Machine Edition.
Note: You cannot directly put a single quote (') on an argument line because the single quote in
Basic denotes that the remainder of the line is a comment.
Examples
• val = PointGet("MyPointName")
Result
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 614
Result
PointGetMultiple (function)
Description Request data from up to 30 points in a single snapshot request. If the function fails, an error is generated.
Comments If you need to get data from several points, use this function rather than issuing a single PointGet
(CimBasic) command for each point. For the example below, it is six times more efficient to use PointGetMultiple ,
since the data is retrieved from the Point Manager in a single request, rather than six separate PointGet
requests.
Parameter Description
pointn Point objects for which data is going to be requested. Up to 30 may be specified as function
parameters.
Example
Sub Main()
(CimBasic) Dim x As New Point: x.Id = "R1"
Dim x1 As New Point: x1.Id = "R2"
Dim x2 As New Point: x2.Id = "R3"
Dim x3 As New Point: x3.Id = "R4"
Dim x4 As New Point: x4.Id = "R5"
Dim x5 As New Point: x5.Id = "R6"
PointGetMultiple x,x1,x2,x3,x4,x5
End Sub
PointGetMultiple takes an array of Point objects, which is different from CimBasic where CimBasic
functions take variable arguments with each being a Point object. Otherwise .NET and CimBasic behavior
is the same for this function.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 615
Example
using System;
(.NET) using System.Collections.Generic;
using Proficy.CIMPLICITY;
public class PGM
{
public void Main()
{
Point[] array = new Point[3];
using (Point one = new Point(), two = new Point(), three = new Point())
{
one.Id = "PGM_01";
one.OnChange();
two.Id = "PGM_02";
two.OnChange();
three.Id = "PGM_03";
three.OnChange();
array[0] = one;
array[1] = two;
array[2] = three;
try
{
Cimplicity.PointGetMultiple(array);
PointGetNext (function)
Description To return the next point value from a list of points with a timeout.
Positive
Integer
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 616
Point1 is a point object with an outstanding request. Up to 16 points can be specified on the function call.
Alternatively, the user may pass an array of point objects. The function returns the object whose value
changed or empty. Parameter: timeOutMs, pointn, PointArray.
Example
' Trace the values of 2 point as they change or trace timeout if neither
(CimBasic) ' point change in 1 second.
Sub Main()
Dim Point1 as new Point ' Declare Point Object
Dim Point2 as new Point ' Declare Point Object
Point1.Id = "TANK_LEVEL" ' Set the Id
Point2.Id = "TANK_TEMP" ' Set the Id
Point1.OnChange ' Register OnChange request
Point2.OnChange ' Register OnChange request
Dim Result as Point ' Declare result pointer
Top :
' Set result equal to result of waiting on Point1 and Point2
' to change for 1 second
Set Result = PointGetNext(1000, Point1, Point2)
if Result is Nothing then ' Nothing is returned if timeout
Trace "TimeOut"
Else
' Otherwise Result is Point1 or Point2 depending on which one
' changed last.
Trace Result.Id & " " & str$(Result.TimeStamp) & Result.Value
end if
goto top
End Sub
PointGetNext takes an array of Point objects, which is different from CimBasic where CimBasic functions
take variable arguments with each being a Point object. Otherwise .NET and CimBasic behavior is the
same for this function.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 617
Example
using System;
(.NET) using System.Collections.Generic;
using Proficy.CIMPLICITY;
public class PGN
{
public void Main()
{
Point[] array = new Point[3];
using (Point one = new Point(), two = new Point(), three = new Point())
{
one.Id = "PGN_1";
one.OnChange();
two.Id = "PGN_2";
two.OnChange();
three.Id = "PGN_3";
three.OnChange();
array[0] = one;
array[1] = two;
array[2] = three;
try
{
Point result;
do
{
result = Cimplicity.PointGetNext(30000, array);
if (result != null)
{
Cimplicity.Trace("Point that changed is " + result.Id);
}
} while (result != null);
}
catch (Exception x)
{
Cimplicity.Trace("Failure: " + x.Message);
}
finally
{
Cimplicity.Trace("No more changes after 30 seconds");
}
}
}
}
PointSet (statement)
Example
Sub Main()
PointSet InputBox$("Point Id:"), InputBox$("Value:")
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 618
Enclose CIMPLICITY Machine Edition array point names (that are passed through CIMPLICITY
Plant Edition Basic) in the the ASCII encoding for single quotes Chr$(39).
CIMPLICITY Machine Edition returns array points as single values using the form name[index].
• Is not enclosed in Chr$(39), BASIC will parse this out as a reference to an array element. You
will receive an error indicating a bad point name.
• Is enclosed in Chr$(39) the point will not be parsed in the PointSet and PointGet BASIC
procedures. The name will be passed straight through to Machine Edition.
Note: You cannot directly put a single quote (') on an argument line because the single quote in
Basic denotes that the remainder of the line is a comment.
Examples
Result
Result
PointSet sets the element with the index 10 of the Machine Edition array point
MEArrayPointName to the value of val.
Important: This syntax will not work for Plant Edition array points.
Result
PointSet sets the element with the index 10 of the Plant Edition array point PEArrayPointName to
the value of val
PointSetMultiple (function)
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 619
Description Performs setpoints for up to 30 points in a single setpoint request. If a failure occurs the function returns
false, otherwise true is returned.
Comments If you need to set the value of multiple points, use this function rather than issuing multiple single setpoint
requests for faster script execution. The point ErrCode property will be set to a non-zero value for a
setpoint that failed. The point ErrMsg property will contain the associated error message.
There are two variants of PointSetMultiple. The first variant takes all the points declared in the argument
list. The second variant takes an array.
Example 1
This example in Basic demonstrates both variants, argument list and array.
Sub Main()
Dim status As Boolean
Dim sp1 As New Point: sp1.Id = "SP1"
Dim sp2 As New Point: sp2.Id = "SP2"
Dim sp3 As New Point: sp3.Id = "SP3"
Dim sp4 As New Point: sp4.Id = "SP4"
sp1.Value = 1
sp2.Value = 2
sp3.Value = 3
sp4.Value = 4
status = PointSetMultiple(sp1,sp2,sp3,sp4)
If status = False Then
If sp1.ErrCode <> 0 Then
MsgBox sp1.ErrMsg
End If
End If
’r; Using an array
Dim points(1 To 4) As Point
Set points(1) = sp1
Set points(2) = sp2
Set points(3) = sp3
Set points(4) = sp4
status = PointSetMultiple(points)
End Sub
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 620
PointSetMultipleEx (function)
Description Performs setpoints for up to 30 points in a single setpoint request, using the provided setpoint password.
If a failure occurs the function returns false, otherwise true is returned.
Comments If you need to set the value of multiple points, use this function rather than issuing multiple single setpoint
requests for faster script execution. The point ErrCode property will be set to a non-zero value for a
setpoint that failed. The point ErrMsg property will contain the associated error message.
There are two variants of PointSetMultiple. The first variant takes all the points declared in the argument
list. The second variant takes an array.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 621
Example 1 This example in Basic demonstrates both variants, argument list and array.
Sub Main()
Dim status As Boolean
Dim pwd As String
pwd = "mypassword"
Dim sp1 As New Point: sp1.Id = "SP1"
Dim sp2 As New Point: sp2.Id = "SP2"
Dim sp3 As New Point: sp3.Id = "SP3"
Dim sp4 As New Point: sp4.Id = "SP4"
sp1.Value = 1
sp2.Value = 2
sp3.Value = 3
sp4.Value = 4
status = PointSetMultipleEx(pwd,sp1,sp2,sp3,sp4)
If status = False Then
If sp1.ErrCode <> 0 Then
MsgBox sp1.ErrMsg
End If
End If
’r; Using an array
Dim points(1 To 4) As Point
Set points(1) = sp1
Set points(2) = sp2
Set points(3) = sp3
Set points(4) = sp4
status = PointSetMultipleEx(pwd,points)
End Sub
Error
Message Point.ErrCode
Integer value containing the error code for a failed call to PointSetMulitple or PointSetMultipleEx, or zero
for a successful operation.
Point.ErrMsg
String value containing the error message for a failed call to PointSetMulitple or PointSetMultipleEx, or
empty string for a successful operation
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 622
SetTimecomponentsHR (function)
Description Given components of the time. Current time divided into time components of year, month, day, hour, min,
sec and nanoseconds.
Example
Sub OnMouseUp(x As Long, y As Long, flags As Long)
'Declare variables
Dim yy As Integer
Dim mm As Integer
Dim dd As Integer
Dim hh As Integer
Dim min As Integer
Dim sec As Integer
Dim nano As Long
Dim qlow As Double
Dim qhigh As Double
'Initialize Objects
yy = 2011
mm = 7
dd = 13
min = 43
sec = 10
nano = 0
SetTimeFromComponentsHR qhigh,qlow,yy,mm,dd,hh,min,sec,nano
MsgBox qhigh
MsgBox qlow
End Sub
QINTFromString (function)
Description To convert one numeric string into QINT , split it’s value into 2 doubles and return them.
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 623
Param1 String.
Example
Sub Main()
Dim qlow as Double
Dim qhigh as Double
Dim qstr as String
Dim MyPoint as new Point ' Declare the point object
MyPoint.Id = "QINT" ' Set the point id
qstr = "1000000899876543212"
QINTFromString qstr,qhigh1,qlow1
ret = MyPoint.SetQuadIntValue(qhigh,qlow)
End Sub
StringFromQINT (function)
Description To convert two doubles into one signed 64-bit value and finally to a string
Param1 String.
Param2 Double.
Param3 Double.
Example
Sub Main()
Dim qlow as Double
Dim qhigh as Double
Dim qstr as String
Dim MyPoint as new Point ' Declare the point object
MyPoint.Id = "QINT" ' Set the point id
ret = MyPoint.GetQuadIntValue(qhigh,qlow)
qstr = StringFromQINT(qhigh,qlow) 'Get the value as
‘string from two doubles qhigh and
‘qlow
End Sub
StringFromUQINT (function)
Description To convert two doubles into one signed 64-bit value and finally to a string
Basic Control Engine and Scripting Reference | 3 - Basic Control Engine Language Reference | 624
Param1 String.
Param2 Double.
Param3 Double.
Example
Sub Main()
Dim qlow as Double
Dim qhigh as Double
Dim qstr as String
Dim MyPoint as new Point ' Declare the point object
MyPoint.Id = "QINT" ' Set the point id
ret = MyPoint.GetUQuadIntValue(qhigh,qlow)
qstr = StringFromUQINT(qhigh,qlow) 'Get the value as
‘string from two doubles qhigh and
‘qlow
End Sub
Trace (statement)
Syntax Trace a$
Description Traces (prints) a string to the trace output. By default, when running in the Program Editor, tracing will be
output to the trace window. When running from the Event Manager, tracing must be specifically enabled
(TraceEnable) in order for tracing to occur.
Example
Sub Main()
Dim x as new Point
a$ = InputBox$("Enter a point id")
x.Id = a$
x.OnChange
top :
x.GetNext
Trace str$(x.TimeStamp) & " " & x.Value
goto top
End Sub
TraceEnable/TraceDisable (statement)
Description TraceEnable enables tracing to a file. The file will be located in your project's log directory. Tracing to a
file is only supported from the event manager. The trace output will be written to the log directory. Tracing
has a performance impact since the file is opened and closed for each write. Tracing is intended for debug
use only and should be removed from production code.
Example
Sub Main()
if PointSet("TRACE_TRIGGER") = TRUE then
TraceEnable "MY_LOG"
end if
Trace "Trace Message 1"
Trace "Trace Message 2"
TraceDisable
End Sub
UQINTFromString (function)
Description To convert one numeric string into UQINT , take a positive value with the highest value that can be taken
by ULONGLONG and return it.
Param1 String.
Example
Sub Main()
Dim qlow as Double
Dim qhigh as Double
Dim qstr as String
Dim MyPoint as new Point ' Declare the point object
MyPoint.Id = "QINT" ' Set the point id
qstr = "1000000899876543212"
UQINTFromString qstr,qhigh1,qlow1
ret = MyPoint.SetQuadIntValue(qhigh,qlow)
End Sub
The BCEUI window displays the status of actions triggered by events that are currently being
monitored by BCEUI. You can use the Paused option to display this list in dynamic or paused mode.
• In dynamic mode, the list is automatically refreshed as events occur or change status.
• In paused mode, the list remains fixed until you update it. To update the list, you can select
Refresh from the View menu, or press F5.
• Actions for all running projects that BCEUI is connected to are displayed in black.
• If BCEUI is connected to a CIMPLICITY project and monitoring events, and the project stops:
• All events for the project are grayed out in the Properties dialog box.
• Triggering is disabled for events in the stopped project.
• A $Disconnected event displays in the main window with a message telling you which project is
stopped. This event runs and tries to reconnect to the project until either the project starts or you
close your BCEUI session.
• All unfinished actions in the main window are grayed out to indicate that their current status is
unknown.
• When a CIMPLICITY project that BCEUI is attempting to connect to restarts, grayed actions
are redisplayed in black and refreshed to their current status.
1. Select Project>Basic Control Engine>BCE User Interface in the Workbench left pane.
Either Or
BCEUI Menus
BCEUI Menus
Basic Control Engine and Scripting Reference | 4 - Basic Control Engine User Interface | 628
You can use the menu options to save and restore event monitoring configurations, add or list events,
pause, stop or resume scripts, trigger events, pause and resume dynamic updates, refresh the display
and access Help.
Events menu
Scripts menu
View menu
Help menu
Open Opens an existing BCEUI document in your currently active BCEUI window.
Save Saves the current BCEUI document to a file. Use this option if you want to specify the pathname of the
As… saved file.
Recent Displays a list of recently opened BCEUI document files for easy retrieval.
File
Add Opens the Select an Event browser, from which you can connect to a project and select events to add to the list
of monitored events.
Stop Stops any currently selected scripts that are paused or running.
Clear Finished Actions Clears finished actions from the event list.
About BCEUI Displays the program identification, version number and copyright for the BCEUI.
Basic Control Engine and Scripting Reference | 4 - Basic Control Engine User Interface | 630
BCEUI Toolbar
You can use the Toolbar option on the View menu to turn on and off the display of the BCEUI
Toolbar. You can fix the Toolbar in the BCEUI window or display it in a separate window at your
discretion.
Event List Opens the Properties dialog box, from which you can add, delete or trigger events.
Add Events Opens the Select an Event browser, from which you can connect to a project and select events
to add to the list of monitored events.
Stop Scripts Stops any currently selected scripts that are paused or running.
About Displays the program identification, version number and copyright for the BCEUI.
The following are the more commonly used keystrokes that are available for your use in the BCEUI:
Ctrl+N Creates a new BCEUI view.
BCEUI Viewer
BCEUI Viewer
• Use the Select an Event browser to connect to a project and select events to add to the BCEUI
event list.
• Use the Properties dialog box to list monitored events, add or remove events from the view, and
trigger events manually.
After you create a BCEUI view, you can select script actions and pause, resume, or stop the scripts.
Once you create a BCEUI view, you can save it. You can recall saved views at any time.
1 Select events.
(page
632)
3 Connect to a project.
(page
633)
4 Select events.
(page
633)
9 Trigger events.
(page
635)
When you select Add from the Events menu or click the Add Events button on the Toolbar, the
Select an Event browser opens.
After you select events and click OK, the Properties dialog box automatically opens so that you can
add the selected events to your view. If you click Cancel, the Select an Event browser closes and the
main BCEUI window is redisplayed.
By default, the Auto Browse option is disabled. If you enable the Auto Browse option, whenever you
open the Select a Event dialog box, the events for the first project in the Project list are automatically
displayed in the list window.
Basic Control Engine and Scripting Reference | 4 - Basic Control Engine User Interface | 633
If Auto Browse is enabled, a check mark is displayed to its left in the View menu.
3. Connect to a Project
1. Click the drop-down list button to the right of the Project field to see the list of currently
available projects.
2. Select a project from the list.
3. Click Browse to see the list of events available for the project.
4. Select Events
1. Highlight the events you want to select. You may use the Shift and Ctrl keys when selecting
multiple events.
2. Click OK to transfer your selection to the BCEUI event list and close the Select an Event
browser.
• Triggering is enabled only for events in connected projects that are running.
• All events for projects that are running and BCEUI is connected to are displayed in black.
• Events in the list that belong to projects that are not currently running or that become
disconnected are grayed out.
• When you add events for a new project, they are grayed out in the Properties dialog box because
BCEUI has not connected to the project yet.
• The first time you select an event for a newly selected project, then select Apply, BCEUI
connects to the project. When the connection completes successfully, all the events for the
project are displayed in black.
• You can select events for projects that are not currently running or that are disconnected. When
the project starts, BCEUI will automatically connect with the project and start monitoring the
events.
The default maximum number of completed actions that the BCEUI window can display is 100. You
can choose less or more than this number. Once the list reaches its maximum, the oldest completed
action is removed when the newest one is added.
Basic Control Engine and Scripting Reference | 4 - Basic Control Engine User Interface | 635
1. Select the events you want to monitor from the list of events in the Select an Event browser.
You can use the Shift and Ctrl keys to select multiple events.
2. Click Apply to add the events to the view and keep the Properties dialog box open, or click OK
to add the events to the view and close the Properties dialog box.
1. Select the events in the list that you want to remove. You can use the Shift and Ctrl keys to
select multiple events. You can also click Select All to select all events in the list.
2. Click Delete.
The events you select are removed from the BCEUI window and the Properties dialog box.
They will not appear again in Properties dialog box until you add them in the Select a Event
browser, and they will not be monitored again in the BCEUI window until you select them for
viewing in the Properties dialog box.
9. Trigger Events
Your role must have the Trigger Event privilege enabled for you to be able to trigger events for a
particular project.
1. Select the events in the list that you want to trigger. You can use the Shift and Ctrl keys to
select multiple events. You can also click Select All to select all events in the list.
2. Click Trigger.
The Confirm Trigger Action message box opens and displays the first event to trigger.
Note: If you click Yes or No and you are triggering multiple events, you are automatically
prompted to confirm the next trigger action.
The statuses of the events you trigger are displayed in the BCEUI window.
Control Scripts
Control Scripts
Your role must have the Script Control privilege enabled for you to be able to pause, resume and stop
scripts in the BCEUI window in specific projects.
Pause Scripts
1. Select the actions whose scripts you want to pause in the BCEUI window. You can use the Shift
and Ctrl keys to select multiple actions.
You may safely select multiple scripts, even if some of the scripts you select cannot be paused
(such as stopped scripts or scripts that are already paused). Such scripts will not be affected by
the Pause Scripts request.
Note: If you click Yes or No and you are pausing multiple scripts, you are automatically
prompted to confirm the next script in the list.
Resume Scripts
1. Select the actions whose scripts you want to resume in the BCEUI window. You can use the
Shift and Ctrl keys to select multiple actions.
Note: If you click Yes or No and you are resuming multiple scripts, you are automatically
prompted to confirm the next script in the list.
Basic Control Engine and Scripting Reference | 4 - Basic Control Engine User Interface | 638
Stop Scripts
1. Select the actions whose scripts you want to stop in the BCEUI window. You can use the Shift
and Ctrl keys to select multiple actions.
Note: If you click Yes or No and you are stopping multiple scripts, you are automatically
prompted to confirm the next script in the list.
The status of the scripts for the events you select changes from Paused or Running to Stopped and
the message field for each stopped script displays the line number where the script was stopped.
Note: Once you stop a script, you cannot restart it with the Resume command.
Chapter 5. Event Editor
An event can be defined as a changing point or alarm state, or even a time of day.
At run-time, the Basic Control Engine monitors for events and executes the configured actions.
The Basic Control Engine is based on a multi-threaded design, which allows the system to invoke
and execute multiple Basic Control Engine scripts concurrently.
The order of execution of event actions is a sequential execution from top to bottom.
Note: The script is run in parallel with all actions that are being executed for the event. In other
words, the Basic Control Engine does not wait for the script to complete before it initiates the next
action defined for the event.
Point Actions Based on Alarm Events Allow a physical indication of an alarm, such as activating a light on
a control panel.
Events Whose Actions Call A User-Defined Defines custom functions that are invoked in response to configured
Routine or Script system events.
Note: The Basic Control Engine calls a startup script when the Event Manager starts up and
a termination script when it shuts down. These scripts are initially null (that is, they do not do
Basic Control Engine and Scripting Reference | 5 - Event Editor | 640
anything). You can use these scripts to perform initialization and termination tasks, such as restoring
and saving the value of a global variable. The two scripts are:
• EM_INIT.BCL
• EM_TERM.BCL
You will find copies of these scripts in your project's \scripts directory.
Step 6 Copy, filter, select display fields for events and actions.
(page
672)
Either Or
Either Or
You can use the menu options to create new events and actions, modify, delete or copy selected
events and actions, reorder the actions for an event, display the attributes for an event or action,
toggle dynamic updates, and access Help.
• File menu
• Edit menu
• View menu
• Tools menu
• Help menu
File menu
New Event... Left Event Creates a new Event. This option is displayed if the Event pane is active.
(page
646)
New Right Event Creates a new action for the currently selected Event. This option is displayed
Event_Action... (page if the Event pane is active, and you have clicked the mouse once in the Action
671) pane.
New Action... Left Action Creates a new Action. This option is displayed if the Action pane is active.
(page
659)
Edit Menu
1 An event is selected.
2 An action is selected.
Modify Event Opens the Modify Event dialog box, and lets you change the Event Type and associated fields.
Modify Action Opens the Modify Action dialog box, and lets you change the Action Type and associated fields.
Delete Event Deletes the selected Event from the list of available Events
Delete Event- Removes the selected Action from the list of Actions for the selected Event.
Action
Delete Action Deletes the Action. This function will remove the Action from all Events that use it and remove it from
the list of available Actions.
Copy Event Copies the selected Event to a new Event. You can also choose to copy the Actions.
Move Up While viewing Event-Actions, controls the execution order of the selected Action by moving it up in the
list of Actions for the Event.
Move Down While viewing Event-Actions, controls the execution order of the selected Action by moving it down in
the list of Actions for the Event.
Alarm Filter Opens the Alarm Setup dialog box and lets you set the filter for the alarms the Event Manager will
respond to.
Note: Scripts run a-synchronously, so their order in the list does not guarantee their order of
execution. Other actions, like Setpoint , can be ordered.
View menu
Basic Control Engine and Scripting Reference | 5 - Event Editor | 644
1 An event is selected.
2 An action is selected.
Search If you are displaying By Event, opens the Event Search dialog box. If you are displaying By Action,
opens the Action Search dialog box.
Event If you are displaying By Event, opens the Configure Display Attributes dialog box for Events, and lets you
Attributes... select Event attributes to display in the window.
Action If you are displaying By Action, opens the Configure Display Attributes dialog box for Actions, and lets
Attributes... you select Action attributes to display in the window.
All Actions Displays all Actions in the Action pane. You can then select Actions and drag them into an Event.
Tools menu
Dynamic Enables or disables Dynamic Configuration of points, alarms, etc., when configuring Events or Actions.
Update Dynamically updates the Basic Control Engine with the current Event configuration and scripts used by the
Actions in the configuration. The Basic Control Engine normally loads and compiles your scripts at project
startup. If you modify a script and save it to disk while your project is running, the Basic Control Engine will
not load the modified script until you perform an Update or the until project is stopped and restarted.
Help menu
Index Displays the main Help window for the Event Editor.
Basic Control Engine and Scripting Reference | 5 - Event Editor | 645
Using Help Displays the main Help window for Windows operating system.
About Eventmgr Cfg... Displays the program identification, version number, and copyright for the Event Editor.
2 Action is selected
F Attributes Opens the Field Chooser dialog box for events or actions.
J Action order up Moves the selected action up in the list for an event.
K Action order down Moves the selected action down in the list for an event.
The following are the more commonly used keystrokes that are available for your use in the Event
Editor:
Keystroke Description
Method 1
Method 2
a. Right-click the Event Editor left pane.
b. Select New Event on the popup menu.
Method 3
Select New Event on the Event Editor File menu (page 642).
Method 4
Note: The event ID can be a maximum of 256 characters and mixed case.
5. Click OK.
Basic Control Engine and Scripting Reference | 5 - Event Editor | 648
Events are:
• Alarm Acknowledged
• Alarm Deleted
• Alarm Generated
• Alarm Reset
• Point Change
• Point Equals
• Point Transition High
• Point Transition Low
• Point Unavailable
• Point Update
• Run Once
• Timed
Note: You can modify these fields in the Modify Event (page 673) dialog box.
The dialog box closes and the new event appears in the Event list in the CIMPLICITY Event Editor
window.
An Alarm Acknowledged Event occurs when the alarm identified in the Alarm ID field for the
Event is acknowledged.
Field Description
Alarm ID ID of an alarm or wild card to specify a group of alarms that will trigger this event when the alarm is
acknowledged.
Displays popup menu to create a new alarm, browse for or edit an existing alarm
Displays popup menu to create a new resource, browse for or edit an existing resource.
Class ID Alarm classification that will evaluate this event. Note: This field is unavailable if an Alarm ID is selected
Displays popup menu to create a new alarm class, browse for or edit an existing alarm class.
An Alarm Deleted Event occurs when the alarm identified in the Alarm ID field for the Event is
deleted.
Basic Control Engine and Scripting Reference | 5 - Event Editor | 650
Field Description
Alarm ID ID of an alarm or wild card to specify a group of alarms that will trigger this event when the alarm is deleted.
Displays popup menu to create a new alarm, browse for or edit an existing alarm
Displays popup menu to create a new resource, browse for or edit an existing resource.
Class ID Alarm classification that will evaluate this event. Note: This field is unavailable if an Alarm ID is selected
Displays popup menu to create a new alarm class, browse for or edit an existing alarm class.
An Alarm Generated Event occurs when the alarm identified in the Alarm ID field for the Event
is generated.
Basic Control Engine and Scripting Reference | 5 - Event Editor | 651
Field Description
Alarm ID ID of an alarm or wild card to specify a group of alarms that will trigger this event when the alarm is
generated.
Displays popup menu to create a new alarm, browse for or edit an existing alarm
Displays popup menu to create a new resource, browse for or edit an existing resource.
Class ID Alarm classification that will evaluate this event. Note: This field is unavailable if an Alarm ID is selected
Displays popup menu to create a new alarm class, browse for or edit an existing alarm class.
Note: All alarm events allow wild cards for pattern matching. Valid wild cards are * and ?. In
the above example, the event "Alarm" will occur whenever a HIGH Class alarm occurs.
An Alarm Reset Event occurs when the alarm identified in the Alarm ID field for the Event is
reset.
Basic Control Engine and Scripting Reference | 5 - Event Editor | 652
Field Description
Alarm ID ID of an alarm or wild card to specify a group of alarms that will trigger this event when the alarm is reset.
Displays Popup menu to create a new alarm, browse for or edit an existing alarm
Displays Popup menu to create a new resource, browse for or edit an existing resource.
Class ID Alarm classification that will evaluate this event. Note: This field is unavailable if an Alarm ID is selected
Displays Popup menu to create a new alarm class, browse for or edit an existing alarm class.
A Point Change Event occurs when value of the point identified in the Point ID changes.
Basic Control Engine and Scripting Reference | 5 - Event Editor | 653
Note: Point value changes to and from the unavailable value are not Point Change events. Use
the Point Update (page 656) event to detect these changes.
Field Description
Point ID ID of a point that will trigger this event when the point value changes.
Displays Popup menu to create a new alarm, browse for or edit an existing alarm
A Point Equals Event occurs when value of the point identified in the Point ID field equals the
value in the Value field.
Field Description
Point ID ID of a point that will trigger this event when the value equals the value in the Value field.
Displays Popup menu to create a new point, browse for or edit an existing point.
A Point Transition High Event occurs when value of the Digital type point identified in the Point
ID field transitions to HIGH (that is, it changes value from 0 to 1).
The code explicitly runs the action for transition high (or transition low events) if the value was
unavailable.
Field Description
Point ID ID of a point that will trigger this event when the point value transitions to HIGH. If
the point is an array point, you can specify the element that will trigger this event.
To specify an element, append the index in brackets at the end of the Point ID (for
example, ARRAY_PT[3]). If you do not specify the element for an array point, the first
element is assumed.
Displays Popup menu to create a new point, browse for or edit an existing point.
A Point Transition Low Event occurs when value of the Digital type point identified in the Point
ID field transitions to LOW (that is, it changes value from 1 to 0).
Basic Control Engine and Scripting Reference | 5 - Event Editor | 655
The code explicitly runs the action (for transition high or) transition low events if the value was
unavailable.
Field Description
Point ID ID of a point that will trigger this event when the point value transitions to LOW. If
the point is an array point, you can specify the element that will trigger this event.
To specify an element, append the index in brackets at the end of the Point ID (for
example, ARRAY_PT[3]). If you do not specify the element for an array point, the first
element is assumed.
Displays Popup menu to create a new point, browse for or edit an existing point.
A Point Unavailable Event occurs when value of the point identified in the Point ID field
becomes unavailable.
Field Description
Basic Control Engine and Scripting Reference | 5 - Event Editor | 656
Point ID ID of a point that will trigger this event when the point becomes unavailable.
Displays Popup menu to create a new point, browse for or edit an existing point.
A Point Update Event occurs when value of the point identified in the Point ID field is updated.
The rate at which the point is updated is a function of its Update criteria, which will be one of the
following:
Update Criteria The point is updated:
On Demand On Scan The point is updated at each scan interval while it is being requested by a CIMPLICITY
process.
On Demand On When its value changes while it is being requested by a CIMPLICITY process.
Change
Field Description
Point ID ID of a point that will trigger this event when the point value updates.
Displays Popup menu to create a new point, browse for or edit an existing point.
Note: Point value changes to and from the unavailable value are also Point Update (page 656)
events.
Run Once
The Event Type, Run Once , is invoked once when the Event Manager starts.
Field Description
Timed Events
The various options in the Advanced section in the New Event dialog box are as follows.
Basic Control Engine and Scripting Reference | 5 - Event Editor | 658
Option Description
Script In Parallel Runs a script each time an event is invoked. More than one copy of the script may run at a
Execution time. You must use critical sections to control access to resources.
The maximum number of scripts that run in parallel is undefined. Thus, several threads are
created to execute the scripts in parallel, thereby requiring more computing resources.
In the
thread Runs the script in threads from a thread pool. The thread pool is created when the EMRP
pool process starts.
The scripts also run in parallel, but the number of threads is limited to the size of the thread
pool. For details on the thread pool size and how to configure it, see Running a script in
parallel (in the thread pool).
In
Sequence (Default) When an event is triggered, if an existing instance of the event is still executing, the
script will be queued to start after the current script is done.
The maximum number of script actions that can run simultaneously is CE_MAX_THREADS
+ CE_POOL_THREADS.
Maximum If the option In sequence is selected, you must specify a maximum queue size. In this case, when more
Queue than 20 events are queued, the oldest will be discarded.
Generate (Default) If the sequential queue overflows, select this check box to generate an $EM_QUEUE alarm.
Alarm on
Overflow If your event is an alarm event, generating an alarm may cause your event to trigger again and generate
another alarm. This will cause a circular cycle of alarms.
Log (Default) If the sequential queue overflows, check to generate a message in the status log.
Error on
Overflow
Basic Control Engine and Scripting Reference | 5 - Event Editor | 659
Method 1
Method 2
a. Right-click the Event Editor left pane.
b. Select New Action on the popup menu.
Method 3
Select New Acton on the Event Editor File menu (page 642).
Method 4
Note: The action ID can be a maximum of 256 characters and mixed case.
Basic Control Engine and Scripting Reference | 5 - Event Editor | 660
5. Enter the name of the new Action in the Action ID field and click OK.
Log Only
Recipe Upload/Download
Run Script
Set Point
Transition Set
The dialog box closes and the new action appears in the Action list in the CIMPLICITY Event Editor
window.
Note: You can modify these fields in the Modify Action (page 674) dialog box.
Basic Control Engine and Scripting Reference | 5 - Event Editor | 661
(Required) enter the name of the CIMPLICITY Alarm ID for which the action will be taken.
Important: When you create the Alarm ID in the Alarm Definition dialog box, you must:
A Log Only action logs the associated Event in the Database Logger Event Log. No other action is
taken.
A Point Alarm Acknowledge action acknowledges the alarm defined by the Alarm ID and
Resource ID.
To create this Action, enter the following information in the New Action dialog box:
1 Alarm ID
(page
662)
2 Resource
(page
662)
1 Alarm ID
ID of an alarm to be acknowledged.
Popup Menu button Displays Popup menu to create a new alarm, browse for or edit an existing alarm
2 Resource
Note: This field is automatically filled in, when an Alarm ID is entered, with the resource
assigned to the alarm.
Popup Menu button Displays Popup menu to create a new resource, browse for or edit an existing resource.
A Point Alarm Disable action disables alarming for the point in the Point ID field.
To create this Action, enter the following information in the New Action dialog box:
Point ID
Basic Control Engine and Scripting Reference | 5 - Event Editor | 663
Popup Menu button Displays Popup menu to create a new point, browse for or edit an existing point.
A Point Alarm Enable action enables alarming for the point in the Point ID field.
To create this Action, enter the following information in the New Action dialog box:
Point ID
Popup Menu button Displays Popup menu to create a new point, browse for or edit an existing point.
Recipe Upload/Download
A Recipe Upload/Download action uploads or downloads the recipe defined by a selected parameter
file.
To create this Action, enter the following information in the New Action dialog box:
Basic Control Engine and Scripting Reference | 5 - Event Editor | 664
Parameter file
Popup Menu Displays a Popup menu to create a new automatic action Recipe file, browse for or edit an
button existing automatic action Recipe file.
The selected script name cannot exceed 48 characters. If you try to select an action with a name
longer than 48 characters CIMPLICITY will not allow you to use it.
A Run Script action executes a selected script. Event Manager supports the following types of
scripts:
• Basic Script
• C# Script
• Visual Basic .Net Script
• Python Script
The script is run in parallel with all actions that are being executed for the event. In other words,
the Basic Control Engine does not wait for the script to complete before it initiates the next action
defined for the event.
Basic Control Engine and Scripting Reference | 5 - Event Editor | 665
3. Select OK.
2. Select New.
When the event to which the script is added occurs, the script gets executed. You can view the status
of the script execution in the BCE User Interface.
Note: The selected script name cannot have more than 48 characters. If you try to select a script
with a name longer than 48 characters CIMPLICITY will display an error message and will not allow
Important: The Basic Control Engine loads and compiles your scripts when your project starts
up. If you modify a script and save it to disk while your project is running you need to do either of
the following to make the Basic Control Engine load the modified script.
Method 1
Select Update.
Method 2
• In sequence
• In parallel (includes thread pool)
To configure an event with the type of script execution, see Step 3.2. Enter Advanced Event
Specifications (page 657).
Running a script in parallel vs. in sequence
You can run scripts in parallel if they wait on Input/Output (I/O) operations for extended periods of
time. This will support running more threads.
Basic Control Engine and Scripting Reference | 5 - Event Editor | 667
You can run scripts in sequence if they interact with an external system that cannot perform multiple
operations in parallel.
The set of threads used to run scripts in parallel or in sequence are managed by a common thread
manager. The CE_MAX_THREADS global parameter controls the maximum number of threads the
thread manager will use to run scripts, and decides when and if the script will be run.
• If there are fewer than CE_MAX_THREADS scripts currently running in parallel, the script
will be run immediately.
• If there are CE_MAX_THREADS or more scripts running in parallel, the script is discarded and
a Too many executing threads, action ignored message is logged to the status log.
• If there is another script running in sequence for a configured event and there are fewer actions
queued than the maximum queue size of the configured event, the script is queued.
• If there is no other script running in sequence for a configured event and there are fewer than
CE_MAX_THREADS scripts currently running in sequence, the script is run immediately.
• If as many actions as the maximum queue size of the configured event are queued, the script
running in sequence is discarded and an alarm is generated and/or a message is logged to the
status log depending on the configuration of the event.
• If there is no other script running in sequence for a configured event and there are
CE_MAX_THREADS or more scripts currently running in sequence, the script is discarded and
a Too many executing threads, action ignored message is logged to the status log.
You can run a CPU-intensive script in parallel in a set of threads managed by a thread pool. The
thread pool should be sized so that there is one thread per logical processor in the system. This helps
minimize the time spent in switching CPU cores.
Note: For cores that support hyperthreading, the number of logical processors is twice the
number of cores. For cores that do not support hyperthreading, the number of logical processors is
equal to the number of cores.
The CE_POOL_THREADS global parameter controls the maximum size of the thread pool, and also
decides when the script will be run.
• If there are fewer than CE_POOL_THREADS scripts currently running, the script will be run
immediately.
• If there are CE_POOL_THREADS or more scripts running, the script is queued.
• In the Setup dialog box, select the Set thread pool size to option, and enter a number.
Notes
• The thread pool size ranges between 0 and 200, and when calculated automatically will be twice
the number of logical processors in the system. When the size is set to 0, its size is automatically
calculated.
• CE_MAX_THREADS should be set to the expected number of simultaneous events. The
actions of the surplus events triggered will be ignored.
• The maximum number of script actions that can run simultaneously is CE_MAX_THREADS +
CE_POOL_THREADS.
• BCL and .NET scripts share the same set of threads.
• When a script is started, it can run in any available thread.
• The CE_THREAD_TIMEOUT global parameter controls the number of seconds a thread
managed for parallel and sequential events will be idle before it is freed. This period should be
long enough so that regularly executed events do not need to create threads, but short enough
so that infrequent events do not cause the event manager to consume an abnormal amount of
memory for extended periods of time.
• The CE_MIN_STANDBY_THREAD_COUNT global parameter controls the
number of threads allowed by the event manager to be idle indefinitely. Threads
that are idle for CE_THREAD_TIMEOUT seconds will not be freed if there are
CE_MIN_STANDBY_THREAD_COUNT or fewer threads in the idle state.
The following table provides the differences between BCL and .NET variables:
Lifetime of Multi-
Variable Scope of variable Shared
variable value threading issues
BCL public Global, visible to all script files Forever, across event Yes Yes
(modules) instances
BCL private Visible only to this script file Forever, across event Yes Yes
(module) instances
.NET class Visible only to this script file Forever, across event Yes Yes
static (AppDomain) instances
.NET class Visible only to this script file Forever, across event No No
instance (AppDomain) instances
• Scope of variable - Denotes the visibility of the variable to other script files, such as modules
and AppDomains.
Basic Control Engine and Scripting Reference | 5 - Event Editor | 669
• Lifetime of variable value - Denotes how long the value of a variable will last.
• Shared - Denotes if two or more event instances will share the value of the variable.
• Multi-threading issues - Denotes if multi-threading issues occur when multiple instances run at
the same time.
To create this Action, enter the following information in the New Action dialog box:
1 Point ID
Popup Menu button Displays Popup menu to create a new point, browse for or edit an existing point.
2 Value
A Source Transition Set action sets the value of the point in the Point ID field to the value of the
point in the Source field.
To create this Action, enter the following information in the New Action dialog box:
Basic Control Engine and Scripting Reference | 5 - Event Editor | 670
1 Point ID
Popup Menu button Displays Popup menu to create a new point, browse for or edit an existing point.
2 Source
Note: If the source point is the same as the point that triggered the event, the old value of the
source point will be copied to the point ID. This lets you save a point value before it is updated. If
you want to copy the new value of the point, use the Transition Set (page 670) action.
A Transition Set action sets the value of the point in the Point ID to the value of the point in the
Point ID field of the Event associated with this Action.
To create this Action, enter the following information in the New Action dialog box
Point ID
Basic Control Engine and Scripting Reference | 5 - Event Editor | 671
ID of a point that will be updated with the value of an associated event's point ID. Valid entries are
either a device or global point ID
Popup Menu button Displays Popup menu to create a new point, browse for or edit an existing point.
1. Make sure you are displaying the Event Editor By Event. (page 643)
4. Do the following.
a. Right-click an event in the right pane.
b. Do one of the following.
• Select New Event Action on the popup menu.
Basic Control Engine and Scripting Reference | 5 - Event Editor | 672
Field Description
Displays popup menu to create a new action, browse for or edit an existing action.
Log Checked Logs the event and action to the Database Logger Event
Flag Management log.
Tip: You can also use the Toggle Logging button on the Event Editor toolbar to enable
or disable logging the selected event and action.
Method 1
Method 2
a. Right-click the selected event.
b. Select Modify Event on the Popup menu.
Basic Control Engine and Scripting Reference | 5 - Event Editor | 674
Method 3
Select Modify Event on the Event Editor Edit menu (page 643).
Method 4
A Modify Event dialog box opens with the configuration for the selected event.
3. Change any of the fields as you did when you created (page 646) the event.
Method 1
Method 2
a. Right-click the selected action.
b. Select Modify Action on the popup menu.
Method 3
Select Modify Acton on the Event Editor Edit menu (page 643).
Method 4
A Modify Action dialog box opens with the configuration for the selected event.
3. Change any of the fields as you did when you created (page 659) the action.
Method 1
Method 2
a. Right-click the selected event.
b. Select Copy Event on the popup menu.
Method 3
Select Copy Event on the Event Editor Edit menu (page 643) .
Method 4
Selection Description
To Name of the event to which the selected event's configuration will be copied.
Add the associated Checked Copies all actions associated with the source event to the target
actions? event.
Unchecked Copies only the event configuration; does not copy associated
actions.
Basic Control Engine and Scripting Reference | 5 - Event Editor | 677
6. Click OK
The dialog box closes and the new Event appears on the Event list.
Method 1
Method 2
a. Right-click the selected action.
b. Select Copy action on the popup menu.
Method 3
Method 4
To Name of the action to which the selected action's configuration will be copied.
Add the associated Checked Copies all events associated with the source action to the target
events? event.
Unchecked Copies only the action configuration; does not copy associated
events..
5. Click OK.
The dialog box closes and the new Action appears on the Action list.
The Alarm Setup dialog box lets you filter the alarms to which the Event Manager will respond.
• Resource ID
• Alarm Class ID.
Basic Control Engine and Scripting Reference | 5 - Event Editor | 679
You can also have the Event Manager respond to either or both;
Important: You must enter information in the Setup (page 680) dialog box in order to receive
alarm and/or event data.
Do one of the following to open the Alarm Setup dialog box. The Setup dialog box opens when you
use any of these methods.
Method 1:
Method 2
Method 3
• Select Alarm Filter on the CIMPLICITY Event Editor Edit (page 643) menu.
• Method 4
• Press Ctrl+F in the CIMPLICITY Event Editor.
Setup Options
Option Description
Resource ID Resource ID for which the Event Manager can receive information.
Alarm Class ID Alarm Class for which the Event Manager can receive information.
Option Description
Cleared The Event Manager will not
receive any Event Log data.
Maximum Concurrent Specifies the maximum number of scripts that can execute concurrently within the Event
Scripts Manager. When this limit is exceeded:
Maximum concurrent
scripts Specifies the maximum number of scripts that can execute concurrently within the Event
Manager.
Automatically calculate Sets the thread pool size to twice the number of logical processors in the system.
thread pool size
If you enter a value that is greater than twice the number of logical processors in the
system, a warning is displayed.
.Net Assembly References Additional .NET assembly references for C# and VB .NET; additional references can be
(page 172) added or removed
Example 1
Enter and select the following to make the Event Manager receive all alarms and events.
A Alarms Check
B Events Check
Basic Control Engine and Scripting Reference | 5 - Event Editor | 683
Example 2
Enter and select the following to make the Event Manager receive only Event data for system
resources.
B Alarms Clear
Events Check
Example 3
C Alarms Check
D Events Check
Basic Control Engine and Scripting Reference | 5 - Event Editor | 684
Method 1
Method 2
a. Click the right mouse button in the Event Editor left pane.
b. Select Field Chooser on the popup menu.
Method 3
Select Field Chooser on the Event Editor View menu (page 643) .
Result: The Field Chooser dialog box for the Event field columns opens.
Feature Description
Lists Available Event fields that are not currently being displayed.
Field
Display Event fields that are currently being displayed. The fields display in columns. Columns go
Fields from left to right, starting at the top of the list and moving down.
Fields Selections correspond to the selections in the Event dialog boxes (page 646).
Buttons Add Add selected available fields to the Display Fields list
Remove Stops displaying selected fields by sending them back to the Available Field list.
Move Up Each click moves a selected field one column to the left. Note: Event ID is always the
farthest left.
Move Each click moves a selected field one column to the right.
Down
Method 1
Method 2
Basic Control Engine and Scripting Reference | 5 - Event Editor | 686
a. Click the right mouse button in the Event Editor left pane.
b. Select Field Chooser on the popup menu.
Method 3
Select Field Chooser on the Event Editor View menu (page 643).
Result: The Field Chooser dialog box for the Action field columns opens.
Feature Description
Lists Available Action fields that are not currently being displayed.
Field
Display Action fields that are currently being displayed. The fields display in columns. Columns go
Fields from left to right, starting at the top of the list and moving down.
Fields Selections correspond to the selections in the Action dialog boxes (page 659).
Buttons Add Add selected available fields to the Display Fields list
Remove Stops displaying selected fields by sending them back to the Available Field list.
Move Up Each click moves a selected field one column to the left. Note: Action ID is always the
farthest left.
Move Each click moves a selected field one column to the right.
Down
Method 1
Method 2
a. Right-click the Event Editor left pane.
b. Select Search on the popup menu.
Basic Control Engine and Scripting Reference | 5 - Event Editor | 688
Method 3
Method 4
Field Description
A Event ID ID or partial ID with a * wild card of the event or events you want to find.
4. Click OK.
Tip: Leave the fields blank in the Event search dialog box to re-display all of the events in the
Event Editor after you have searched for selected events.
Method 1
Method 2
a. Right-click the Event Editor left pane.
b. Select Search on the popup menu.
Method 3
Method 4
Field Description
Basic Control Engine and Scripting Reference | 5 - Event Editor | 690
A Action ID ID or partial ID with a * wild card of the action or actions you want to find.
4. Click OK.
Tip: Leave the fields blank in the Event search dialog box to re-display all of the actions in the
Event Editor after you have searched for selected actions.
• Make entries in the Global Parameters file to change the maximum number of scripts that can
run simultaneously, or specify how long an idle thread should remain active.
CE_THREAD_TIMEOUT
• Make entries in the Basic Control Engine points file to cache frequently used points.
Each time a script uses a point, it must retrieve the point's definition. You can use the bce_points.cfg
file to pre-load point definitions into the Basic Control Engine for the Event Manager. This can
provide a performance boost.
The bce_points.cfg file is an ASCII file that needs to be located in your project's Data directory.
Basic Control Engine and Scripting Reference | 5 - Event Editor | 691
2. Type cd %SITE_ROOT%\data.
4. Enter all the point IDs that you want to cache, one per line in the file.
6. Stop and restart your project to have the caching take effect.
Chapter 6. Action Calendar
This Application Module is fully integrated with CIMPLICITY software's Base System functionality
to enhance its already powerful monitoring capability in a full range of computer integrated
manufacturing environments. Designed from the ground up as a true client / server architecture,
CIMPLICITY has always provided more than simple monitoring and control. CIMPLICITY
software's flexible system architecture and modular design also allows for easy add-on of
functionality. When you take on the challenge of an enterprise wide system, you face challenges
which simple MMI systems just cannot handle. With the CIMPLICITY Action Calendar you can
coordinate plant operations on a timed basis.
The Action Calendar Application Module, which interfaces with the Base System Point Management
facility and User Interface, allows you to easily schedule the execution events in your system
through a simple calendar based user interface. Configured events can drive real world I/O through
CIMPLICITY and turn equipment/utilities on and off based on production schedules. In addition
internal events can be activated to trigger:
• Data collection
• Data logging
• Report generation
• Execution of scripts or programs.
Managing events and activities associated with your production schedule are made easy with the
CIMPLICITY Action Calendar.
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 693
The Action Calendar option gives you, the system administrator, the ability to build a set of
automated events that can be applied in one area of or throughout your plant. You can invoke events
with associated actions at specific times of a day and during day types (for example, weekdays) that
you define.
An action can be any action supported by the Event Editor. For example an action can set a point,
generate an alarm, download a recipe or even run a user written Basic Script.
Note: The Action Calendar schedules events with associated actions. It is not designed for
Production scheduling.
1. Graphical User Interface (page 694) (GUI) allows users to interactively configure and view
schedule information.
2. Scheduler (page 696) is responsible for ensuring that your operations are initiated at the
appropriate times.
The Graphical User Interface, which has a familiar electronic day planner appearance:
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 694
• Provides the screens needed for you to configure all Calendar data, including areas, event
actions, and schedules.
• Lets you project what events are scheduled either today or for any date in the future, based
on existing Action Calendar configuration data.
• Lets you specify exceptions to these standard schedules, as needed, to meet production
needs for a specific date. These schedule overrides can be used to completely alter a day's
schedule (for example, to accommodate holidays), or to modify, add, or skip a single event
on a specified date.
4. Applying all overrides associated with that date, until the total plant wide schedule has been
calculated.
• Initiates events based on these schedules.
• Performs periodic cleanup of the Action Calendar configuration data so that outdated
information (in particular, overrides that correspond to dates in the past) is automatically
purged from the system.
1. If you want to schedule an event to execute every minute, use the CIMPLICITY Event Editor.
The Event Editor provides an easier way than the Action Calendar to schedule these types of
repetitive events.
2. If you want to schedule an event in less than one-second real time intervals, use a PLC or a
CIMPLICITY PC control to perform the real time control. In the Action Calendar, events can
be scheduled to the second. On a normally loaded system, your event will execute within +1
second of the target time.
The Action Calendar lets you divide your facility into any number of areas, each with its own unique
set of events and schedules.
An Area defines specific locations, stations, or work units with which schedule information may be
associated. Examples of areas are
• ASSEMBLY
• Inspection
• Factory
Each area has its own configuration data. One immediate benefit of this feature is that users only
need to be familiar with their own area, and do not need to understand the entire plant's operation in
order to create or modify schedules. Of course, you, the system administrator, may also define plant
wide areas, to schedule events for the entire factory.
For example, you may dedicate an area to factory_lights. You can then create a configuration that
will instruct the Action Calendar to turn the lights on and off throughout the plant, at the times you
designate.
• Events
• Day types with associated weekdays
• Schedules for the day types
Event Definitions
An Event definition (page 699) provides a list of actions to perform such as Setpoints, and assigns
a unique event name to the association.
Example
Area A
Area B
• Workday. Tuesday
• Maintenance. Friday
Schedules
A Schedule definition (page 729) specifies the sequence and timing of events associated with the
area. All times may be specified to the nearest second on a 24-hour clock.
Example
The schedule for a FACTORY area specifies the event MAIN_LIGHTS_ON to occur at 6:00:00am.
Projected Schedules
Projected schedules (page 729) display a time ordered list of events that are scheduled to occur on
a selected date.
In addition to building base schedules for each area, the Graphical User Interface provides you with
the mechanism to:
• Project what an area's schedule will look like for today or for any date in the future.
• Override any or all events associated with that date with:
• Day type overrides completely replace the set of events associated with one-day type with the
base schedule associated with a new day type.
• Event overrides affect individual events, letting you dynamically add, skip, or reschedule events
at any time.
This day type will be either the standard day type for the area or, if the day type has been
overridden, the new requested day type.
3. Reads that day type's schedule, along with any event overrides specific to today's schedule, and
merges with all other area schedules for that day.
4. Begins processing of the events once the complete schedule has been built.
Important: Some important notes about how the Action Calendar Scheduler deals with
events include:
• If any events are being scheduled during the time that the Action Calendar is actually
generating the schedule, these events will be initiated, in order, immediately upon
completion of the schedule generation.
• There will be no predictable order for events that are scheduled to execute simultaneously.
• If a single event performs more than one action, the sequence of the actions is guaranteed.
When the Calendar determines that an event needs to be initiated, it sends an event request to
the Event Manager (EM) subsystem. If the event has been configured with logging enabled,
then the success or failure of the actions will be logged.
1. Areas
4. Actual Schedules
Once you have completed the overall plan, you can then:
Setting up Areas
Setting up Areas
When setting up your configuration you need to decide what are the:
You may want to begin planning by defining what appear to be obvious areas. As you continue
planning your configuration, you may see different relationships that prompt you to redefine your
original areas.
• Physically independent areas that have their own repetitive actions in machinery or peripheral
equipment, for example, a raw material cutting area that has its own light source.
• Logical areas, each with its scheduling needs, for example, reporting that is due every Friday.
Note: The Action Calendar lets you handle your entire facility through a single area. In fact,
Action Calendar provides a pre-configured area, Plant that you can use as a starting point.
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 699
A plant wide area may be appropriate for company wide actions. However, most likely you will also
need to define more specific areas.
Once you have your initially defined areas, review each area to determine the types of operations that
occur in that area. There may be one or more events associated with each operation and one or more
actions associated with each event.
Each operation typically corresponds to something that is controllable through a CIMPLICITY point.
In most cases, there will be a set of two or more events (or ultimately, event point values) that
correspond with the operation point referenced in your configuration.
Note: The Action Calendar lets you configure events for points which have been defined but
which have not been incorporated into the runtime system via a Configuration Update operation.
This enables you to set up a system for a future point configuration modification that will make
these events valid at a future date. Until that time, these events will be ignored by the Calendar,
and messages will be logged whenever an attempt is made to incorporate these events into a day's
schedule.
Example
A machine requires a light to be on for part of the day and to be off for the remainder.
unit_on
unit_off .
The Action Calendar will turn the machine light on and off, based on the times for which you
schedule unit_on and unit_off.
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 700
You may also have a series of actions that involve turning off the machine light, which you can
call up through the use of a script.
Having determined at least the initial set of events that will be required within an area, you can begin
to determine when these events may be invoked. As you review the day types, you may need to
redefine some areas.
The Action Calendar carries out events that you schedule for day types.
You may:
• Require multiple standard day types to handle the scheduling requirements such as weekdays,
weekends and holidays.
• Configure additional reserved day types for a specific area because your plant has other
conditions, which you must accommodate (for example, extended production days or
shutdown).
• Configure a day type that has no events. Any days of the week assigned to that day type will
have no events scheduled for that area.
However, within one area, you can only assign a specific day of the week, for example, Friday, to
one day type.
Example
1. Define Weekdays as a day type to which you assign Monday through Friday
2. Decide that the area has additional events on Friday and, therefore, define Friday as a day type.
You assign Friday to it, thereby removing Friday from Weekdays
or
• Keep Friday as a day type in this area with a schedule that includes all the events for
Weekdays and Friday's additional events. Action See "Configuring the Action Calendar –
Copying Day Types"
Once you have designed and configured standard configuration data, you can analyze your system's
needs for any date specific overrides. Overrides supported by the Action Calendar can be divided
into two distinct categories:
They are:
Note: Since the configuration screens are intended to accommodate standard, repetitive events,
exception conditions should not be included in the initial schedules. Instead, these can be more
appropriately handled through event or day type overrides, discussed in more detail below.
Day type overrides replace an entire day's schedule for the designated area.
This is particularly useful in the case of holidays or special events that fall on a day in which
production would normally run.
Example
If July 4 falls on a Monday, which is configured as a Weekday in the base configuration, you use a
day type override to define July 4 as a Holiday.
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 702
Another example is a case where, due to increased production demands, the plant decides to run extra
hours to meet these demands. If an alternate schedule and day type have been configured to meet
these additional production hours, you can use the alternate day type to override the standard day
type.
This type of override is useful in situations when an operation is required on a given date where
it normally would not be part of that day's schedule.
This override can be used to alter the time at which a scheduled event is initiated.
This override is useful in situations where a standard event is not desired on a particular date.
There are a number of rules associated with overrides, which are important to understand.
• Any override, which is scheduled for the current day, will be incorporated into the current
schedule immediately upon being requested by the user.
• If a day type override is configured, all existing event overrides for that same date and area
will be immediately deleted, so that an override is not inadvertently applied to an event for
which it was not intended.
• Initiate all day type and event overrides after you project a schedule for the date in
question. These overrides will be automatically reflected in the projected schedule being
presented to the user.
As you define an area's events and their scheduling requirements, including needs for overrides, you
may discover groups of events that are logically related and are, therefore, always processed as a set.
You can expedite scheduling the group at any time, by establishing an Initial/Offset Event
relationship among these events.
An Initial Event is one that, whenever scheduled, has one or more offset events scheduled static to it
at fixed time intervals.
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 703
An offset event occurs static to when the initial event occurs. For example, it may occur one minute
before the initial event, or three hours after.
Establishing an initial/offset event relationship has the following impact on a schedule, no matter
whether you are adding it to the base schedule or as an event type override.
• Adding an unscheduled initial event to a schedule causes all the initial event's offset events to be
scheduled automatically.
• Rescheduling an initial event to a new time causes all the initial event's offset events to be
rescheduled automatically, so that the fixed time intervals between all the events in the set are
preserved.
• Skipping or deleting an initial event, which would otherwise be initiated, causes all the initial
event's offset events to be skipped or deleted automatically.
• Changing the interval of the offset events causes all instances of the scheduled event/offsets to
change automatically.
You uniquely define Initial/offset event relationships for each area. Within an area, the relationships
you define apply across schedules for all day types.
If your plant has multiple shifts and 24 hour or nonstandard productions days, you may have to
customize the Action Calendar definitions of production shifts and days.
If your production facility operates in a multiple shift environment, it may be desirable from an
operational or maintenance viewpoint to configure your system so that each shift maintains its own
schedule of operations. Since an Action Calendar area may only be associated with a single day type
at any given time, you can define Pseudoareas within an Action Calendar.
A pseudoarea maintains its own event, day type, schedule, and day of the week definitions, while still
merging the individual schedules at runtime into a single plant wide schedule for any given day.
Within a given area, each Pseudoarea will really represent the same set of devices, locations, points,
etc., but will only schedule events against these points during the respective timeframe of each shift.
Example
Pseudoareas could be "Assembly_Shift1" and "Assembly_Shift2", each with their own respective
schedules.
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 704
By default, Action Calendar is set up to display a production day as midnight this morning through
midnight tonight.
However, if your production facility has production days that run 24 hours, with one production shift
running through midnight, you may want to set up different parameters for your production day.
If you prefer, you can configure the Action Calendar to adjust the 24hour-production period to a
period more desirable for your production facility.
As you configure schedules through the Action Calendar User Interface, the data is sent to the Action
Calendar, which stores it in a set of Action Calendar configuration files. The data is immediately
incorporated into the runtime system. This means that if you modify a day type schedule that is in
effect for the day, your modifications will be applied immediately to the currently running schedule.
When you have to add an event to the current day's schedule you may add it to the schedule using an
Add Event (page 702) override.
In order to control production activities, a set of CIMPLICITY Point IDs is needed as follows:
Point ID Point Type Function
Note: : This example assumes that these points are already configured.
1. PLANTWIDE
2. KILN_AREA
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 706
3. ASSEMBLY
Having defined three areas, we can now split the list of events (as indicated above) into area specific
events, and begin to configure each area.
PLANTWIDE Events
Beginning with the PLANTWIDE area, we can define the following events:
Event ID Point ID Point Value
LIGHTS_ON_EV MAIN_LIGHTS 1
LIGHTS_OFF_EV MAIN_LIGHTS 0
START_BREAK_EV BREAK_LIGHT 1
END_BREAK_EV BREAK_LIGHT 0
START_LUNCH_EV BREAK_LIGHT 1
END_LUNCH_EV BREAK_LIGHT 0
KILN_ONLY Events
KILN_ON_EV KILN_ENABLED 1
KILN_OFF_EV KILN_ENABLED 0
CONVEYOR_ON_EV ASSY_CONVEY 1
CONVEYOR_OFF_EV ASSY_CONVEY 0
Having defined events for each area, we can now create sets of events that are done in a group.
Creating events offset from a base event by a static time does this.
Beginning with the PLANTWIDE area, we can define the following offset events:
Base Event Offset Event Offset Time
There is one set of day types for the PLANTWIDE Area and one for the KILN_ONLY and
ASSEMBLY areas.
The day types associated with both the KILN_ONLY and ASSEMBLY areas is:
Day Type ID Purpose
The base schedule associated with the ASSEMBLY area would be:
Day Type ID Event ID Time Offset Flag
Finally, the days of the week are assigned to day types for each area as follows:
• Define and automatically execute events in your plant, based on a standard schedule.
• Project a schedule of automated events for any day in the future
• Add, delete or reschedule events for a specific day.
Once you have planned your areas and events, entering information into the Action Calendar is very
straightforward.
Note: If the icon does not appear in the Workbench left pane, you may need to enable the
Action Calendar optionin your project.
Either Or
Either Or
When you open the Action Calendar, you see the Action Calendar window that is divided into
four parts:
• Area
• Schedule Type
• Day Type Legend (page 720)
• Weekday Schedule
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 711
Area
The Area box displays the current area being viewed, for example an area called Plant. Selecting
the new menu option accessed by clicking the right mouse button over the control or selecting
the menu button can configure new areas .
Schedule Type
The Day Type Legend grid provides configuration and selection of the day type being viewed.
Each day type is assigned a color. Each day of the week (for example, Tuesday) displays the
color of the day type to which it is assigned.
When your Schedule Type is in Day Type mode, the Day Type Legend displays the:
• Color and Day Type grid
• Days: Mon through Sat
When your Schedule Type is in Calendar mode, the Day Type Legend displays the:
• Color and Day Type grid
• Year
• Month
• Days—Mon through Sat
• Days of the month: from 1 – 31 depending on how many days are in the displayed month.
Weekday Schedule
A Print Preview window opens displaying the document that will be printed.
• Select Print Setup.
A Windows Print Setup dialog box opens enabling you to set up the appropriate printer.
• Select Print.
A Windows Print dialog box opens enabling you to enter print specifications and print the
Action Calendar schedule.
Note: You can also click the Print button on the Action Calendar toolbar to open the Print
dialog box.
When you have completed planning each area's events, day types and schedules and are ready to
enter data into the Action Calendar, it is recommended that you enter information in the following
order.
When you have completed planning each area's events, day types and schedules and are ready to
enter data into the Action Calendar, there is an efficient configuration sequence..
• Configure areas.
• Create day types.
• Assign days of the week to day types.
Area Configuration
Area Configuration
Method 1:
a. Click File on the Action Calendar's menu bar.
b. Select New.
c. Select Area.
Method 2:
a. Click the Popup menu button , to the right of the Area dialog box.
b. Select New.
Description A 40 character or less description used by you to provide more information about the area.
Resource The Resource ID to use for the area. Resources can be used to implement access control for the
ID user interface. If you don't know yet what sort of security you will implement, select the $SYSTEM
resource. The configuration can always be changed later.
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 715
Edit Areas
2. Click the Popup menu button to the right of the Area field...
3. Select Edit.
Delete Areas
Important: When an area is deleted, all of its day types, events and scheduling information
are also deleted.
Before you begin to schedule events, you need to define day types and assign days of the week to the
day types, for each area in your plant.
• Use immediately and to which you assign one or more days of the week (for example, Friday).
• Reserve for future use, by creating it but not assigning any days of the week to it.
These reserved day types can then have days of the week assigned to them whenever their schedules
are needed. This feature is particularly useful when one schedule replaces another for extended
periods of time.
Note: If you only need to change the schedule for a few Thursdays, you can override each
Thursday that requires the long production run. You do this when the selected Schedule Type is in
Calendar mode.
Example
A cutting machine, in the Cutting Area, normally runs from 1:00pm through 4:00pm every Monday
through Friday.
• You schedule the Action Calendar to turn the machine on and off.
• The Cutting Area has already been defined.
Now you will create a day type in the Cutting Area called Weekdays and assign Monday through
Friday to that day type.
• The plant manager tells you that every Thursday the cutting machine will have to run from
Noon through 6:00pm.
You create a day type called Long Run and assign Thursday to that day type. Every Thursday the
Action Calendar will run the Long Run Schedule. You do this when the Action Calendar is in Day
Type mode.
Method 1
a. Click File on the Action Calendar menu bar.
b. Select New.
c. Select Day Type.
Method 2
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 717
Method 3
a. Click the right mouse button on the Day Type grid.
b. Select New.
2. Enter the following information in the Day Type Properties dialog box:
Name The 16 character mixed case name for the day type.
Description A 40 character or less description used by you to provide more information about the day type.
Color A color used to represent the day type graphically in the week and month calendars. Black is an
invalid color, it is used to represent unassigned days.
You can:
3. Either:
• Click the standard color you want once. It will appear both in the grid and, for the
corresponding days, on the Weekday Title bar.
• Click a custom color or custom color square. The Color dialog box appears in which you
can create a custom color.
Method 1
Method 2:
A menu appears.
2. Select Edit.
Using either method, the Day Type Properties dialog box appears for the Day Type that you want to
edit.
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 719
You can copy an existing day type to a new day type within an area. To get the greatest benefit from
this feature, use it after you have created the original day type's entire schedule. When you do, you
will copy the entire schedule for the original day type to the new day type.
This feature is particularly useful when you want to create a new day type that contains a slightly
modified schedule from the original. You can then easily edit the new day type and assign days of the
week to it whenever the modified schedule is required.
1. Select the day type in the Day Type grid that you want to copy.
4. Type the name of the new day type in the New Day Type field.
5. Click OK.
The Action Calendar creates a new day type with the name you specified and copies the original
day type's weekday schedule to the new day type.
Example
For example, you have a Weekday schedule for the spring and summer to start and stop a
molding machine that is in the Molding area . However, in the fall and winter you need to
lengthen the molding machine's run time on Wednesday and Thursday. You create a Long Run
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 720
day type by copying the Weekday schedule and editing it to extend the molding machine's
runtime hours. When the fall season begins, you can then assign Wednesday and Thursday to
the Long Run day type.
Method 1:
2. Click Delete.
Method 2:
Note: A day type cannot be deleted when it has a day of the week assigned to it or is used
as a day type override.
Once you have created day types you can assign each day of the week that requires scheduling in an
area to its appropriate day type.
Example
For example, if you created a day type called Weekend and your plant adheres to a weekend schedule
on both Saturday and Sunday, you assign Saturday and Sunday to the Weekend day type.
Note: In each area, you can only assign a day of the week (for example, Monday) to one day
type.
However, you can have day types to which no days of the week are assigned
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 721
When you assign a day of the week to a day type, the day of the week (for example, Wed) displays in
its day type color. The Action Calendar displays days that you have not yet assigned in black. Once
you assign a day of the week to a day type you can assign it to a different day type. However, you
cannot change it back to being unassigned.
There are several methods to assign days of the week to day types. Following is a description of three
methods to assign days of the week to day types. You perform the first two in Day Type mode, the
third in Calendar mode
When you select Day Type mode in the Schedule Type group (above the Day Type Legend) you will
see the days Sun through Sat underneath the grid. (You will not see days of the month.). While in this
mode you can either call up the Day of Week Assignments dialog box or use a shortcut method..
1. Double click the appropriate day of the week from the row of days.
3. Click the right mouse button over the appropriate day of the week (for example Tue) from the
row of days.
A Popup menu lists all of the day types you configured for the area.
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 722
5. Click the right mouse button on the Day of the Month grid.
Event Configuration
Event Configuration
In addition to creating day types for each area, you need to create the events that may be scheduled
during one or more day types in that area.
• Creating a new event, which can include a series of one or more actions that make up the event.
Actions include:
• Setpoints
• Alarm generation
• Scripts
• Recipes.
• Modifying an existing event
• Scheduling the event to occur at specific times in your schedule
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 723
• When necessary, changing the event. All of your changes affect all instances of the event in the
schedule.
• Creating offset events to expedite scheduling
• Before you begin scheduling, when the Schedule Type is in Day Type mode.
• While you are entering schedules and the Schedule Type is in Calendar mode.
When you complete any method, the General tab of the New Event Properties dialog box
displays.
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 724
2. Use the side buttons on the General tab of the New Events Properties dialog box as follows:
New Add new actions.
Move Up / Move Down Position an Action item in the desired order of execution.
The fields you fill in on the bottom of the General tab of the New Events Properties dialog box
depend on what action you select in the Action type field.
Action The default action is Setpoint(,). This action appears in the Actions box the first time you click New. You
type can configure that action or select another from the Action type. menu field. If you select another action
the fields will change to reflect your choice.
4. Select Edit.
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 725
Result: The General tab of the Event Properties dialog box appears, displaying the event you
want to modify.
5. Use the buttons in the General tab of the Event Properties dialog box as follows:
New Add a new action to the list.
The fields you fill in on the bottom of the Event Properties dialog box depend on what action
you select in the Action type field.
Action If you did not select an action when you created the event, the default action, Setpoint(,), appears in the
type Actions box the first time you click New.You can configure that action or select another from the Action
type menu field. If you select another action the fields will change to reflect your choice.
View Events
• At first, you will see a tree of the events along with scheduling information for each event..
• As you navigate through the tree, the hour Schedule part of the Action dialog box will update
and position the corresponding event.
• Events can be:
• Deleted
• Added
• Edited
• Scheduled
• Unscheduled
Note: Events can only be deleted when they are not scheduled.
Offset Events allow you to specify a sequence of events that always occur in a certain order and at a
certain time.
Offset Events provide you with a way to expedite any rescheduling that occurs for the sequenced
events by reducing the number of calendar entries you have to make for each time the sequence is
scheduled to one (1). Needless to say this also minimizes the possibility for error.
Important: Offset events only support one level of offset. You cannot create an offset of an
offset.
In the next example, the Kiln_Start event, which is an offset of Kiln_On cannot have an event that
is scheduled static to when it occurs. For example, Kiln_Preheat has to occur static to Kiln_On (20
minutes prior). It cannot be configured to occur 10 minutes after Kiln_Start. Simply said, if you are a
programmer—offsets cannot be nested.
Example
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 727
For the sake of the example, say your factory has a Kiln. To start this Kiln, you must perform the
following events in the following order:
There are at least three methods to configure your schedule. However, the first is inefficient; the
second is problematic; the third is the best choice. See the example below.
Important: Events with offset that wrap around the end of the day are not supported.
Example
You schedule an event for 11:59 PM on March 1 and an offset event of two minutes. The offset
event will be scheduled for 12:01 AM on March 1, NOT 12:01 AM on March 2.
Method 1. (Inefficient)
4. 7:00 – Kiln_Start
5. 7:10 – Kiln_Preheat
6. 7:30 – Kiln_On_Full
However, if you decide to start the Kiln 30 minutes earlier tomorrow, you need to reschedule
three events. Or if you decide that the preheat cycle can be decreased to 10 minutes, you need to
move all Kiln_On_Full events back 10 minutes in all of our schedules.
Method 2. (Problematic)
One possible offset configuration is, in the Offset tab of the Event Properties dialog box, to
configure the event:
7. Kiln_Start
This way when you schedule Kiln_Start the other two events are automatically scheduled.
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 728
The problem with this strategy is that you need the Kilns to be on at 7:30. If the preheat cycle is
decreased by 10 minutes you still need to change your schedules to move Kiln_Start forward .
The correct solution is illustrated below. In the Offset tab of the Event Properties dialog box,
configure the event:
Now if you need the kilns to be ready at 7:30 you simply place the Kiln_On event at 7:30.
3. Either:
a. Select Edit on the event's popup menu.
b. Select New to create a new event and associated offset events.
5. Use the buttons in the Offset tab of the Event Properties dialog box as follows:
New Add a new offset event to the list.
6. Enter the following information in the Offset tab of the Event Properties dialog box fields:
Event Name of an offset event.
Offset Time that should pass between the initial event and the offset event. If the offset event occurs before the
initial event, make a negative entry; after, make a positive entry in an HH:MM:SS format.
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 729
Schedules
Schedules
When you have defined a plant's areas and configured each area's day types, you are ready to
configure schedules.
Schedule
A schedule defines the series of activities that should occur on the days of the week that are assigned
to a day type.
If you created the area's events, you now only need to schedule them. If you did not create the events,
you can create them during scheduling.
First, when your Schedule Type is in Day Type mode, configure the basic day type schedules for each area.
You configure a schedule of events for each day type. As a result, the Action Calendar will apply a day type's
schedule of events to each day of the week assigned to it
Later, you can switch your Schedule Type to Calendar mode and override any specific days or events, where
necessary.
Example
You assign Monday, Wednesday and Friday to a day type called Weekday. The Action Calendar
will carry out whatever schedule you create for the day type Weekday on Monday, Wednesday and
Friday.
Before you get started, you may want to take a look at how you can adjust the Schedule View.
There are several options available to you when viewing the schedule. The options can be found on
the applications view menu, or by using the right mouse button on the schedule.
Option Description
Time Allows you to specify the time interval to use in the day view. Valid intervals are 10, 15, 30 and 60 minutes.
Interval
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 730
Time Bar Toggles the time bar on the left of the schedule. The time bar allows you to rapidly find events.
24 Hour Enables you to switch back and forth between a 24 hour clock and a 12 hour AM/PM clock.
Clock
Show Lets you decide if offset events are viewed in the schedule.
Offset
Events
Day Lets you toggle back and forth between a day view and a list to display the scheduled events. If you find the
Schedule day view becoming cluttered due to many events scheduled in the same time slot, try the list view.
a. Click the Popup menu button to the right of the Browse button.
b. Select New from the popup menu.
c. Configure a new event. (page 723)
Actions cannot be scheduled to at the exact same time as the start of the day. This is because
this is the transition period from one day schedule to the next, and this time is ambiguous.
To help work with this limitation the start of day configuration has been modified so that the
start of the day can be configured with 1 minute resolution.
The start of the day should be selected to coincide with a time between shifts that
• Will have no need for scheduled activities
• Is a natural breaking point from 1 day to the next.
Midnight is often a good time for this, but for others 3:00 am may be better.
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 731
5. Double click on a scheduled event in an hour row of the Action Calendar Schedule part.
7. Select the scheduled event in the hour Schedule part of the Action Dialog box.
When you have completed configuring an area's basic schedule, you may have specific days or
events that will need to be changed during a specified calendar day.
Day Type Overrides allow you to change the day type for a specified calendar day. You might need
to make the change for a variety of reasons including holidays, long weekends, plant shutdowns or to
accommodate a longer production schedule.
Example
You normally run your cutting machine, in the Cutting Area, from 1:00pm through 4:00pm every
Monday through Friday. You schedule the Action Calendar to turn the machine on and off. You
have all ready defined the Cutting Area. Now you will create a day type in the Cutting Area called
Weekdays and assign Monday through Friday to that day type.
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 732
The plant manager tells you that beginning three weeks from the current week, the cutting machine
will have to run from noon through 6:00pm for four Thursdays in a row.
Anticipating these long runs you have created a day type called Long Run that turns the machine on
at noon and off at 6:00pm. You can immediately select the four involved Thursdays and override the
Weekdays day type with Long Run. On those four Thursdays the Action Calendar will follow the
Long Run schedule.
Note: : Switch the Schedule Type to Calendar mode to assign Day Type Overrides.
• Add
• Remove
• View
• Edit
• Delete
The Day Type Override dialog box tells you (read only) the:
• Area you are in
• Date you selected
• Currently assigned day type
2. Enter the following information in the Day Type Override dialog box to override the day type.
Override Day Type Select to override the currently assigned day type
New Day Type The day type to use instead of the currently assigned day type
2. Uncheck the Override Day Type check box in the Day Type Override dialog box.
3. Click OK.
Event Overrides
Event Overrides
Event Overrides allow you to change an event n a schedule during a specific calendar day.
For example, you want to start production an hour early tomorrow or extend lunch by an hour. You
use an event override to make the change.
Note: All event overrides are performed when the Action Calendar is in Calendar mode.
2. Add an event that exists or a new event (page 723) to the same time.
The Scheduled Event dialog box tells you (read only) the:
• Time the event is currently scheduled
• Event that is currently scheduled
2. Enter the following in information to skip or reschedule an event in the Scheduled Event dialog
box:
Skip Event Select to skip the event on the selected calendar day.
Reschedule Enter the time the event should occur on the selected calendar day. The event and all of its
Time offsets, if any, will be rescheduled.
Note: When a day has event overrides, an asterisk is displayed next to the day in the month
calendar.
An O displays in the Schedule part of the Action Dialog box on the Events that are overridden.
The Scheduled Event dialog box associated with that event override appears.
Security
Security
The Action Calendar provides access control to CIMPLICITY users logged into the system.
Security is provided and can be enforced only when the project is running.
When the project is not running, any user may perform configuration from the configuration cabinet.
You, the system administrator, have assigned each CIMPLICITY user a role. Each role has a set of
privileges associated with it. When the Action Calendar is part of the project, the Calendar tab of the
Role Properties dialog box is displayed:
Choices for the Calendar tab of the Role Properties dialog box are:
Area Based When resource based security is:
Security
Enabled A user will only be able to see areas whose Resource ID is assigned to the user
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 739
Example If you have schedules across several parts of your plant, you may wish to restrict the paint
booth operator from modifying the assembly schedule. Resource based security is the way to do this.
Checked Users will be able to configure a schedule for any areas they can see.
2. Select Setup.
Important: Day Start cannot be changed when the project is running. Changing the
Day Start requires that the application be exited.
The CalCfg.exe program takes command line options. These can be useful if you want to launch
CalCfg from a CimView screen.
Command Description
/AREA areaId Specifies the default area to select.
/ Application can only run when CIMPLICITY project is active. This is useful if you want to require
ONLINEONLY operators to be logged in and subject to role privileges.
Basic Control Engine and Scripting Reference | 6 - Action Calendar | 740
Command Description
/PROJECT Specifies the path to the project's file (e.g. C:\Program Files\Proficy\Proficy CIMPLICITY\projects
path \cimpdemo\cimpdemo.gef) to use.
/READONLY Do not allow any configuration to be performed while the project is or is not running regardless of Role
configuration.