working model 2d - user's manual

794
Working Model 2D Working Model Basic User’s Manual ®

Upload: alexander-pazmino

Post on 30-Oct-2014

953 views

Category:

Documents


147 download

TRANSCRIPT

Page 1: Working Model 2D - User's Manual

Working Model2DWorking

Model2

D W

orking Model Basic

User’s Manual

Working Model Basic™

User’s Manual

®

Page 2: Working Model 2D - User's Manual

Information in this document is subject to change without notice. No part of this documentmay be reproduced or transmitted in any form or by any means, electronic or mechanical, forany purpose, without the express written permission of Knowledge Revolution.

© 1995 Knowledge Revolution. All rights reserved.Portions © 1992-1995 Summit Software Company.

Working Model is a registered trademark of Knowledge Revolution. Working Model Basicand WM Basic are trademarks of Knowledge Revolution. All other trademarks are theproperty of their respective holders.

Page 3: Working Model 2D - User's Manual

Introduction.........................................................................1Using the WM Basic Language Reference.............................................................1Tables... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2Language Elements By Category........................................................................2

Chapter 1: Getting Started with Working Model Basic... . . .17What is Working Model Basic?........................................................................18WM Basic Objects.......................................................................................29Putting it All Together: A Simple WM Basic Program..............................................37Where to Go from Here .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .39

Chapter 2: A–Z Reference ................................................40

Chapter 3: Working Model Basic Extensions Reference.517

Chapter 4: Editing and Debugging Scripts .....................641Script Editor Basics....................................................................................642Editing Your Scripts .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .649Running Your Scripts..................................................................................658Debugging Your Scripts...............................................................................659Exiting from Script Editor.............................................................................667Menu Reference ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .667

Chapter 5: Editing Custom Dialog Boxes (WindowsOnly) ...............................................................................673

Overview........ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .674Using the Dialog Editor................................................................................674Creating a Custom Dialog Box ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .678Editing a Custom Dialog Box.........................................................................683

Contents

Page 4: Working Model 2D - User's Manual

Editing an Existing Dialog Box.......................................................................695Testing an Edited Dialog Box.........................................................................697Incorporating a Dialog Box Template into Your Script............................................699Exiting from Dialog Editor............................................................................700Menu/Tools Reference.................................................................................700Using a Custom Dialog................................................................................706Using a Dynamic Dialog Box.........................................................................709

Chapter 6: Controlling Working Model from AnotherApplication......................................................................713

Sending a WM Basic Program via DDE.............................................................714Sending a WMBasic Program via Apple Events....................................................716

Appendix A: Runtime Error Messages ............................719Visual Basic Compatible Error Messages ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .719WM Basic-Specific Error Messages ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .722Error Messages in Working Model Operations.....................................................724

Appendix B: Compiler Error Messages ...........................725

Appendix C: Language Elements by Platform ................731

Appendix D: WM Basic Limitations .................................747

Appendix E: WM Basic/Visual Basic Differences ............749

Index ...............................................................................757

Page 5: Working Model 2D - User's Manual

1

Welcome to the Working Model Basic User’s Manual. This manual contains both an alphabetic listing of allWM Basic language keywords as well as chapters describing how to use the WM Basic tools such as theDialog Editor and Script Editor.

ContentsThe Working Model Basic User’s Manual contains the following sections:

Chapter 1, Getting Started with Working Model Basic, provides a brief butcomprehensive introduction to this powerful feature.Chapter 2, A-Z Reference, contains an alphabetical list of all language keywords,including all functions, subroutines, keywords, constants, and so on. This chapter canbe used to look up a function’s parameters or to understand the purpose of a languageelement.Chapter 3, Working Model Basic Extensions Reference, contains an alphabeticallist of extensions to the Basic language that are specific to Working Model.Chapter 4, Editing and Debugging Scripts, explains how to use the Script Editor, atool that allows you to edit and debug WM Basic scripts.Chapter 5, Editing Custom Dialog Boxes, explains how to use the Dialog Editor, atool that enables you to create and modify custom dialog boxes for use within yourWM Basic scripts.Chapter 6, Controlling Working Model from Another Application, describes howto use Working Model as a DDE or Apple events server.Appendix A, Runtime Error Messages, provides a complete listing of WM Basicruntime error messages, including the error numbers and error text.Appendix B, Compiler Error Messages, provides a complete listing of WM Basiccompiler error messages, including the error numbers and error text.Appendix C, Language Elements by Platform, provides a listing of all WM Basiclanguage keywords and on which platforms those keywords are supported.Appendix D, WM Basic Limitations, describes some limits of the WM Basicruntime and compiler.Appendix E, WM Basic/Visual Basic Differences, describes the differencesbetween WM Basic and Visual Basic 3.0 and Visual Basic for Applications 1.0.

Using the WM Basic Language ReferenceThe Reference section is organized like a dictionary containing an entry for each language element. In theReference section, the language elements are categorized as follows:

Category Description

data type Any of the supported 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.

Introduction

Page 6: Working Model 2D - User's Manual

2 Working Model Basic User's Manual

statement Language element that takes zero or more parameters andperforms an action.

operator Language elements that cause an evaluation to beperformed either on one or two operands.

topic Describes information about a topic rather than a languageelement.

keyword Language element that does not fit into any of the othercategories.

Each entry in the Reference section contains the following headings:Heading Description

Syntax The syntax of the language element. The conventions usedin describing the syntax are described in Chapter 1.

Description Contains a one-line description of that language element.

Comments Contains any other important information about thatlanguage keyword.

Example Contains an example of that language keyword in use. Thelanguage keyword to which the example applies alwaysappears in bold within the example. An example isprovided for every language keyword.

See Also Contains a list of other entries in the Reference sectionthat relate either directly or indirectly to that languageelement.

Platforms Contains a list of platforms that support that languagekeyword. The word All indicates that the languagekeyword is supported by all platforms on which WMBasic runs.

PlatformNotes

Contains information about that language keywordspecific to a given platform.

TablesIncluded in the Working Model Basic User’s Manual are a number of tables used for cross-referencing thelanguage elements. The following tables are included:

Language Elements by Category. This table lists the language elements by category,providing a one line description for each one. This table appears later in this section.Language Elements by Platform. This table lists all WM Basic language elements andon which platforms these elements are supported. This table appears in Appendix C.

Language Elements By CategoryThe following subsections list WM Basic language elements by category.

Arrays

ArrayDims Return the number of dimensions of anarray

ArraySort Sort an arrayErase Erase the elements in one or more arraysLBound Return the lower bound of a given array

dimensionOption Base Change the default lower bound for array

Page 7: Working Model 2D - User's Manual

Language Elements By Category 3

declarationsReDim Re-establish the dimensions of an arrayUBound Return the upper bound of a dimension of

an array

Clipboard

Clipboard$ (function) Return the content of the clipboard as astring

Clipboard$ (statement) Set the content of the clipboardClipboard.Clear Clear the clipboardClipboard.GetFormat Get the type of data stored in the clipboardClipboard.GetText Get text from the clipboardClipboard.SetText Set the content of the clipboard to text

Comments

' Comment to end-of-lineREM Add a comment

Comparison operators

< Less than<= Less than or equal to<> Not equal= Equal> Greater than>= Greater than or equal to

Controlling other programs

AppActivate Activate an applicationAppClose Close an applicationAppFileName$ Return the filename corresponding to an

applicationAppFind Return the full name of an applicationAppGetActive$ Return the name of the active applicationAppGetPosition Get the position and size of an applicationAppGetState Get the window state of an applicationAppHide Hide an applicationAppList Fill an array with a list of running

applicationsAppMaximize Maximize an applicationAppMinimize Minimize an applicationAppMove Move an applicationAppRestore Restore an applicationAppSetState Set the state of an application’s windowAppShow Show an applicationAppSize Change the size of an applicationAppType Return the type of an applicationDoKeys Simulate keystrokes in another applicationHLine Scroll the active window left/right by a

specified number of linesHPage Scroll the active window left/right by a

specified number of pagesHScroll Scroll the active window left/right to a

Page 8: Working Model 2D - User's Manual

4 Working Model Basic User's Manual

specified absolute positionHWND.Value Return the operating system value of a

windowMenu Execute a menu command in another

applicationMenuItemChecked Determine if a menu item is checked in

another applicationMenuItemEnabled Determine if a menu item is enabled in

another applicationMenuItemExists Determine if a menu item exists in another

applicationQueEmpty Empty a queueQueFlush Play back all events stored in a queueQueKeyDn Add key down event to the queueQueKeys Add key down/up events to the queueQueKeyUp Add key up event to the queueQueMouseClick Add mouse click to the queueQueMouseDblClk Add mouse double-click to the queueQueMouseDblDn Add mouse down/up/down events to the

queueQueMouseDn Add mouse down event to the queueQueMouseMove Add mouse move event to the queueQueMouseMoveBatch Add many mouse move events to the queueQueMouseUp Add mouse up event to the queueQueSetRelativeWindow Make all mouse positions in a queue

relative to a windowSendKeys Send keystrokes to another applicationShell Execute another applicationVLine Scroll the active window up/down by a

specified number of linesVPage Scroll the active window up/down by a

specified number of pagesVScroll Scroll the active window up/down to a

specified absolute positionWinActivate Activate a windowWinClose Close a windowWinFind Find a window given its nameWinList Fill an array with window objects, one for

each top-level windowWinMaximize Maximize a windowWinMinimize Minimize a windowWinMove Move a windowWinRestore Restore a windowWinSize Size a window

Controlling program flow

Call Call a subroutineChoose Return a value at a given indexDo...Loop Execute a group of statements repeatedlyDoEvents (function) Yield control to other applications

Page 9: Working Model 2D - User's Manual

Language Elements By Category 5

DoEvents (statement) Yield control to other applicationsEnd Stop execution of a scriptExit Do Exit a Do loopExit For Exit a For loopFor...Next Repeat a block of statement a specified

number of timesGoSub Execute at a specific label, allowing control

to return laterGoto Execute at a specific labelIf...Then...Else Conditionally execute one or more

statementsIIf Return one of two values depending on a

conditionMain Define a subroutine where execution beginsReturn Continue execution after the most recent

GoSubSelect...Case Execute one of a series of statementsSleep Pause for a specified number of

millisecondsStop Suspend execution, returning to a debugger

(if present)Switch Return one of a series of expressions

depending on a conditionWhile...Wend Repeat a group of statements while a

condition is True

Controlling the operating environment

Command, Command$ Return the command lineDesktop.ArrangeIcons Arrange the icons on the desktopDesktop.Cascade Cascades all non-minimized applicationsDesktop.SetColors Set the desktop colorsDesktop.SetWallpaper Set the desktop wallpaperDesktop.Snapshot Capture an image, placing it in the

clipboardDesktop.Tile Tiles all non-minimized applicationsEnvironm Environ$ Return a string from the environmentPrinterGetOrientation Retrieve the current printer orientationPrinterSetOrientation Set the printer orientationScreen.DlgBaseUnitsX Return the x dialog base unitsScreen.DlgBaseUnitsY Return the y dialog base unitsScreen.Height Return the height of the display, in pixelsScreen.TwipsPerPixelX Return the number of twips per pixel in the

x directionScreen.TwipsPerPixelY Return the number of twips per pixel in the

y directionScreen.Width Return the width of the display, in pixelsSystem.Exit Exit the operating environmentSystem.FreeMemory Return the free memory in the operating

environmentSystem.FreeResources Return the free resources in the operating

environmentSystem.MouseTrails Toggle mouse trails on or off

Page 10: Working Model 2D - User's Manual

6 Working Model Basic User's Manual

System.Restart Restart the operating environmentSystem.TotalMemory Return the total available memory in the

operating environmentSystem.WindowsDirectory$

Return the directory containing Windows

System.WindowsVersion$

Return the Windows version

Conversion

Asc Return the value of a characterCBool Convert a value to a BooleanCCur Convert a value to CurrencyCDate Convert a value to a DateCDbl Convert a value to a DoubleChr, Chr$ Convert a character value to a stringCInt Convert a value to an IntegerCLng Convert a value to a LongCSng Convert a value to a SingleCStr Convert a value to a StringCVar Convert a value to a VariantCVDate Convert a value to a DateCVErr Convert a value to an errorHex, Hex$ Convert a number to a hexadecimal stringIsDate Determine if an expression is convertible to

a dateIsError Determine if a variant contains a user-

defined error valueIsNumeric Determine if an expression is convertible to

a numberOct. Oct$ Convert a number to an octal stringStr, Str$ Convert a number to a stringVal Convert a string to a number

Data types

Boolean Data type representing True of False valuesCurrency Data type used to hold monitary valuesDate Data type used to hold dates and timesDouble Data type used to hold real number with

15-16 digits of precisionHWND Data type used to hold windowsInteger Data type used to hold whole numbers with

4 digits of precisionLong Data type used to hold whole numbers with

10 digits of precisionObject Data type used to hold OLE automation

objectsSingle Data type used to hold real number with 7

digits of precisionString Data type used to hold sequences of

characters

Page 11: Working Model 2D - User's Manual

Language Elements By Category 7

Variant Data type that holds a number, string, orOLE automation object

Database

SQLBind Specify where to place results withSQLRetrieve

SQLClose Close a connection to a databaseSQLError Return error information when an SQL

function failsSQLExecQuery Execute a query on a databaseSQLGetSchema Return information about the structure of a

databaseSQLOpen Establishes a connection with a databaseSQLRequest Run a query on a databaseSQLRetrieve Retrieve all or part of a querySQLRetrieveToFile Retrieve all or part of a query, placing

results in a file

Date/time

Date, Date$ (functions) Return the current dateDate, Date$ (statements) Change the system dateDateAdd Add a number of date intervals to a dateDateDiff Subtract a number of date intervals from a

dateDatePart Return a portion of a dateDateSerial Assemble a date from date partsDateValue Convert a string to a dateDay Return the day component of a date valueHour Return the hour part of a date valueMinute Return the minute part of a date valueMonth Return the month part of a date valueNow Return the date and timeSecond Return the seconds part of a date valueTime, Time$ (functions) Return the current system timeTime, Time$ (statements) Set the system timeTimer Return the number of elapsed seconds since

midnightTimeSerial Assemble a date/time value from time

componentsTimeValue Convert a string to a date/time valueWeekday Return the day of the week of a date valueYear Return the year part of a date value

DDE

DDEExecute Execute a command in another applicationDDEInitiate Initiate a DDE conversation with another

applicationDDEPoke Set a value in another applicationDDERequest,DDERequest$

Return a value from another application

DDESend Establishe a DDE conversation, then sets avalue in another application

Page 12: Working Model 2D - User's Manual

8 Working Model Basic User's Manual

DDETerminate Terminate a conversation with anotherapplication

DDETerminateAll Terminate all conversationsDDETimeOut Set the timeout used for non-responding

applications

Dialog manipulation

ActivateControl Activate a controlButtonEnabled Determine if a button in another

application’s dialog is enabledButtonExists Determine if a button in another

application’s dialog existsCheckBoxEnabled Determine if a check box in another

application’s dialog is enabledCheckBoxExists Determine if a check box in another

application’s dialog existsComboBoxEnabled Determine if a combo box in another

application’s dialog is enabledComboBoxExists Determine if a combo box in another

application’s dialog existsEditEnabled Determine if a text box in another

application’s dialog is enabledEditExists Determine if a text box in another

application’s dialog existsGetCheckBox Get the state of a check box in another

application’s dialog boxGetComboBoxItem$ Get an item from a combo box item in

another application’s dialog boxGetComboBoxItemCount Get the number of items in a combo box on

another application’s dialog boxGetEditText$ Get the content of a text box in another

application’s dialog boxGetListBoxItem$ Get an item from a list box in another

application’s dialog boxGetListBoxItemCount Get the number of items from a list box in

another application’s dialog boxGetOption Get the state of an option button in another

application’s dialog boxListBoxEnabled Determine if a list box in another

application’s dialog box is enabledListBoxExists Determine if a list box in another

application’s dialog box existsOptionEnabled Determine if an option button in another

application’s dialog is enabledOptionExists Determine if an option button in another

application’s dialog existsSelectButton Select a push button in another

application’s dialog boxSelectComboboxItem Select an item from a combo box in another

application’s dialog boxSelectListboxItem Select an item from a list box in another

application’s dialog box

Page 13: Working Model 2D - User's Manual

Language Elements By Category 9

SetCheckbox Set the state of a check box in anotherapplication’s dialog box

SetEditText Set the content of a text box in anotherapplication’s dialog box

SetOption Set the state of an option button in anotherapplication’s dialog box

Error handling

Erl Return the line with the errorErr (function) Return the error that caused the current

error trapErr (statement) Set the value of the errorError Simulate a trappable runtime errorError, Error$ Return the text of a given errorOn Error Trap an errorResume Continue execution after an error trap

File I/O

Close Close one or more filesEof Determine if the end-of-file has been

reachedFreeFile Return the next available file numberGet Read data from a random or binary fileInput# Read data from a sequential file into

variablesInput, Input$ Read a specified number of bytes from a

fileLine Input # Read a line of text from a sequential fileLoc Return the record position of the file

pointer within a fileLock Lock a section of a fileLof Return the number of bytes in an open fileOpen Open a file for reading or writingPrint # Print data to a filePut Write data to a binary or random fileReset Close all open filesSeek Return the byte position of the file pointer

within a fileSeek Set the byte position of the file pointer

which a fileUnLock Unlock part of a fileWidth# Specify the line width for sequential filesWrite # Write data to a sequential file

File system

ChDir Change the current directoryChDrive Change the current driveCurDir, CurDir$ Return the current directoryDir, Dir$ Return files in a directoryDiskDrives Fill an array with valid disk drive lettersDiskFree Return the free space on a given disk driveFileAttr Return the mode in which a file is open

Page 14: Working Model 2D - User's Manual

10 Working Model Basic User's Manual

FileCopy Copy a fileFileDateTime Return the date and time when a file was

last modifiedFileDirs Fill an array with a subdirectory listFileExists Determine if a file existsFileLen Return the length of a file in bytesFileList Fill an array with a list of filesFileParse$ Return a portion of a filenameFileType Return the type of a fileGetAttr Return the attributes of a fileKill Delete files from diskMacID Return a value representing a collection of

same-type files on the MacintoshMkDir Create a subdirectoryName Rename a fileRmDir Remove a subdirectorySetAttr Change the attributes of a file

Financial

DDB Return depreciation of an asset usingdouble-declining balance method

Fv Return the future value of an annuityIPmt Return the interest payment for a given

period of an annuityIRR Return the internal rate of return for a

series of payments and receiptsMIRR Return the modified internal rate of returnNPer Return the number of periods of an annuityNpv Return the net present value of an annuityPmt Return the payment for an annuityPPmt Return the principal payment for a given

period of an annuityPv Return the present value of an annuityRate Return the interest rate for each period of

an annuitySln Return the straight-line depreciation of an

assetSYD Return the Sum of Years’ Digits

depreciation of an asset

Getting information from WM Basic

Basic.Capability Return capabilities of the platformBasic.Eoln$ Return the end-of-line character for the

platformBasic.FreeMemory Return the available memoryBasic.HomeDir$ Return the directory where WM Basic is

locatedBasic.OS Return the platform idBasic.PathSeparator$ Return the path separator character for the

platform

Page 15: Working Model 2D - User's Manual

Language Elements By Category 11

Basic.Version$ Return the version of WM Basic

INI Files

ReadIni$ Read a string from an INI fileReadIniSection Read all the item names from a given

section of an INI fileWriteIni Write a new value to an INI file

Logical/binary operators

And Logical or binary conjunctionEqv Logical or binary equivalenceImp Logical or binary implicationNot Logical or binary negationOr Logical or binary disjunctionXor Logical or binary exclusion

Math

Abs Return the absolute value of a numberAtn Return the arc tangent of a numberCos Return the cosine of an angleExp Return e raised to a given powerFix Return the integer part of a numberInt Return the integer portion of a numberLog Return the natural logarithm of a numberRandom Return a random number between two

valuesRandomize Initialize the random number generatorRnd Generate a random number between 0 and

1Sgn Return the sign of a numberSin Return the sine of an angleSqr Return the square root of a numberTan Return the tangent of an angle

Miscellaneous

() Force parts of an expression to be evaluatedbefore others

_ Line continuationBeep Make a soundInline Allow execution or interpretation of a

block of textMacScript Execute an AppleScript scriptMci Execute an MCI commandPrintFile Print a file using the application to which

the file belongs

Networks

Net.AddCon$ Redirect a local device to a shared deviceon a network

Net.Browse$ Display a dialog requesting a networkdirectory or printer resource

Net.CancelCon Cancel a network connection

Page 16: Working Model 2D - User's Manual

12 Working Model Basic User's Manual

Net.Dialog Display a dialog allowing configuration ofthe network

Net.GetCaps Return information about the capabilities ofthe network

Net.GetCon$ Return the name of the network resourceassociated with a local device

Net.User$ Return the name of the user on the network

Numeric operators

* Multiply+ Add- Subtract/ Divide\ Integer divide^ PowerMod Remainder

Objects

CreateObject Instantiate an OLE automation objectGetObject Return an OLE automation object from a

file, or returns a previously instantiatedOLE automation object

Is Compare two object variablesNothing Value indicating no valid object

Parsing

Item$ Return a range of items from a stringItemCount Return the number of items in a stringLine$ Retrieve a line from a stringLineCount Return the number of lines in a stringWord$ Return a sequence of words from a stringWordCount Return the number of words in a string

Predefined dialogs

AnswerBox Display a dialog asking a questionAskBox$ Display a dialog allowing the user to type a

responseAskPassword$ Display a dialog allowing the user to type a

passwordInputBox, InputBox$ Display a dialog allowing the user to type a

responseMsgBox (function) Display a dialog containing a message and

some buttonsMsgBox (statement) Display a dialog containing a message and

some buttonsMsgClose Close a modeless message boxMsgOpen Open a modeless message boxMsgSetText Set the message contained within a

modeless message boxMsgSetThermometer Set the percentage of the thermometer in a

modeless message box

Page 17: Working Model 2D - User's Manual

Language Elements By Category 13

OpenFilename$ Display a dialog requesting a file to openPopupMenu Display a popup menu containing items

from an arraySaveFilename$ Display a dialog requesting the name of a

new fileSelectBox Display a dialog allowing selection of an

item from an array

Printing

Print Print data to the screenSpc Print a number of spaces within a Print

statementTab Used with Print to print spaces up to a

column positionViewportClear Clear the contents of the viewportViewportClose Close the viewportViewportOpen Open a viewport

Procedures

Declare Define an external routine or a forwardreference

Exit Function Exit a functionExit Sub Exit a subroutineFunction...End Create a user-defined functionSub...End Create a user-defined subroutine

String operators

& Concetenate two stringsLike Compare a string against a pattern

Strings

Format, Format$ Return a string formatted to a givenspecification

InStr Return the position of one string withinanother

LCase, LCase$ Convert a string to lower caseLeft, Left$ Return the left portion of a stringLen Return the length of a string or the size of a

data itemLSet Left align a string or user-defined type

within anotherLTrim, LTrim$ Remove leading spaces from a stringMid, Mid$ Return a substring from a stringMid, Mid$ Replace one part of a string with anotherOption Compare Change the default comparison between

text and binaryOption CStrings Allow interpretation of C-style escape

sequences in stringsRight, Right$ Return the right portion of a stringRSet Right align a string within anotherRTrim, RTrim$ Remove trailing spaces from a stringSpace, Space$ Return a string os spaces

Page 18: Working Model 2D - User's Manual

14 Working Model Basic User's Manual

StrComp Compare two stringsString, String$ Return a string consisting of a repeated

characterTrim, Trim$ Trim leading and trailing spaces from a

stringUCase, UCase$ Return the upper case of a string

User dialogs

Begin Dialog Begin definition of a dialog templateCancelButton Define a Cancel button within a dialog

templateCheckBox Define a combo box in a dialog templateComboBox Define a combo box in a dialog templateDialog (function) Invoke a user-dialog, returning which

button was selectedDialog (statement) Invoke a user-dialogDlgControlId Return the id of a control in a dynamic

dialogDlgEnable Determine if a control is enabled in a

dynamic dialogDlgEnable Enable or disables a control in a dynamic

dialogDlgFocus Return the control with the focus in a

dynamic dialogDlgFocus Set focus to a control in a dynamic dialogDlgListBoxArray Set the content of a list box or combo box

in a dynamic dialogDlgListBoxArray Set the content of a list box or combo box

in a dynamic dialogDlgSetPicture Set the picture of a control in a dynamic

dialogDlgText (statement) Set the content of a control in a dynamic

dialogDlgText$ (function) Return the content of a control in a

dynamic dialogDlgValue (function) Return the value of a control in a dynamic

dialogDlgValue (statement) Set the value of a control in a dynamic

dialogDlgVisible (function) Determine if a control is visible in a

dynamic dialogDlgVisible (statement) Set the visibility of a control in a dynamic

dialogDropListBox Define a drop list box in a dialog templateGroupBox Define a group box in a dialog templateListBox Add a list box to a dialog templateOKButton Add an OK button to a dialog templateOptionButton Add an option button to a dialog templateOptionGroup Add an option group to a dialog templatePicture Add a picture control to a dialog templatePictureButton Add a picture button to a dialog template

Page 19: Working Model 2D - User's Manual

Language Elements By Category 15

PushButton Add a push button to a dialog templateText Add a text control to a dialog templateTextBox Add a text box to a dialog template

Variables and constants

= AssignmentConst Define a constantDefBool Set the default data type to BooleanDefCur Set the default data type to CurrencyDefDate Set the default data type to DateDefDbl Set the default data type to DoubleDefInt Set the default data type to IntegerDefLng Set the default data type to LongDefObj Set the default data type to ObjectDefSng Set the default data type to SingleDefStr Set the default data type to StringDefVar Set the default data type to VariantDim Declare a local variableGlobal Declare variables for sharing between

scriptsLet Assign a value to a variablePrivate Declare variables accessible to all routines

in a scriptPublic Declare variables accessible to all routines

in all scriptsSet Assign an object variableType Declare a user-defined data type

Variants

IsEmpty Determine if a variant has been initializedIsError Determine if a variant contains a user-

defined errorIsMissing Determine if an optional parameter was

specifiedIsNull Determine if a variant contains valid dataIsObject Determine if an expression contains an

objectVarType Return the type of data stored in a variant

Page 20: Working Model 2D - User's Manual
Page 21: Working Model 2D - User's Manual

17

C H A P T E R 1

This chapter is an introduction to Working Model Basic (WM Basic), a powerfulprogramming language embedded in Working Model. An overview of the language will beprovided, followed by simple programming examples using Working Model Basic.

ContentsWhat is Working Model Basic?Working Model Basic ObjectsPutting it All Together: Simple WM Basic Program

Notes: This documentation, Working Model Basic User's Manual, is not designed as a guidefor those who are new to programming. The documentation assumes that you have someexperience in programming and that you have functional knowledge of Microsoft VisualBasic. Although this document serves as the complete reference for the Working ModelBasic language, you may find the literature on Visual Basic useful in more advancedprogramming.The documentation also assumes that you are somewhat familiar with Working Model. Ifyou have never used Working Model, we strongly recommend that you go through severaltutorial exercises in the accompanying Working Model Tutorial. The Guided Tour chapter inthe Working Model User's Manual will also help you become familiar with Working Model.

Getting Started with WorkingModel Basic

Page 22: Working Model 2D - User's Manual

18 Working Model Basic User's Manual

What is Working Model Basic?WM Basic (short for Working Model Basic) is an object-oriented programming languagebased on Visual Basic. Visual Basic is a multi-purpose, industry-standard programminglanguage developed by Microsoft Corporation. WM Basic is a combination of the versatilefeatures available in Visual Basic and special extensions that allow easy access to uniquesimulation features of Working Model.As a result, WM Basic has all the following characteristics combined:

traditional high-level programming language features (e.g., English-like syntax, conditional flow control, subroutines), inherited from theoriginal BASIC programming languageobject-oriented language structure and simple interface design tools(e.g., creating dialog boxes and buttons), inherited from Visual Basica complete set of language extensions specific to Working Model

Using WM Basic, you can write programs to create and run simulations in Working Model.This mode of operation—called scripting—expands the capability of Working Modelenormously. Below are but a few examples of what you can accomplish with WM Basic.

Run a four-bar linkage simulation repeatedly. Each time, modify thegeometry of the links, plot the trajectory of the coupled link, andexport the data to a file. Also, save each simulation with a completesimulation history to a hard disk for future reviews.Develop a simulation environment using custom-made dialog boxes.The user only needs to specify a set of parameters through graphicaluser interface controls (such as buttons and menus), and WorkingModel will automatically create a model that satisfies the parameters.The user does not need to be familiar with Working Model.Develop an analysis program on your own and link it with WorkingModel. You can write a signal processing program to performfrequency-domain analysis on time-domain simulation data.

Scripting and Interactive OperationsTo introduce the idea of scripting, let us show you two ways of creating five rectangles ofsize 10” (width) by 20” (height) located at (0, 0), (20,0), (40,0), (60,0), and (80,0).

Interactive OperationOne way of accomplishing this task is by using the mouse with click-and-drag operations.You would normally perform the task by using the mouse, the toolbar, and the Properties andGeometry windows.

Scripting OperationAnother, easier way of accomplishing this task is by scripting through WM Basic. Shownbelow is a program, or script, which performs the task (characters following the single quote(') are comments and not part of the program):

Sub Main()Dim Rect as WMBody 'Declare the rectangle.For I = 0 to 4

Set Rect = WM.ActiveDocument.NewBody("rectangle")

Page 23: Working Model 2D - User's Manual

Chapter 1 What is Working Model Basic? 19Rect.Height.Value = 20Rect.Width.Value = 10Rect.PX.Value = I*20 ' position increments by 20Rect.PY.Value = 0

NextEnd Sub

The result of executing this script is as follows:

Later, we will show you how to save and run a script.

Advantages of ScriptingAdvantages of WM Basic over the interactive use of Working Model include:

You can pack a frequently-performed series of operations into amacro. You can quickly execute these macros as often as you like;scripts can be put under the Script menu of Working Model. You can,of course, share your macros with other users.You can combine a set of commands and operations already availablein Working Model and write a large program. The new programworks as if it were one of the Working Model features, because otherusers need not understand or be aware of the mechanism of theprogram.You can create a customized simulation/modeling environment usingdialog boxes and informative messages. The environment can guide anovice user swiftly through Working Model without fullyunderstanding the application or reading the manuals.You can instruct Working Model to perform a series of simulations.Given a carefully written script, Working Model will autonomouslyrepeat simulations while fine-tuning simulation parameters based onthe previous results each time, until desired results can be obtained.

Shown above are but few examples of what you can do with scripting. You will realize theunlimited potential using WM Basic as you read through this chapter.

Page 24: Working Model 2D - User's Manual

20 Working Model Basic User's Manual

Please note that you are not forced to choose either Interactive or Scripting operation.Rather, depending on your application needs, you may wish to operate Working Modelcompletely from scripting level, or you may wish to use scripting as a small macro whichaccelerates your day-to-day modeling effort. You have enormous flexibility in customizinghow you use Working Model.

Objects, Properties, and MethodsThis section introduces you to objects, properties, and methods, which are the crucialconcepts of WM Basic.These concepts are common to most object-oriented programming languages, such as C++.If you are experienced in object-oriented programming, you may be already familiar withthese terms and concepts.

ObjectsObjects are arguably the most basic elements of WM Basic programs. An object is a specialdata type which holds a set of information (called properties) and actions (called methods).If you have programmed in another high-level language such as C or PASCAL, you may befamiliar with data types called structures or records. You can think of an object in WMBasic as an abstraction similar to a structure or record, except an object has its own functionsand commands (methods) in addition to data members such as integers and strings.Since an object already has data members and methods built-in, you do not need to definefunctions and procedures once you define an object in your program. You can immediatelystart calling the methods associated with the object. For example, once you define aWMDocument object, you do not need to define functions or procedures that will create a newbody; they are all built-in, as soon as you define the WMDocument object.WM Basic has predefined object types which represent elements of Working Model. Shownbelow are relationships between objects available in the WM Basic programming languageand elements of the Working Model application.

Page 25: Working Model 2D - User's Manual

Chapter 1 What is Working Model Basic? 21

WMInput object WMBody object

WMPoint object

WMDocument object

WMOutput object

WMConstraint object

Most objects in WM Basic are direct equivalents of physical objects in Working Model, andthey feature very similar, if not identical, functionality. For example, most menu commandsare implemented as part of a WMDocument object, which represents a Working Modeldocument. Likewise, all the entries in Properties, Geometry, and Appearance windows areavailable to a WMBody object which represents a body in Working Model.

Properties of an ObjectA property describes a state of the object. A WMBody object, for example, has mass as one ofits properties.To access the information contained in the properties, you need to specify the object nameand add a period (.) followed by the name of the property. For example, if you want toaccess the mass property of the WMBody object called Wheel, type:

Wheel.Mass.ValueMost of the properties can be modified as well, for example, in an assignment statement. Ifyou want to change the mass of the Wheel to 10, simply type:

Wheel.Mass.Value = 10(The quantity 10 is interpreted in the current unit system.) Note that the result of thisassignment statement is equivalent to that of typing the number "10" in the mass field of theProperties utility window.

Methods of an ObjectBesides having properties, objects also know how to perform certain actions. These actionsare called methods. A WMDocument object, for example, has a method called Run, which runsthe Working Model simulation.As with properties, if you want to use methods associated with an object, you need to specifythe object and add a period (.), followed by the name of the method. For example, suppose

Page 26: Working Model 2D - User's Manual

22 Working Model Basic User's Manual

you have a WMDocument object called MyModel. If you want to run the simulation for 200frames, type:

MyModel.Run 200and the simulation on the document (represented by a WMDocument object called MyModel)will run for 200 frames, at which point Working Model will automatically pause.

Statements and Functions

Methods can be further subdivided into two categories: statements and functions. Statementssimply execute the given instruction and do not return anything. The Reset method shownabove is an example of a statement.On the other hand, functions have a return value. For example, the WMDocument object has amethod called Body, which takes the name of a body and looks for an object with a matchingname. The Body method is a function and therefore has a return value; Body either returnsthe object requested, or returns a special value called Nothing, if no object matching thedescription is found (see “Comparing Objects” on page 26).For example, you would set the object Cam1 to a body called “cam lobe” in Doc1 as follows:

Set Cam1 = Doc1.Body("cam lobe")When you browse through Chapters 2 and 3 of this manual for references, you can easilydistinguish between statements and functions by looking at the syntax section of each entry.Functions must be used with trailing parentheses at all times, whereas statements must beused without parentheses. For example, the syntaxes for the following methods indicate thatthey are functions (note that a pair of parentheses always follow the keyword, whether or nota parameter is provided):

Syntax WM.GetMenuItem(Index [, PathString])

Syntax WMConstraint.Point(index)

Syntax WMDocument.Input(name | id)

Syntax WMDocument.NewOutput()

On the other hand, the syntaxes for the following methods indicate that they are statements.

Syntax WM.DeleteMenuItem Index

Syntax WMConstraint.GetVertex index, x, y

Syntax WMDocument.Run [frames]

Parameters and Return Values for MethodsMost methods take parameters, which are values or objects passed as necessary informationto invoke the method. The return value of a method is yielded as the result of the method.For example, the NewBody method (of a WMDocument object) takes a String parameter whichspecifies the type of the body to be created. If you typed:

Dim MyCircle as WMBody ' declare MyCircle as a WMBody objectSet MyCircle = Doc1.NewBody("circle")

then Working Model would create a circle. Note that parameters are provided to functionswith a pair of parentheses.

Page 27: Working Model 2D - User's Manual

Chapter 1 What is Working Model Basic? 23

Since the NewBody method is a function, it has a return value. In order to invoke anyfunction, you need to store the return value. In the above example, an object of typeMyCircle is used to store the return value of the NewBody method. You cannot simply type:

Doc1.NewBody("circle") ' incorrect usage of a statement.and expect it to be accepted; the return value has to be stored.On the other hand, when you invoke a statement, you need to specify parameters withoutusing parentheses. For example, when you save a document under a specified name (SaveAs), type:

Doc1.SaveAs "c:\mymodel.wm"on Windows, or

Doc1.SaveAs "Macintosh HD:Model 1"on Macintosh.Another example would be to run a simulation. For instance:

Doc1.Run 25will run the simulation for 25 frames and pause.Note that neither SaveAs nor Run have a return value since both are statements and notfunctions.

Declaring ObjectsObject types, such as WMDocument, define an object and its properties and methods. Thetype names (e.g., WMDocument) are not actual variables but a definition of an object type.To create an object variable, you use the Dim statement.1 For example, to declare Doc1 as aWMDocument object variable, use:

Dim Doc1 as WMDocumentLikewise, if you want to declare aBody as a WMBody object variable:

Dim aBody as WMBodyNow you can use the Doc1 and aBody as WMDocument and WMBody object variables,respectively.

Creating, Assigning, and Deleting ObjectsIn most high-level programming languages, you can assign a value to a variable using theequal (=) sign. This rule is true in WM Basic as well. For example:

I = 5assigns 5 to the variable I. You can use the equal sign to assign variables of types Integer(integers), Double (floating point numbers) and String (character strings).The only exceptions to this rule are objects. When you want to assign one object to another,you need to use the Set statement. For example, the following code segment:

Dim BaseMount as WMBodySet BaseMount = WM.ActiveDocument.NewBody("square")

creates a new body (square) in Working Model and assigns the body to the object variablecalled BaseMount. When created with the NewBody method, squares have a defaultdimension (its side is equal to the grid size) and are located at the origin.The assignment statement using Set only assigns pointers to actual objects. For example, ifthe above example is followed by:

1 Dim stands for “dimension” because it needs to allocate a certain space in memory todeclare these objects.

Page 28: Working Model 2D - User's Manual

24 Working Model Basic User's ManualDim SubMount as WMBodySet SubMount = BaseMount

then SubMount also “points to” the same square that BaseMount refers to. Therefore, if youmodify the property of BaseMount as follows:

BaseMount.Width.Value = 1.5then the property SubMount.Width.Value also becomes 1.5.Likewise, if you delete BaseMount by:

WM.ActiveDocument.Delete BaseMount(Delete is a method of a WMDocument object)then the object SubMount becomes Nothing as well (see “Comparing Objects” below);accessing properties such as SubMount.Mass results in a run-time error.Please see the section on Objects in Chapter 2 for more information.

Comparing ObjectsWhen you compare objects in WM Basic, you can use an English-like syntax. For example,the following script searches through the active document for a body called "wheel".

Sub Main()If WM.ActiveDocument.Body("wheel") is Nothing then

MsgBox "The wheel cannot be found in the document"Else

MsgBox "There is a wheel"End If

End SubThe method Body (of WMDocument objects) returns a special value called Nothing when aspecified object could not be found in the document. (Other methods of a WMDocumentobjectsuch as Constraint, Point, Input, and Outputwork the same way; each methodlooks for a specific type of objects, such as a constraint, point, input, or output.)The following code segment checks to see if a WMPoint object (called MyPoint) is attachedto a WMBody object (called MyBody).2 If not, the code will attach MyPoint to MyBody.

If MyPoint.Body is not MyBody thenMsgBox "MyPoint is not attached to MyBody"Set MyPoint.Body = MyBody

End IfNote the use of the "is not" operator for objects.

Your First WM Basic ProgramThis section will walk you through creating and running a simple WM Basic program. Theprogram will create a projectile and a meter to measure the position of the projectile.The sole purpose of this program is to give you an overview of how a WM Basic programmight be structured. This program is not designed to make you master the WM Basicprogramming language—just yet. Do not be alarmed if you cannot understand all the details.If you are experienced in programming in another language, you may wish to try makingmodifications to the program and test your understanding.

2 For more information on WMPoint objects, please refer to the section titled WMPoint (object)in Chapter 3 of this manual.

Page 29: Working Model 2D - User's Manual

Chapter 1 What is Working Model Basic? 25

To Launch the Editor:You start writing programs by launching the Script Editor within Working Model. (StartWorking Model if you have not already done so.)

1. Choose Editor from the Scripts menu.The Script Editor appears as shown below. The figure shows theWindows version of Script Editor; the Macintosh version is virtuallyidentical.

Start (run script)End (stop script)

Toolbar

Procedure Step

Single Step

Calls (show call stack)

Add Watch

Toggle Breakpoint

For details on theScript Editor, pleaserefer to Chapter 4.

All WM Basic programs must have at least these two statements as shown in the blank ScriptEditor window. Sub Main() indicates the starting point of the program, so that WorkingModel knows where to start. End Sub indicates that the program ends there. The content ofthe program is to be "sandwiched" between these two statements.The Script Editor can stay open while you are running Working Model. At times, WorkingModel window may cover the Script Editor window. In such cases, either click anywhere inthe Script Editor, or choose “Editor” in the Script menu of Working Model; this action willbring the Editor window to the front.When you no longer need the Script Editor while using Working Model, you can close thewindow by simply double-clicking on the top left corner of the Script Editor.

To enter the sample program:1. Start Working Model.

A blank, untitled document appears.2. Open the Script Editor (see "To Launch the Editor:" above).

Shown below is the code, followed by explanations. A few remarks about WM Basic codeshould be provided here:

The single quotation mark (') indicates the beginning of a comment.Any character beyond the comment symbol in each line is ignored byWorking Model.

Page 30: Working Model 2D - User's Manual

26 Working Model Basic User's Manual

WM Basic language is not case-sensitive. You can use lower- orupper-case letters in the program and they will be interpreted asidentical. Therefore, when you define or declare two variables such asdoc and Doc, they will be treated as the same variable.You can concatenate two lines of WM Basic using a colon (:).

Enter the following program.Sub Main() ' Line 1

Dim Doc as WMDocument ' Line 2Dim Sphere as WMBody ' Line 3Dim Meter as WMOutput ' Line 4Set Doc = WM.ActiveDocument ' Line 5Set Sphere = Doc.NewBody("circle") ' Line 6Sphere.PX.Value = 0: Sphere.PY.Value = 0 ' Line 7Sphere.Radius.Value = 0.5 ' Line 8Set Meter = Doc.NewOutput() ' Line 9Meter.Column(1).Cell.Formula = "body[1].p.y" ' Line 10Doc.Run 30 ' Line 11

End Sub ' Line 12Each line means the following:

Line 1 serves as the entry point (where the program starts) for anyWM Basic program. When you start writing programs using functionsand procedures, the starting point of a program may not always belocated at the first line. The code Sub Main() needs to be there toclearly indicate that this line is where the main program starts.Lines 2 through 4 are simply declaring object variables to be used forthe rest of the program, as Working Model needs to know the types ofeach object variable before it is used. WMDocument, WMBody, andWMOutput are all (pre-defined) object type names. From here on,objects Doc, Sphere, and Meter have all the properties and methodsassociated with each object types. (But you cannot use them just yet,because you need to assign objects to these object variables first!)Line 5 assigns the object Doc to be the current (active) document of theWorking Model application. WM is a special pre-defined object thatrepresents the Working Model application.Line 6 creates a new body (circle) within Doc, and assigns the newbody to the variable Sphere. NewBody is a method of any WMDocumentobject. Since the object variable Doc has already been defined as avalid WMDocument object (in Line 5), Doc has access to the method aswell.Line 7 specifies the position of the circle to be at the origin (0, 0). PXand PY are properties of B (a WMBody object). Note how the colon (:) isused to separate two statements on the same line.Line 8 specifies the radius of the circle to be 0.5. By default, a circlecreated by the NewBody method has a diameter equal to the current gridsize.Line 9 creates a new output within Doc, and assigns it to the objectMeter.

Page 31: Working Model 2D - User's Manual

Chapter 1 What is Working Model Basic? 27

Line 10 defines the first field of the output Meter so that it displays they position of the body. We typed "body[1]" for simplicity, becausewe know the body created in Line 6 is body[1] (this is the first objectcreated in the document).Note that the columns of a meter need to be specified using WorkingModel’s formula language. The expression "body[1].p.y" means they position of body[1]. Please refer to Working Model User’s Manualfor more information.Line 11 runs the simulation for 30 frames, after which Working Modelwill automatically pause.Line 12 indicates the exit point of the program. The statement EndSub could indicate the end of any program module (such as asubroutine, function, or the main program). In this example, line 12has the matching entry point Sub Main().

Note how each line of the program uses object methods and creates, assigns, or modifies theobject properties.

To run the Sample Program1. Choose Run under the Run menu of the Script Editor, or simply press

the Run button on the Script Editor’s toolbar.Working Model will immediately execute the program. The resultresembles the following picture.

To Run the Program Step By StepRunning a program step by step can be an effective tool for debugging. You can run theprogram one line at a time and watch each line execute. To run a WM Basic script step bystep, simply press the F8 key, or choose Step in the Debug menu of the Script Editor. Thesource code line that is about to be executed appears highlighted in the Script Editor.For more information on debugging scripts, please see Chapter 4 of this manual.

Page 32: Working Model 2D - User's Manual

28 Working Model Basic User's Manual

Saving Your ScriptsYou can save the script you have just written to a file.

To Save a Script1. In the Script Editor, choose Save As in the File menu. The following

dialog box appears.

Choose the desired option (source or object).On the Macintosh version, a check box appears instead.

2. On Windows, choose the Source Code Only option. On Macintosh,leave the check box titled “Save script object code only” blank.A script can be saved as source code (text file) or as object code(compiled). Please see below for implications. On the Windowsversion, you can choose either option from the pop-up menu. On theMacintosh version, you can click the check box titled “Save scriptobject code only”, if you choose to save scripts as object code only.

3. Specify the filename.4. Click OK.

Saving as Source CodeWhen a script is saved as text, you are saving exactly what you typed. You can later open,modify, and debug the code. The debugger (please see Chapter 4 for more details) shows thelines of the source code that is being executed.When a text script is executed, however, Working Model needs to compile the source codebefore executing it. The compile time is almost negligible for small files, but will increase asthe script becomes larger.By default, a source code text is saved with the .wbs suffix on Windows.

Saving as Object CodeWhen a script is saved as object code, Working Model will compile the code first and storethe result in binary format. You can run the compiled script at a later time, but you will notbe able to see or edit the source code. The debugger will not be able to show exact lines ofcode being executed. If you choose to let other Working Model users run your script but donot want them to see the code, you should distribute the script in the object code format.

Page 33: Working Model 2D - User's Manual

Chapter 1 WM Basic Objects 29

WM Basic programs saved as object code are cross-platform; you can run them on bothMacintosh and Windows Working Model, provided that the program does not use platform-specific features. See Appendix C for the list of platform-specific features.Since the code is already compiled, a binary script does not require any additionalcompilation before being executed.By default, object-only scripts are saved with the .wbx suffix on Windows.

WM Basic ObjectsSince Working Model handles sophisticated and complex data such as bodies, constraints,and the simulation setup, you need more than integers and strings which are standard datatypes of a high level programming language. WM Basic has implemented the followingobject types to make writing simulation scripts simple and easy. This section will show youhow WM Basic objects interact with entities in Working Model.The following objects are discussed in this section:Object Description

WMApplication Represents the Working Model application itself.

WMDocument Represents a Working Model document.

WMBody Represents a body in a Working Model document (such as a rectangle,square, circle, and polygon).

WMPoint Represents a point element in a Working Model document (such as asquare point element or an endpoint of a constraint).

WMConstraint Represents a constraint object in a Working Model document (such as aspring, pin joint, and actuator).

WMOutput Represents an output object (meter) in a Working Model document.

WMInput Represents a control object in a Working Model document (such as aslider).

Please refer to Chapter 3, "Working Model Basic Extensions Reference" for completedescriptions on objects, properties, and methods available in WM Basic. The followingsections provide brief descriptions of these object types.

WMApplication ObjectA WMApplication object is the representation of the Working Model application itself.Below are some examples of what you can accomplish using the WMApplication object.To simplify your work, Working Model has already defined a built-in WMApplication objectcalled WM. You cannot define any other WMApplication object. Please refer to the section on“WM (constant)” in Chapter 3 of this document for its complete description.

Creating a New DocumentA WM Basic code to create a new document would be:

Dim Doc as WMDocumentSet Doc = WM.New() ' Creates a new document

Page 34: Working Model 2D - User's Manual

30 Working Model Basic User's Manual

Recall that you need a Set statement to assign objects (see “Creating, Assigning, andDeleting Objects” on page 25).Note that New method has a pair of trailing parentheses because New is a function (see“Statements and Functions” on page 24).

Choosing and Setting the Active DocumentWM Basic provides a facility to access the active document. The active document is thedocument that appears in the foreground of the Working Model application window.To set a WMObject object Doc to the currently active Working Model document, type:

Set Doc = WM.ActiveDocumentWhen Working Model has multiple documents open, you can control which documentshould be the active document (document that appears foreground). You simply need toassign the property to the desired document. Suppose Working Model has two documentsDoc1 and Doc2 open, and you want to set the active document to Doc2. You can type:

Set WM.ActiveDocument = Doc2 ' brings Doc2 to foreground

Opening a Working Model FileTo open a file is saved as "c:\wm30\model1.wm" on Windows, type:

Set Doc = WM.Open("c:\wm30\model1.wm")On Macintosh, use a colon (:) to specify the folder hierarchy. For example, suppose youhave a file called Simulation, your hard disk is called Macintosh HD, and the file is locatedin Working Model 3.0. Then type:

Set Doc = WM.Open("Macintosh HD:Working Model 3.0:Simulation")

WMDocument ObjectA WMDocument object is the representation of a Working Model document. Shown below aresome examples of the operations you can accomplish using a WMDocument object. Pleaserefer to the section WMDocument in Chapter 3 for the complete description.

Saving the Document Under a Specific NameTo save the document Doc under a specific name, you would type:

Doc.SaveAs "c:\mydir\model1.wm" (on Windows)Doc.SaveAs "Hard Disk:My Folder:Model 1" (on Macintosh)

Since SaveAs is a statement, it has no return value.You can also store the time history of the simulation. Please refer to the section onWMDocument.SaveAs in Chapter 3.

Changing the Simulation ModeTo change the simulation mode, modify the SimulationMode property of the WMDocumentobject. For example, if you want to set the current simulation mode of Doc to Fast mode(assume Doc has been declared and defined as a valid WMDocument object):

Doc.SimulationMode = "fast" ' set to Fast simulation modeYou could also type "FAST", "Fast", or any lower- or upper-case combination. For othersimulation modes, please refer to the section WMDocument.SimulationMode in Chapter 3.

Page 35: Working Model 2D - User's Manual

Chapter 1 WM Basic Objects 31

Changing the Unit SystemTo change the unit system, simply modify the UnitSystem property. For example, if youwant to set the current unit system of the document Doc (assume it has been declared anddefined as a valid WMDocument object) to English with pounds:

Doc.UnitSystem = "English (earth pounds)"For the complete description, please refer to the section WMDocument.UnitSystem in Chapter3.

Showing and Hiding the ToolbarYou can show or hide the Toolbar by modifying the ShowToolPalette property of theWMDocument object. The property is of type Boolean; you can set it to either True or False(no quotation marks (") are necessary). By default, ShowToolPalette is set to True,indicating that the Toolbar is shown. To hide the Toolbar of the document D (assume it isdeclared as a WMDocument object):

Doc.ShowToolPalette = False ' Hide the ToolbarSetting it to True will show the Toolbar again.

Running and Resetting a SimulationYou can run, pause, and reset the simulation using methods available to WMDocument objects.For example, to run a simulation of the document Doc (assume it is declared as a WMDocumentobject):

Doc.Run ' runs the simulation indefinitelyThe simulation runs indefinitely, until stopped by the user through Working Model'sgraphical interface (such as the Stop button on the toolbar or Pause Control).If you want to run the simulation for 25 frames and pause, type:

Doc.Run 25 ' runs the simulation for 25 framesTo reset the simulation:

Doc.Reset ' resets the simulation (has no return code)(Please note that the Run method runs the simulation but not the script. For the Run methodto take effect, you still need to execute the script itself, which can be accomplished bypressing the F5 key.)

WMBody ObjectA WMBody object is the representation of a physical body in Working Model (such as a circleor a rectangle). The following sections show examples of what you can accomplish using aWMBody object. Please refer to the section on WMBody in Chapter 3 for the completedescription.

Creating a New BodyTo create a new body within a document:

1. Declare an object variable of type WMBody.2. Assign the variable by using NewBody, which is a method of the

WMDocument object.To create a rectangle, for example, type:

' Suppose the object Doc is set as a valid WMDocument object.Dim Rect as WMBodySet Rect = Doc.NewBody("rectangle")

Page 36: Working Model 2D - User's Manual

32 Working Model Basic User's Manual

The NewBody method takes a string parameter—either "rectangle", "square", "circle", or"polygon"—and creates the body within the document.Initially, the properties of the body are set to default values. For example, squares andrectangles are initially located at (0, 0), and their width and height are equal to the currentgrid size. The grid size can be viewed by activating the grid lines (either from theWorkspace submenu in the World menu, or by modifying WMDocument.ShowGridLinesproperty).The code shown above will create a rectangle (which looks like a square) at (0, 0). Pleaseproceed to the next section to modify these properties.

Specifying Dimensions and Position of a BodyOnce the object is created, you can change its dimensions and position by modifying itsproperties. For example, suppose you want to set the rectangle just created to be 1 1/2"(width) by 2" (height), located at (1.0, 0). Simply type:

Rect.PX.Value = 1.0 ' x-positionRect.PY.Value = 0 ' y-positionRect.Width.Value = 1.5 ' widthRect.Height.Value = 2 ' height

Note: the numerical values are interpreted in the current unit system. See “Changing theUnit System” on page 33 for more information.Note that the properties such as PX, PY, Width, and Height are all WMCell objects. See thesection on WMCell in Chapter 3 for more information.

WMPoint ObjectWMPoint objects represent point elements in Working Model. A WMPoint object hasproperties such as position (local and global), and you can modify them. In addition, aWMPoint object contains information regarding which body the point is attached to, andwhich constraint the point is part of. The following sections show examples of usingWMPoint objects.

Creating a New Point ElementTo create a new point element within a document, declare a WMPoint object and useNewPoint, a method of WMDocument.To create a point element, for example, type:

Dim Pt as WMPoint ' Declare a WMPoint objectSet Pt = WM.ActiveDocument.NewPoint("point")

The NewPoint method takes a String parameter—"point", "squarepoint", or"anchor"—and creates the corresponding point element within the document. The positionof the new point element defaults to (0, 0). Upon creation, the point attaches itself to thebackground, regardless of whether a body may exist near (0, 0) or not.

Modifying the Position of a Point ElementTo modify the position of a point element, simply modify the PX and PY properties of theWMPoint object. For example:

' Create a point at (2.0, 3.5).Dim Pt as WMPointSet Pt = WM.ActiveDocument.NewPoint("point")Pt.PX.Value = 2.0

Page 37: Working Model 2D - User's Manual

Chapter 1 WM Basic Objects 33Pt.PY.Value = 3.5

If you have already attached a point to a body, then the properties PX and PY hold the localcoordinates, given with respect to the frame of reference of the body. You can still accessglobal position of the point as well. See the section “Attaching Points to Bodies” below formore information.

Attaching Points to BodiesTo attach a point to a body, simply assign the Body property of the WMPoint object to thedesired body. For example, you can create a point and a body (both will default to theposition (0, 0) when created), and attach the point to the body in the following fashion:

' Create a point and a square. Attach the point to the square.Dim Pt as WMPointDim Square as WMBodySet Square = WM.ActiveDocument.NewBody("square") ' at (0, 0)Square.Width.Value = 1.0 ' specify the dimension of the squareSet Pt = WM.ActiveDocument.NewPoint("point") ' at (0, 0)Set Pt.Body = Square ' attaches the point to Square.Pt.PX.Value = 0.0: Pt.PY.Value = 0.0

The last line is not necessary; it is there to emphasize that the position of the point element isnow (0, 0) (with respect to the square).After executing this code, your screen should look like the following:

Square islocated at (0, 0)

Point is attached at(0, 0) of the square

From then on , the position properties of the WMPoint object will be based on the frame ofreference of the WMBody object. For example, suppose you added the following code segmentto the above example:

' Move the square just created to (6.0, 4.0)B.PX.Value = 6.0B.PY.Value = 4.0

Then the point element P, previously attached to the square, would move together with thesquare. Since the point element is still attached at (0, 0) of the square, the propertiesP.PX.Value and P.PY.Value both remain 0.

Page 38: Working Model 2D - User's Manual

34 Working Model Basic User's Manual

Accessing Global Position of a Point ElementOn the other hand, the global position of this point element is (6.0, 4.0), since the square wasmoved to that position. To access the global position of the point element, use theexpressions P.GlobalPX and P.GlobalPY.Note: GlobalPX and GlobalPY are not accessible if formula expressions are used to specifyPX and PY properties of the point element. This is because any formula expressions in PX andPY override any specifications in GlobalPX and GlobalPY. For example, if you are usinggeometry-based expressions (e.g. body[3].width, body[4].radius) to define the pointcoordinates on a body, GlobalPX and GlobalPY are not accessible (i.e., you can neithermodify them or read them; they always return 0).

WMConstraint ObjectWMConstraint objects represent constraints used in Working Model. A WMConstraintobject has type-dependent properties and information regarding its endpoint(s), and you canmodify them. The following sections show examples of what you can accomplish withWMConstraint objects.

Creating ConstraintsTo create a new constraint, declare a WMConstraint object and use NewConstraint, amethod of a WMDocument object. You need to specify which type of constraint you wish tocreate as a parameter to the NewConstraint method.To create a spring, for example, type:

Dim Spring as WMConstraint ' Declare WMconstraint objectSet Spring = WM.ActiveDocument.NewConstraint("spring")

The NewConstraint method takes a String parameter, which specifies the type of theconstraint to be created. Once a constraint is created, you cannot change its type. Please seethe section on WMConstraint in Chapter 3 for the full descriptions of the type parameters.The above code segment simply creates a spring, and by default, both endpoints are attachedto the background and located at (0, 0). Please see the following sections to attach theendpoints properly to desired bodies and to change properties of the constraint.

Attaching Constraints to BodiesTo attach a constraint to a body,

1. Attach the endpoints of the constraint object to the desired body (aWMBody object) using the Point method of the WMConstraint.

2. Modify the positions of the endpoints so that the they are attached tothe desired location on the body.

For example, suppose Square is a body (as created in “WMBody Object” on page 33). Thenyou can create a spring and attach it to the body as follows.

' Assume Doc is a valid WMDocument object.' Assume Square is a valid WMBody object.Dim Spring as WMConstraint ' Declare WMconstraint objectSet Spring = Doc.NewConstraint("spring") ' Create spring' At this point, both endpoints of the spring are attached' to the background and located at (0, 0).' Attach one of the endpoints to B and position the point to

Page 39: Working Model 2D - User's Manual

Chapter 1 WM Basic Objects 35' (3, 5) on the body.Set Spring.Point(1).Body = Square' From here on, the PX/PY fields of Point(1) are measured' with respect to the FOR of the body.Spring.Point(1).PX.Value = 0.2Spring.Point(1).PY.Value = 0.5' Set the position of the other endpoint to (3, 0) (global)Spring.Point(2).PX.Value = 3.0Spring.Point(2).PY.Value = 0.0

The result of the above code segment results in the following:

Point(1) located at (0.2,0.5) on the square

Point(2) located at (3.0, 0.0)

Modifying Constraint PropertiesEvery constraint has properties that may or may not be unique to its type. For example, aspring has properties such as spring constant and rest length, but these properties are notmeaningful for a motor. The section on WMConstraint in Chapter 3 describes exactly whichproperties are available for each type of constraints.For example, to modify the spring constant to 120, simply type (assume MySpring is a validWMConstraint object whose type is spring):

MySpring.K.Value = 120 ' Change the spring constant to 120To change the natural length of the spring to 2.5 (again, assume MySpring is a valid springconstraint):

MySpring.Length.Value = 2.5 ' Change the rest length to 2.5Again, please refer to individual sections (such as WMConstraint.K andWMConstraint.Length) in Chapter 3 for the complete descriptions of these properties.

WMOutput ObjectWMOutput objects represent meter objects used in Working Model. A WMOutput object hasproperties describing the meter columns, as well as its own position and size in the documentwindow.

Creating MetersTo create a new meter in a document, declare a WMOutput object and use NewOutput, amethod of WMDocument. Please see the section on WMOutput for more information.

Page 40: Working Model 2D - User's Manual

36 Working Model Basic User's Manual

To create a meter, for example, type:Dim Meter as WMOutput ' Declare WMOutput objectSet Meter = WM.ActiveDocment.NewOutput()

By default, the NewOutput method will create a time meter. You can customize the meter tomeasure desired properties, change the meter type to graph plots, and move it to an arbitraryposition on the document as well.Each WMOutput object has X, Y (for x- and y-positions), Width, and Height (width andheight) properties. You can modify these properties to position and size the meter arbitrarily.

Specifying Quantities to be MeasuredJust like every meter in Working Model, one WMOutput object can measure up to fourquantities.Each measured quantity is specified using the Column method of the WMOutput object. Forexample, in order to measure the y-position of body[1], you would use the following codesegment:

Dim Meter as WMOutput ' Declare WMOutput objectSet Meter = WM.ActiveDocument.NewOutput()' Modify the column y1 to measure the y position of body[1]Meter.Column(1).Cell.Formula = "body[1].p.y"Meter.Column(1).Label = "Y-pos of body[1]" ' optional

The parameter "1" passed to the Column method accesses the first column of the meter(labeled y1 in the Properties window of the meter). The property Cell returns to a WMCellobject, hence the subsequent property Formula (please see the section on WMCell in Chapter3 for more information). The Label property is used as an informative label for the user(appears as the column label on the meter) and therefore optional.Note: You must specify the columns using Working Model's formula expressions or numericconstants. You cannot apply WM Basic expressions such as "Body.PY.Value", since themeter columns are designed to accept only formula expressions or numeric constants.For the complete descriptions of WMOutput objects, please see the section on WMOutput inChapter 3.

WMInput ObjectWMInput objects represent controls (input objects) used in Working Model. A WMInputobject has properties regarding its style (e.g., slider, button, textbox), position, anddimensions on the screen.

Creating InputsTo create a new input in a document, declare a WMInput object and use NewInput, a methodof WMDocument. Inputs default to the slider type.The following example shows how to create a slider in a document. This code segmentcorresponds to choosing “Generic Control” in the Define -> Control menu.

Dim I as WMInput ' Declare a WMInput objectSet I = D.NewInput() ' Assume D is a WMDocument

Each WMInput object has X, Y (for x- and y-positions), Width, and Height (width and height),just like a WMOutput object. You can modify these properties to position and size theWMInput object arbitrarily. Please see the section on WMInput for more information.

Page 41: Working Model 2D - User's Manual

Chapter 1 Putting it All Together: A Simple WM Basic Program 37

Specifying Objects to be ControlledTo link WMInput to other objects in Working Model, you simply need to assign the input IDto the desired property to be controlled.For example, the following code segment shows how to create a new control to specify theinitial x-velocity of a body called Circle (assume Circle has been declared and defined as avalid WMBody object):

Dim Slider as WMInputSet Slider = WM.ActiveDocument.NewInput()Circle.VX.Formula = "input["+str$(Slider.ID)+"]"

The third line above warrants an explanation. Typically, you would specify an expressionsuch as "input[5]", but the ID number of the Input just created may not be necessarily 5.The ID property of the WMInput object retains the number, and the number is converted to astring by the str$ function. Finally, the number is concatenated with "input[" followedby "]" to create a valid Working Model formula expression.

Changing the Input ValueAn input control in Working Model is a flexible tool which allows you to change its valuewhile the simulation is running. In interactive operation, the user moves the slider bar tochange the input values. In scripting operation, you can simply modify the Value property ofthe WMInput object to change the value. The Value property holds values of type Double.For example, the following line sets the slider value of a WMInput object called Slider to be5.5.

Slider.Value = 5.5

Putting it All Together: A Simple WM BasicProgramNow that you know the fundamental elements of Working Model Basic, we will walk youthrough a simple WM Basic program.

Spring-Mass SimulationThe following code performs the following tasks:

1. Creates a new Working Model document.2. Creates a disk.3. Attaches a spring to the disk.4. Creates an input slider to specify the downward initial velocity of the

disk.4. Creates a meter to measure the y position and velocity of the disk.5. Runs the simulation for 50 frames and exports the meter data to a file.6. Closes and saves the document.

Most of the functions are derived from examples provided in the preceding sections in thecurrent chapter.

Sub Main()' Declare objectsDim Doc as WMDocumentDim Disk as WMBodyDim Spring1 as WMConstraint

Page 42: Working Model 2D - User's Manual

38 Working Model Basic User's ManualDim Slider as WMInputDim Meter1 as WMOutput

' Create a new documentSet Doc = WM.New()

' Change the unit system and view sizeDoc.UnitSystem = "si degrees"Doc.ViewWidth = 20.0Doc.ScrollTo 0, 0

' Create a circleSet Disk = Doc.NewBody("circle")Disk.Radius.Value = 2.0

' Create a spring and attach it to the bodySet Spring1 = Doc.NewConstraint("spring") ' Create springSet Spring1.Point(1).Body = Disk ' Attach to DiskSpring1.Point(1).PX.Value = 0.0Spring1.Point(1).PY.Value = 0.0Spring1.Point(2).PX.Value = 0.0Spring1.Point(2).PY.Value = 5.0

' Create a new meterSet Meter1 = Doc.NewOutput()Dim DiskID as IntegerDiskID = Disk.IDMeter1.Column(1).Cell.Formula =

"body["+str$(DiskID)+"].p.y"Meter1.Column(1).Label = "Py"Meter1.Column(2).Cell.Formula =

"body["+str$(DiskID)+"].v.y"Meter1.Column(2).Label = "Vy"Meter1.Column(2).AutoScale = TrueMeter1.Format = "Graph"Meter1.X = 10: Meter1.Y = 10

' Create a new inputSet Slider = Doc.NewInput()Slider.X = 50: Slider.Y = 150Disk.VY.Formula = "input["+str$(Slider.ID)+"]"Slider.Min = -20: Slider.Max = 20 ' set input rangeSlider.Value = -5 ' set current valueSlider.Name = "Initial Y-velocity"

' Run the simulation for 100 frames and resetDoc.Run 100Doc.Reset

' Exports the meter data to a fileDoc.ExportStartFrame = 0Doc.ExportStopFrame = 100Doc.ExportMeterData "data1.txt"Doc.Reset

' Saves the simulation file with history

Page 43: Working Model 2D - User's Manual

Where to Go from Here 39Doc.SaveAs "pendulum.wm", TrueDoc.Close

End Sub

Where to Go from HereNow that you know the fundamentals of WM Basic, you are ready to take full advantage ofthe scripting feature.If you are interested in more about the Script Editor and its flexible debugging feature. Youshould consult Chapter 4, Editing and Debugging Scripts. As you write longer and longerscripts, you will find the debugging feature tremendously useful.Chapter 2 and Chapter 3 provide complete references for all the keywords, functions,methods, and objects available in WM Basic. The chapters show not only syntax and usagebut also small examples.To tie in dialog boxes and other graphical user interface tools of WM Basic, consult Chapter5 for details. You can create a whole new simulation environment using custom dialog boxesand scripts.Chapter 6 provides an overview for those interested in using Working Model as a DDE orApple event server. Other applications such as Excel or MATLAB can control WorkingModel by sending commands written in WM Basic.

Page 44: Working Model 2D - User's Manual

40 Working Model Basic User's Manual

C H A P T E R 2

This chapter of the Working Model Basic User's Manual contains a complete, alphabeticallisting of all keywords in the Working Model Basic (WM Basic) language. When syntax isdescribed, the following notations are used:

Notation Description

While...Wend Elements belonging to the WM Basic language,referred to in this manual as keywords, appear in thetypeface shown to the left.

variable Items that are to be replaced with information that yousupply appear in italics. The type of replacement isindicated in the following description.

text$ The presence of a type-declaration character followinga parameter signifies that the parameter must be avariable of that type or an expression that evaluates tothat type.

If a parameter does not appear with a type-declarationcharacter, then its type is described in the text.

[parameter] Square brackets indicate that the enclosed items areoptional.

Note: In WM Basic, you cannot end a statement with acomma, even if the parameters are optional:

MsgBox "Hello",,"Message" 'OK

MsgBox "Hello",, 'Not valid

{Input | Binary} Braces indicate that you must choose one of theenclosed items, which are separated by a vertical bar.

... Ellipses indicate that the preceeding expression can berepeated any number of times.

A–Z Reference

Page 45: Working Model 2D - User's Manual

Chapter 2 & (operator) 41

& (operator)Syntax expression1 & expression2

Description Returns the concatenation of expression1 and expression2.

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 aString variant. If both expressions are Null, then a Null variant isreturned. If only one expression is Null, then it is treated as a zero-lengthstring. Empty variants are also treated as zero-length strings.

In many instances, the plus (+) operator can be used in place of &. Thedifference is that + attempts addition when used with at least one numericexpression, whereas & always concatenates.

Example 'This example assigns a concatenated string to variable s$ and astring 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 + (operator); Operator Precedence (topic).

Platform(s) Windows and Macintosh.

' (keyword)Syntax 'text

Description Causes the compiler to skip all characters between this character and the end ofthe 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 (statement); Comments (topic).

Platform(s) Windows and Macintosh.

Page 46: Working Model 2D - User's Manual

42 Working Model Basic User's Manual

() (keyword)Syntax 1 ...(expression)...

Syntax 2 ...,(parameter),...

Description Forces parts of an expression to be evaluated before others or forces aparameter to be passed by value.

Comments Parentheses within Expressions

Parentheses override the normal precedence order of WM Basic operators,forcing a subexpression to be evaluated before other parts of the expression.For example, the use of parentheses in the following expressions causesdifferent results:

i = 1 + 2 * 3 'Assigns 7.i = (1 + 2) * 3 'Assigns 9.

Use of parentheses can make your code easier to read, removing anyambiguity in complicated expressions.

Parentheses Used in Parameter Passing

Parentheses can also be used when passing parameters to functions orsubroutines 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, thefollowing statement appears to be calling a function called ShowForm withoutassigning the result:

ShowForm(i)

The above statement actually calls a subroutine called ShowForm, passing it thevariable i by value. It may be clearer to use the ByVal keyword in this case,which accomplishes the same thing:

ShowForm ByVal i

Note: The result of an expression is always passed by value.

Page 47: Working Model 2D - User's Manual

Chapter 2 * (operator) 43

Example 'This example uses parentheses to clarify an expression.

Sub Main()bill = Falsedave = Truejim = True

If (dave And bill) Or (jim And bill) ThenMsgbox "The required parties for the meeting are here."

ElseMsgBox "Someone is late again!"

End IfEnd Sub

See Also ByVal (keyword); Operator Precedence (topic).

Platform(s) Windows and Macintosh.

* (operator)Syntax expression1 * expression2

Description Returns the product of expression1 and expression2.

Comments The result is the same type as the most precise expression, with the followingexceptions:

If one and the other then the typeexpression is expression is of the result is

Single Long Double

Boolean Boolean Integer

Date Date Double

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 theresult is automatically promoted to a Long variant.

If the type of the result is a Single, Long, or Date variant thatoverflows, then the result is automatically promoted to a Double variant.

If expression1 is Null and expression2 is Boolean, then the result isEmpty. Otherwise, If either expression is Null, then the result is Null.

Page 48: Working Model 2D - User's Manual

44 Working Model Basic User's Manual

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.55t# = 2.55u# = s# * t#MsgBox s# & " * " & t# & " = " & s# * t#

End Sub

See Also Operator Precedence (topic).

Platform(s) Windows and Macintosh.

+ (operator)Syntax expression1 + expression2

Description Adds or concatenates two expressions.

Comments Addition operates differently depending on the type of the two expressions:

If one and the otherexpression is expression is then

Numeric Numeric Perform a numeric add (see below).

String String Concatenate, returning a string.

Numeric String A runtime error is generated.

Variant String Concatenate, returning a Stringvariant.

Variant Numeric Perform a variant add (see below).

Empty variant Empty variant Return an Integer variant, value 0.

Empty variant Boolean variant Return an Integer variant (value 0 or -1)

Empty variant Any data type Return the non-Empty expressionunchanged.

Null variant Any data type Return Null.

Variant Variant If either is numeric, add; otherwise,concatenate.

When using + to concatenate two variants, the result depends on the types ofeach variant at runtime. You can remove any ambiguity by using the &operator.

Page 49: Working Model 2D - User's Manual

Chapter 2 – (operator) 45

Numeric Add

A numeric add is performed when both expressions are numeric (i.e., notvariant or string). The result is the same type as the most precise expression,with the following exceptions:

If one and the other then the typeexpression is expression is of the result is

Single Long Double

Boolean Boolean Integer

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 otherexpression is Variant, then a variant add is performed. The rules for variantadd are the same as those for normal numeric add, with the followingexceptions:

If the type of the result is an Integer variant that overflows, then theresult is a Long variant.

If the type of the result is a Long, Single, or Date variant thatoverflows, 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$ = "Concatenation" + " is fun!"j% = 120 + 5 'Addition of numeric literalsk# = j% + 2.7 'Addition of numeric variableMsgBox "This concatenation becomes: '" i$ + Str(j%) + Str(k#) & "'"

End Sub

See Also & (operator); Operator Precedence (topic).

Platform(s) Windows and Macintosh.

– (operator)Syntax 1 expression1 – expression2

Syntax 2 –expression

Description Returns the difference between expression1 and expression2 or, in the secondsyntax, returns the negation of expression.

Page 50: Working Model 2D - User's Manual

46 Working Model Basic User's Manual

Comments Syntax 1

The type of the result is the same as that of the most precise expression, withthe following exceptions:

If one and the other then the typeexpression is expression is of the result is

Long Single Double

Boolean Boolean Integer

A runtime error is generated if the result overflows its legal range.

When either or both expressions are Variant, then the following additionalrules apply:

If expression1 is Null and expression2 is Boolean, then the result isEmpty. 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 theresult is a Long variant.

If the type of the result is a Long, Single, or Date variant thatoverflows, then the result is a Double variant.

Syntax 2

If expression is numeric, then the type of the result is the same type asexpression, with the following exception:

If expression is Boolean, then the result is Integer.

Note: In 2's compliment arithmetic, unary minus may result in an overflowwith Integer and Long variables when the value of expression is the largestnegative number representable for that data type. For example, the followinggenerates an overflow error:

Sub Main()Dim a As Integera = -32768a = -a 'Generates overflow here.

End Sub

When negating variants, overflow will never occur because the result will beautomatically promoted: integers to longs and longs to doubles.

Page 51: Working Model 2D - User's Manual

Chapter 2 . (keyword) 47

Example 'This example assigns values to two numeric variables and their'difference to a third variable, then displays the result.

Sub Main()i% = 100j# = 22.55k# = i% - j#MsgBox "The difference is: " & k#

End Sub

See Also Operator Precedence (topic).

Platform(s) Windows and Macintosh.

. (keyword)Syntax 1 object.property

Syntax 2 structure.member

Description Separates an object from a property or a structure from a structure member.

Examples 'This example uses the period to separate an object from a property.

Sub Main()MsgBox Clipboard.GetText()

End Sub

'This example uses the period to separate a structure from a member.

Type Rectleft As Integertop As Integerright As Integerbottom As Integer

End Type

Sub Main()Dim r As Rectr.left = 10r.right = 12

End Sub

See Also Objects (topic).

Platform(s) Windows and Macintosh.

/ (operator)Syntax expression1 / expression2

Description Returns the quotient of expression1 and expression2.

Page 52: Working Model 2D - User's Manual

48 Working Model Basic User's Manual

Comments The type of the result is Double, with the following exceptions:

If one and the other then the typeexpression is expression is of the result is

Integer Integer Single

Single Single Single

Boolean Boolean Single

A runtime error is generated if the result overflows its legal range.

When either or both expressions is Variant, then the following additionalrules 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 resultoverflows, 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% = 100j# = 22.55k# = i% / j#MsgBox "The quotient of i/j is: " & k#

End Sub

See Also \ (operator); Operator Precedence (topic).

Platform(s) Windows and Macintosh.

< (operator)See Comparison Operators (topic).

<= (operator)See Comparison Operators (topic).

<> (operator)See Comparison Operators (topic).

Page 53: Working Model 2D - User's Manual

Chapter 2 = (statement) 49

= (statement)Syntax variable = expression

Description Assigns the result of an expression to a variable.

Comments When assigning expressions to variables, internal type conversions areperformed automatically between any two numeric quantities. Thus, you canfreely assign numeric quantities without regard to type conversions. However,it is possible for an overflow error to occur when converting from larger tosmaller types. This occurs when the larger type contains a numeric quantity thatcannot be represented by the smaller type. For example, the following code willproduce a runtime error:

Dim amount As LongDim 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 Setstatement instead.

Example Sub Main()a$ = "This is a string"b% = 100c# = 1213.3443MsgBox a$ & "," & b% & "," & c#

End Sub

See Also Let (statement); Operator Precedence (topic); Set (statement); ExpressionEvaluation (topic).

Platform(s) Windows and Macintosh.

= (operator)See Comparison Operators (topic).

> (operator)See Comparison Operators (topic).

>= (operator)See Comparison Operators (topic).

\ (operator)Syntax expression1 \ expression2

Page 54: Working Model 2D - User's Manual

50 Working Model Basic User's Manual

Description Returns the integer division of expression1 and expression2.

Comments Before the integer division is performed, each expression is converted to thedata type of the most precise expression. If the type of the expressions is eitherSingle, Double, Date, or Currency, then each is rounded to Long.

If either expression is a Variant, then the following additional rules apply:

If either expression is Null, then the result is Null.

Empty is treated as an Integer of value 0.

Example 'This example assigns the quotient of two literals to a variable and'displays the result.

Sub Main()s% = 100.99 \ 2.6MsgBox "Integer division of 100.99\2.6 is: " & s%

End Sub

See Also / (operator); Operator Precedence (topic).

Platform(s) Windows and Macintosh.

^ (operator)Syntax expression1 ^ expression2

Description Returns expression1 raised to the power specified in expression2.

Comments The following are special cases:

Special Case Value

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 areallowed.

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 afractional result.

Page 55: Working Model 2D - User's Manual

Chapter 2 _ (keyword) 51

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

See Also Operator Precedence (topic).

Platform(s) Windows and Macintosh.

_ (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 WM Basicstatement onto more than one line.

Comments The line-continuation character cannot be used within strings and must bepreceded by white space (either a space or a tab).

The line-continuation character can be followed by a comment, as shownbelow:

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.

msg = "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 calculationlines.

b# = .124a# = .223s# = ( (((Sin(b#) ^ 2) + (Cos(a#) ^ 2)) ^ .5) / _

(((Sin(a#) ^ 2) + (Cos(b#) ^ 2)) ^ .5) ) * 2.00MsgBox msg & crlf & "The value of s# is: " & s#

End Sub

Platform(s) Windows and Macintosh.

Abs (function)Syntax Abs(expression)

Page 56: Working Model 2D - User's Manual

52 Working Model Basic User's Manual

Description Returns the absolute value of expression.

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 followingexceptions:

If expression is an Integer that overflows its legal range, then the result isreturned as a Long. This only occurs with the largest negative Integer:

Dim a As VariantDim i As Integeri = -32768a = Abs(i) 'Result is a Long.i = Abs(i) 'Overflow!

If expression is a Long that overflows its legal range, then the result isreturned as a Double. This only occurs with the largest negative Long:

Dim a As VariantDim l As Longl = -2147483648a = Abs(l) 'Result is a Double.l = Abs(l) 'Overflow!

If expression is a Currency value that overflows its legal range, anoverflow 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

See Also Sgn (function).

Platform(s) Windows and Macintosh.

ActivateControl (statement)Syntax ActivateControl control

Description Sets the focus to the control with the specified name or ID.

Page 57: Working Model 2D - User's Manual

Chapter 2 And (operator) 53

Comments The control parameter specifies either the name or the ID of the control to beactivated, as shown in the following table:

If control is Then

String A control associated with that name is activated.

For push buttons, option buttons, or check boxes, the control with this name isactivated. For list boxes, combo boxes, and text boxes, the control thatimmediately follows the text control with this name is activated.

Numeric A control with this ID is activated. The ID is first converted to an Integer.

The ActivateControl statement generates a runtime error if the dialogcontrol referenced by control cannot be found.

You can use the ActivateControl statement to set the focus to a customcontrol within a dialog box. First, set the focus to the control that immediatelyprecedes the custom control, then simulate a Tab keypress, as in the followingexample:

ActivateControl "Portrait"DoKeys "{TAB}"

Note: The ActivateControl statement is used to activate a control in anotherapplication's dialog box. Use the DlgFocus statement to activate a control in adynamic dialog box.

Example 'This example runs Notepad using Program Manager's Run command. It usesthe'ActivateControl command to switch focus between the different controlsof'the Run dialog box.

Sub Main()If AppFind$("Program Manager") = "" Then Exit SubAppActivate "Program Manager"Menu "File.Run"SendKeys "Notepad"ActivateControl "Run minimized"SendKeys " "ActivateControl "OK"SendKeys "{Enter}"

End Sub

See Also DlgFocus (statement).

Platform(s) Windows.

And (operator)Syntax expression1 And expression2

Page 58: Working Model 2D - User's Manual

54 Working Model Basic User's Manual

Description Performs a logical or binary conjunction on two expressions.

Comments If both expressions are either Boolean, Boolean variants, or Null variants,then a logical conjunction is performed as follows:

If the first and the second then theexpression is expression is result is

True True TrueTrue False FalseTrue Null NullFalse True FalseFalse False FalseFalse Null NullNull True NullNull False FalseNull Null Null

Binary Conjunction

If the two expressions are Integer, then a binary conjunction is performed,returning an Integer result. All other numeric types (including Emptyvariants) 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 thebinary representations of the two expressions according to the following table:

1 And 1 = 1 Example:0 And 1 = 0 5 000010011 And 0 = 0 6 00001010 0 And 0 = 0 And 00001000

Page 59: Working Model 2D - User's Manual

Chapter 2 AnswerBox (function) 55

Example Sub Main()n1 = 1001n2 = 1000b1 = Trueb2 = 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 anddisplays the

'result.If b1 And b2 Then

MsgBox "b1 and b2 are True; n3 is: " & n3Else

MsgBox "b1 and b2 are False; n3 is: " & n3End If

End Sub

See Also Operator Precedence (topic); Or (operator); Xor (operator); Eqv (operator); Imp(operator).

Platform(s) Windows and Macintosh.

AnswerBox (function)Syntax AnswerBox(prompt [,[button1] [,[button2] [,button3]]]]])

Description Displays a dialog box prompting the user for a response and returns anInteger indicating which button was clicked (1 for the first button, 2 for thesecond, and so on).

Comments The AnswerBox function takes the following parameters:

Parameter Description

prompt Text to be displayed above the text box. The prompt parameter can be anyexpression convertible to a String.

WM Basic resizes the dialog box to hold the entire contents of prompt, up to amaximum width of 5/8 of the width of the screen and a maximum height of 5/8of the height of the screen. WM Basic word-wraps any lines too long to fitwithin the dialog box and truncates all lines beyond the maximum number oflines that fit in the dialog box.

You can insert a carriage-return/line-feed character in a string to cause a linebreak in your message.

A runtime error is generated if this parameter is Null.

button1 Text for the first button. If omitted, then "OK" and "Cancel" are used. Aruntime error is generated if this parameter is Null.

Page 60: Working Model 2D - User's Manual

56 Working Model Basic User's Manual

button2 Text for the second button. A runtime error is generated if this parameter isNull.

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. Itdisplays'an additional message based on which of the three buttons is selected.

Sub Main()r% = AnswerBox("Copy files?", "Save", "Restore", "Cancel")Select Case r%

Case 1MsgBox "Files will be saved."

Case 2MsgBox "Files will be restored."

Case ElseMsgBox "Operation canceled."

End SelectEnd Sub

See Also MsgBox (statement); AskBox$ (function); AskPassword$ (function); InputBox,InputBox$ (functions); OpenFilename$ (function); SaveFilename$ (function);SelectBox (function).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

AnswerBox displays all text in its dialog box in 8-point MS Sans Serif.

Page 61: Working Model 2D - User's Manual

Chapter 2 Any (data type) 57

Any (data type)Description Used with the Declare statement to indicate that type checking is not to be

performed with a given argument.

Comments Given the following declaration:

Declare Sub Foo Lib "FOO.DLL" (a As Any)

the following calls are valid:

Foo 10Foo "Hello, world."

Example 'The following example calls the FindWindow to determine if ProgramManager'is running. This example will only run under Windows.

'This example uses the Any keyword to pass a NULL pointer, which isaccepted'by the FindWindow function.

Declare Function FindWindow16 Lib "user" Alias "FindWindow" (ByValClass _

As Any,ByVal Title As Any) As Integer

Sub Main()Dim hWnd As Variant

If Basic.Os = ebWin16 ThenhWnd = FindWindow16("PROGMAN",0&)

ElsehWnd = 0

End If

If hWnd <> 0 ThenMsgBox "Program manager is running, window handle is " & hWnd

End IfEnd Sub

See Also Declare (statement).

Platform(s) Windows and Macintosh.

AppActivate (statement)Syntax AppActivate name$ | taskID

Description Activates an application given its name or task ID.

Page 62: Working Model 2D - User's Manual

58 Working Model Basic User's Manual

Comments The AppActivate statement takes the following parameters:

Parameter Description

name$ String containing the name of the application to be activated.

taskID Number specifying the task ID of the application to be activated. Acceptabletask IDs are returned by the Shell function.

Note: When activating applications using the task ID, it is important to declarethe variable used to hold the task ID as a Variant. The type of the IDdepends on the platform on which WM Basic is running.

Examples 'This example activates Program Manager.

Sub Main()AppActivate "Program Manager"

End Sub

'This example runs another application, then activates it.

Sub Main()Dim id as variantid = Shell("Notepad",7) 'Run Notepad minimized.AppActivate "Program Manager" 'Activate Program Manager.AppActivate id 'Now activate Notepad.

End Sub

See Also Shell (function); SendKeys (statement); WinActivate (statement).

Platform(s) Windows and Macintosh..

PlatformNotes:

Windows

The name$ parameter is the exact string appearing in the title bar of the namedapplication's main window. If no application is found whose title exactlymatches name$, then a second search is performed for applications whose titlestring begins with name$. If more than one application is found that matchesname$, then the first application encountered is used.

Minimized applications are not restored before activation. Thus, activating aminimized 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 thecase if that application is currently displaying a modal dialog box.

Page 63: Working Model 2D - User's Manual

Chapter 2 AppClose (statement) 59

PlatformNotes:

Macintosh

On the Macintosh, the name$ parameter specifies the title of the desiredapplication. The MacID function can be used to specify the applicationsignature of the application to be activated:

AppActivate MacID(text$) | task

The text$ parameter is a four-character string containing an applicationsignature. A runtime error occurs if the MacID function is used on platformsother than the Macintosh.

AppClose (statement)Syntax AppClose [name$]

Description Closes the named application.

Comments The name$ parameter is a String containing the name of the application. Ifthe name$ parameter is absent, then the AppClose statement closes the activeapplication.

Example 'This example activates Excel, then closes it.

Sub Main()If AppFind$("Microsoft Excel") = "" Then 'Make sure Excel is

there.MsgBox "Excel is not running."Exit Sub

End IfAppActivate "Microsoft Excel" 'Activate it (unnecessary).AppClose "Microsoft Excel" 'Close it.

End Sub

See Also AppMaximize (statement); AppMinimize (statement); AppRestore (statement);AppMove (statement); AppSize (statement).

Platform(s) Windows.

PlatformNotes:

Windows

A runtime error results if the application being closed is not enabled, as is thecase if that application is currently displaying a modal dialog box.

The name$ parameter is the exact string appearing in the title bar of the namedapplication's main window. If no application is found whose title exactlymatches name$, then a second search is performed for applications whose titlestring begins with name$. If more than one application is found that matchesname$, then the first application encountered is used.

AppFilename$ (function)Syntax AppFilename$([name$])

Page 64: Working Model 2D - User's Manual

60 Working Model Basic User's Manual

Description Returns the filename of the named application.

Comments The name$ parameter is a String containing the name of the desiredapplication. If the name$ parameter is omitted, then the AppFilename$function returns the filename of the active application.

Example 'This example switches the focus to Excel, then changes the currentdirectory'to be the same as that of Excel.

Sub Main()If AppFind$("Microsoft Excel") = "" Then 'Make sure Excel is

there.MsgBox "Excel is not running."Exit Sub

End IfAppActivate "Microsoft Excel" 'Activate Excel.s$ = AppFilename$ 'Find where the Excel executable is.d$ = FileParse$(s$,2) 'Get the path portion of the

filename.MsgBox d$ 'Display directory name.

End Sub

See Also AppFind$ (function).

Platform(s) Windows.

PlatformNotes:

Windows

For DOS applications launched from Windows, the AppFilename functionreturns the name of the DOS program, not winoldap.exe.

The name$ parameter is the exact string appearing in the title bar of the namedapplication's main window. If no application is found whose title exactlymatches name$, then a second search is performed for applications whose titlestring begins with name$. If more than one application is found that matchesname$, then the first application encountered is used.

AppFind$ (function)Syntax AppFind$(partial_name$)

Description Returns a String containing the full name of the application matching thepartial_name$.

Page 65: Working Model 2D - User's Manual

Chapter 2 AppGetActive$ (function) 61

Comments The partial_name$ parameter specifies the title of the application to find. Ifthere is no exact match, WM Basic will find an application whose title beginswith partial_name$.

AppFind$ returns a zero-length string if the specified application cannot befound.

AppFind$ is generally used to determine whether a given application isrunning. The following expression returns True if Microsoft Word is running:

AppFind$("Microsoft Word")

Example 'This example checks to see whether Excel is running before activatingit.

Sub Main()If AppFind$("Microsoft Excel") <> "" Then

AppActivate "Microsoft Excel"Else

MsgBox "Excel is not running."End If

End Sub

See Also AppFileName$ (function).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, this function returns a String containing the exact textappearing in the title bar of the active application's main window.

AppGetActive$ (function)Syntax AppGetActive$()

Description Returns a String containing the name of the application.

Comments If no application is active, the AppGetActive$ function returns a zero-lengthstring.

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 (statement); WinFind (function).

Platform(s) Windows.

Page 66: Working Model 2D - User's Manual

62 Working Model Basic User's Manual

PlatformNotes:

Windows

Under Windows, this function returns a String containing the exact textappearing in the title bar of the active application's main window.

AppGetPosition (statement)Syntax AppGetPosition X,Y,width,height [,name$]

Description Retrieves the position of the named application.

Comments The AppGetPosition statement takes the following parameters:

Parameter Description

X, Y Names of Integer variables to receive the position of the application'swindow.

width, height Names of Integer variables to receive the size of the application's window.

name$ String containing the name of the application. If the name$ parameter isomitted, then the active application is used.

The x, y, width, and height variables are filled with the position and size of theapplication's window. If an argument is not a variable, then the argument isignored, as in the following example, which only retrieves the x and yparameters and ignores the width and height parameters:

Dim x as integer, y as integerAppGetPosition x,y,0,0,"Program Manager"

Example Sub Main()Dim x As Integer, y As IntegerDim cx As Integer, cy As IntegerAppGetPosition x,y,cx,cy,"Program Manager"

End Sub

See Also AppMove (statement); AppSize (statement).

Platform(s) Windows.

PlatformNotes:

Windows

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 namedapplication's main window. If no application is found whose title exactlymatches name$, then a second search is performed for applications whose titlestring begins with name$. If more than one application is found that matchesname$, then the first application encountered is used.

Page 67: Working Model 2D - User's Manual

Chapter 2 AppGetState (function) 63

AppGetState (function)Syntax AppGetState[([name$])]

Description Returns an Integer specifying the state of the top-level window.

Comments The AppGetState function returns any of the following values:

If the window is then AppGetState returns

Maximized ebMaximized

Minimized ebMinimized

Restored ebRestored

The name$ parameter is a String containing the name of the desiredapplication. If it is omitted, then the AppGetState function returns the nameof the active application.

Examples 'This example saves the state of Program Manager, changes it, thenrestores'it to its original setting.

Sub Main()If AppFind$("Program Manager") = "" Then

MsgBox "Can't find Program Manager."Exit Sub

End IfAppActivate "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 (statement); AppMinimize (statement); AppRestore (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the name$ parameter is the exact string appearing in the titlebar of the named application's main window. If no application is found whosetitle exactly matches name$, then a second search is performed for applicationswhose title string begins with name$. If more than one application is found thatmatches name$, then the first application encountered is used.

AppHide (statement)Syntax AppHide [name$]

Description Hides the named application.

Page 68: Working Model 2D - User's Manual

64 Working Model Basic User's Manual

Comments If the named application is already hidden, the AppHide statement will haveno effect.

The name$ parameter is a String containing the name of the desiredapplication. If it is omitted, then the AppHide statement hides the activeapplication.

AppHide generates a runtime error if the named application is not enabled, asis the case if that application is displaying a modal dialog box.

Example 'This example hides Program Manager.

Sub Main()'See whether Program Manager is running.If AppFind$("Program Manager") = "" Then Exit SubAppHide "Program Manager"MsgBox "Program Manager is now hidden. Press OK to show it once

again."AppShow "Program Manager"

End Sub

See Also AppShow (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the name$ parameter is the exact string appearing in the titlebar of the named application's main window. If no application is found whosetitle exactly matches name$, then a second search is performed for applicationswhose title string begins with name$. If more than one application is found thatmatches name$, then the first application encountered is used.

AppList (statement)Syntax AppList AppNames$()

Description Fills an array with the names of all open applications.

Comments The AppNames$ parameter must specify either a zero- or one-dimensioneddynamic String array or a one-dimensional fixed String array. If the arrayis dynamic, then it will be redimensioned to match the number of openapplications. For fixed arrays, AppList first erases each array element, thenbegins assigning application names to the elements in the array. If there arefewer elements than will fit in the array, then the remaining elements areunused. WM Basic returns a runtime error if the array is too small to hold thenew elements.

After calling this function, you can use LBound and UBound to determine thenew size of the array.

Page 69: Working Model 2D - User's Manual

Chapter 2 AppMaximize (statement) 65

Example 'This example minimizes all applications on the desktop.

Sub Main()Dim apps$()AppList apps

'Check to see whether any applications were found.If ArrayDims(apps) = 0 Then Exit Sub

For i = LBound(apps) To UBound(apps)AppMinimize apps(i)

Next iEnd Sub

See Also WinList (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the name of an application is considered to be the exact textthat appears in the title bar of the application's main window.

AppMaximize (statement)Syntax AppMaximize [name$]

Description Maximizes the named application.

Comments The name$ parameter is a String containing the name of the desiredapplication. If it is omitted, then the AppMaximize function maximizes theactive application.

Example Sub Main()AppMaximize "Program Manager" 'Maximize Program Manager.

If AppFind$("NotePad") <> "" ThenAppActivate "NotePad" 'Set the focus to NotePad.AppMaximize 'Maximize it.

End IfEnd Sub

See Also AppMinimize (statement); AppRestore (statement); AppMove (statement);AppSize (statement); AppClose (statement).

Platform(s) Windows.

Page 70: Working Model 2D - User's Manual

66 Working Model Basic User's Manual

PlatformNotes:

Windows

If the named application is maximized or hidden, the AppMaximize statementwill have no effect.

The name$ parameter is the exact string appearing in the title bar of the namedapplication's main window. If no application is found whose title exactlymatches name$, then a second search is performed for applications whose titlestring begins with name$. If more than one application is found that matchesname$, then the first application encountered is used.

AppMaximize generates a runtime error if the named application is notenabled, as is the case if that application is displaying a modal dialog box.

AppMinimize (statement)Syntax AppMinimize [name$]

Description Minimizes the named application.

Comments The name$ parameter is a String containing the name of the desiredapplication. If it is omitted, then the AppMinimize function minimizes theactive application.

Example Sub Main()AppMinimize "Program Manager" 'Maximize Program Manager.

If AppFind$("NotePad") <> "" ThenAppActivate "NotePad" 'Set the focus to NotePad.AppMinimize 'Maximize it.

End IfEnd Sub

See Also AppMaximize (statement); AppRestore (statement); AppMove (statement);AppSize (statement); AppClose (statement).

Platform(s) Windows.

PlatformNotes:

Windows

If the named application is minimized or hidden, the AppMinimize statementwill have no effect.

The name$ parameter is the exact string appearing in the title bar of the namedapplication's main window. If no application is found whose title exactlymatches name$, then a second search is performed for applications whose titlestring begins with name$. If more than one application is found that matchesname$, then the first application encountered is used.

AppMinimize generates a runtime error if the named application is notenabled, as is the case if that application is displaying a modal dialog box.

Page 71: Working Model 2D - User's Manual

Chapter 2 AppMove (statement) 67

AppMove (statement)Syntax AppMove X, Y [,name$]

Description Sets the upper left corner of the named application to a given location.

Comments The AppMove statement takes the following parameters:

Parameter Description

X, Y Integer coordinates specifying the upper left corner of the new location of theapplication, relative to the upper left corner of the display.

name$ String containing the name of the application to move. If this parameter isomitted, 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 (statement); AppMinimize (statement); AppRestore (statement);AppSize (statement); AppClose (statement).

Platform(s) Windows.

PlatformNotes:

Windows

If the named application is maximized or hidden, the AppMove statement willhave 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 namedapplication's main window. If no application is found whose title exactlymatches name$, then a second search is performed for applications whose titlestring begins with name$. If more than one application is found that matchesname$, then the first application encountered is used.

AppMove generates a runtime error if the named application is not enabled, asis the case if that application is currently displaying a modal dialog box.

AppRestore (statement)Syntax AppRestore [name$]

Page 72: Working Model 2D - User's Manual

68 Working Model Basic User's Manual

Description Restores the named application.

Comments The name$ parameter is a String containing the name of the application torestore. If this parameter is omitted, then the active application is restored.

Example 'This example minimizes Program Manager, then restores it.

Sub Main()If AppFind$("Program Manager") = "" Then Exit SubAppActivate "Program Manager"AppMinimize "Program Manager"MsgBox "Program Manager is now minimized. Press OK to restore it."AppRestore "Program Manager"

End Sub

See Also AppMaximize (statement); AppMinimize (statement); AppMove (statement);AppSize (statement); AppClose (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the name$ parameter is the exact string appearing in the titlebar of the named application's main window. If no application is found whosetitle exactly matches name$, then a second search is performed for applicationswhose title string begins with name$. If more than one application is found thatmatches name$, then the first application encountered is used.

AppRestore will have an effect only if the main window of the namedapplication 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 notenabled, as is the case if that application is currently displaying a modal dialogbox.

AppSetState (statement)Syntax AppSetState newstate [,name$]

Description Maximizes, minimizes, or restores the named application, depending on thevalue of newstate.

Page 73: Working Model 2D - User's Manual

Chapter 2 AppShow (statement) 69

Comments The AppSetState statement takes the following parameters:

Parameter Description

newstate Integer specifying the new state of the window. It can be any of the followingvalues:

Value Description

ebMaximized The named application is maximized.

ebMinimized The named application is minimized.

ebRestored The named application is restored.

name$ String containing the name of the application to change. If this parameter isomitted, then the active application is used.

Example See AppGetState (function).

See Also AppGetState (function); AppMinimize (statement); AppMaximize (statement);AppRestore (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the name$ parameter is the exact string appearing in the titlebar of the named application's main window. If no application is found whosetitle exactly matches name$, then a second search is performed for applicationswhose title string begins with name$. If more than one application is found thatmatches name$, then the first application encountered is used.

AppShow (statement)Syntax AppShow [name$]

Description Makes the named application visible.

Comments The name$ parameter is a String containing the name of the application toshow. If this parameter is omitted, then the active application is shown.

Example See AppHide (statement).

See Also AppHide (statement).

Platform(s) Windows.

Page 74: Working Model 2D - User's Manual

70 Working Model Basic User's Manual

PlatformNotes:

Windows

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 namedapplication's main window. If no application is found whose title exactlymatches name$, then a second search is performed for applications whose titlestring begins with name$. If more than one application is found that matchesname$, then the first application encountered is used.

AppShow generates a runtime error if the named application is not enabled, asis the case if that application is displaying a modal dialog box.

AppSize (statement)Syntax AppSize width,height [,name$]

Description Sets the width and height of the named application.

Comments The AppSize statement takes the following parameters:

Parameter Description

width, height Integer coordinates specifying the new size of the application.

name$ String containing the name of the application to resize. If this parameter isomitted, 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 (statement); AppMinimize (statement); AppRestore (statement);AppMove (statement); AppClose (statement).

Platform(s) Windows.

Page 75: Working Model 2D - User's Manual

Chapter 2 AppType (function) 71

PlatformNotes:

Windows

The width and height parameters are specified in twips.

This statement will only work if the named application is restored (i.e., notminimized or maximized).

The name$ parameter is the exact string appearing in the title bar of the namedapplication's main window. If no application is found whose title exactlymatches name$, then a second search is performed for applications whose titlestring begins with name$. If more than one application is found that matchesname$, then the first application encountered is used.

A runtime error results if the application being resized is not enabled, which isthe case if that application is displaying a modal dialog box when an AppSizestatement is executed.

AppType (function)Syntax AppType [(name$)]

Description Returns an Integer indicating the executable file type of the namedapplication:

ebDos DOS executable

ebWindows Windows executable

Comments The name$ parameter is a String containing the name of the application. Ifthis parameter is omitted, then the active application is used.

Page 76: Working Model 2D - User's Manual

72 Working Model Basic User's Manual

Example 'This example creates an array of strings containing the names of allthe'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 Thenwapps(n) = apps(i)n = n + 1

End IfNext 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

See Also AppFilename$ (function).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the name$ parameter is the exact string appearing in the titlebar of the named application's main window. If no application is found whosetitle exactly matches name$, then a second search is performed for applicationswhose title string begins with name$. If more than one application is found thatmatches name$, then the first application encountered is used.

ArrayDims (function)Syntax ArrayDims(arrayvariable)

Description Returns an Integer containing the number of dimensions of a given array.

Page 77: Working Model 2D - User's Manual

Chapter 2 ArrayDims (function) 73

Comments This function can be used to determine whether a given array contains anyelements or if the array is initially created with no dimensions and thenredimensioned by another function, such as the FileList function, as shownin the following example.

Example 'This example allocates an empty (null-dimensioned) array; fills thearray'with a list of filenames, which resizes the array; then tests thearray'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 (function); UBound (function); Arrays (topic).

Platform(s) Windows and Macintosh.

Page 78: Working Model 2D - User's Manual

74 Working Model Basic User's Manual

Arrays (topic)Declaring Array Variables

Arrays in WM Basic are declared using any of the following statements:

DimPublicPrivate

For example:

Dim a(10) As IntegerPublic LastNames(1 to 5,-2 to 7) As VariantPrivate

Arrays of any data type can be created, including Integer, Long, Single,Double, Boolean, Date, Variant, Object, user-defined structures, anddata objects.

The lower and upper bounds of each array dimension must be within thefollowing 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. Oncedeclared, a fixed array will always require the same amount of storage. Fixedarrays can be declared with the Dim, Private, or Public statement bysupplying explicit dimensions. The following example declares a fixed array often strings:

Dim a(10) As String

Fixed arrays can be used as members of user-defined data types. The followingexample shows a structure containing fixed-length arrays:

Type Foorect(4) As Integercolors(10) As Integer

End Type

Only fixed arrays can appear within structures.

Page 79: Working Model 2D - User's Manual

Chapter 2 Arrays (topic) 75

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 redimensionedany number of times. When redimensioning an array, the old array is firsterased unless you use the Preserve keyword, as shown below:

Redim Preserve Ages$(100)

Dynamic arrays cannot be members of user-defined data types.

Passing Arrays

Arrays are always passed by reference.

Querying Arrays

The following table describes the functions used to retrieve information aboutarrays.

Use this function to

LBound Retrieve the lower bound of an array. A runtime error is generated if the arrayhas no dimensions.

UBound Retrieve the upper bound of an array. A runtime error is generated if the arrayhas no dimensions.

ArrayDims Retrieve the number of dimensions of an array. This function returns 0 if thearray 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, orvariants.

FileList Fill an array with a list of files in a given directory.

DiskDrives Fill an array with a list of valid drive letters.

AppList Fill an array with a list of running applications.

WinList Fill an array with a list of top-level windows.

SelectBox Display the contents of an array in a list box.

Page 80: Working Model 2D - User's Manual

76 Working Model Basic User's Manual

PopupMenu Display the contents of an array in a pop-up menu.

ReadIniSection Fill an array with the item names from a section in an ini file.

FileDirs Fill an array with a list of subdirectories.

Erase Erase all the elements of an array.

ReDim Establish the bounds and dimensions of an array.

Dim Declare an array.

ArraySort (statement)Syntax ArraySort array()

Description Sorts a single-dimensioned array in ascending order.

Comments If a string array is specified, then the routine sorts alphabetically in ascendingorder using case-sensitive string comparisons. If a numeric array is specified,the ArraySort statement sorts smaller numbers to the lowest array indexlocations.

WM Basic generates a runtime error if you specify an array with more than onedimension.

When sorting an array of variants, the following rules apply:

A runtime error is generated if any element of the array is an object.

String is greater than any numeric type.

Null is less than String and all numeric types.

Empty is treated as a number with the value 0.

String comparison is case-sensitive (this function is not affected by theOption Compare setting).

Example 'This example dimensions an array and fills it with filenames usingFileList,'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 (function); LBound (function); UBound (function).

Platform(s) Windows and Macintosh.

Page 81: Working Model 2D - User's Manual

Chapter 2 Asc (function) 77

Asc (function)Syntax Asc(text$)

Description Returns an Integer containing the numeric code for the first character oftext$.

Comments The return value is an integer between 0 and 255.

Example 'This example fills an array with the ASCII values of the string scomponents'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.For i = 1 To Len(s$)

msg = msg & Asc(Mid$(s$,i,1)) & crlfNext iMsgBox "The Asc values of the string are:" & msg

End Sub

See Also Chr, Chr$ (functions).

Platform(s) Windows and Macintosh.

AskBox$ (function)Syntax AskBox$(prompt$ [,default$])

Description Displays a dialog box requesting input from the user and returns that input as aString.

Page 82: Working Model 2D - User's Manual

78 Working Model Basic User's Manual

Comments The AskBox$ function takes the following parameters:

Parameter Description

prompt$ String containing the text to be displayed above the text box. The dialog box issized to the appropriate width depending on the width of prompt$. A runtimeerror is generated if prompt$ is Null.

default$ String containing the initial content of the text box. The user can return thedefault by immediately selecting OK. A runtime error is generated if default$ isNull.

The AskBox$ function returns a String containing the input typed by theuser in the text box. A zero-length string 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 byAskBox$.

s$ = AskBox$("Type in the filename:")

s$ = AskBox$("Type in the filename:","filename.txt")

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 (statement); AskPassword$ (function); InputBox, InputBox$(functions); OpenFilename$ (function); SaveFilename$ (function); SelectBox(function).

Page 83: Working Model 2D - User's Manual

Chapter 2 AskPassword$ (function) 79

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

The text in the dialog box is displayed in 8-point MS Sans Serif.

AskPassword$ (function)Syntax AskPassword$(prompt$)

Description Returns a String containing the text that the user typed.

Comments Unlike the AskBox$ function, the user sees asterisks in place of the charactersthat are actually typed. This allows the hidden input of passwords.

The prompt$ parameter is a String containing the text to appear above thetext box. The dialog box is sized to the appropriate width depending on thewidth of prompt$.

When the dialog box is displayed, the text box has the focus.

A maximum of 255 characters can be typed into the text box.

A zero-length string is returned if the user selects Cancel.

s$ = AskPassword$("Type in the password:")

Example Sub Main()s$ = AskPassword$("Type in the password:")MsgBox "The password entered is: " & s$

End Sub

See Also MsgBox (statement); AskBox$ (function); InputBox, InputBox$ (functions);OpenFilename$ (function); SaveFilename$ (function); SelectBox (function);AnswerBox (function).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

The text in the dialog box is displayed in 8-point MS Sans Serif.

Page 84: Working Model 2D - User's Manual

80 Working Model Basic User's Manual

Atn (function)Syntax Atn(number)

Description Returns the angle (in radians) whose tangent is number.

Comments Some helpful conversions:

Pi (3.1415926536) radians = 180 degrees.

1 radian = 57.2957795131 degrees.

1 degree = .0174532925 radians.

Example 'This example finds the angle whose tangent is 1 (45 degrees) anddisplays'the result.

Sub Main()a# = Atn(1.00)MsgBox "1.00 is the tangent of " & a# & " radians (45 degrees)."

End Sub

See Also Tan (function); Sin (function); Cos (function).

Platform(s) Windows and Macintosh.

Basic.Capability (method)Syntax Basic.Capability(which)

Description Returns True if the specified capability exists on the current platform; returnsFalse otherwise.

Comments The which parameter is an Integer specifying the capability for which totest. It can be any of the following values:

Value Returns True If the Platform Supports

1 Disk drives

2 System file attribute (ebSystem)

3 Hidden file attribute (ebHidden)

4 Volume label file attribute (ebVolume)

5 Archive file attribute (ebArchive)

6 Denormalized floating-point math

7 File locking (i.e., the Lock and Unlock statements)

8 Big endian byte ordering

Page 85: Working Model 2D - User's Manual

Chapter 2 Basic.Eoln$ (property) 81

Example 'This example tests to see whether your current platform supports disk'drives and hidden file attributes and displays the result.

Sub Main()msg = "This operating system "

If Basic.Capability(1) Thenmsg = msg & "supports disk drives."

Elsemsg = msg & "does not support disk drives."

End If

MsgBox msgEnd Sub

See Also Cross-Platform Scripting (topic); Basic.OS (property).

Platform(s) Windows and Macintosh.

Basic.Eoln$ (property)Syntax Basic.Eoln$

Description Returns a String containing the end-of-line character sequence appropriate tothe current platform.

Comments This string will be either a carriage return, a carriage return/line feed, or a linefeed.

Example 'This example writes two lines of text in a message box.

Sub Main()MsgBox "This is the first line of text." & Basic.Eoln$ & "This is

the second line of text."End Sub

See Also Cross-Platform Scripting (topic); Basic.PathSeparator$ (property).

Platform(s) Windows and Macintosh.

Basic.FreeMemory (property)Syntax Basic.FreeMemory

Description Returns a Long representing the number of bytes of free memory in WMBasic's data space.

Comments This function returns the size of the largest free block in WM Basic's dataspace. Before this number is returned, the data space is compacted,consolidating free space into a single contiguous free block.

WM Basic's data space contains strings and dynamic arrays.

Page 86: Working Model 2D - User's Manual

82 Working Model Basic User's Manual

Example 'This example displays free memory in a dialog box.

Sub Main()MsgBox "The largest free memory block is: " & Basic.FreeMemory

End Sub

See Also System.TotalMemory (property); System.FreeMemory (property);System.FreeResources (property); Basic.FreeMemory (property).

Platform(s) Windows and Macintosh.

Basic.HomeDir$ (property)Syntax Basic.HomeDir$

Description Returns a String specifying the directory containing WM Basic.

Comments This method is used to find the directory in which the WM Basic files arelocated.

Example 'This example assigns the home directory to HD and displays it.

Sub Main()hd$ = Basic.HomeDir$MsgBox "The WM Basic home directory is: " & hd$

End Sub

See Also System.WindowsDirectory$ (property).

Platform(s) Windows and Macintosh.

Basic.OS (property)Syntax Basic.OS

Description Returns an Integer indicating the current platform.

Comments Value Constant Platform0 ebWin16 Microsoft Windows10 ebMacintosh Apple MacintoshThe value returned is not necessarily the platform under which WM Basic isrunning but rather an indicator of the platform for which WM Basic wascreated. For example, it is possible to run WM Basic for Windows underWindows NT Workstation. In this case, Basic.OS will return 0.

Page 87: Working Model 2D - User's Manual

Chapter 2 Basic.PathSeparator$ (property) 83

Example 'This example determines the operating system for which this versionwas'created and displays the appropriate message.

Sub Main()Select Case Basic.OS

Case ebWin16s = "Windows"

Case ebMacintoshs = "Macintosh"

Case Elses = "neither Windows nor Macintosh"

End SelectMsgBox "You are currently running " & s

End Sub

See Also Cross-Platform Scripting (topic).

Platform(s) Windows and Macintosh.

Basic.PathSeparator$ (property)Syntax Basic.PathSeparator$

Description Returns a String containing the path separator appropriate for the currentplatform.

Comments The returned string is any one of the following characters: / (slash), \ (backslash), : (colon)

Example Sub Main()MsgBox "The path separator for this platform is: " &

Basic.PathSeparator$End Sub

See Also Basic.Eoln$ (property); Cross-Platform Scripting (topic).

Platform(s) Windows and Macintosh.

Basic.Version$ (property)Syntax Basic.Version$

Description Returns a String containing the version of WM Basic.

Comments This function returns the major and minor version numbers in the formatmajor.minor.BuildNumber, as in "2.00.30."

Example 'This example displays the current version of WM Basic.

Sub Main()MsgBox "Version " & Basic.Version$ & " of WM Basic is running"

End Sub

Page 88: Working Model 2D - User's Manual

84 Working Model Basic User's Manual

Platform(s) Windows and Macintosh.

Beep (statement)Syntax Beep

Description Makes a single system beep.

Example 'This example causes the system to beep five times and displays areminder'message.

Sub Main()For i = 1 To 5

BeepSleep(200)

Next iMsgBox "You have an upcoming appointment!"

End Sub

See Also Mci (function).

Platform(s) Windows and Macintosh.

Begin Dialog (statement)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.

Comments A dialog box template is constructed by placing any of the following statementsbetween the Begin Dialog and End Dialog statements (no otherstatements besides comments can appear within a dialog box template):

Picture OptionButton OptionGroupCancelButton Text TextBoxGroupBox DropListBox ListBoxComboBox CheckBox PictureButtonPushButton OKButton

Page 89: Working Model 2D - User's Manual

Chapter 2 Begin Dialog (statement) 85

The Begin Dialog statement requires the following parameters:

Parameter Description

x, y Integer coordinates specifying the position of the upper left corner of thedialog box relative to the parent window. These coordinates are in dialog units.

If either coordinate is unspecified, then the dialog box will be centered in thatdirection on the parent window.

width, height Integer coordinates specifying the width and height of the dialog box (indialog 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 thisparameter specifies a zero-length string, then the name "WM Basic" is used.

.DlgProc Name of the dialog function. The routine specified by .DlgProc will be calledby WM Basic when certain actions occur during processing of the dialog box.(See DlgProc [prototype] for additional information about dialog functions.)

If this omitted, then WM Basic processes the dialog box using the defaultdialog box processing behavior.

PicName$ String specifying the name of a DLL containing pictures. This DLL is used asthe origin for pictures when the picture type is 10. If omitted, then no picturelibrary will be used.

style Specifies extra styles for the dialog. It can be any of the following values:

Value Meaning

0 Dialog does not contain a title or close box.

1 Dialog contains a title and no close box.

2 (or omitted) Dialog contains both the title and close box.

WM Basic generates an error if the dialog box template contains no controls.

A dialog box template must have at least one PushButton, OKButton, orCancelButton statement. Otherwise, there will be no way to close thedialog box.

Dialog units are defined as 1/4 the width of the font in the horizontal directionand 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 createdusing a different name as the DialogName. Only one user dialog box may beinvoked at any time.

Page 90: Working Model 2D - User's Manual

86 Working Model Basic User's Manual

Expression Evaluation within the Dialog Box Template

The Begin Dialog statement creates the template for the dialog box. Anyexpression or variable name that appears within any of the statements in thedialog box template is not evaluated until a variable is dimensioned of typeDialogName. The following example shows this behavior:

MyTitle$ = "Hello, World"Begin Dialog MyTemplate 16,32,116,64,MyTitle$

OKButton 12,40,40,14End DialogMyTitle$ = "Sample Dialog"Dim Dummy As MyTemplaterc% = Dialog(Dummy)

The above example creates a dialog box with the title "Sample Dialog".

Expressions within dialog box templates cannot reference external subroutinesor functions.

All controls within a dialog box use the same font. The fonts used for text andtext box control can be changed explicitly by setting the font parameters in theText and TextBox statements. A maximum of 128 fonts can be used within asingle dialog, although the practical limitation may be less.

Example 'This example creates an exit 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",.SaveChangesOKButton 12,40,40,14CancelButton 60,40,40,14

End DialogDim QuitDialog As QuitDialogTemplaterc% = Dialog(QuitDialog)

End Sub

See Also CancelButton (statement); CheckBox (statement); ComboBox (statement);Dialog (function); Dialog (statement); DropListBox (statement); GroupBox(statement); ListBox (statement); OKButton (statement); OptionButton(statement); OptionGroup (statement); Picture (statement); PushButton(statement); Text (statement); TextBox (statement); DlgProc (function).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Within user dialog boxes, the default font is 8-point MS Sans Serif.

Page 91: Working Model 2D - User's Manual

Chapter 2 Boolean (data type) 87

PlatformNotes:

Macintosh

Within user dialog boxes, the default font is 10-point Geneva.

Boolean (data type)Syntax Boolean

Description A data type capable of representing the logical values True and False.

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 Privatestatement.

Variants can hold Boolean values when assigned the results of comparisonsor 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 ofstorage.

When used within binary or random files, 2 bytes of storage are required.

When passed to external routines, Boolean values are sign-extended to thesize of an integer on that platform (either 16 or 32 bits) before pushing onto thestack.

There is no type-declaration character for Boolean variables.

Boolean variables that have not yet been assigned are given an initial value ofFalse.

See Also Currency (data type); Date (data type); Double (data type); Integer (datatype); Long (data type); Object (data type); Single (data type); String (datatype); Variant (data type); DefType (statement); CBool (function); True(constant); False (constant).

Platform(s) Windows and Macintosh.

ButtonEnabled (function)Syntax ButtonEnabled(name$ | id)

Page 92: Working Model 2D - User's Manual

88 Working Model Basic User's Manual

Description Returns True if the specified button within the current window is enabled;returns False otherwise.

Comments The ButtonEnabled function takes the following parameters:

Parameter Description

name$ String containing the name of the push button.

id Integer specifying the ID of the push button.

When a button is enabled, it can be clicked using the SelectButtonstatement.

Note: The ButtonEnabled function is used to determine whether a push buttonis enabled in another application's dialog box. Use the DlgEnable function toretrieve the enabled state of a push button in a dynamic dialog box.

Example 'This code fragment checks to see whether a button is enabled before'clicking it.

Sub Main()If ButtonEnabled("Browse...") Then

SelectButton "Browse..."Else

MsgBox "Can't browse right now."End If

End Sub

See Also ButtonExists (function); SelectButton (statement).

Platform(s) Windows.

ButtonExists (function)Syntax ButtonExists(name$ | id)

Description Returns True if the specified button exists within the current window; returnsFalse otherwise.

Comments The ButtonExists function takes the following parameters:

Parameter Description

name$ String containing the name of the push button.

id Integer specifying the ID of the push button.

Note: The ButtonExists function is used to determine whether a push buttonexists in another application's dialog box. There is no equivalent function foruse with dynamic dialog boxes.

Page 93: Working Model 2D - User's Manual

Chapter 2 ByRef (keyword) 89

Example 'This code fragment selects the More button if it exists. If it doesnot'exist, then this code fragment does nothing.

Sub Main()If ButtonExists("More >>") Then

SelectButton "More >>" 'Display more stuff.End If

End Sub

See Also ButtonEnabled (function); SelectButton (statement).

Platform(s) Windows.

ByRef (keyword)Syntax ...,ByRef parameter,...

Description Used within the Sub...End Sub, Function...End Function, or Declarestatement to specify that a given parameter can be modified by the calledroutine.

Comments Passing a parameter by reference means that the caller can modify thatvariable's value.

Unlike the ByVal keyword, the ByRef keyword cannot be used when passing aparameter. The absence of the ByVal keyword is sufficient to force a parameterto 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 = 12Test bMsgBox "The ByRef value is: " & b 'Displays 14.

End Sub

See Also () (keyword), ByVal (keyword).

Platform(s) Windows and Macintosh.

ByVal (keyword)Syntax ...ByVal parameter...

Description Forces a parameter to be passed by value rather than by reference.

Page 94: Working Model 2D - User's Manual

90 Working Model Basic User's Manual

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 aparameter by value means that the caller cannot modify that variable's value.

Enclosing a variable within parentheses has the same effect as the ByValkeyword:

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 (i.e., routines defined using theDeclare statement), the ByVal keyword forces the parameter to be passed byvalue regardless of the declaration of that parameter in the Declare statement.The following example shows the effect of the ByVal keyword used to passedan Integer to an external routine:

Declare Sub Foo Lib "MyLib" (ByRef i As Integer)

i% = 6Foo 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 toFoo will have unpredictable results.

Example 'This example demonstrates the use of the ByVal keyword.

Sub Foo(a As Integer)a = a + 1

End Sub

Sub Main()Dim i As Integeri = 10Foo iMsgBox "The ByVal value is: " & i 'Displays 11 (Foo changed the

value).Foo ByVal iMsgBox "The Byval value is still: " & i 'Displays 11 (Foo did

not change the value).End Sub

See Also () (keyword), ByRef (keyword).

Platform(s) Windows and Macintosh.

Call (statement)Syntax Call subroutine_name [(arguments)]

Description Transfers control to the given subroutine, optionally passing the specifiedarguments.

Page 95: Working Model 2D - User's Manual

Chapter 2 CancelButton (statement) 91

Comments Using this statement is equivalent to:

subroutine_name [arguments]

Use of the Call statement is optional. The Call statement can only be used toexecute subroutines; functions cannot be executed with this statement. Thesubroutine to which control is transferred by the Call statement must bedeclared outside of the Main procedure, as shown in the following example.

Example 'This example demonstrates the use of the Call statement to passcontrol 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 (statement); GoSub (statement); Declare (statement).

Platform(s) Windows and Macintosh.

CancelButton (statement)Syntax CancelButton X, Y, width, height [,.Identifier]

Description Defines a Cancel button that appears within a dialog box template.

Page 96: Working Model 2D - User's Manual

92 Working Model Basic User's Manual

Comments This statement can only appear within a dialog box template (i.e., between theBegin 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 redefinethis behavior.) Pressing the Esc key or double-clicking the close box will haveno 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)relative to the upper left corner of the dialog box.

width, height Integer coordinates specifying the dimensions of the control in dialog units.

.Identifier Optional parameter specifying the name by which this control can be referencedby statements in a dialog function (such as DlgFocus and DlgEnable). Ifomitted, then the word Cancel is used.

A dialog box must contain at least one OKButton, CancelButton, orPushButton statement; otherwise, the dialog box cannot be dismissed.

Example 'This example creates a dialog box with OK and Cancel buttons.

Sub Main()Begin Dialog SampleDialogTemplate 37,32,48,52,"Sample"

OKButton 4,12,40,14,.OKCancelButton 4,32,40,14,.Cancel

End DialogDim SampleDialog As SampleDialogTemplater% = Dialog(SampleDialog)If r% = 0 Then MsgBox "Cancel was pressed!"

End Sub

See Also CheckBox (statement); ComboBox (statement); Dialog (function); Dialog(statement); DropListBox (statement); GroupBox (statement); ListBox(statement); OKButton (statement); OptionButton (statement); OptionGroup(statement); Picture (statement); PushButton (statement); Text (statement);TextBox (statement); Begin Dialog (statement), PictureButton (statement).

Platform(s) Windows and Macintosh.

CBool (function)Syntax CBool(expression)

Description Converts expression to True or False, returning a Boolean value.

Page 97: Working Model 2D - User's Manual

Chapter 2 CCur (function) 93

Comments The expression parameter is any expression that can be converted to aBoolean. A runtime error is generated if expression is Null.

All numeric data types are convertible to Boolean. If expression is zero, thenthe CBool returns False; otherwise, CBool returns True. Empty is treated asFalse.

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 ifexpression cannot be converted to a number.

A runtime error is generated if expression cannot be converted to a Boolean.

Example 'This example uses CBool to determine whether a string is numeric'or just plain text.

Sub Main()Dim IsNumericOrDate As Booleans$ = "34224.54"IsNumericOrDate = CBool(IsNumeric(s$) Or IsDate(s$))If IsNumericOrDate = True Then

MsgBox s$ & " is either a valid date or number!"Else

MsgBox s$ & " is not a valid date or number!"End If

End Sub

See Also CCur (function); CDate, CVDate (functions); CDbl (function); CInt (function);CLng (function); CSng (function); CStr (function); CVar (function); CVErr(function); Boolean (data type).

Platform(s) Windows and Macintosh.

CCur (function)Syntax CCur(expression)

Description Converts any expression to a Currency.

Comments This function accepts any expression convertible to a Currency, includingstrings. A runtime error is generated if expression is Null or a String notconvertible to a number. Empty is treated as 0.

When passed a numeric expression, this function has the same effect asassigning the numeric expression number to a Currency.

When used with variants, this function guarantees that the variant will beassigned a Currency (VarType 6).

Page 98: Working Model 2D - User's Manual

94 Working Model Basic User's Manual

Example 'This example displays the value of a String converted into a Currencyvalue.

Sub Main()i$ = "100.44"MsgBox "The currency value is: " & CCur(i$)

End Sub

See Also CBool (function); CDate, CVDate (functions); CDbl (function); CInt(function); CLng (function); CSng (function); CStr (function); CVar (function);CVErr (function); Currency (data type).

Platform(s) Windows and Macintosh.

CDate, CVDate (functions)Syntax CDate(expression)

CVDate(expression)

Description Converts expression to a date, returning a Date value.

Comments The expression parameter is any expression that can be converted to a Date. Aruntime error is generated if expression is Null.

If expression is a String, an attempt is made to convert it to a Date using thecurrent country settings. If expression does not represent a valid date, then anattempt is made to convert expression to a number. A runtime error is generatedif 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.

Example 'This example takes two dates and computes the difference between them.

Sub Main()Dim date1 As DateDim date2 As DateDim 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 (function); CBool (function); CDbl (function); CInt (function); CLng(function); CSng (function); CStr (function); CVar (function); CVErr (function);Date (data type).

Platform(s) Windows and Macintosh.

Page 99: Working Model 2D - User's Manual

Chapter 2 CDbl (function) 95

CDbl (function)Syntax CDbl(expression)

Description Converts any expression to a Double.

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 asassigning the numeric expression number to a Double.

When used with variants, this function guarantees that the variant will beassigned a Double (VarType 5).

Example 'This example displays the result of two numbers as a Double.

Sub Main()i% = 100j! = 123.44MsgBox "The double value is: " & CDbl(i% * j!)

End Sub

See Also CCur (function); CBool (function); CDate, CVDate (functions); CInt(function); CLng (function); CSng (function); CStr (function); CVar (function);CVErr (function); Double (data type).

Platform(s) Windows and Macintosh.

ChDir (statement)Syntax ChDir newdir$

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 olddirectory,'and displays it.

Const crlf = Chr$(13) + Chr$(10)

Sub Main()save$ = CurDir$ChDir (Basic.PathSeparator$)MsgBox "Old: " & save$ & crlf & "New: " & CurDir$ChDir (save$)MsgBox "Directory restored to: " & CurDir$

End Sub

See Also ChDrive (statement); CurDir, CurDir$ (functions); Dir, Dir$ (functions);MkDir (statement); RmDir (statement); DirList (statement).

Page 100: Working Model 2D - User's Manual

96 Working Model Basic User's Manual

Platform(s) Windows and Macintosh.

PlatformNotes:

Macintosh

The Macintosh does not support drive letters.

The Macintosh uses the colon (":") as the path separator. A double colon ("::")specifies the parent directory.

ChDrive (statement)Syntax ChDrive DriveLetter$

Description Changes the default drive to the specified drive.

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.

Example 'This example saves the current directory in CD, then extracts thecurrent'drive letter and saves it in Save$. If the current drive is D, then itis'changed to C; otherwise, it is changed to D. Then the saved drive is'restored and displayed.

Const crlf$ = Chr$(13) + Chr$(10)

Sub Main()cd$ = CurDir$save$ = Mid$(CurDir$,1,1)If save$ = "D" Then

ChDrive("C")Else

ChDrive("D")End IfMsgBox "Old: " & save$ & crlf & "New: " & CurDir$ChDrive (save$)MsgBox "Directory restored to: " & CurDir$

End Sub

See Also ChDir (statement); CurDir, CurDir$ (functions); Dir, Dir$ (functions);MkDir (statement); RmDir (statement); DiskDrives (statement).

Platform(s) Windows.

PlatformNotes:

Macintosh

Macintosh does not support drive letters.

CheckBox (statement)Syntax CheckBox X, Y, width, height, title$, .Identifier

Page 101: Working Model 2D - User's Manual

Chapter 2 CheckBox (statement) 97

Description Defines a check box within a dialog box template.

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 theBegin 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)relative to the upper left corner of the dialog box.

width, height Integer coordinates specifying the dimensions of the control in dialog units.

title$ String containing the text that appears within the check box. This text maycontain an ampersand character to denote an accelerator letter, such as "&Font"for Font (indicating that the Font control may be selected by pressing the Faccelerator key).

.Identifier Name by which this control can be referenced by statements in a dialogfunction (such as DlgFocus and DlgEnable). This parameter also creates aninteger 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 usedto set the initial state of the check box. When the dialog box is dismissed, thefinal state of the check box is placed into this variable. By default, the.Identifier variable contains 0, meaning that the check box is unchecked.

Example 'This example displays a dialog box with two check boxes in differentstates.

Sub Main()Begin Dialog SaveOptionsTemplate 36,32,151,52,"Save"

GroupBox 4,4,84,40,"GroupBox"CheckBox 12,16,67,8,"Include heading",.IncludeHeadingCheckBox 12,28,73,8,"Expand keywords",.ExpandKeywordsOKButton 104,8,40,14,.OKCancelButton 104,28,40,14,.Cancel

End DialogDim SaveOptions As SaveOptionsTemplateSaveOptions.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

Page 102: Working Model 2D - User's Manual

98 Working Model Basic User's Manual

See Also CancelButton (statement); Dialog (function); Dialog (statement);DropListBox (statement); GroupBox (statement); ListBox (statement);OKButton (statement); OptionButton (statement); OptionGroup (statement);Picture (statement); PushButton (statement); Text (statement); TextBox(statement); Begin Dialog (statement), PictureButton (statement).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

On Windows, accelerators are underlined, and the accelerator combinationAlt+letter is used.

PlatformNotes:

Macintosh

On the Macintosh, accelerators are normal in appearance, and the acceleratorcombination Command+letter is used.

CheckBoxEnabled (function)Syntax CheckBoxEnabled(name$ | id)

Description Returns True if the specified check box within the current window is enabled;returns False otherwise.

Comments The CheckBoxEnabled function takes the following parameters:

Parameter Description

name$ String containing the name of the check box.

id Integer specifying the ID of the check box.

When a check box is enabled, its state can be set using the SetCheckBoxstatement.

Note: The CheckBoxEnabled function is used to determine whether a checkbox is enabled in another application's dialog box. Use the DlgEnable functionwithin dynamic dialog boxes.

Example 'This code checks to see whether a check box is enabled.

Sub Main()If CheckBoxEnabled("Portrait") Then

SetCheckBox "Portrait",1End If

End Sub

See Also CheckBoxExists (function); GetCheckBox (function); SetCheckBox(statement).

Platform(s) Windows.

Page 103: Working Model 2D - User's Manual

Chapter 2 CheckBoxExists (function) 99

CheckBoxExists (function)Syntax CheckBoxExists(name$ | id)

Description Returns True if the specified check box exists within the current window;returns False otherwise.

Comments The CheckBoxExists function takes the following parameters:

Parameter Description

name$ String containing the name of the check box.

id Integer specifying the ID of the check box.

Note: The CheckBoxExists function is used to determine whether a check boxexists in another application's dialog box. There is no equivalent function foruse with dynamic dialog boxes.

Example 'This code fragment checks to ensure that the Portrait check box is'selectable before selecting it.

Sub Main()If CheckBoxExists("Portrait") Then

If CheckBoxEnabled("Portrait") ThenSetCheckBox "Portrait",1

End IfEnd If

End Sub

See Also CheckBoxEnabled (function); GetCheckBox (function); SetCheckBox(statement).

Platform(s) Windows.

Choose (function)Syntax Choose(index,expression1,expression2,...,expression13)

Description Returns the expression at the specified index position.

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 soon. 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. Eachexpression is evaluated before returning the selected one.

Page 104: Working Model 2D - User's Manual

100 Working Model Basic User's Manual

Example 'This example assigns a variable of indeterminate type to a.

Sub Main()Dim a As VariantDim c As Integerc% = 2a = Choose(c%,"Hello, world",#1/1/94#,5.5,False)MsgBox "Item " & c% & " is '" & a & "'" 'Displays the date

passed as parameter 2.End Sub

See Also Switch (function); IIf (function); If...Then...Else (statement);Select...Case (statement).

Platform(s) Windows and Macintosh.

Chr, Chr$ (functions)Syntax Chr[$](Code)

Description Returns the character whose value is Code.

Comments Code must be an Integer between 0 and 255.

Chr$ returns a string, whereas Chr returns a String variant.

The Chr$ function can be used within constant declarations, as in thefollowing example:

Const crlf = Chr$(13) + Chr$(10)

Some common uses of this function are:

Chr$(9) TabChr$(13) + Chr$(10) End-of-line (carriage return, linefeed)Chr$(26) End-of-fileChr$(0) Null

Page 105: Working Model 2D - User's Manual

Chapter 2 CInt (function) 101

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."

'Fills an array with the ASCII characters for ABC and displaystheir

'corresponding characters.Dim a%(2)For i = 0 To 2

a%(i) = (65 + i)Next iMsgBox "The first three elements of the array are: " & Chr$(a%(0))

& Chr$(a%(1)) & Chr$(a%(2))End Sub

See Also Asc (function); Str, Str$ (functions).

Platform(s) Windows and Macintosh.

CInt (function)Syntax CInt(expression)

Description Converts expression to an Integer.

Comments This function accepts any expression convertible to an Integer, includingstrings. 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 asassigning a numeric expression to an Integer. Note that integer variables arerounded before conversion.

When used with variants, this function guarantees that the expression isconverted to an Integer variant (VarType 2).

Page 106: Working Model 2D - User's Manual

102 Working Model Basic User's Manual

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.55MsgBox "The value of CInt(i) = " & CInt(i#)

'(2) Sets j# to 100.22 and displays the CInt representation (100).j# = 100.22MsgBox "The value of CInt(j) = " & CInt(j#)

'(3) Assigns k% (integer) to the CInt sum of j# and k% and displaysk% (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 theresult

'(note rounding).i# = 50.35k% = CInt(i# + j#)MsgBox "The integer sum of 50.35 and 100.22 is: " & k%

End Sub

See Also CCur (function); CBool (function); CDate, CVDate (functions); CDbl(function); CLng (function); CSng (function); CStr (function); CVar (function);CVErr (function); Integer (data type).

Platform(s) Windows and Macintosh.

Clipboard$ (function)Syntax Clipboard$[()]

Description Returns a String containing the contents of the 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 theClipboard,'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.ClearMsgBox "The text in the Clipboard is:" & crlf & Clipboard$

End Sub

Page 107: Working Model 2D - User's Manual

Chapter 2 Clipboard$ (statement) 103

See Also Clipboard$ (statement); Clipboard.GetText (method); Clipboard.SetText(method).

Platform(s) Windows and Macintosh.

Clipboard$ (statement)Syntax Clipboard$ NewContent$

Description Copies NewContent$ into the Clipboard.

Example 'This example puts text on the Clipboard, displays it, clears theClipboard,'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.ClearMsgBox "The text in the Clipboard is:" & crlf & Clipboard$

End Sub

See Also Clipboard$ (function); Clipboard.GetText (method); Clipboard.SetText(method).

Platform(s) Windows and Macintosh.

Clipboard.Clear (method)Syntax Clipboard.Clear

Description This method clears the Clipboard by removing any content.

Example 'This example puts text on the Clipboard, displays it, clears theClipboard,'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.ClearMsgBox "The text in the Clipboard is:" & crlf & Clipboard$

End Sub

Platform(s) Windows and Macintosh.

Clipboard.GetFormat (method)Syntax WhichFormat = Clipboard.GetFormat(format)

Page 108: Working Model 2D - User's Manual

104 Working Model Basic User's Manual

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 aparticular format. The format parameter is an Integer representing theformat to be queried:

Format Description1 Text2 Bitmap3 Metafile8 Device-independent bitmap (DIB)9 Color palette

Example 'This example puts text on the Clipboard, checks whether there is texton'the Clipboard, and if there is, displays it.

Sub Main()Clipboard$ "Hello out there!"If Clipboard.GetFormat(1) Then MsgBox Clipboard$Else

MsgBox "There is no text in the Clipboard."End If

End Sub

See Also Clipboard$ (function); Clipboard$ (statement).

Platform(s) Windows and Macintosh.

Clipboard.GetText (method)Syntax text$ = Clipboard.GetText([format])

Description Returns the text contained in the Clipboard.

Comments The format parameter, if specified, must be 1.

Page 109: Working Model 2D - User's Manual

Chapter 2 Clipboard.SetText (method) 105

Example 'This example retrieves the text from the Clipboard and checks to'make sure that it contains the word "dog."

Option Compare Text

Sub Main()If Clipboard.GetFormat(1) Then

If Instr(Clipboard.GetText(1),"dog",1) = 0 ThenMsgBox "The Clipboard doesn't contain the word ""dog."""

ElseMsgBox "The Clipboard contains the word ""dog""."

End IfElse

MsgBox "The Clipboard does not contain text."End If

End Sub

See Also Clipboard$ (statement); Clipboard$ (function); Clipboard.SetText(method).

Platform(s) Windows and Macintosh.

Clipboard.SetText (method)Syntax Clipboard.SetText data$ [,format]

Description Copies the specified text string to the Clipboard.

Comments The data$ parameter specifies the text to be copied to the Clipboard. Theformat parameter, if specified, must be 1.

Example 'This example gets the contents of the Clipboard and uppercases it.

Sub Main()If Not Clipboard.GetFormat(1) Then Exit SubClipboard.SetText UCase$(Clipboard.GetText(1)),1

End Sub

See Also Clipboard$ (statement); Clipboard.GetText (method); Clipboard$(function).

Platform(s) Windows and Macintosh.

CLng (function)Syntax CLng(expression)

Description Converts expression to a Long.

Page 110: Working Model 2D - User's Manual

106 Working Model Basic User's Manual

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 asassigning the numeric expression to a Long. Note that long variables arerounded before conversion.

When used with variants, this function guarantees that the expression isconverted to a Long variant (VarType 3).

Example 'This example displays the results for various conversions of i and j(note'rounding).

Sub Main()i% = 100j& = 123.666MsgBox "The result is: " & CLng(i% * j&) 'Displays 12367.MsgBox "The variant type is: " & Vartype(CLng(i%))

End Sub

See Also CCur (function); CBool (function); CDate, CVDate (functions); CDbl(function); CInt (function); CSng (function); CStr (function); CVar (function);CVErr (function); Long (data type).

Platform(s) Windows and Macintosh.

Close (statement)Syntax Close [[#] filenumber [,[#] filenumber]...]

Description Closes the specified files.

Comments If no arguments are specified, then all files are closed.

Example 'This example opens four files and closes them in various combinations.

Sub Main()Open "test1" For Output As #1Open "test2" For Output As #2Open "test3" For Random As #3Open "test4" For Binary As #4MsgBox "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

Page 111: Working Model 2D - User's Manual

Chapter 2 ComboBox (statement) 107

See Also Open (statement); Reset (statement); End (statement).

Platform(s) Windows and Macintosh.

ComboBox (statement)Syntax ComboBox X,Y,width,height,ArrayVariable,.Identifier

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 elementsfrom the specified array variable.

This statement can only appear within a dialog box template (i.e., between theBegin 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)relative 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. Ifthis array has no dimensions, then the combo box will be initialized with noelements. A runtime error results if the specified array contains more than onedimension.

ArrayVariable can specify an array of any fundamental data type (structures arenot allowed). Null and Empty values are treated as zero-length strings.

.Identifier Name by which this control can be referenced by statements in a dialogfunction (such as DlgFocus and DlgEnable). This parameter also creates astring variable whose value corresponds to the content of the edit field of thecombo box. This variable can be accessed using the syntax:

DialogVariable.Identifier.

When the dialog box is invoked, the elements from ArrayVariable are placedinto the combo box. The .Identifier variable defines the initial content of theedit field of the combo box. When the dialog box is dismissed, the .Identifiervariable is updated to contain the current value of the edit field.

Page 112: Working Model 2D - User's Manual

108 Working Model Basic User's Manual

Example 'This example creates a dialog box that allows the user to select a dayof'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"

Begin Dialog DaysDialogTemplate 16,32,124,96,"Days"OKButton 76,8,40,14,.OKText 8,10,39,8,"&Weekdays:"ComboBox 8,20,60,72,days$,.Days

End DialogDim DaysDialog As DaysDialogTemplateDaysDialog.Days = "Tuesday"r% = Dialog(DaysDialog)MsgBox "You selected: " & DaysDialog.Days

End Sub

See Also CancelButton (statement); CheckBox (statement); Dialog (function); Dialog(statement); DropListBox (statement); GroupBox (statement); ListBox(statement); OKButton (statement); OptionButton (statement); OptionGroup(statement); Picture (statement); PushButton (statement); Text (statement);TextBox (statement); Begin Dialog (statement), PictureButton (statement).

Platform(s) Windows and Macintosh.

ComboBoxEnabled (function)Syntax ComboBoxEnabled(name$ | id)

Description Returns True if the specified combo box is enabled within the current windowor dialog box; returns False otherwise.

Page 113: Working Model 2D - User's Manual

Chapter 2 ComboBoxExists (function) 109

Comments The ComboBoxEnabled function takes the following parameters:

Parameter Description

name$ String containing the name of the combo box.

The name of a combo box is determined by scanning the window list lookingfor a text control with the given name that is immediately followed by a combobox. A runtime error is generated if a combo box with that name cannot befound within the active window.

id Integer specifying the ID of the combo box.

A runtime error is generated if the specified combo box does not exist.

Note: The ComboBoxEnabled function is used to determine whether a combobox is enabled in another application's dialog box. Use the DlgEnable functionin dynamic dialog boxes.

Example 'This example checks to see whether a combo box is active. If it is,'then it inserts some text into it.

Sub Main()If ComboBoxEnabled("Filename:") Then

SelectComboBoxItem "Filename:","sample.txt"End IfIf ComboBoxEnabled(365) Then

SelectComboBoxItem 365,3 'Select the third item.End If

End Sub

See Also ComboBoxExists (function); GetComboBoxItem$ (function);GetComboBoxItemCount (function); SelectComboBoxItem (statement).

Platform(s) Windows.

ComboBoxExists (function)Syntax ComboBoxExists(name$ | id)

Description Returns True if the specified combo box exists within the current window ordialog box; returns False otherwise.

Page 114: Working Model 2D - User's Manual

110 Working Model Basic User's Manual

Comments The ComboBoxExists function takes the following parameters:

Parameter Description

name$ String containing the name of the combo box.

The name of a combo box is determined by scanning the window list lookingfor a text control with the given name that is immediately followed by a combobox. A runtime error is generated if a combo box with that name cannot befound within the active window.

id Integer specifying the ID of the combo box.

Note: The ComboBoxExists function is used to determine whether a combobox exists in another application's dialog box. There is no equivalent functionfor use with dynamic dialog boxes.

Example 'This code fragment checks to ensure that a combo box exists and isenabled'before selecting the last item.

Sub Main()If ComboBoxExists("Filename:") Then

If ComboBoxEnabled("Filename:") ThenNumItems = GetComboBoxItemCount("Filename:")SelectComboBoxItem "Filename:",NumItems

End IfEnd If

End Sub

See Also ComboBoxEnabled (function); GetComboBoxItem$ (function);GetComboBoxItemCount (function); SelectComboBoxItem (statement).

Platform(s) Windows.

Command, Command$ (functions)Syntax Command[$][()]

Description Returns the argument from the command line used to start the application.

Comments Command$ returns a string, whereas Command returns a String variant.

Page 115: Working Model 2D - User's Manual

Chapter 2 Comments (topic) 111

Example 'This example gets the command line and parameters, checks to seewhether'the string "/s" is present, and displays the result.

Sub Main()cmd$ = Command$If (InStr(cmd$,"/s")) <> 0 Then

MsgBox "Application was started with the /s switch."Else

MsgBox "Application was started without the /s switch."End If

If cmd$ <> "" ThenMsgBox "The command line startup options were: " & cmd$

ElseMsgBox "No command line startup options were used!"

End IfEnd Sub

See Also Environ, Environ$ (functions).

Platform(s) Windows and Macintosh.

Comments (topic)Comments can be added to WM Basic 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.

WM Basic supports C-style multiline comment blocks /*...*/, as shown inthe 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"

Note: C-style comments can be nested.

Comparison Operators (topic)Syntax expression1 [< | > | <= | >= | <> | =] expression2

DescriptionComparison operators return True or False depending on the operator.

Page 116: Working Model 2D - User's Manual

112 Working Model Basic User's Manual

Comments The comparison operators are listed in the following table:

Operator Returns True If

> expression1 is greater than expression2

< expression1 is less than expression2

<= expression1 is less than or equal to expression2

>= expression1 is greater than or equal to expression2

<> expression1 is not equal to expression2

= expression1 is equal to expression2

This operator behaves differently depending on the types of the expressions, asshown in the following table:

If one and the otherexpression is expression is then

Numeric Numeric A numeric comparison is performed (seebelow).

String String A string comparison is performed (seebelow).

Numeric String A compile error is generated.

Variant String A string comparison is performed (seebelow).

Variant Numeric A variant comparison is performed (seebelow).

Null variant Any data type Returns Null.

Variant Variant A variant comparison is performed (seebelow).

String Comparisons

If the two expressions are strings, then the operator performs a text comparisonbetween the two string expressions, returning True if expression1 is less thanexpression2. The text comparison is case-sensitive if Option Compare isBinary; otherwise, the comparison is case-insensitive.

When comparing letters with regard to case, lowercase characters in a stringsort greater than uppercase characters, so a comparison of "a" and "A" wouldindicate that "a" is greater than "A".

Page 117: Working Model 2D - User's Manual

Chapter 2 Comparison Operators (topic) 113

Numeric Comparisons

When comparing two numeric expressions, the less precise expression isconverted to be the same type as the more precise expression.

Dates are compared as doubles. This may produce unexpected results as it ispossible to have two dates that, when viewed as text, display as the same datewhen, in fact, they are different. This can be seen in the following example:

Sub Main()Dim date1 As DateDim date2 As Date

date1 = Nowdate2 = date1 + 0.000001 'Adds a fraction of a second.

MsgBox date2 = date1 'Prints False (the dates aredifferent).

MsgBox date1 & "," & date2 'Prints two dates that are thesame.

End Sub

Variant Comparisons

When comparing variants, the actual operation performed is determined atexecution time according to the following table:

If one and the othervariant is variant is then

Numeric Numeric The variants are compared as numbers.

String String The variants are compared as text.

Numeric String The number is less than the string.

Null Any other data type Null.

Numeric Empty The number is compared with 0.

String Empty The string is compared with a zero-lengthstring.

Page 118: Working Model 2D - User's Manual

114 Working Model Basic User's Manual

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 (topic); Is (operator); Like (operator); Option Compare(statement).

Platform(s) Windows and Macintosh.

Const (statement)Syntax Const name [As type] = expression [,name [As type] = expression]...

Description Declares a constant for use within the current script.

Comments The name is only valid within the current WM Basic script. Constant namesmust 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 tofunctions 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 5Const b# = 5 'Constant Double whose value is 5.0Const c$ = "5" 'Constant String whose value is "5"Const d! = 5 'Constant Single whose value is 5.0Const e& = 5 'Constant Long whose value is 5

Page 119: Working Model 2D - User's Manual

Chapter 2 Const (statement) 115

The type can also be given by specifying the As type clause:

Const a As Integer = 5 'Constant Integer whose value is 5Const b As Double = 5 'Constant Double whose value is 5.0Const c As String = "5" 'Constant String whose value is "5"Const d As Single = 5 'Constant Single whose value is 5.0Const e As Long = 5 'Constant Long whose value is 5

You cannot specify both a type-declaration character and the type:

Const a% As Integer = 5 'THIS IS ILLEGAL.

If an explicit type is not given, then WM Basic will choose the most imprecisetype that completely represents the data, as shown below:

Const a = 5 'Integer constantConst b = 5.5 'Single constantConst c = 5.5E200 'Double constant

Constants defined within a Sub or Function are local to that subroutine orfunction. Constants defined outside of all subroutines and function can be usedanywhere within that script. The following example demonstrates the scopingof constants:

Const DefFile = "default.txt"

Sub Test1Const DefFile = "foobar.txt"MsgBox DefFile 'Displays "foobar.txt".

End Sub

Sub Test2MsgBox DefFile 'Displays

"default.txt".End Sub

Example 'This example displays the declared constants in a dialog box (crlfproduces'a new line in the dialog box).

Const crlf = Chr$(13) + Chr$(10)Const s As String = "This is a constant."

Sub Main()MsgBox s$ & crlf & "The constants are shown above."

End Sub

See Also DefType (statement); Let (statement); = (statement); Constants (topic).

Platform(s) Windows and Macintosh.

Page 120: Working Model 2D - User's Manual

116 Working Model Basic User's Manual

Constants (topic)Constants are variables that cannot change value during script execution. Thefollowing constants are predefined by WM Basic:

True False EmptyPi ebRightButton ebLeftButtonebPortrait ebLandscape ebEmptyebWindows ebMaximized ebMinimizedebRestored ebNormal ebReadOnlyebHidden ebSystem ebVolumeebDirectory ebArchive ebNoneebOKOnly ebOKCancel ebAbortRetryIgnoreebYesNoCancel ebYesNo ebRetryCancelebCritical ebQuestion ebExclamationebInformation ebApplicationModalebDefaultButton1ebDefaultButton2 ebDefaultButton3 ebSystemModalebOK ebCancel ebAbortebRetry ebIgnore ebYesebNo ebWin16 ebMacintoshebInteger ebLong ebSingleebDouble ebDate ebBooleanebObject ebDataObject ebVariantebCurrency ebNull

You can define your own constants using the Const statement.

Cos (function)Syntax Cos(angle)

Description Returns a Double representing the cosine of angle.

Comments The angle parameter is a Double specifying an angle in radians.

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 (function); Sin (function); Atn (function).

Platform(s) Windows and Macintosh.

Page 121: Working Model 2D - User's Manual

Chapter 2 CreateObject (function) 117

CreateObject (function)Syntax CreateObject(class$)

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 thetype of object being created. It uses the following syntax:

"application.class",

where application is the application used to create the object and class is thetype of the object to create.

At runtime, CreateObject looks for the given application and runs thatapplication if found. Once the object is created, its properties and methods canbe accessed using the dot syntax (e.g., object.property = value).

There may be a slight delay when an automation server is loaded (this dependson the speed with which a server can be loaded from disk). This delay isreduced if an instance of the automation server is already loaded.

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

Page 122: Working Model 2D - User's Manual

118 Working Model Basic User's Manual

'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 ObjectDim doc As ObjectDim page As ObjectDim shape As Object

Set Visio = CreateObject("visio.application") 'Create Visio object.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 Sub

See Also GetObject (function); Object (data type).

Platform(s) Windows and Macintosh..

Cross-Platform Scripting (topic)This section discusses different techniques that can be used to ensure that agiven script runs on all platforms that support WM Basic.

Querying the Platform

A script can query the platform in order to take appropriate actions for thatplatform. This is done using the Basic.OS property. The following exampleuses this method to display a message to the user:

Sub Main()If Basic.OS = ebWin16 Then

MsgBox "Running on Windows"Else

Print "Not running on Windows"End If

End Sub

Page 123: Working Model 2D - User's Manual

Chapter 2 Cross-Platform Scripting (topic) 119

Querying the Capabilities of a Platform

Some capabilities of the current platform can be determined using theBasic.Capability method. This method takes a number indicating whichcapability is being queried and returns either True or False depending onwhether that capability is or is not supported on the current platform. Thefollowing example uses this technique to read hidden files:

Sub Main()If Basic.Capability(3) Then

f$ = Dir$("*",ebHidden)'This platform supports hidden files.Else

f$ = Dir$("*") 'This platform doesn't supporthidden files.

End If

'Print all the files.While f$ <> ""

x = x + 1Msgbox "Matching file " & x & " is: " & f$f$ = Dir$

WEndEnd Sub

Byte Ordering with Files

One of the main differences between platforms is byte ordering. On someplatforms, the processor requires that the bytes that make up a given data itembe reversed from their expected ordering.

Byte ordering becomes problematic if binary data is transferred from oneplatform to another. This can only occur when writing data to files. For thisreason, it is strongly recommended that files that are to be transported to adifferent platform with different byte ordering be sequential (i.e., do not useBinary and Random files).

If a Binary or Random file needs to be transported to another platform, youwill have to take into consideration the following:

1. You must either decide on a byte ordering for your file or write informationto the file indicating its byte ordering so that it can be queried by the scriptthat is to read the file.

2. When reading a file on a platform in which the byte ordering matches,nothing further needs to be done. If the byte ordering is different, then thebytes of each data item read from a file need to be reversed. This is adifficult proposition.

Byte Ordering with Structures

Due to byte ordering differences between platforms, structure copying using theLSet statement produces different results. Consider the following example:

Page 124: Working Model 2D - User's Manual

120 Working Model Basic User's Manual

Type TwoIntsfirst As Integersecond As Integer

End Type

Type OneLongfirst As Long

End Type

Sub Main()Dim l As OneLongDim i As TwoIntsl.First = 4LSet i = lMsgBox "First integer: " & i.firstMsgBox "Second integer: " & i.second

End Sub

On Intel-based platforms, bytes are stored in memory with the most significantbyte first (known as little-endian format). Thus, the above example displays twodialog boxes, the first one displaying the number 4 and the second displayingthe number 0.

On Macintosh platforms, bytes are stored in memory with the least significantbyte first (known as big-endian format). Thus, the above example displays twodialog boxes, the first one displaying the number 0 and the second displayingthe number 4.

Script that rely on binary images of data must take the byte ordering of thecurrent platform into account.

Reading Text Files and Writing to Them

Different platforms use different characters to represent end-of-line in a file.For example, under Windows, a carriage-return/line-feed pair is used. On theMacintosh, a carriage return is used.

WM Basic takes this into account when reading text files. The followingcombinations are recognized and interpreted as end-of-line:

Carriage return Chr(13)Carriage return/line feed Chr(13) + Chr(10)Line feed Chr(10)

When writing to text files, WM Basic uses the end-of-line appropriate to thatplatform. You can retrieve the same end-of-line used by WM Basic using theBasic.Eoln$ property:

crlf = Basic.Eoln$Print #1,"Line 1." & crlf & "Line 2."

Alignment

A major difference between platforms supported by WM Basic is the forcedalignment of data. WM Basic handles most alignment issues itself.

Page 125: Working Model 2D - User's Manual

Chapter 2 Cross-Platform Scripting (topic) 121

Portability of Compiled Code

Scripts compiled under WM Basic can be executed without recompilation onany platform supported by WM Basic.

Unsupported Language Elements

A compiled WM Basic script is portable to any platform on which WM Basicruns. Because of this, it is possible to execute a script that was compiled onanother platform and contains calls to language elements not supported by thecurrent platform.

WM Basic generates a runtime error when unsupported language elements areencountered during execution.

If you trap a call to an unsupported function, the function will return one of thefollowing values:

Data Type Skipped Function Returns

Integer 0Double 0.0Single 0.0Long 0Date December 31, 1899Boolean FalseVariant EmptyObject Nothing

Path Separators

Different file systems use different characters to separate parts of a pathname.For example, under Windows, the backslash character is used:

s$ = "c:\sheets\bob.xls"

When creating scripts that operate on any of these platforms, WM Basicrecognizes the forward slash universally as a valid path separator. Thus, thefollowing file specification is valid on all these platforms:

s$ = "/sheets/bob.xls"

On the Macintosh, the slashes are valid filename characters. Instead, WM Basicrecognizes the colon as the valid file separator character:

s$ = "sheets:bob.xls"

You can find out the path separator character for your platform using theBasic.PathSeparator$ property:

s$ = "sheets" & Basic.PathSeparator$ & "bob.xls"

Page 126: Working Model 2D - User's Manual

122 Working Model Basic User's Manual

Relative Paths

Specifying relative paths is different across platforms. Under Windows, aperiod (.) is used to specify the current directory, and two periods (..) are usedto indicate the parent directory, as shown below:

s$ = ".\bob.xls" 'File in the current directorys$ = "..\bob.xls" 'File in the parent directory

On the Macintosh, double colons are used to specify the parent folder:

s$ = "::bob.xls" 'File in the parent folder

Drive Letters

Not all platforms support drive letters. For example, considering the followingfile specification:

c:\test.txt

Under Windows, this specifies a file called test.txt in the root directory ofdrive c. On the Macintosh, this specifies a file called \test.txt in a foldercalled c. You can use the Basic.Capability method to determine whetheryour platform supports drive letters:

Sub Main()If Basic.Capability(1) Then s$ = "c:/" Else s$ = ""s$ = s$ & "test.xls"MsgBox "The platform-specific filename is: " & s$

End Sub

CSng (function)Syntax CSng(expression)

Description Converts expression to a Single.

Comments This function accepts any expression convertible to a Single, includingstrings. A runtime error is generated if expression is Null. Empty is treated as0.0.

A runtime error results if the passed expression is not within the valid range forSingle.

When passed a numeric expression, this function has the same effect asassigning the numeric expression to a Single.

When used with variants, this function guarantees that the expression isconverted to a Single variant (VarType 4).

Page 127: Working Model 2D - User's Manual

Chapter 2 CStr (function) 123

Example 'This example displays the value of a String converted to a Single.

Sub Main()s$ = "100"MsgBox "The single value is: " & CSng(s$)

End Sub

See Also CCur (function); CBool (function); CDate, CVDate (functions); CDbl(function); CInt (function); CLng (function); CStr (function); CVar (function);CVErr (function); Single (data type).

Platform(s) Windows and Macintosh.

CStr (function)Syntax CStr(expression)

Description Converts expression to a String.

Comments Unlike Str$ or Str, the string returned by CStr will not contain a leadingspace if the expression is positive. Further, the CStr function correctlyrecognizes thousands and decimal separators for your locale.

Different data types are converted to String in accordance with the followingrules:

Data Type CStr Returns

Any numeric type A string containing the number without the leading space for positive values.

Date A string converted to a date using the short date format.

Boolean A string containing either "True" or "False".

Null variant A runtime error.

Empty variant A zero-length string.

Example 'This example displays the value of a Double converted to a String. SubMain()

s# = 123.456MsgBox "The string value is: " & CStr(s#)

End Sub

See Also CCur (function); CBool (function); CDate, CVDate (functions); CDbl(function); CInt (function); CLng (function); CSng (function); CVar (function);CVErr (function); String (data type); Str, Str$ (functions).

Platform(s) Windows and Macintosh.

CurDir, CurDir$ (functions)Syntax CurDir[$][(drive$)]

Page 128: Working Model 2D - User's Manual

124 Working Model Basic User's Manual

Description Returns the current directory on the specified drive. If no drive$ is specified ordrive$ is zero-length, then the current directory on the current drive is returned.

Comments CurDir$ returns a String, whereas CurDir returns a String variant.

WM Basic 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 originaldirectory'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 (statement); ChDrive (statement); Dir, Dir$ (functions); MkDir(statement); RmDir (statement).

Platform(s) Windows and Macintosh.

Currency (data type)Syntax Currency

Description A data type used to declare variables capable of holding fixed-point numberswith 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 calculationsinvolving money.

The type-declaration character for Currency is @.

Storage

Internally, currency values are 8-byte integers scaled by 10000. Thus, whenappearing within a structure, currency values require 8 bytes of storage. Whenused with binary or random files, 8 bytes of storage are required.

See Also Date (data type); Double (data type); Integer (data type); Long (data type);Object (data type); Single (data type); String (data type); Variant (datatype); Boolean (data type); DefType (statement); CCur (function).

Page 129: Working Model 2D - User's Manual

Chapter 2 CVar (function) 125

Platform(s) Windows and Macintosh.

CVar (function)Syntax CVar(expression)

Description Converts expression to a Variant.

Comments This function is used to convert an expression into a variant. Use of thisfunction is not necessary (except for code documentation purposes) becauseassignment to variant variables automatically performs the necessaryconversion:

Sub Main()Dim v As Variantv = 4 & "th" 'Assigns "4th" to v.MsgBox "You came in: " & vv = CVar(4 & "th") 'Assigns "4th" to v.MsgBox "You came in: " & v

End Sub

Example 'This example converts an expression into a Variant.

Sub Main()Dim s As StringDim a As Variants = CStr("The quick brown fox ")msg = CVar(s & "jumped over the lazy dog.")MsgBox msg

End Sub

See Also CCur (function); CBool (function); CDate, CVDate (functions); CDbl(function); CInt (function); CLng (function); CSng (function); CStr (function);CVErr (function); Variant (data type).

Platform(s) Windows and Macintosh.

CVErr (function)Syntax CVErr(expression)

Description Converts expression to an error.

Page 130: Working Model 2D - User's Manual

126 Working Model Basic User's Manual

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 asfollows:

0 <= expression <= 65535

If expression is Boolean.

If expression is a String that can't be converted to a number within thelegal range.

Empty is treated as 0.

Example 'This example simulates a user-defined error and displays the errornumber.

Sub Main()MsgBox "The error is: " & CStr(CVErr(2046))

End Sub

See Also CCur (function); CBool (function); CDate, CVDate (functions); CDbl(function); CInt (function); CLng (function); CSng (function); CStr (function);CVar (function), IsError (function).

Platform(s) Windows and Macintosh.

Page 131: Working Model 2D - User's Manual

127

Date (data type)Syntax Date

Description A data type capable of holding date and time values.

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 holdsthe number of days since December 31, 1899, and the fractional part holds thenumber of seconds as a fraction of the day. For example, the number 32874.5represents 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 Dated = #January 1, 1990#

The interpretation of the date string (i.e., January 1, 1990 in the aboveexample) occurs at runtime, using the current country settings. This is aproblem 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 isFebruary 1, 1990. To remove any ambiguity when interpreting dates, use theuniversal date format:

date_variable = #YY/MM/DD HH:MM:SS#

The following example specifies the date June 3, 1965 using the universal dateformat:

Dim d As Dated = #1965/6/3 10:23:45#

See Also Currency (data type); Double (data type); Integer (data type); Long (datatype); Object (data type); Single (data type); String (data type); Variant(data type); Boolean (data type); DefType (statement); CDate, CVDate(functions).

Platform(s) Windows and Macintosh.

Page 132: Working Model 2D - User's Manual

128 Working Model Basic User's Manual

Date, Date$ (functions)Syntax Date[$][()]

Description Returns the current system date.

Comments The Date$ function returns the date using the short date format. The Datefunction returns the date as a Date variant.

Use the Date/Date$ statements to set the system date.

Note: In prior versions of WM Basic, the Date$ function returned the dateusing a fixed date format. The date is now returned using the current short dateformat (defined by the operating system), which may differ from the previousfixed format.

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 CDate, CVDate (functions); Time, Time$ (functions); Date, Date$(statements); Now (function); Format, Format$ (functions); DateSerial(function); DateValue (function).

Platform(s) Windows and Macintosh.

Date, Date$ (statements)Syntax Date[$] = newdate

Description Sets the system date to the specified date.

Page 133: Working Model 2D - User's Manual

Chapter 2 Date, Date$ (statements) 129

Comments The Date$ statement requres a string variable using one of the followingformats:

MM-DD-YYYYMM-DD-YYMM/DD/YYYYMM/DD/YY,

where MM is a two-digit month between 1 and 31, DD is a two-digit daybetween 1 and 31, and YYYY is a four-digit year between 1/1/100 and12/31/9999.

The Date statement converts any expression to a date, including string andnumeric values. Unlike the Date$ statement, Date recognizes many differentdate formats, including abbreviated and full month names and a variety ofordering options. If newdate contains a time component, it is accepted, but thetime is not changed. An error occurs if newdate cannot be interpreted as a validdate.

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$ (functions); Time, Time$ (statements).

Platform(s) Windows and Macintosh.

PlatformNotes

On some platforms, you may not have permission to change the date, causingruntime error 70 to be generated. This can occur on Win32 and OS/2.

The range of valid dates varies from platform to platform. The following tabledescribes the minimum and maximum dates accepted by various platforms:

Platform Minimum Date Maximum Date

Macintosh January 1, 1904 February 6, 2040

Windows January 1, 1980 December 31, 2099

Windows 95 January 1, 1980 December 31, 2099

OS/2 January 1, 1980 December 31, 2079

Page 134: Working Model 2D - User's Manual

130 Working Model Basic User's Manual

DateAdd (function)Syntax DateAdd(interval$, increment&, date)

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 theDateAdd 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. Positivevalues result in dates in the future; negative values result in dates in the past.

date Any expression convertible to a Date.

The interval$ parameter specifies what unit of time is to be added to the givendate. It can be any of the following:

Time Interval"y" Day of the year"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, asthey are all equivalent ("d", "y", "w").

The DateAdd function will never return an invalid date/time expression. Thefollowing 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".

WM Basic generates a runtime error if you try subtracting a time interval that islarger than the time value of the date.

Page 135: Working Model 2D - User's Manual

Chapter 2 DateDiff (function) 131

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

See Also DateDiff (function).

Platform(s) Windows and Macintosh.

DateDiff (function)Syntax DateDiff(interval$,date1,date2)

Description Returns a Date variant representing the number of given time intervalsbetween date1 and date2.

Comments The following table describes the parameters:

Parameter Description

interval$ String expression indicating the specific time interval you wish to find thedifference between.

date1 Any expression convertible to a Date. An example of a valid date/time stringwould be "January 1, 1994".

date2 Any expression convertible to a Date. An example of a valid date/time stringwould be "January 1, 1994".

Page 136: Working Model 2D - User's Manual

132 Working Model Basic User's Manual

The following table lists the valid time interval strings and the meanings ofeach. The Format$ function uses the same expressions.

Time Interval"y" Day of the year"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 dayof the year, as they are both equivalent ("d", "y").

The time interval weekday ("w") will return the number of weekdays occurringbetween date1 and date2, counting the first occurrence but not the last.However, if the time interval is week ("ww"), the function will return thenumber of calendar weeks between date1 and date2, counting the number ofSundays. If date1 falls on a Sunday, then that day is counted, but if date2 fallson a Sunday, it is not counted.

The DateDiff function will return a negative date/time value if date1 is adate later in time than date2.

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 " & NextWeeks$ = s$ & " is: " & DifDays# & " days or " & DifWeek# & " weeks"MsgBox s$

End Sub

See Also DateAdd (function).

Platform(s) Windows and Macintosh.

DatePart (function)Syntax DatePart(interval$,date)

Page 137: Working Model 2D - User's Manual

Chapter 2 DatePart (function) 133

Description Returns an Integer representing a specific part of a date/time expression.

Comments The DatePart function decomposes the specified date and returns a givendate/time element. The following table describes the parameters:

Parameter Description

interval$ String expression that indicates the specific time interval you wish to identifywithin the given date.

date Any expression convertible to a Date. An example of a valid date/time stringwould be "January 1, 1995".

The following table lists the valid time interval strings and the meanings ofeach. The Format$ function uses the same expressions.

Time Interval"y" Day of the year"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.

Example 'This example displays the parts of the current date.

Const crlf = Chr$(13) + Chr$(10)

Sub Main()today$ = Date$qtr = DatePart("q",today$)yr = DatePart("yyyy",today$)mo = DatePart("m",today$)wk = DatePart("ww",today$)da = DatePart("d",today$)s$ = "Quarter: " & qtr & crlfs$ = s$ & "Year : " & yr & crlfs$ = s$ & "Month : " & mo & crlfs$ = s$ & "Week : " & wk & crlfs$ = s$ & "Day : " & da & crlfMsgBox s$

End Sub

See Also Day (function); Minute (function); Second (function); Month (function); Year(function); Hour (function); Weekday (function), Format (function).

Platform(s) Windows and Macintosh.

Page 138: Working Model 2D - User's Manual

134 Working Model Basic User's Manual

DateSerial (function)Syntax DateSerial(year,month,day)

Description Returns a Date variant representing the specified date.

Comments The DateSerial function takes the following parameters:

Parameter Description

year Integer between 100 and 9999

month Integer between 1 and 12

day Integer between 1 and 31

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 (function); TimeSerial (function); TimeValue (function); CDate,CVDate (functions).

Platform(s) Windows and Macintosh.

DateValue (function)Syntax DateValue(date_string$)

Description Returns a Date variant representing the date contained in the specified stringargument.

Example 'This example returns the day of the month for today's date.

Sub Main()tdate$ = Date$tday = DateValue(tdate$)MsgBox tdate & " date value is: " & tday$

End Sub

See Also TimeSerial (function); TimeValue (function); DateSerial (function).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Under Windows, date specifications vary depending on the internationalsettings contained in the "intl" section of the win.ini file. The date items mustfollow the ordering determined by the current date format settings in use byWindows.

Page 139: Working Model 2D - User's Manual

Chapter 2 Day (function) 135

Day (function)Syntax Day(date)

Description Returns the day of the month specified by date.

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 (function); Second (function); Month (function); Year (function); Hour(function); Weekday (function); DatePart (function).

Platform(s) Windows and Macintosh.

DDB (function)Syntax DDB(Cost, Salvage, Life, Period)

Description Calculates the depreciation of an asset for a specified Period of time using thedouble-declining balance method.

Page 140: Working Model 2D - User's Manual

136 Working Model Basic User's Manual

Comments The double-declining balance method calculates the depreciation of an asset atan accelerated rate. The depreciation is at its highest in the first period andbecomes progressively lower in each additional period. DDB uses the followingformula to calculate the depreciation:

DDB =((Cost – Total_depreciation_from_all_other_periods) * 2)/Life

The DDB function uses the following parameters:

Parameter Description

Cost Double representing the initial cost of the asset

Salvage Double representing the estimated value of the asset at the end of its predicteduseful life

Life Double representing the predicted length of the asset's useful life

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 isexpressed 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 & crlfFor yy = 1 To 4

CurDep# = DDB(10000.0,2000.0,10,yy)s$ = s$ & "Year " & yy & " : " & CurDep# & crlf

Next yyMsgBox s$

End Sub

See Also Sln (function); SYD (function).

Platform(s) Windows and Macintosh.

DDEExecute (statement)Syntax DDEExecute channel, command$

Description Executes a command in another application.

Page 141: Working Model 2D - User's Manual

Chapter 2 DDEInitiate (function) 137

Comments The DDEExecute statement takes the following parameters:

Parameter Description

channel Integer containing the DDE channel number returned from DDEInitiate. Anerror 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, WM Basicgenerates a runtime error.

Example 'This example selects a cell in an Excel spreadsheet.

Sub Main()q$ = Chr(34)ch% = DDEInitiate("Excel","c:\sheets\test.xls")cmd$ = "Select(" & q$ & "R1C1:R8C1" & q$ & ")"DDEExecute ch%,cmd$DDETerminate ch%

End Sub

See Also DDEInitiate (function); DDEPoke (statement); DDERequest, DDERequest$(functions); DDESend (function); DDETerminate (statement); DDETerminateAll(statement); DDETimeout (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the DDEML library is required for DDE support. This libraryis loaded when the first DDEInitiate statement is encountered and remainsloaded until the WM Basic system is terminated. Thus, the DDEML library isrequired only if DDE statements are used within a script.

DDEInitiate (function)Syntax DDEInitiate(application$, topic$)

Description Initializes a DDE link to another application and returns a unique numbersubsequently used to refer to the open DDE channel.

Page 142: Working Model 2D - User's Manual

138 Working Model Basic User's Manual

Comments The DDEInitiate statement takes the following parameters:

Parameter Description

application$ String containing the name of the application (the server) with which a DDEconversation will be established.

topic$ String containing the name of the topic for the conversation. The possiblevalues for this parameter are described in the documentation for the serverapplication.

This function returns 0 if WM Basic cannot establish the link. This will occurunder any of the following circumstances:

• The specified application is not running.

• The topic was invalid for that application.

• Memory or system resources are insufficient to establish the DDE link.

Example 'This example selects a range of cells in an Excel spreadsheet.

Sub Main()q$ = Chr(34)ch% = DDEInitiate("Excel","c:\sheets\test.xls")cmd$ = "Select(" & q$ & "R1C1:R8C1" & q$ & ")"DDEExecute ch%,cmd$DDETerminate ch%

End Sub

See Also DDEExecute (statement); DDEPoke (statement); DDERequest, DDERequest$(functions); DDESend (function); DDETerminate (statement); DDETerminateAll(statement); DDETimeout (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the DDEML library is required for DDE support. This libraryis loaded when the first DDEInitiate statement is encountered and remainsloaded until the WM Basic system is terminated. Thus, the DDEML library isrequired only if DDE statements are used within a script.

DDEPoke (statement)Syntax DDEPoke channel, DataItem, value

Description Sets the value of a data item in the receiving application associated with anopen DDE link.

Page 143: Working Model 2D - User's Manual

Chapter 2 DDERequest, DDERequest$ (functions) 139

Comments The DDEPoke statement takes the following parameters:

Parameter Description

channel Integer containing the DDE channel number returned from DDEInitiate. Anerror will result if channel is invalid.

DataItem Data item to be set. This parameter can be any expression convertible to aString. The format depends on the server.

value The new value for the data item. This parameter can be any expressionconvertible to a String. The format depends on the server. A runtime error isgenerated if value is Null.

Example 'This example pokes a value into an Excel spreadsheet.

Sub Main()ch% = DDEInitiate("Excel","c:\sheets\test.xls")DDEPoke ch%,"R1C1","980"DDETerminate ch%

End Sub

See Also DDEExecute (statement); DDEInitiate (function); DDERequest, DDERequest$(functions); DDESend (function); DDETerminate (statement); DDETerminateAll(statement); DDETimeout (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the DDEML library is required for DDE support. This libraryis loaded when the first DDEInitiate statement is encountered and remainsloaded until the WM Basic system is terminated. Thus, the DDEML library isrequired only if DDE statements are used within a script.

DDERequest, DDERequest$ (functions)Syntax DDERequest[$](channel,DataItem$)

Description Returns the value of the given data item in the receiving application associatedwith the open DDE channel.

Page 144: Working Model 2D - User's Manual

140 Working Model Basic User's Manual

Comments DDERequest$ returns a String, whereas DDERequest returns a Stringvariant.

The DDERequest/DDERequest$ functions take the following parameters:

Parameter Description

channel Integer containing the DDE channel number returned from DDEInitiate. Anerror will result if channel is invalid.

DataItem$ String containing the name of the data item to request. The format for thisparameter depends on the server.

The format for the returned value depends on the server.

Example 'This example gets a value from an Excel spreadsheet.

Sub Main()ch% = DDEInitiate("Excel","c:\excel\test.xls")s$ = DDERequest$(ch%,"R1C1")DDETerminate ch%MsgBox s$

End Sub

See Also DDEExecute (statement); DDEInitiate (function); DDEPoke (statement);DDESend (function); DDETerminate (statement); DDETerminateAll (statement);DDETimeout (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the DDEML library is required for DDE support. This libraryis loaded when the first DDEInitiate statement is encountered and remainsloaded until the WM Basic system is terminated. Thus, the DDEML library isrequired only if DDE statements are used within a script.

DDESend (statement)Syntax DDESend application$, topic$, DataItem, value

Description Initiates a DDE conversation with the server as specified by application$ andtopic$ and sends that server a new value for the specified item.

Page 145: Working Model 2D - User's Manual

Chapter 2 DDETerminate (statement) 141

CommentsThe DDESend statement takes the following parameters:

Parameter Description

application$ String containing the name of the application (the server) with which a DDEconversation will be established.

topic$ String containing the name of the topic for the conversation. The possiblevalues for this parameter are described in the documentation for the serverapplication.

DataItem Data item to be set. This parameter can be any expression convertible to aString. The format depends on the server.

value New value for the data item. This parameter can be any expression convertibleto a String. The format depends on the server. A runtime error is generated ifvalue is Null.

The DDESend statement performs the equivalent of the following statements:

ch% = DDEInitiate(application$, topic$)DDEPoke ch%, item, dataDDETerminate ch%

Example 'This code fragment sets the content of the first cell in'an Excel spreadsheet.

Sub Main()On Error Goto Trap1DDESend "Excel","c:\excel\test.xls","R1C1","Hello, world."On Error Goto 0'Add more lines here.

Trap1:MsgBox "Error sending data to Excel."Exit Sub 'Reset error handler.

End Sub

See Also DDEExecute (statement); DDEInitiate (function); DDEPoke (statement);DDERequest, DDERequest$ (functions); DDETerminate (statement);DDETerminateAll (statement); DDETimeout (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the DDEML library is required for DDE support. This libraryis loaded when the first DDEInitiate statement is encountered and remainsloaded until the WM Basic system is terminated. Thus, the DDEML library isrequired only if DDE statements are used within a script.

DDETerminate (statement)Syntax DDETerminate channel

Page 146: Working Model 2D - User's Manual

142 Working Model Basic User's Manual

Description Closes the specified DDE channel.

Comments The channel parameter is an Integer containing the DDE channel numberreturned from DDEInitiate. An error will result if channel is invalid.

All open DDE channels are automatically terminated when the script ends.

Example 'This code fragment sets the content of the first cell in'an Excel spreadsheet.

Sub Main()q$ = Chr(34)ch% = DDEInitiate("Excel","c:\sheets\test.xls")cmd$ = "Select(" & q$ & "R1C1:R8C1" & q$ & ")"DDEExecute ch%,cmd$DDETerminate ch%

End Sub

See Also DDEExecute (statement); DDEInitiate (function); DDEPoke (statement);DDERequest, DDERequest$ (functions); DDESend (function);DDETerminateAll (statement); DDETimeout (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the DDEML library is required for DDE support. This libraryis loaded when the first DDEInitiate statement is encountered and remainsloaded until the WM Basic system is terminated. Thus, the DDEML library isrequired only if DDE statements are used within a script.

DDETerminateAll (statement)Syntax DDETerminateAll

Description Closes all open DDE channels.

Comments All open DDE channels are automatically terminated when the script ends.

Example 'This code fragment selects the contents of the first cell in'an Excel spreadsheet.

Sub Main()q$ = Chr(34)ch% = DDEInitiate("Excel","c:\sheets\test.xls")cmd$ = "Select(" & q$ & "R1C1:R8C1" & q$ & ")"DDEExecute ch%,cmd$DDETerminateAll

End Sub

See Also DDEExecute (statement); DDEInitiate (function); DDEPoke (statement);DDERequest, DDERequest$ (functions); DDESend (function); DDETerminate(statement); DDETimeout (statement).

Platform(s) Windows.

Page 147: Working Model 2D - User's Manual

Chapter 2 DDETimeout (statement) 143

PlatformNotes:

Windows

Under Windows, the DDEML library is required for DDE support. This libraryis loaded when the first DDEInitiate statement is encountered and remainsloaded until the WM Basic system is terminated. Thus, the DDEML library isrequired only if DDE statements are used within a script.

DDETimeout (statement)Syntax DDETimeout milliseconds

Description Sets the number of milliseconds that must elapse before any DDE commandtimes 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 Sub Main()q$ = Chr(34)ch% = DDEInitiate("Excel","c:\sheets\test.xls")DDETimeout(20000)cmd$ = "Select(" & q$ & "R1C1:R8C1" & q$ & ")"DDEExecute ch%,cmd$DDETerminate ch%

End Sub

See Also DDEExecute (statement); DDEInitiate (function); DDEPoke (statement);DDERequest, DDERequest$ (functions); DDESend (function); DDETerminate(statement); DDETerminateAll (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the DDEML library is required for DDE support. This libraryis loaded when the first DDEInitiate statement is encountered and remainsloaded until the WM Basic system is terminated. Thus, the DDEML library isrequired only if DDE statements are used within a script.

Declare (statement)Syntax Declare {Sub | Function} name[TypeChar] [CDecl | Pascal | System |

StdCall] _[Lib "LibName$" [Alias "AliasName$"]] [([ParameterList])] [As type]

Where ParameterList is a comma-separated list of the following (up to 30parameters are allowed):

[Optional] [ByVal | ByRef] ParameterName[()] [As ParameterType]

Description Creates a prototype for either an external routine or a WM Basic routine thatoccurs later in the source module or in another source module.

Page 148: Working Model 2D - User's Manual

144 Working Model Basic User's Manual

Comments Declare statements must appear outside of any Sub or Functiondeclaration.

Declare statements are only valid during the life of the script in which theyappear.

The Declare statement uses the following parameters:

Parameter Description

name Any valid WM Basic name. When you declare functions, you can include atype-declaration character to indicate the return type.

This name is specified as a normal WM Basic keyword—i.e., it does not appearwithin quotes.

TypeChar An optional type-declaration character used when defining the type of datareturned from functions. It can be any of the following characters: #, !, $, @, %,or &. For external functions, the @ character is not allowed.

Type-declaration characters can only appear with function declarations, andtake the place of the As type clause.

Note: Currency data cannot be returned from external functions. Thus, the @type-declaration character cannot be used when declaring external functions.

CDecl Optional keyword indicating that the external subroutine or function uses the Ccalling convention. With C routines, arguments are pushed right to left on thestack and the caller performs stack cleanup.

Pascal Optional keyword indicating that this external subroutine or function uses thePascal calling convention. With Pascal routines, arguments are pushed left toright on the stack and the called function performs stack cleanup.

System Optional keyword indicating that the external subroutine or function uses theSystem calling convention. With System routines, arguments are pushed rightto left on the stack, the caller performs stack cleanup, and the number ofarguments is specified in the AL register.

StdCall Optional keyword indicating that the external subroutine or function uses theStdCall calling convention. With StdCall routines, arguments are pushed rightto left on the stack and the called function performs stack cleanup.

LibName$ Must be specified if the routine is external. This parameter specifies the nameof the library or code resource containing the external routine and must appearwithin quotes.

The LibName$ parameter can include an optional path specifying the exactlocation of the library or code resource..

Page 149: Working Model 2D - User's Manual

Chapter 2 Declare (statement) 145

AliasName$ Alias name that must be given to provide the name of the routine if the nameparameter is not the routine's real name. For example, the following twostatements declare the same routine:

Declare Function GetCurrentTime Lib "user" () AsInteger

Declare Function GetTime Lib "user" Alias"GetCurrentTime" _As Integer

Use an alias when the name of an external routine conflicts with the name of aWM Basic internal routine or when the external routine name contains invalidcharacters.

The AliasName$ parameter must appear within quotes.

type Indicates the return type for functions.

For external functions, the valid return types are: Integer, Long, String,Single, Double, Date, Boolean, and data objects.

Note: Currency, Variant, fixed-length strings, arrays, user-defined types, andOLE automation objects cannot be returned by external functions.

Optional Keyword indicating that the parameter is optional. All optional parameters mustbe of type Variant. Furthermore, all parameters that follow the first optionalparameter must also be optional.

If this keyword is omitted, then the parameter being defined is required whencalling this subroutine or function.

ByVal Optional keyword indicating that the caller will pass the parameter by value.Parameters passed by value cannot be changed by the called routine.

ByRef Optional keyword indicating that the caller will pass the parameter byreference. Parameters passed by reference can be changed by the called routine.If neither ByVal or ByRef are specified, then ByRef is assumed.

Page 150: Working Model 2D - User's Manual

146 Working Model Basic User's Manual

ParameterName Name of the parameter, which must follow WM Basic naming conventions:

1. Must start with a letter.

2. May contain letters, digits, and the underscore character(_). Punctuation and type-declaration characters are notallowed. The exclamation point (!) can appear within thename as long as it is not the last character, in which caseit is interpreted as a type-declaration character.

3. Must not exceed 80 characters in length.

Additionally, ParameterName can end with an optional type-declarationcharacter specifying the type of that parameter (i.e., any of the followingcharacters: %, &, !, #, @).

() Indicates that the parameter is an array.

ParameterType Specifies the type of the parameter (e.g., Integer, String, Variant, and soon). The As ParameterType clause should only be included if ParameterNamedoes not contain a type-declaraction character.

In addition to the default WM Basic data types, ParameterType can specify anyuser-defined structure, data object, or OLE automation object. If the data typeof the parameter is not known in advance, then the Any keyword can be used.This forces the WM Basic compiler to relax type checking, allowing any datatype to be passed in place of the given argument.

Declare Sub Convert Lib "mylib" (a As Any)

The Any data type can only be used when passing parameters to externalroutines.

Passing Parameters

By default, WM Basic passes arguments by reference. Many external routinesrequire a value rather than a reference to a value. The ByVal keyword doesthis. For example, this C routine

void MessageBeep(int);

would be declared as follows:

Declare Sub MessageBeep Lib "user" (ByVal n As Integer)

Page 151: Working Model 2D - User's Manual

Chapter 2 Declare (statement) 147

As an example of passing parameters by reference, consider the following Croutine which requires a pointer to an integer as the third parameter:

int SystemParametersInfo(int,int,int *,int);

This routine would be declared as follows (notice the ByRef keyword in thethird parameter):

Declare Function SystemParametersInfo Lib "user" (ByVal action AsInteger, _

ByVal uParam As Integer,ByRef pInfo As Integer, _ByVal updateINI As Integer) As Integer

Strings can be passed by reference or by value. When they are passed byreference, a pointer to the internal handle to the WM Basic string is passed.When they are passed by value, WM Basic passes a 32-bit pointer to a null-terminated string (i.e., a C string). If an external routine modifies a passedstring variable, then there must be sufficient space within the string to hold thereturned characters. This can be accomplished using the Space function, asshown in the following example:

Declare Sub GetWindowsDirectory Lib "kernel" (ByVal dirname$, ByVallength%)

:Dim s As Strings = Space(128)GetWindowsDirectory s,128

Another alternative to ensure that a string has sufficient space is to declare thestring with a fixed length:

Declare Sub GetWindowsDirectory Lib "kernel" (ByVal dirname$, ByVallength%)

:Dim s As String * 128 'Declare a fixed-length string.GetWindowsDirectory s,len(s) 'Pass it to an external subroutine.

Calling Conventions with External Routines

For external routines, the argument list must exactly match that of thereferenced routine. When calling an external subroutine or function, WM Basicneeds to be told how that routine expects to receive its parameters and who isresponsible for cleanup of the stack.

The following table describes which calling conventions are supported onwhich platform, and indicates what the default calling convention is when noexplicit calling convention is specified in the Declare statement.

Supported Calling Default CallingPlatform Conventions Convention

Windows Pascal, CDecl Pascal

Macintosh Pascal, CDecl Pascal

Page 152: Working Model 2D - User's Manual

148 Working Model Basic User's Manual

Passing Null Pointers

To pass a null pointer to an external procedure, declare the parameter that is toreceive the null pointer as type Any, then pass a long value 0 by value:

Declare Sub Foo Lib "sample" (ByVal lpName As Any)

Sub Main()Sub Foo "Hello" 'Pass a 32-bit pointer to a null-terminated

stringSub Foo ByVal 0& 'Pass a null pointer

End Sub

Passing Data to External Routines

The following table shows how the different data types are passed to externalroutines:

Data Type Is Passed As

ByRef Boolean A 32-bit pointer to a 2-byte value containing –1 or 0.

ByVal Boolean A 2-byte value containing –1 or 0.

ByVal Integer A 32-bit pointer to a 2-byte short integer.

ByRef Integer A 2-byte short integer.

ByVal Long A 32-bit pointer to a 4-byte long integer.

ByRef Long A 4-byte long integer.

ByRef Single A 32-bit pointer to a 4-byte IEEE floating-point value (a float).

ByVal Single A 4-byte IEEE floating-point value (a float).

ByRef Double A 32-bit pointer to an 8-byte IEEE floating-point value (a double).

ByVal Double An 8-byte IEEE floating-point value (a double).

ByVal String A 32-bit pointer to a null-terminated string. With strings containing embeddednulls (Chr$(0)), it is not possible to determine which null represents the end ofthe string. Therefore, the first null is considered the string terminator.

An external routine can freely change the content of a string. It cannot,however, write beyond the end of the null terminator.

ByRef String A 32-bit pointer to a 2-byte internal value representing the string. This valuecan only be used by external routines written specifically for WM Basic.

ByRef Date A 32-bit pointer to an 8-byte IEEE floating-point value (a double).

ByVal Date An 8-byte IEEE floating-point value (a double).

ByRef Currency A 32-bit pointer to an 8-byte integer scaled by 10000.

ByVal Currency An 8-byte integer scaled by 10000.

Page 153: Working Model 2D - User's Manual

Chapter 2 Declare (statement) 149

ByRef Variant A 32-bit pointer to a 16-byte internal variant structure. This structure contains a2-byte type (the same as that returned by the VarType function), followed by 6bytes of slop (for alignment), followed by 8 bytes containing the value.

ByVal Variant A 16-byte variant structure. This structure contains a 2-byte type (the same asthat returned by the VarType function), followed by 6 bytes of slop (foralignment), followed by 8 bytes containing the value.

ByVal Object For data objects, a 32-bit pointer to a 4-byte unsigned long integer. This valuecan only be used by external routines written specifically for WM Basic.

For OLE automation objects, a 32-bit pointer to an LPDISPATCH handle ispassed.

ByRef Object For data objects, a 32-bit pointer to a 4-byte unsigned long integer thatreferences the object. This value can only be used by external routines writtenspecifically for BasicScript.

For OLE automation objects, a 32-bit pointer to a 4-byte internal ID is passed.This value can only be used by external routines written specifically for WMBasic.

User-defined type A 32-bit pointer to the structure. User-defined types can only be passed byreference.

It is important to remember that structures in WM Basic are packed on 2-byteboundaries, meaning that the individual structure members may not be alignedconsistently with similar structures declared in C.

Arrays A 32-bit pointer to a packed array of elements of the given type. Arrays canonly be passed by reference.

Dialogs Dialogs cannot be passed to external routines.

Only variable-length strings can be passed to external routines; fixed-lengthstrings are automatically converted to variable-length strings.

Page 154: Working Model 2D - User's Manual

150 Working Model Basic User's Manual

WM Basic passes data to external functions consistent with that routine'sprototype as defined by the Declare statement. There is one exception to thisrule: you can override ByRef parameters using the ByVal keyword whenpassing individual parameters. The following example shows a number ofdifferent ways to pass an Integer to an external routine called Foo:

Declare Sub Foo Lib "MyLib" (ByRef i As Integer)

Sub MainDim i As Integeri = 6Foo 6 'Passes a temporary integer (value 6) by referenceFoo i 'Passes variable "i" by referenceFoo (i) 'Passes a temporary integer (value 6) by referenceFoo i + 1 'Passes temporary integer (value 7) by referenceFoo ByVal i 'Passes i by value

End Sub

The above example shows that the only way to override passing a value byreference is to use the ByVal keyword.

Note: Use caution when using the ByVal keyword in this way. The externalroutine Foo expects to receive a pointer to an Integer—a 32-bit value; usingByVal causes WM Basic to pass the Integer by value—a 16-bit value. Passingdata of the wrong size to any external routine will have unpredictable results.

Example Declare Function IsLoaded% Lib "Kernel" Alias "GetModuleHandle" (ByValname$)

Declare Function GetProfileString Lib "Kernel" (ByVal SName$,ByValKName$,_

ByVal Def$,ByVal Ret$,ByVal Size%) As Integer

Sub Main()SName$ = "Intl" 'Win.ini section name.KName$ = "sCountry" 'Win.ini country setting.ret$ = String$(255, 0) 'Initialize return string.

If GetProfileString(SName$,KName$,"",ret$,Len(ret$)) ThenMsgBox "Your country setting is: " & ret$

ElseMsgBox "There is no country setting in your win.ini file."

End If

If IsLoaded("Progman") ThenMsgBox "Progman is loaded."

ElseMsgBox "Progman is not loaded."

End IfEnd Sub

See Also Call (statement), Sub...End Sub (statement), Function...End Function(statement).

Page 155: Working Model 2D - User's Manual

Chapter 2 Declare (statement) 151

Platform(s) All platforms support Declare for forward referencing.

You can also use of Declare for referencing external routines. See below fordetails.

PlatformNotes:

Windows

Under Windows, external routines are contained in DLLs. The librariescontaining the routines are loaded when the routine is called for the first time(i.e., not when the script is loaded). This allows a script to reference externalDLLs that potentially do not exist.

All the Windows API routines are contained in DLLs, such as "user", "kernel",and "gdi". The file extension ".exe" is implied if another extension is not given.

If the libname$ parameter does not contain an explicit path to the DLL, thefollowing search will be performed for the DLL (in this order):

1. The current directory

2. The Windows directory

3. The Windows system directory

4. The directory containing WM Basic

5. All directories listed in the path environment variable

If the first character of aliasname$ is #, then the remainder of the charactersspecify the ordinal number of the routine to be called. For example, thefollowing two statements are equivalent (under Windows, GetCurrentTime isdefined as ordinal 15 in the user.exe module):

Declare Function GetTime Lib "user" Alias "GetCurrentTime" () AsInteger

Declare Function GetTime Lib "user" Alias "#15" () As Integer

Under Windows, the names of external routines declared using the CDeclkeyword are usually preceeded with an underscore character. When WM Basicsearches for your external routine by name, it first attempts to load the routineexactly as specified. If unsuccessful, WM Basic makes a second attempt byprepending an underscore character to the specified name. If both attempts fail,then WM Basic generates a runtime error.

Windows has a limitation that prevents Double, Single, and Date values frombeing returned from routines declared with the CDecl keyword. Routines thatreturn data of these types should be declared Pascal.

Page 156: Working Model 2D - User's Manual

152 Working Model Basic User's Manual

PlatformNotes:

Macintosh

On the Macintosh, external routines are implemented in code resources. If acode resource does not contain an explicit folder name, then WM Basic looks inthe following areas:

1. The current folder

2. The folder containing the application

3. The Extension folder within the System folder

When using the C calling convention (with the CDecl keyword), WM Basicassumes 4-byte integers (the int data type in C). This may be problematic, assome compilers on the Macintosh assume 2-byte integers.

On the Macintosh, the code resource type is specified in aliasname$ as follows:

"[ResourceType]$[ResourceName]"

Parameter Description

ResourceType Any valid four-character name containing the type of the resource. If thisparameter is omitted, then CODE is assumed.

ResourceName Name of the procedure in the code resource. If this parameter is omitted, thenResourceName is assumed to be the same as name.

On the Macintosh, the format for parameters passed to external code resourcesis different than on other platforms. The differences only occur when using thePascal calling convention (i.e., when the CDecl keyword is omitted). Thefollowing list describes these differences:

Singles, doubles, and dates passed by value or by reference are passed as a32-bit pointer to a 10-byte value—an extended type. When passed by value,modification of the extended type does not change the original value in WMBasic.

Variants passed by value are passed as a 32-bit pointer to the internalvariant structure used by WM Basic. Modifications to this internal structuredo not affect the original value of the variable in WM Basic.

Currencies passed by value are passed as a 32-bit pointer to an 8-byteinteger scaled by 10000.

Page 157: Working Model 2D - User's Manual

Chapter 2 DefType (statement) 153

DefType (statement)Syntax DefInt letterrange

DefLng letterrangeDefStr letterrangeDefSng letterrangeDefDbl letterrangeDefCur letterrangeDefObj letterrangeDefVar letterrangeDefBool letterrangeDefDate letterrange

Description Establishes the default type assigned to undeclared or untyped variables.

Comments The DefType statement controls automatic type declaration of variables.Normally, if a variable is encountered that hasn't yet been declared with theDim, Public, or Private statement or does not appear with an explicittype-declaration character, then that variable is declared implicitly as a variant(DefVar A–Z). This can be changed using the DefType statement to specifystarting letter ranges for type other than integer. The letterrange parameter isused to specify starting letters. Thus, any variable that begins with a specifiedcharacter will be declared using the specified Type.

The syntax for letterrange is:

letter [-letter] [,letter [-letter]]...

DefType variable types are superseded by an explicit type declarationusingeither a type-declaration character or the Dim, Public, or Privatestatement.

The DefType statement only affects how WM Basic compiles scripts and hasno effect at runtime.

The DefType statement can only appear outside all Sub and Function declarations.

Page 158: Working Model 2D - User's Manual

154 Working Model Basic User's Manual

The following table describes the data types referenced by the differentvariations of the DefType statement:

Statement Data Type

DefInt IntegerDefLng LongDefStr StringDefSng SingleDefDbl DoubleDefCur CurrencyDefObj ObjectDefVar VariantDefBool BooleanDefDate Date

Example DefStr a-lDefLng m-rDefSng s-uDefDbl v-wDefInt x-z

Const crlf = Chr$(13) + Chr$(10)

Sub Main()a = 100.52m = 100.52s = 100.52v = 100.52x = 100.52msg = "The values are:"msg = msg & "(String) a: " & amsg = msg & "(Long) m: " & mmsg = msg & "(Single) s: " & smsg = msg & "(Double) v: " & vmsg = msg & "(Integer) x: " & xMsgBox msg

End Sub

See Also Currency (data type); Date (data type); Double (data type); Long (data type);Object (data type); Single (data type); String (data type); Variant (datatype); Boolean (data type); Integer (data type).

Platform(s) Windows and Macintosh.

Desktop.ArrangeIcons (method)Syntax Desktop.ArrangeIcons

Description Reorganizes the minimized applications on the desktop.

Page 159: Working Model 2D - User's Manual

Chapter 2 Desktop.Cascade (method) 155

Example Sub Main()Desktop.ArrangeIcons

End Sub

See Also Desktop.Cascade (method); Desktop.Tile (method).

Platform(s) Windows.

Desktop.Cascade (method)Syntax Desktop.Cascade

Description Cascades all nonminimized windows.

Example 'This example cascades all the windows on the desktop. It first'restores any minimized applications so that they are included in the'cascade.

Sub Main()Dim apps$()AppList apps$For i = LBound(apps) To UBound(apps)

AppRestore apps(i)Next iDesktop.Cascade

End Sub

See Also Desktop.Tile (method); Desktop.ArrangeIcons (method).

Platform(s) Windows.

Desktop.SetColors (method)Syntax Desktop.SetColors ControlPanelItemName$

Description Changes the system colors to one of a predefined color set.

Example 'This example allows the user to select any of the available Windows'color schemes.

Sub Main()'Get color schemes from WindowsDim names$()ReadINISection "color schemes",names$,"CONTROL.INI"

SelectAgain: 'Allow user to select color schemeitem = SelectBox("Set Colors","Available Color Sets:",names$)If item <> -1 Then

Desktop.SetColors names$(item)Goto SelectAgain

End IfEnd Sub

See Also Desktop.SetWallpaper (method).

Page 160: Working Model 2D - User's Manual

156 Working Model Basic User's Manual

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the names of the color sets are contained in the control.ini file.

Desktop.SetWallpaper (method)Syntax Desktop.SetWallpaper filename$, isTile

Description Changes the desktop wallpaper to the bitmap specified by filename$.

Comments The wallpaper will be tiled if isTile is True; otherwise, the bitmap will becentered on the desktop.

To remove the wallpaper, set the filename$ parameter to "", as in the followingexample:

Desktop.SetWallpaper "",True

Page 161: Working Model 2D - User's Manual

Chapter 2 Desktop.Snapshot (method) 157

Example 'This example reads a list of .BMP files from the Windows directory'and allows the user to select any of these as wallpaper.

Sub Main()Dim list$()

' Create the prefix for the bitmap filenamesd$ = System.WindowsDirectory$If Right(d$,1) <> "\" Then d$ = d$ & "\"f$ = d$ & "*.BMP"

FileList list$,f$ 'Get list of bitmaps from Windows directory

' Were there any bitmaps?If ArrayDims(list$) = 0 Then

MsgBox "There aren't any bitmaps in the Windows directory"Exit Sub

End If

'Add "(none)"ReDim Preserve list$ (UBound(list$) + 1)list$(UBound(list$)) = "(none)"

SelectAgain: 'Allow user to select itemitem = SelectBox("Set Wallpaper","Available Wallpaper:",list$)

Select Case itemCase -1

EndCase UBound(list$)

Desktop.SetWallPaper "",TrueGoto SelectAgain

Case ElseDesktop.SetWallPaper d$ & list$(item),TrueGoto SelectAgain

End SelectEnd Sub

See Also Desktop.SetColors (method).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the Desktop.SetWallpaper method makes permanentchanges to the wallpaper by writing the new wallpaper information to thewin.ini file.

Desktop.Snapshot (method)Syntax Desktop.Snapshot [spec]

Description Takes a snapshot of a particular section of the screen and saves it to theClipboard.

Page 162: Working Model 2D - User's Manual

158 Working Model Basic User's Manual

Comments The spec parameter is an Integer specifying the screen area to be saved. Itcan be any of the following:

0 Entire screen

1 Client area of the active application

2 Entire window of the active application

3 Client area of the active window

4 Entire window of the active window

Before the snapshot is taken, each application is updated. This ensures that anyapplication that is in the middle of drawing will have a chance to finish beforethe snapshot is taken.

There is a slight delay if the specified window is large.

Example 'This example takes a snapshot of Program Manager and pastes the'resulting bitmap into Windows Paintbrush.

Sub Main()AppActivate "Program Manager" 'Activate Program Manager.Desktop.Snapshot 2 'Place snapshot into Clipboard.id = Shell("pbrush") 'Run Paintbrush.Menu "Edit.Paste" 'Paste snapshot into Paintbrush.

End Sub

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, pictures are placed into the Clipboard in bitmap format.

Desktop.Tile (method)Syntax Desktop.Tile

Description Tiles all nonminimized windows.

Example 'This example tiles all the windows on the desktop. It first'restores any minimized applications so that they are included in the'tile.

Sub Main()Dim apps$()AppList apps$For i = LBound(apps) To UBound(apps)

AppRestore apps(i)Next iDesktop.Tile

End Sub

See Also Desktop.Cascade (method); Desktop.ArrangeIcons (method).

Page 163: Working Model 2D - User's Manual

Chapter 2 Dialog (function) 159

Platform(s) Windows.

Dialog (function)Syntax Dialog(DialogVariable [,[DefaultButton] [,Timeout]])

Description Displays the dialog box associated with DialogVariable, returning anInteger indicating which button was clicked.

Comments The Dialog function returns any of the following values:

-1 The OK button was clicked.

0 The Cancel button was clicked.

>0 A push button was clicked. The returned number represents which button wasclicked based on its order in the dialog box template (1 is the first push button,2 is the second push button, and so on).

The Dialog function accepts the following parameters:

Parameter Description

DialogVariable Name of a variable that has previously been dimensioned as a user dialog box.This is accomplished using the Dim statement:

Dim MyDialog As MyTemplate

All dialog variables are local to the Sub or Function in which they are defined.Private and public dialog variables are not allowed.

Page 164: Working Model 2D - User's Manual

160 Working Model Basic User's Manual

DefaultButton An Integer specifying which button is to act as the default button in the dialogbox. The value of DefaultButton can be any of the following:

_2 This value indicates that there is no defaultbutton.

_1 This value indicates that the OK button, ifpresent, should be used as the default.

0 This value indicates that the Cancel button, ifpresent, should be used as the default.

>0 This value indicates that the Nth buttonshould be used as the default. This number isthe index of a push button within the dialogbox template.

If DefaultButton is not specified, then _1 is used. If the number specified byDefaultButton does not correspond to an existing button, then there will be nodefault button.

The default button appears with a thick border and is selected when the userpresses Enter on a control other than a push button.

Timeout An Integer specifying the number of milliseconds to display the dialog boxbefore 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 returns0.

Example 'This example displays an abort/retry/ignore disk error dialog box.

Sub Main()Begin Dialog DiskErrorTemplate 16,32,152,48,"Disk Error"

Text 8,8,100,8,"The disk drive door is open."PushButton 8,24,40,14,"Abort",.AbortPushButton 56,24,40,14,"Retry",.RetryPushButton 104,24,40,14,"Ignore",.Ignore

End DialogDim DiskError As DiskErrorTemplater% = Dialog(DiskError,3,0)MsgBox "You selected button: " & r%

End Sub

See Also CancelButton (statement); CheckBox (statement); ComboBox (statement);Dialog (statement); DropListBox (statement); GroupBox (statement); ListBox(statement); OKButton (statement); OptionButton (statement); OptionGroup(statement); Picture (statement); PushButton (statement); Text (statement);TextBox (statement); Begin Dialog (statement), PictureButton (statement).

Page 165: Working Model 2D - User's Manual

Chapter 2 Dialog (statement) 161

Platform(s) Windows and Macintosh.

Dialog (statement)Syntax Dialog DialogVariable [,[DefaultButton] [,Timeout]]

Description Same as the Dialog function, except that the Dialog statement does notreturn a value. (See Dialog [function].)

Example 'This example displays an abort/retry/ignore disk error dialog box.

Sub Main()Begin Dialog DiskErrorTemplate 16,32,152,48,"Disk Error"

Text 8,8,100,8,"The disk drive door is open."PushButton 8,24,40,14,"Abort",.AbortPushButton 56,24,40,14,"Retry",.RetryPushButton 104,24,40,14,"Ignore",.Ignore

End DialogDim DiskError As DiskErrorTemplateDialog DiskError,3,0

End Sub

See Also Dialog (function).

Platform(s) Windows and Macintosh.

Dim (statement)Syntax Dim name [(<subscripts>)] [As [New] type] [,name [(<subscripts>)] [As [New]

type]]...

Description Declares a list of local variables and their corresponding types and sizes.

Comments If a type-declaration character is used when specifying name (such as %, @, &, $,or !), the optional [As type] expression is not allowed. For example, thefollowing are allowed:

Dim Temperature As IntegerDim Temperature%

The subscripts parameter allows the declaration of dynamic and fixed arrays.The subscripts parameter uses the following syntax:

[lower to] upper [,[lower to] upper]...

The lower and upper parameters are integers specifying the lower and upperbounds of the array. If lower is not specified, then the lower bound as specifiedby Option Base is used (or 1 if no Option Base statement has beenencountered). WM Basic supports a maximum of 60 array dimensions.

The total size of an array (not counting space for strings) is limited to 64K.

Page 166: Working Model 2D - User's Manual

162 Working Model Basic User's Manual

Dynamic arrays are declared by not specifying any bounds:

Dim a()

The type parameter specifies the type of the data item being declared. It can beany of the following data types: String, Integer, Long, Single,Double, Currency, Object, data object, built-in data type, or any user-defined data type.

A Dim statement within a subroutine or function declares variables local to thatsubroutine or function. If the Dim statement appears outside of any subroutineor function declaration, then that variable has the same scope as variablesdeclared with the Private statement.

Fixed-Length Strings

Fixed-length strings are declared by adding a length to the String type-declaration character:

Dim name As String * length

where length is a literal number specifying the string's length.

Implicit Variable Declaration

If WM Basic encounters a variable that has not been explicitly declared withDim, then the variable will be implicitly declared using the specified type-declaration character (#, %, @, $, or &). If the variable appears without a type-declaration character, then the first letter is matched against any pendingDefType statements, using the specified type if found. If no DefTypestatement has been encountered corresponding to the first letter of the variablename, then Variant is used.

Creating New Objects

The optional New keyword is used to declare a new instance of the specifieddata object. This keyword can only be used with data object types. Furthermore,this keyword cannot be used when declaring arrays.

At runtime, the application or extension that defines that object type is notifiedthat a new object is being defined. The application responds by creating a newphysical object (within the appropriate context) and returning a reference to thatobject, which is immediately assigned to the variable being declared.

When that variable goes out of scope (i.e., the Sub or Function procedure inwhich the variable is declared ends), the application is notified. The applicationthen performs some appropriate action, such as destroying the physical object.

Page 167: Working Model 2D - User's Manual

Chapter 2 Dim (statement) 163

Initial Values

All declared variables are given initial values, as described in the followingtable:

Data Type Initial Value

Integer 0

Long 0

Double 0.0

Single 0.0

Date December 31, 1899 00:00:00

Currency 0.0

Boolean False

Object Nothing

Variant Empty

String "" (zero-length string)

User-defined type Each element of the structure is given an initial value, as described above.

Arrays Each element of the array is given an initial value, as described above.

Naming Conventions

Variable names must follow these naming rules:

1. Must start with a letter.

2. May contain letters, digits, and the underscore character (_); punctuation isnot allowed. The exclamation point (!) can appear within the name as longas it is not the last character, in which case it is interpreted as a type-declaration character.

The last character of the name can be any of the following type-declarationcharacters: #, @, %, !, &, and $.

3. Must not exceed 80 characters in length.

4. Cannot be a reserved word.

Page 168: Working Model 2D - User's Manual

164 Working Model Basic User's Manual

Examples 'The following examples use the Dim statement to declare various'variable types.

Sub Main() Dim i As Integer

Dim l& 'longDim s As SingleDim d# 'doubleDim c$ 'stringDim MyArray(10) As Integer '10 element integer arrayDim MyStrings$(2,10) '2-10 element string arraysDim Filenames$(5 to 10) '6 element string arrayDim Values(1 to 10, 100 to 200) '111 element variant array

End Sub

See Also Redim (statement); Public (statement); Private (statement); Option Base(statement).

Platform(s) Windows and Macintosh.

Dir, Dir$ (functions)Syntax Dir$[(filespec$ [,attributes])]

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. Iffilespec$ is not specified, then the next file matching the initial filespec$ isreturned.

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 filespecification. If this parameter is omitted, then the next file matching the initialfile 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 describedbelow. If omitted, then only the normal, read-only, and archive files arereturned.

An error is generated if Dir$ is called without first calling it with a validfilespec$.

If there is no matching filespec$, then a zero-length string is returned.

Page 169: Working Model 2D - User's Manual

Chapter 2 Dir, Dir$ (functions) 165

Wildcards

The filespec$ argument can include wildcards, such as * and ?. The * charactermatches any sequence of zero or more characters, whereas the ? charactermatches any single character. Multiple *'s and ?'s can appear within theexpression to form complete searching patterns. The following table showssome examples:

This pattern Matches these files Doesn't match these files

*S*.TXT SAMPLE.TXT SAMPLEGOOSE.TXT SAMPLE.DATSAMS.TXT

C*T.TXT CAT.TXT CAP.TXTACATS.TXT

C*T CAT CAT.DOCCAP.TXT

C?T CAT CAT.TXTCUT CAPIT

CT

* (All files)

Attributes

You can control which files are included in the search by specifying theoptional attributes parameter. The Dir, Dir$ functions always return allnormal, read-only, and archive files (ebNormal Or ebReadOnly OrebArchive). To include additional files, you can specify any combination ofthe following attributes (combined with the Or operator):

Constant Value Includes

ebNormal 0 Normal, Read-only, and archive filesebHidden 2 Hidden filesebSystem 4 System filesebVolume 8 Volume labelebDirectory 16 DOS subdirectories

Page 170: Working Model 2D - User's Manual

166 Working Model Basic User's Manual

Example 'This example dimensions a null array and fills it with directory'entries. The result is displayed in a dialog box.

Const crlf = Chr$(13) + Chr$(10)

Sub Main()Dim a$(10)a(1) = Dir$("*.*")i% = 1While (a(i%) <> "") And (i% < 10)

i% = i% + 1a(i%) = Dir$

WendMsgBox a(1) & crlf & a(2) & crlf & a(3) & crlf & a(4)

End Sub

See Also ChDir (statement); ChDrive (statement); CurDir, CurDir$ (functions); MkDir(statement); RmDir (statement); FileList (statement).

Platform(s) Windows and Macintosh.

PlatformNotes:

Macintosh

The Macintosh does not support wildcard characters such as * and ?. These arevalid filename characters. Instead of wildcards, the Macintosh uses the MacIDfunction to specify a collection of files of the same type. The syntax for thisfunction is:

Dir$(filespec$,MacID(text$))

The text$ parameter is a four-character string containing a file type, a resourcetype, an application signature, or an Apple event. A runtime error occurs if theMacID function is used on platforms other than the Macintosh.

When the MacID function is used, the filespec$ parameter specifies thedirectory in which to search for files of the indicated type.

PlatformNotes:

Windows

Notice that WM Basic's filename matching is different than DOS's. The pattern"*.*" under DOS matches all files. With WM Basic, this pattern matches onlyfiles that have file extensions.

DiskDrives (statement)Syntax DiskDrives array()

Description Fills the specified String or Variant array with a list of valid drive letters.

Page 171: Working Model 2D - User's Manual

Chapter 2 DiskFree (function) 167

Comments The array() parameter specifies either a zero- or a one-dimensioned array ofstrings or variants. The array can be either dynamic or fixed.

If array() is dynamic, then it will be redimensioned to exactly hold the newnumber of elements. If there are no elements, then the array will beredimensioned to contain no dimensions. You can use the LBound, UBound, andArrayDims functions to determine the number and size of the new array'sdimensions.

If the array is fixed, each array element is first erased, then the new elementsare 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 Stringarrays) or Empty (for Variant arrays). A runtime error results if the array is toosmall 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

See Also ChDrive (statement); DiskFree (function).

Platform(s) Windows.

DiskFree (function)Syntax DiskFree&([drive$])

Description Returns a Long containing the free space (in bytes) available on the specifieddrive.

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 (statement); DiskDrives (statement).

Platform(s) Windows and Macintosh.

Page 172: Working Model 2D - User's Manual

168 Working Model Basic User's Manual

PlatformNotes:

On systems that do not support drive letters, the drive$ parameter specifies thename of the path from which to retrieve the free disk space.

DlgControlId (function)Syntax DlgControlId(ControlName$)

Description Returns an Integer containing the index of the specified control as it appearsin the dialog box template.

Comments The first control in the dialog box template is at index 0, the second is at index1, and so on.

The ControlName$ parameter contains the name of the .Identifier parameterassociated with that control in the dialog box template.

The WM Basic statements and functions that dynamically manipulate dialogbox controls identify individual controls using either the .Identifier name of thecontrol or the control's index. Using the index to refer to a control is slightlyfaster but results in code that is more difficult to maintain.

Example Function DlgProc(ControlName$,Action%,SuppValue%) As Integer'If a control is clicked, disable the next three controls.If Action% = 2 Then

'Enable the next three controls.start% = DlgControlId(ControlName$)

For i = start% + 1 To start% + 3DlgEnable i,True

Next iDlgProc = 1 'Don't close the dialog box.

End IfEnd Function

See Also DlgEnable (function); DlgEnable (statement); DlgFocus (function); DlgFocus(statement); DlgListBoxArray (function); DlgListBoxArray (statement);DlgSetPicture (statement); DlgText (statement); DlgText (function);DlgValue (function); DlgValue (statement); DlgVisible (statement);DlgVisible (function).

Platform(s) Windows and Macintosh.

DlgEnable (function)Syntax DlgEnable(ControlName$ | ControlIndex)

Description Returns True if the specified control is enabled; returns False otherwise.

Page 173: Working Model 2D - User's Manual

Chapter 2 DlgEnable (statement) 169

Comments Disabled controls are dimmed and cannot receive keyboard or mouse input.

The ControlName$ parameter contains the name of the .Identifier parameterassociated with a control in the dialog box template. A case-insensitivecomparison is used to locate the specific control within the template.Alternatively, by specifying the ControlIndex parameter, a control can bereferred to using its index in the dialog box template (0 is the first control in thetemplate, 1 is the second, and so on).

You cannot disable the control with the focus.

Example If DlgEnable("SaveOptions") ThenMsgBox "The Save Options are enabled."

End IfIf DlgEnable(10) And DlgVisible(12) Then code = 1 Else code = 2

See Also DlgControl (statement); DlgEnable (statement); DlgFocus (function);DlgFocus (statement); DlgListBoxArray (function); DlgListBoxArray(statement); DlgSetPicture (statement); DlgText (statement); DlgText(function); DlgValue (function); DlgValue (statement); DlgVisible(statement); DlgVisible (function).

Platform(s) Windows and Macintosh.

DlgEnable (statement)Syntax DlgEnable {ControlName$ | ControlIndex} [,isOn]

Description Enables or disables the specified control.

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. Itcan 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 individualoption button) or as a group (by specifying the name of the option group).

The ControlName$ parameter contains the name of the .Identifier parameterassociated with a control in the dialog box template. Alternatively, byspecifying the ControlIndex parameter, a control can be referred to using itsindex in the dialog box template (0 is the first control in the template, 1 is thesecond, and so on).

Page 174: Working Model 2D - User's Manual

170 Working Model Basic User's Manual

Example DlgEnable "SaveOptions", False 'Disable the Save Options control.

DlgEnable "EditingOptions" 'Toggle a group of option buttons.

For i = 0 To 5DlgEnable i,True 'Enable six controls.

Next i

See Also DlgControl (statement); DlgEnable (function); DlgFocus (function);DlgFocus (statement); DlgListBoxArray (function); DlgListBoxArray(statement); DlgSetPicture (statement); DlgText (statement); DlgText(function); DlgValue (function); DlgValue (statement); DlgVisible(statement); DlgVisible (function).

Platform(s) Windows and Macintosh.

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 controlin 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).

If DlgFocus$ = "Files" Then 'Does it have the focus?DlgFocus "OK" 'Change the focus to another control.

End IfDlgEnable "Files", False 'Now we can disable the control.

See Also DlgControl (statement); DlgEnable (function); DlgEnable (statement);DlgFocus (statement); DlgListBoxArray (function); DlgListBoxArray(statement); DlgSetPicture (statement); DlgText (statement); DlgText(function); DlgValue (function); DlgValue (statement); DlgVisible(statement); DlgVisible (function).

Platform(s) Windows and Macintosh.

DlgFocus (statement)Syntax DlgFocus ControlName$ | ControlIndex

Description Sets focus to the specified control.

Page 175: Working Model 2D - User's Manual

Chapter 2 DlgListBoxArray (function) 171

Comments A runtime error results if the specified control is hidden, disabled, ornonexistent.

The ControlName$ parameter contains the name of the .Identifier parameterassociated with a control in the dialog box template. A case-insensitivecomparison is used to locate the specific control within the template.Alternatively, by specifying the ControlIndex parameter, a control can bereferred to using its index in the dialog box template (0 is the first control in thetemplate, 1 is the second, and so on).

Example 'This code fragment makes sure that the control being disabled does'not currently have the focus (otherwise, a runtime error would occur).

If DlgFocus$ = "Files" Then 'Does it have the focus?DlgFocus "OK" 'Change the focus to another control.

End IfDlgEnable "Files", False 'Now we can disable the control.

See Also DlgControl (statement); DlgEnable (function); DlgEnable (statement);DlgFocus (function); DlgListBoxArray (function); DlgListBoxArray(statement); DlgSetPicture (statement); DlgText (statement); DlgText(function); DlgValue (function); DlgValue (statement); DlgVisible(statement); DlgVisible (function).

Platform(s) Windows and Macintosh.

DlgListBoxArray (function)Syntax DlgListBoxArray({ControlName$ | ControlIndex}, ArrayVariable)

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 actuallyset into the control.

Comments The ControlName$ parameter contains the name of the .Identifier parameterassociated with a control in the dialog box template. A case-insensitivecomparison is used to locate the specific control within the template.Alternatively, by specifying the ControlIndex parameter, a control can bereferred to using its index in the dialog box template (0 is the first control in thetemplate, 1 is the second, and so on).

The ArrayVariable parameter specifies a single-dimensioned array used toinitialize the elements of the control. If this array has no dimensions, then thecontrol will be initialized with no elements. A runtime error results if thespecified array contains more than one dimension. ArrayVariable can specifyan array of any fundamental data type (structures are not allowed). Null andEmpty values are treated as zero-length strings.

Page 176: Working Model 2D - User's Manual

172 Working Model Basic User's Manual

Example 'This dialog function refills an array with files.

Function DlgProc(ControlName$,Action%,SuppValue%) As IntegerIf Action% = 2 And ControlName$ = "Files" Then

Dim NewFiles$() 'Create a new dynamic array.FileList NewFiles$,"*.txt" 'Fill the array with files.r% = DlgListBoxArray "Files",NewFiles$ 'Set items in the list

box.DlgValue "Files",0 'Set the selection to the first item.DlgProc = 1 'Don't close the dialog box.

End IfMsgBox r% & " items were added to the list box."

End Function

See Also DlgControl (statement); DlgEnable (function); DlgEnable (statement);DlgFocus (function); DlgFocus (statement); DlgListBoxArray (statement);DlgSetPicture (statement); DlgText (statement); DlgText (function);DlgValue (function); DlgValue (statement); DlgVisible (statement);DlgVisible (function).

Platform(s) Windows and Macintosh.

DlgListBoxArray (statement)Syntax DlgListBoxArray {ControlName$ | ControlIndex}, ArrayVariable

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 parameterassociated with a control in the dialog box template. A case-insensitivecomparison is used to locate the specific control within the template.Alternatively, by specifying the ControlIndex parameter, a control can bereferred to using its index in the dialog box template (0 is the first control in thetemplate, 1 is the second, and so on).

The ArrayVariable parameter specifies a single-dimensioned array used toinitialize the elements of the control. If this array has no dimensions, then thecontrol will be initialized with no elements. A runtime error results if thespecified array contains more than one dimension. ArrayVariable can specifyan array of any fundamental data type (structures are not allowed). Null andEmpty values are treated as zero-length strings.

Page 177: Working Model 2D - User's Manual

Chapter 2 DlgProc (function) 173

Example 'This dialog function refills an array with files.

Function DlgProc(ControlName$,Action%,SuppValue%) As IntegerIf Action% = 2 And ControlName$ = "Files" Then

Dim NewFiles$() 'Create a new dynamicarray.

FileList NewFiles$,"*.txt" 'Fill the array with files.DlgListBoxArray "Files",NewFiles$ 'Set items in the list box.DlgValue "Files",0 'Set the selection to the

first item.End If

End Function

See Also DlgControl (statement); DlgEnable (function); DlgEnable (statement);DlgFocus (function); DlgFocus (statement); DlgListBoxArray (function);DlgSetPicture (statement); DlgText (statement); DlgText (function);DlgValue (function); DlgValue (statement); DlgVisible (statement);DlgVisible (function).

Platform(s) Windows and Macintosh.

DlgProc (function)Syntax Function DlgProc(ControlName$, Action, SuppValue) As Integer

Description Describes the syntax, parameters, and return value for dialog functions.

Comments Dialog functions are called by WM Basic during the processing of a customdialog box. The name of a dialog function (DlgProc) appears in the BeginDialog 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, thisparameter is not used.

When WM Basic 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, WM Basic calls the dialog function, passing it theaction, the name of the control on which the action occurred, and any otherrelevent information associated with the action.

Page 178: Working Model 2D - User's Manual

174 Working Model Basic User's Manual

The following table describes the different actions sent to dialog functions:

Action Description

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. Whenthis action is sent, ControlName$ contains a zero-length string, and SuppValueis 0.

The return value from the dialog function is ignored in this case.

Before Showing the Dialog Box

After action 1 is sent, WM Basic performs additional processing before thedialog box is shown. Specifically, it cycles though the dialog box controlschecking for visible picture or picture button controls. For each visible pictureor picture button control, WM Basic attempts to load the associated picture.

In addition to checking picture or picture button controls, WM Basic willautomatically hide any control outside the confines of the visible portion of thedialog box. This prevents the user from tabbing to controls that cannot be seen.However, it does not prevent you from showing these controls with theDlgVisible statement in the dialog function.

2 This action is sent when:

A button is clicked, such as OK, Cancel, or a pushbutton. In this case, ControlName$ contains the name ofthe button. SuppValue contains 1 if an OK button wasclicked and 2 if a Cancel button was clicked; SuppValueis undefined otherwise.

If the dialog function returns 0 in response to this action,then the dialog box will be closed. Any other valuecauses WM Basic to continue dialog processing.

A check box's state has been modified. In this case,ControlName$ contains the name of the check box, andSuppValue contains the new state of the check box (1 ifon, 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 buttonwithin the option button group (0-based).

The current selection is changed in a list box, drop listbox, or combo box. In this case, ControlName$ containsthe name of the list box, combo box, or drop list box, andSuppValue contains the index of the new item (0 is thefirst item, 1 is the second, and so on).

Page 179: Working Model 2D - User's Manual

Chapter 2 DlgProc (function) 175

3 This action is sent when the content of a text box or combo box has beenchanged. This action is only sent when the control loses focus. When this actionis sent, ControlName$ contains the name of the text box or combo box, andSuppValue 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, andSuppValue 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 dialogfunction returns 1 in response to this action, then the idle action will continue tobe sent. If the dialog function returns 0, then WM Basic will not send anyadditional idle actions.

When the idle action is sent, ControlName$ contains a zero-length string, andSuppValue contains the number of times the idle action has been sent so far.

6 This action is sent when the dialog box is moved. The ControlName$ parametercontains 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 functionof 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 WM Basicstatements and functions. These statements allow you to manipulate the dialogbox controls dynamically.

DlgVisible DlgText$ DlgTextDlgSetPicture DlgListBoxArray DlgFocusDlgEnable DlgControlId

For compatibility with previous versions of WM Basic, the dialog function canoptionally be declared to return a Variant. When returning a variable, WMBasic will attempt to convert the variant to an Integer. If the returned variantcannot be converted to an Integer, then 0 is assumed to be returned from thedialog function.

Page 180: Working Model 2D - User's Manual

176 Working Model Basic User's Manual

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 IfEnd Function

Sub Main()Begin Dialog SampleDialogTemplate

34,39,106,45,"Sample",.SampleDlgProcOKButton 4,4,40,14CancelButton 4,24,40,14CheckBox 56,8,38,8,"Printing",.PrintingOptionGroup .PrintOptions

OptionButton 56,20,51,8,"Landscape",.LandscapeOptionButton 56,32,40,8,"Portrait",.Portrait

End DialogDim SampleDialog As SampleDialogTemplateSampleDialog.Printing = 1r% = Dialog(SampleDialog)

End Sub

See Also Begin Dialog (statement).

Platform(s) Windows and Macintosh.

DlgSetPicture (statement)Syntax DlgSetPicture {ControlName$ | ControlIndex},PictureName$,PictureType

Description Changes the content of the specified picture or picture button control.

Page 181: Working Model 2D - User's Manual

Chapter 2 DlgSetPicture (statement) 177

Comments The DlgSetPicture statement accepts the following parameters:

Parameter Description

ControlName$ String containing the name of the .Identifier parameter associated with acontrol in the dialog box template. A case-insensitive comparison is used tolocate the specified control within the template. Alternatively, by specifying theControlIndex parameter, a control can be referred to using its index in thedialog box template (0 is the first control in the template, 1 is the second, and soon).

PictureName$ String containing the name of the picture. If PictureType is 0, then thisparameter specifies the name of the file containing the image. If PictureType is10, then PictureName$ specifies the name of the image within the resource ofthe picture library.

If PictureName$ is empty, then the current picture associated with the specifiedcontrol will be deleted. Thus, a technique for conserving memory and resourceswould involve setting the picture to empty before hiding a picture control.

PictureType Integer specifying the source for the image. The following sources aresupported:

0 The image is contained in a file on disk.

10 The image is contained in the picture libraryspecified by the Begin Dialog statement.When this type is used, the PictureName$parameter must be specified with the BeginDialog statement.

Examples DlgSetPicture "Picture1","\windows\checks.bmp",0 'Set picture from afile.

DlgSetPicture 27,"FaxReport",10 'Set control 10'simage

'from a library.

See Also DlgControl (statement); DlgEnable (function); DlgEnable (statement);DlgFocus (function); DlgFocus (statement); DlgListBoxArray (function);DlgListBoxArray (statement); DlgText (statement); DlgText (function);DlgValue (function); DlgValue (statement); DlgVisible (statement);DlgVisible (function), Picture (statement), PictureButton (statement).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Under Windows, picture controls can contain either bitmaps or WMFs(Windows metafiles). When extracting images from a picture library, WMBasic assumes that the resource type for metafiles is 256.

Picture libraries are implemented as DLLs on the Windows.

Page 182: Working Model 2D - User's Manual

178 Working Model Basic User's Manual

PlatformNotes:

Macintosh

Picture controls on the Macintosh can contain only PICT images. These arecontained in files of type PICT.

Picture libraries on the Macintosh are files with collections of named PICTresources. The PictureName$ parameter corresponds to the name of one theresources as it appears within the file.

DlgText (statement)Syntax DlgText {ControlName$ | ControlIndex}, NewText$

Description Changes the text content of the specified control.

Comments The effect of this statement depends on the type of the specified control:

Control Type Effect of DlgText

Picture Runtime error.

Option group Runtime error.

Drop list box Sets the current selection to the item matching NewText$. If an exact matchcannot be found, the DlgText statement searches from the first item lookingfor an item that starts with NewText$. If no match is found, then the selection isremoved.

OK button Sets the label of the control to NewText$.

Cancel button Sets the label of the control to NewText$.

Push button Sets the label of the control to NewText$.

List box Sets the current selection to the item matching NewText$. If an exact matchcannot be found, the DlgText statement searches from the first item lookingfor an item that starts with NewText$. If no match is found, then the selection isremoved.

Combo box Sets the content of the edit field of the combo box to NewText$.

Text Sets the label of the control to NewText$.

Text box Sets the content of the text box to NewText$.

Group box Sets the label of the control to NewText$.

Option button Sets the label of the control to NewText$.

The ControlName$ parameter contains the name of the .Identifier parameterassociated with a control in the dialog box template. A case-insensitivecomparison is used to locate the specific control within the template.Alternatively, by specifying the ControlIndex parameter, a control can bereferred to using its index in the dialog box template (0 is the first control in thetemplate, 1 is the second, and so on).

Page 183: Working Model 2D - User's Manual

Chapter 2 DlgText$ (function) 179

Example DlgText "GroupBox1","Save Options" 'Change text of group box 1.

If DlgText$(9) = "Save Options" ThenDlgText 9,"Editing Options" 'Change text to "Editing

Options".End If

See Also DlgControl (statement); DlgEnable (function); DlgEnable (statement);DlgFocus (function); DlgFocus (statement); DlgListBoxArray (function);DlgListBoxArray (statement); DlgSetPicture (statement); DlgText(function); DlgValue (function); DlgValue (statement); DlgVisible(statement); DlgVisible (function).

Platform(s) Windows and Macintosh.

DlgText$ (function)Syntax DlgText$(ControlName$ | ControlIndex)

Description Returns the text content of the specified control.

Comments The text returned depends on the type of the specified control:

Control Type Value Returned by DlgText$

Picture No value is returned. A runtime error occurs.

Option group No value is returned. A runtime error occurs.

Drop list box Returns the currently selected item. A zero-length string is returned if no item iscurrently selected.

OK button Returns the label of the control.

Cancel button Returns the label of the control.

Push button Returns the label of the control.

List box Returns the currently selected item. A zero-length string is returned if no item iscurrently selected.

Combo box Returns the content of the edit field portion of the combo box.

Text Returns the label of the control.

Text box Returns the content of the control.

Group box Returns the label of the control.

Option button Returns the label of the control.

Page 184: Working Model 2D - User's Manual

180 Working Model Basic User's Manual

The ControlName$ parameter contains the name of the .Identifier parameterassociated with a control in the dialog box template. A case-insensitivecomparison is used to locate the specific control within the template.Alternatively, by specifying the ControlIndex parameter, a control can bereferred to using its index in the dialog box template (0 is the first control in thetemplate, 1 is the second, and so on).

Example MsgBox DlgText$(10) 'Display the text in the tenth control.

If DlgText$("SaveOptions") = "EditingOptions" ThenMsgBox "You are currently viewing the editing options."

End If

See Also DlgControl (statement); DlgEnable (function); DlgEnable (statement);DlgFocus (function); DlgFocus (statement); DlgListBoxArray (function);DlgListBoxArray (statement); DlgSetPicture (statement); DlgText(statement); DlgValue (function); DlgValue (statement); DlgVisible(statement); DlgVisible (function).

Platform(s) Windows and Macintosh.

DlgValue (function)Syntax DlgValue(ControlName$ | ControlIndex)

Description Returns an Integer indicating the value of the specified control.

Comments The value of any given control depends on its type, according to the followingtable:

Control Type DlgValue Returns

Option group The index of the selected option button within the group (0 is the first optionbutton, 1 is the second, and so on).

List box The index of the selected item.

Drop list box The index of the selected item.

Check box 1 if the check box is checked; 0 otherwise.

A runtime error is generated if DlgValue is used with controls other thanthose listed in the above table.

The ControlName$ parameter contains the name of the .Identifier parameterassociated with a control in the dialog box template. Alternatively, byspecifying the ControlIndex parameter, a control can be referred to using itsindex in the dialog box template (0 is the first control in the template, 1 is thesecond, and so on).

ExampleSee DlgValue (statement).

Page 185: Working Model 2D - User's Manual

Chapter 2 DlgValue (statement) 181

See Also DlgControl (statement); DlgEnable (function); DlgEnable (statement);DlgFocus (function); DlgFocus (statement); DlgListBoxArray (function);DlgListBoxArray (statement); DlgSetPicture (statement); DlgText(statement); DlgText (function); DlgValue (statement); DlgVisible(statement); DlgVisible (function).

Platform(s) Windows and Macintosh.

DlgValue (statement)Syntax DlgValue {ControlName$ | ControlIndex},Value

Description Changes the value of the given control.

Comments The value of any given control is an Integer and depends on its type,according to the following table:

Control Type Description of Value

Option group The index of the new selected option button within the group (0 is the firstoption button, 1 is the second, and so on).

List box The index of the new selected item.

Drop list box The index of the new selected item.

Check box 1 if the check box is to be checked; 0 if the check is to be removed.

A runtime error is generated if DlgValue is used with controls other thanthose listed in the above table.

The ControlName$ parameter contains the name of the .Identifier parameterassociated with a control in the dialog box template. A case-insensitivecomparison is used to locate the specific control within the template.Alternatively, by specifying the ControlIndex parameter, a control can bereferred to using its index in the dialog box template (0 is the first control in thetemplate, 1 is the second, and so on).

Example 'This code fragment toggles the value of a check box.

If DlgValue("MyCheckBox") = 1 ThenDlgValue "MyCheckBox",0

ElseDlgValue "MyCheckBox",1

End If

See Also DlgControl (statement); DlgEnable (function); DlgEnable (statement);DlgFocus (function); DlgFocus (statement); DlgListBoxArray (function);DlgListBoxArray (statement); DlgSetPicture (statement); DlgText(statement); DlgText (function); DlgValue (function); DlgVisible(statement); DlgVisible (function).

Platform(s) Windows and Macintosh.

Page 186: Working Model 2D - User's Manual

182 Working Model Basic User's Manual

DlgVisible (function)Syntax DlgVisible(ControlName$ | ControlIndex)

Description Returns True if the specified control is visible; returns False otherwise.

The ControlName$ parameter contains the name of the .Identifier parameterassociated with a control in the dialog box template. Alternatively, byspecifying the ControlIndex parameter, a control can be referred to using itsindex in the template (0 is the first control in the template, 1 is the second, andso on).

A runtime error is generated if DlgVisible is called with no user dialog isactive.

Example If DlgVisible("Portrait") Then Beep

If DlgVisible(10) And DlgVisible(12) ThenMsgBox "The 10th and 12th controls are visible."

End If

See Also DlgControl (statement); DlgEnable (function); DlgEnable (statement);DlgFocus (function); DlgFocus (statement); DlgListBoxArray (function);DlgListBoxArray (statement); DlgSetPicture (statement); DlgText(statement); DlgText (function); DlgValue (function); DlgValue (statement);DlgVisible (function).

Platform(s) Windows and Macintosh.

DlgVisible (statement)Syntax DlgVisible {ControlName$ | ControlIndex} [,isOn]

Description Hides or shows the specified control.

Comments Hidden controls cannot be seen in the dialog box and cannot receive the focususing Tab.

The isOn parameter is an Integer specifying the new state of the control. Itcan be any of the following values:

1 The control is shown.

0 The control is hidden.

Omitted Toggles the visibility of the control.

Option buttons can be manipulated individually (by specifying an individualoption button) or as a group (by specifying the name of the option group).

Page 187: Working Model 2D - User's Manual

Chapter 2 DlgVisible (statement) 183

The ControlName$ parameter contains the name of the .Identifier parameterassociated with a control in the dialog box template. A case-insensitivecomparison is used to locate the specific control within the template.Alternatively, by specifying the ControlIndex parameter, a control can bereferred to using its index in the dialog box template (0 is the first control in thetemplate, 1 is the second, and so on).

Picture Caching

When the dialog box is first created and before it is shown, WM Basic calls thedialog function with action set to 1. At this time, no pictures have been loadedinto the picture controls contained in the dialog box template. After controlreturns from the dialog function and before the dialog box is shown, WM Basicwill load the pictures of all visible picture controls. Thus, it is possible for thedialog function to hide certain picture controls, which prevents the associatedpictures from being loaded and causes the dialog box to load faster. When apicture control is made visible for the first time, the associated picture will thenbe loaded.

Page 188: Working Model 2D - User's Manual

184 Working Model Basic User's Manual

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, FalseNext iFor i = start% To finish% 'Enable only the right ones.

DlgVisible i, TrueNext 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 IfIf Action% = 2 And ControlName$ = "SaveOptions" Then

EnableGroup 6, 8 'Enable the save options.DlgProc = 1 'Don't close the dialog box.

End IfIf Action% = 2 And ControlName$ = "EditingOptions" Then

EnableGroup 9, 13 'Enable the editing options.DlgProc = 1 'Don't close the dialog box.

End IfEnd 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",.SaveOptionsOptionButton 8, 20, 65, 8, "Editing Options",.EditingOptions

OKButton 116, 7, 44, 14CancelButton 116, 24, 44, 14

'Save options (controls 6-8)CheckBox 20, 56, 88, 8, "Always create backup",.CheckBox1CheckBox 20, 68, 65, 8, "Automatic save",.CheckBox2CheckBox 20, 80, 70, 8, "Allow overwriting",.CheckBox3

'Editing options (controls 9-13)CheckBox 20, 56, 65, 8, "Overtype mode",.OvertypeModeCheckBox 20, 68, 69, 8, "Uppercase only",.UppercaseOnlyCheckBox 20, 80, 105, 8, "Automatically check

syntax",.AutoCheckSyntaxCheckBox 20, 92, 73, 8, "Full line selection",.FullLineSelectionCheckBox 20, 104, 102, 8, "Typing replaces

selection",.TypingReplacesTextEnd Dialog

Dim OptionsDialog As OptionsTemplateDialog OptionsDialog

End Sub

Page 189: Working Model 2D - User's Manual

Chapter 2 Do...Loop (statement) 185

See Also DlgControl (statement); DlgEnable (function); DlgEnable (statement);DlgFocus (function); DlgFocus (statement); DlgListBoxArray (function);DlgListBoxArray (statement); DlgSetPicture (statement); DlgText(statement); DlgText (function); DlgValue (function); DlgValue (statement);DlgVisible (statement).

Platform(s) Windows and Macintosh.

Do...Loop (statement)Syntax 1 Do {While | Until} condition statements Loop

Syntax 2 Dostatements

Loop {While | Until} condition

Syntax 3 Dostatements

Loop

Description Repeats a block of WM Basic statements while a condition is True or until acondition is True.

Comments If the {While | Until} conditional clause is not specified, then the looprepeats the statements forever (or until WM Basic encounters an Exit Dostatement).

The condition parameter specifies any Boolean expression.

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% = -1Do

i% = i% + 1If 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)

Page 190: Working Model 2D - User's Manual

186 Working Model Basic User's Manual

'This second example uses the Do While...Loop, which checks the'condition and then repeats if the condition is True.

Dim a$(100)i% = 0a(i%) = Dir$("*")Do While a(i%) <> "" And i% <= 99

i% = i% + 1a(i%) = Dir$

Loopr% = SelectBox(i% & " files found",,a)

'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% = 0a(i%) = Dir$("*")Do Until a(i%) = "" Or i% = 100

i% = i% + 1a(i%) = Dir$

Loopr% = SelectBox(i% & " files found",,a)

'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% = -1Do

i% = i% + 1If 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 (statement); While ...WEnd (statement).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Due to errors in program logic, you can inadvertently create infinite loops inyour code. Under Windows, you can break out of infinite loops usingCtrl+Break.

PlatformNotes:

Macintosh

Due to errors in program logic, you can inadvertently create infinite loops inyour code. On the Macintosh, you can break out of infinite loops usingCommand+Period.

Page 191: Working Model 2D - User's Manual

Chapter 2 DoEvents (function) 187

DoEvents (function)Syntax DoEvents[()]

Description Yields control to other applications, returning an Integer 0.

Comments This statement yields control to the operating system, allowing otherapplications to process mouse, keyboard, and other messages.

If a SendKeys statement is active, this statement waits until all the keys in thequeue have been processed.

Example See DoEvents (statement).

See Also DoEvents (statement).

Platform(s) Windows and Macintosh.

DoEvents (statement)Syntax DoEvents

Description Yields control to other applications.

Comments This statement yields control to the operating system, allowing otherapplications to process mouse, keyboard, and other messages.

If a SendKeys statement is active, this statement waits until all the keys in thequeue have been processed.

Examples 'This first example shows a script that takes a long time and hogs the'system. The subroutine explicitly yields to allow other applications'to execute.

Sub Main()Open "test.txt" For Output As #1For i = 1 To 10000

Print #1,"This is a test of the system and stuff."DoEvents

Next iClose #1

End Sub

'In this second example, the DoEvents statement is used to wait until'the queue has been completely flushed.

Sub Main()AppActivate "Notepad" 'Activate Notepad.SendKeys "This is a test.",False 'Send some keys.DoEvents 'Wait for the keys to play back.

End Sub

See Also DoEvents (function).

Platform(s) Windows and Macintosh.

Page 192: Working Model 2D - User's Manual

188 Working Model Basic User's Manual

DoKeys (statement)Syntax DoKeys KeyString$ [,time]

Description Simulates the pressing of the specified keys.

Comments The DoKeys statement accepts the following parameters:

Parameter Description

KeyString$ String containing the keys to be sent. The format for KeyString$ is describedunder the SendKeys statement.

time Integer specifying the number of milliseconds devoted for the output of theentire KeyString$ parameter. It must be within the following range:

0 <= time <= 32767

For example, if time is 5000 (5 seconds) and the KeyString$ parameter containsten keys, then a key will be output every 1/2 second. If unspecified (or 0), thekeys will play back at full speed.

Example 'This code fragment plays back the time and date into Notepad.

Const crlf = Chr$(13) + Chr$(10)

Sub Main()id = Shell("Notepad",4) 'Run Notepad.AppActivate "Notepad"t$ = time$d$ = date$DoKeys "The time is: " & t$ & "." & crlfDoKeys "The date is: " & d$ & "."

End Sub

See Also SendKeys (statement); QueKeys (statement); QueKeyDn (statement); QueKeyUp(statement).

Platform(s) Windows.

PlatformNotes:

Windows

This statement uses the Windows journalizing mechanism to play keystrokesinto the Windows environment.

Double (data type)Syntax Double

Description A data type used to declare variables capable of holding real numbers with 15–16 digits of precision.

Page 193: Working Model 2D - User's Manual

Chapter 2 DropListBox (statement) 189

Comments Double variables are used to hold numbers within the following ranges:

Sign Range

Negative –1.797693134862315E308 <= double <=-4.94066E-324

Positive 4.94066E-324 <= double <= 1.797693134862315E308

The type-declaration character for Double is #.

Storage

Internally, doubles are 8-byte (64-bit) IEEE values. Thus, when appearingwithin a structure, doubles require 8 bytes of storage. When used with binary orrandom files, 8 bytes of storage are required.

Each Double consists of the following

A 1-bit sign

An 11-bit exponent

A 53-bit significand (mantissa)

See Also Currency (data type); Date (data type); Integer (data type); Long (data type);Object (data type); Single (data type); String (data type); Variant (datatype); Boolean (data type); DefType (statement); CDbl (function).

Platform(s) Windows and Macintosh.

DropListBox (statement)Syntax DropListBox X, Y, width, height, ArrayVariable, .Identifier

Description Creates a drop list box within a dialog box template.

Comments When the dialog box is invoked, the drop list box will be filled with theelements contained in ArrayVariable. Drop list boxes are similar to comboboxes, with the following exceptions:

The list box portion of a drop list box is not opened by default. The usermust open it by clicking the down arrow.

The user cannot type into a drop list box. Only items from the list box maybe selected. With combo boxes, the user can type the name of an item fromthe list directly or type the name of an item that is not contained within thecombo box.

This statement can only appear within a dialog box template (i.e., between theBegin Dialog and End Dialog statements).

Page 194: Working Model 2D - User's Manual

190 Working Model Basic User's Manual

The DropListBox statement requires the following parameters:

Parameter Description

X, Y Integer coordinates specifying the position of the control (in dialog units)relative 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. Ifthis array has no dimensions, then the drop list box will be initialized with noelements. A runtime error results if the specified array contains more than onedimension.

ArrayVariable can specify an array of any fundamental data type (structures arenot allowed). Null and Empty values are treated as zero-length strings.

.Identifier Name by which this control can be referenced by statements in a dialogfunction (such as DlgFocus and DlgEnable). This parameter also createsan integer variable whose value corresponds to the index of the drop list box'sselection (0 is the first item, 1 is the second, and so on). This variable can beaccessed 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,.WhichFieldOKButton 120,7,40,14CancelButton 120,27,40,14

End DialogDim FindDialog As FindTemplateFindDialog.WhichField = 1Dialog FindDialog

End Sub

See Also CancelButton (statement); CheckBox (statement); ComboBox (statement);Dialog (function); Dialog (statement); GroupBox (statement); ListBox(statement); OKButton (statement); OptionButton (statement); OptionGroup(statement); Picture (statement); PushButton (statement); Text (statement);TextBox (statement); Begin Dialog (statement), PictureButton (statement).

Platform(s) Windows and Macintosh.

Page 195: Working Model 2D - User's Manual

Chapter 2 DropListBox (statement) 191

Page 196: Working Model 2D - User's Manual

192

ebAbort (constant)Description Returned by the MsgBox function when the Abort button is chosen.

Comments This constant is equal to 3.

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 Then

EndElse

Goto Again:End If

End Sub

See Also MsgBox (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

ebAbortRetryIgnore (constant)Description Used by the MsgBox statement and function.

Comments This constant is equal to 2.

Example 'This example displays a dialog box with Abort, Retry, and Ignore'buttons.

Sub Main()rc% = MsgBox("Wicked disk error!",ebAbortRetryIgnore)

End Sub

See Also MsgBox (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

ebApplicationModal (constant)Description Used with the MsgBox statement and function.

Comments This constant is equal to 0.

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

Page 197: Working Model 2D - User's Manual

Chapter 2 ebArchive (constant) 193

See Also MsgBox (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

ebArchive (constant)Description Bit position of a file attribute indicating that a file hasn't been backed up.

Comments This constant is equal to 32.

Example 'This example dimensions an array and fills it with filenames with the'Archive bit set.

Sub Main()Dim s$()FileList s$,"*",ebArchivea% = 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$ (functions); FileList (statement); SetAttr (statement); GetAttr(function); FileAttr (function).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

This constant only applies to Windows.

ebBold (constant)Description Used with the Text and TextBox statement to specify a bold font.

Comments This constant is equal to 2.

Example Sub Main()Begin Dialog UserDialog 16,32,232,132,"Bold Font Demo"

Text 10,10,200,20,"Hello, world.",,"Helv",24,ebBoldTextBox 10,35,200,20,.Edit,,"Times New Roman",16,ebBoldOKButton 96,110,40,14

End DialogDim a As UserDialogDialog a

End Sub

See Also Text (statement), TextBox (statement).

Platform(s) Windows and Macintosh.

Page 198: Working Model 2D - User's Manual

194 Working Model Basic User's Manual

ebBoldItalic (constant)Description Used with the Text and TextBox statement to specify a bold-italic font.

Comments This constant is equal to 6.

Example Sub Main()Begin Dialog UserDialog 16,32,232,132,"Bold-Italic Font Demo"

Text 10,10,200,20,"Hello, world.",,"Helv",24,ebBoldItalicTextBox 10,35,200,20,.Edit,,"Times New Roman",16,ebBoldItalicOKButton 96,110,40,14

End DialogDim a As UserDialogDialog a

End Sub

See Also Text (statement), TextBox (statement).

Platform(s) Windows and Macintosh.

ebBoolean (constant)Description Number representing the type of a Boolean variant.

Comments This constant is equal to 11.

Example Sub Main()Dim MyVariant as variantMyVariant = TrueIf VarType(MyVariant) = ebBoolean Then

MyVariant = 5.5End If

End Sub

See Also VarType (function); Variant (data type).

Platform(s) Windows and Macintosh.

ebCancel (constant)Description Returned by the MsgBox function when the Cancel button is chosen.

Comments This constant is equal to 2.

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 (function); MsgBox (statement).

Page 199: Working Model 2D - User's Manual

Chapter 2 ebCritical (constant) 195

Platform(s) Windows and Macintosh.

ebCritical (constant)Description Used with the MsgBox statement and function.

Comments This constant is equal to 16.

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 IfEnd Sub

See Also MsgBox (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

ebCurrency (constant)Description Number representing the type of a Currency variant.

Comments This constant is equal to 6.

Example 'This example checks to see whether a variant is of type Currency.

Sub Main()Dim MyVariantIf VarType(MyVariant) = ebCurrency Then

MsgBox "Variant is Currency."End If

End Sub

See Also VarType (function); Variant (data type).

Platform(s) Windows and Macintosh.

ebDataObject (constant)Description Number representing the type of a data object variant.

Comments This constant is equal to 13.

Page 200: Working Model 2D - User's Manual

196 Working Model Basic User's Manual

Example 'This example checks to see whether a variable is a data object.

Sub Main()Dim MyVariant as VariantIf VarType(MyVariant) = ebDataObject Then

MsgBox "Variant contains a data object."End If

End Sub

See Also VarType (function); Variant (data type).

Platform(s) Windows and Macintosh.

ebError (constant)Description Number representing the type of an error variant.

Comments This constant is equal to 10.

Example 'This example checks to see whether a variable is an error.

Function Div(ByVal a As Variant,ByVal b As Variant) As VariantIf b = 0 Then

Div = CVErr(20000)Else

Div = a / bEnd If

End Function

Sub Main()Dim Result as VariantRandomizeResult = Div(10,Random(0,2))If VarType(Result) = ebError Then

MsgBox "An error occurred"Else

MsgBox "The result of the division is: " & ResultEnd If

End Sub

See Also VarType (function); Variant (data type).

Platform(s) Windows and Macintosh.

ebDate (constant)Description Number representing the type of a Date variant.

Comments This constant is equal to 7.

Page 201: Working Model 2D - User's Manual

Chapter 2 ebDefaultButton1 (constant) 197

Example Sub Main()Dim MyVariant as VariantIf VarType(MyVariant) = ebDate Then

MsgBox "This variable is a Date type!"Else

MsgBox "This variable is not a Date type!"End If

End Sub

See Also VarType (function); Variant (data type).

Platform(s) Windows and Macintosh.

ebDefaultButton1 (constant)Description Used with the MsgBox statement and function.

Comments This constant is equal to 0.

Example 'This example invokes MsgBox with the focus on the OK button bydefault.

Sub Main()rc% = MsgBox("Are you sure you want to quit?",ebOKCancel Or ebDefaultButton1)

End Sub

See Also MsgBox (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

ebDefaultButton2 (constant)Description Used with the MsgBox statement and function.

Comments This constant is equal to 256.

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 (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

ebDefaultButton3 (constant)Description Used with the MsgBox statement and function.

Comments This constant is equal to 512.

Page 202: Working Model 2D - User's Manual

198 Working Model Basic User's Manual

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

See Also MsgBox (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

ebDirectory (constant)Description Bit position of a file attribute indicating that a file is a directory entry.

Comments This constant is equal to 16.

Example 'This example dimensions an array and fills it with directory names'using the ebDirectory constant.

Sub Main()Dim s$()FileList s$, "c:\*", ebDirectorya% = 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$ (functions); FileList (statement); SetAttr (statement); GetAttr(function); FileAttr (function).

Platform(s) Windows and Macintosh.

ebDouble (constant)Description Number representing the type of a Double variant.

Comments This constant is equal to 5.

Example See ebSingle (constant).

See Also MsgBox (function); MsgBox (statement); VarType (function); Variant (datatype).

Platform(s) Windows and Macintosh.

ebEmpty (constant)Description Number representing the type of an Empty variant.

Page 203: Working Model 2D - User's Manual

Chapter 2 ebExclamation (constant) 199

Comments This constant is equal to 0.

Example Sub Main()Dim MyVariant as Variant

If VarType(MyVariant) = ebEmpty ThenMsgBox "No data has been input yet!"

End IfEnd Sub

See Also VarType (function); Variant (data type).

Platform(s) Windows and Macintosh.

ebExclamation (constant)Description Used with the MsgBox statement and function.

Comments This constant is equal to 48.

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 (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

ebHidden (constant)Description Bit position of a file attribute indicating that a file is hidden.

Comments This constant is equal to 2.

Example 'This example dimensions an array and fills it with filenames using'the ebHidden attribute.

Sub Main()Dim s$()FileList s$,"*",ebHiddenIf ArrayDims(s$) = 0 Then

MsgBox "No hidden files found!"End

End Ifa% = 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

Page 204: Working Model 2D - User's Manual

200 Working Model Basic User's Manual

See Also Dir, Dir$ (functions); FileList (statement); SetAttr (statement); GetAttr(function); FileAttr (function).

Platform(s) Windows and Macintosh.

ebIgnore (constant)Description Returned by the MsgBox function when the Ignore button is chosen.

Comments This constant is equal to 5.

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 (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

ebInformation (constant)Description Used with the MsgBox statement and function.

Comments This constant is equal to 64.

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 (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

ebInteger (constant)Description Number representing the type of an Integer variant.

Comments This constant is equal to 2.

Page 205: Working Model 2D - User's Manual

Chapter 2 ebItalic (constant) 201

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 BooleanIf VarType(v) = ebInteger Or VarType(v) = ebLong Then

IsInteger = TrueElse

IsInteger = FalseEnd If

End Function

Sub Main()Dim i as Integeri = 123If IsInteger(i) then

Msgbox "i is an Integer."End If

End Sub

See Also VarType (function); Variant (data type).

Platform(s) Windows and Macintosh.

ebItalic (constant)Description Used with the Text and TextBox statement to specify an italic font.

Comments This constant is equal to 4.

Example Sub Main()Begin Dialog UserDialog 16,32,232,132,"Italic Font Demo"

Text 10,10,200,20,"Hello, world.",,"Helv",24,ebItalicTextBox 10,35,200,20,.Edit,,"Times New Roman",16,ebItalicOKButton 96,110,40,14

End Dialog

Dim a As UserDialogDialog a

End Sub

See Also Text (statement), TextBox (statement).

Platform(s) Windows and Macintosh.

ebLandscape (constant)Description Used with the PrinterSetOrientation statement to align the paper

horizontally.

Comments This constant is equal to 2.

Page 206: Working Model 2D - User's Manual

202 Working Model Basic User's Manual

Example 'This example sets the printer orientation to landscape.

Sub Main()PrinterSetOrientation ebLandscapeMsgbox "Printer set to landscape."

End Sub

See Also PrinterSetOrientation (statement); PrinterGetOrientation (function).

Platform(s) Windows.

ebLeftButton (constant)Description Used with the QueMouseXX commands to represent the left button.

Comments This constant is equal to 1.

Example 'This example double-clicks the left mouse button.

Sub Main()QueMouseClick ebLeftButton,1000,1875

End Sub

See Also QueButtonDn (statement); QueButtonUp (statement); QueMouseClick(statement); QueMouseDblClk (statement); QueMouseDblDn (statement).

Platform(s) Windows.

ebLong (constant)Description Number representing the type of a Long variant.

Comments This constant is equal to 3.

Example See ebInteger (constant).

See Also VarType (function); Variant (data type).

Platform(s) Windows and Macintosh.

ebMacintosh (constant)Description Used with the Basic.OS property to indicate the Macintosh version of WM

Basic.

Comments This constant is equal to 10.

The Basic.OS property returns this value when WM Basic is running under theMacintosh operating system

Example Sub Main()If Basic.OS = ebMacintosh Then MsgBox "Running on Macintosh."

End Sub

Page 207: Working Model 2D - User's Manual

Chapter 2 ebMaximized (constant) 203

See Also Basic.OS (property).

Platform(s) Windows and Macintosh.

ebMaximized (constant)Description Used with the AppSetState and AppGetState statements to indicate a

maximized window state.

Comments This constant is equal to 1.

Example 'This example minimizes the current application if it is maximized.

Sub Main()If AppGetState = ebMaximized Then AppMinimize

End Sub

See Also AppSetState (statement); AppGetState (function).

Platform(s) Windows.

ebMinimized (constant)Description Used with the AppSetState and AppGetState statements to indicate a

minimized window state.

Comments This constant is equal to 2.

Example 'This example restores the current application if it is minimized.

Sub Main()If AppGetState = ebMinimized Then

AppMaximizeElse

AppMinimizeEnd If

End Sub

See Also AppSetState (statement); AppGetState (function).

Platform(s) Windows.

ebNo (constant)Description Returned by the MsgBox function when the No button is chosen.

Comments This constant is equal to 7.

Page 208: Working Model 2D - User's Manual

204 Working Model Basic User's Manual

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 (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

ebNone (constant)Description Bit value used to select files with no other attributes.

Comments This value can be used with the Dir$ and FileList commands. Thesefunctions will return only files with no attributes set when used with thisconstant. 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$,"*",ebNoneIf ArrayDims(s$) = 0 Then

MsgBox "No files found without attributes!"End

End Ifa% = 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

See Also Dir, Dir$ (functions); FileList (statement); SetAttr (statement); GetAttr(function); FileAttr (function).

Platform(s) Windows and Macintosh.

ebNormal (constant)Description Used to search for "normal" files.

Comments This value can be used with the Dir$ and FileList commands and willreturn files with the Archive, Volume, ReadOnly, or no attributes set. It will notmatch files with Hidden, System, or Directory attributes. This constant is equalto 0.

Page 209: Working Model 2D - User's Manual

Chapter 2 ebNull (constant) 205

Example 'This example dimensions an array and fills it with filenames with'Normal attributes.

Sub Main()Dim s$()FileList s$,"*", ebNormalIf ArrayDims(s$) = 0 Then

MsgBox "No filesfound!"End

End Ifa% = 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$ (functions); FileList (statement); SetAttr (statement); GetAttr(function); FileAttr (function).

Platform(s) Windows and Macintosh.

ebNull (constant)Description Number representing the type of a Null variant.

Comments This constant is equal to 1.

Example Sub Main()Dim MyVariantMyVariant = NullIf VarType(MyVariant) = ebNull Then

MsgBox "This variant is Null"End If

End Sub

See Also VarType (function); Variant (data type).

Platform(s) Windows and Macintosh.

ebObject (constant)Description Number representing the type of an Object variant (an OLE automation

object).

Comments This constant is equal to 9.

Example Sub Main()If VarType(MyVariant) = ebObject Then

MsgBox MyVariant.ValueEnd If

End Sub

Page 210: Working Model 2D - User's Manual

206 Working Model Basic User's Manual

See Also VarType (function); Variant (data type).

Platform(s) Windows and Macintosh.

ebOK (constant)Description Returned by the MsgBox function when the OK button is chosen.

Comments This constant is equal to 1.

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 (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

ebOKCancel (constant)Description Used with the MsgBox statement and function.

Comments This constant is equal to 1.

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 (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

ebOKOnly (constant)Description Used with the MsgBox statement and function.

Comments This constant is equal to 0.

Example 'This example informs the user of what is going on (no options).

Sub Main()MsgBox "Windows will now shut down.",ebOKOnly

End Sub

See Also MsgBox (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

Page 211: Working Model 2D - User's Manual

Chapter 2 ebPortrait (constant) 207

ebPortrait (constant)Description Used with the PrinterSetOrientation statement to align the paper

vertically.

Comments This constant is equal to 1.

Example 'This example changes the printer's orientation to portrait.

Sub Main()PrinterSetOrientation ebPortrait

End Sub

See Also PrinterSetOrientation (statement); PrinterGetOrientation (function).

Platform(s) Windows.

ebQuestion (constant)Description Used with the MsgBox statement and function.

Comments This constant is equal to 32.

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 (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

ebReadOnly (constant)Description Bit position of a file attribute indicating that a file is read-only.

Comments This constant is equal to 1.

Page 212: Working Model 2D - User's Manual

208 Working Model Basic User's Manual

Example 'This example dimensions an array and fills it with filenames with'ReadOnly attributes.

Sub Main()Dim s$()FileList s$, "*", ebReadOnlyIf ArrayDims(s$) = 0 Then

MsgBox "No read only files found!"End

End Ifa% = 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$ (functions); FileList (statement); SetAttr (statement); GetAttr(function); FileAttr (function).

Platform(s) Windows and Macintosh.

ebRegular (constant)Description Used with the Text and TextBox statement to specify an normal-styled font

(i.e., neither bold or italic).

Comments This constant is equal to 1.

Example Sub Main()Begin Dialog UserDialog 16,32,232,132,"Regular Font Demo"

Text 10,10,200,20,"Hello, world.",,"Helv",24,ebRegularTextBox 10,35,200,20,.Edit,,"Times New Roman",16,ebRegularOKButton 96,110,40,14

End DialogDim a As UserDialogDialog a

End Sub

See Also Text (statement), TextBox (statement).

Platform(s) Windows and Macintosh.

ebRestored (constant)Description Used with the AppSetState and AppGetState statements to indicate a

normal window state.

Comments This constant is equal to 3.

Page 213: Working Model 2D - User's Manual

Chapter 2 ebRetry (constant) 209

Example 'This example minimizes the current application only if it is'restored.

Sub Main()state% = AppGetStateIf state% = ebRestored Then

AppMinimizeEnd If

End Sub

See Also AppSetState (statement); AppGetState (function).

Platform(s) Windows.

ebRetry (constant)Description Returned by the MsgBox function when the Retry button is chosen.

Comments This constant is equal to 4.

Example 'This example displays a Retry message box.

Sub Main()rc% = MsgBox("Unable to open file.",ebRetryCancel)If rc% = ebRetry Then

MsgBox "User selected Retry."End If

End Sub

See Also MsgBox (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

ebRetryCancel (constant)Description Used with the MsgBox statement and function.

Comments This constant is equal to 5.

Example 'This example invokes a dialog box with Retry and Cancel buttons.

Sub Main()rc% = MsgBox("Unable to open file.",ebRetryCancel)

End Sub

See Also MsgBox (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

ebRightButton (constant)Description Used with the QueMouseXX commands to represent the right button.

Comments This constant is equal to 2.

Page 214: Working Model 2D - User's Manual

210 Working Model Basic User's Manual

Example 'This example clicks the right mouse button at 1000,1200.

Sub Main()QueMouseClick ebRightButton,1000,1200

End Sub

See Also QueButtonDn (statement); QueButtonUp (statement); QueMouseClick(statement); QueMouseDblClk (statement); QueMouseDblDn (statement).

Platform(s) Windows.

ebSingle (constant)Description Number representing the type of a Single variant.

Comments This constant is equal to 4.

Example 'This example defines a function that returns True if the passed'variant is a Real number.

Function IsReal(v As Variant) As BooleanIf VarType(v) = ebSingle Or VarType(v) = ebDouble Then

IsReal = TrueElse

IsReal = FalseEnd If

End Function

Sub Main()Dim i as Integeri = 123If IsReal(i) then

Msgbox "i is Real."End If

End Sub

See Also VarType (function); Variant (data type).

Platform(s) Windows and Macintosh.

ebString (constant)Description Number representing the type of a String variant.

Comments This constant is equal to 8.

Example Sub Main()Dim MyVariant as variantMyVariant = "This is a test."If VarType(MyVariant) = ebString Then

MsgBox "Variant is a string."End If

End Sub

See Also VarType (function); Variant (data type).

Page 215: Working Model 2D - User's Manual

Chapter 2 ebSystem (constant) 211

Platform(s) Windows and Macintosh.

ebSystem (constant)Description Bit position of a file attribute indicating that a file is a system file.

Comments This constant is equal to 4.

Example 'This example dimensions an array and fills it with filenames with'System attributes.

Sub Main()Dim s$()FileList s$,"*",ebSystema% = 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

See Also Dir, Dir$ (functions); FileList (statement); SetAttr (statement); GetAttr(function); FileAttr (function).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

This constant only applies to Windows.

ebSystemModal (constant)Description Used with the MsgBox statement and function.

Comments This constant is equal to 4096.

Example Sub Main()MsgBox "All applications are halted!",ebSystemModal

End Sub

See Also ebApplicationModal (constant); Constants (topic); MsgBox (function); MsgBox(statement).

Platform(s) Windows and Macintosh.

ebVariant (constant)Description Number representing the type of a Variant.

Comments Currently, it is not possible for variants to use this subtype. This constant isequal to 12.

Page 216: Working Model 2D - User's Manual

212 Working Model Basic User's Manual

See Also VarType (function); Variant (data type).

Platform(s) Windows and Macintosh.

ebVolume (constant)Description Bit position of a file attribute indicating that a file is the volume label.

Comments This constant is equal to 8.

Example 'This example dimensions an array and fills it with filenames with'Volume attributes.

Sub Main()Dim s$()FileList s$, "*", ebVolumeIf ArrayDims(s$) > 0 Then

MsgBox "The volume name is: " & s(1)Else

MsgBox "No volumes found."End If

End Sub

See Also Dir, Dir$ (functions); FileList (statement); SetAttr (statement); GetAttr(function); FileAttr (function).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

This constant only applies to Windows.

ebWin16 (constant)Description Used with the Basic.OS property to indicate the 16-bit Windows version of

WM Basic.

Comments This constant is equal to 0.

The Basic.OS property returns this value when WM Basic is running under theWindows 3.1 operating system

Example Sub Main()If Basic.OS = ebWin16 Then MsgBox "Running under Windows 3.1."

End Sub

See Also Basic.OS (property).

Platform(s) Windows and Macintosh.

ebWindows (constant)Description Used with the AppType function to indicate a Windows application.

Page 217: Working Model 2D - User's Manual

Chapter 2 ebYes (constant) 213

Comments This constant is equal to 2.

Example 'This example determines whether a Windows application was selected.

Sub Main()s$ = OpenFilename$("Run","Programs:*.exe")If s$ <> "" Then

If FileType(s$) = ebWindows ThenMsgBox "You selected a Windows .exe file."

End IfEnd If

End Sub

See Also AppGetType (function); AppFileType (function).

Platform(s) Windows.

ebYes (constant)Description Returned by the MsgBox function when the Yes button is chosen.

Comments This constant is equal to 6.

Example 'This example queries the user for a response.

Sub Main()rc% = MsgBox("Overwrite file?",ebYesNoCancel)If rc% = ebYes Then

MsgBox "You elected to overwrite the file."End If

End Sub

See Also MsgBox (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

ebYesNo (constant)Description Used with the MsgBox statement and function.

Comments This constant is equal to 4.

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 (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

Page 218: Working Model 2D - User's Manual

214 Working Model Basic User's Manual

ebYesNoCancel (constant)Description Used with the MsgBox statement and function.

Comments This constant is equal to 3.

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 (function); MsgBox (statement).

Platform(s) Windows and Macintosh.

EditEnabled (function)Syntax EditEnabled(name$ | id)

Description Returns True if the given text box is enabled within the active window ordialog box; returns False otherwise.

Comments The EditEnabled function takes the following parameters:

Parameter Description

name$ String containing the name of the text box.

The name of a text box is determined by scanning the window list looking for atext control with the given name that is immediately followed by a text box.

id Integer specifying the ID of the text box.

A runtime error is generated if a text box control with the given name or IDcannot be found within the active window.

If enabled, the text box can be given the focus using the ActivateControlstatement.

Note: The EditEnabled function is used to determine whether a text box isenabled in another application's dialog box. Use the DlgEnable function indynamic dialog boxes.

Page 219: Working Model 2D - User's Manual

Chapter 2 EditExists (function) 215

Example 'This example adjusts the left margin if this control is enabled.

Sub Main()Menu "Format.Paragraph"If EditEnabled("Left:") Then

SetEditText "Left:","5 pt"End If

End Sub

See Also EditExists (function); GetEditText$ (function); SetEditText (statement).

Platform(s) Windows.

EditExists (function)Syntax EditExists(name$ | id)

Description Returns True if the given text box exists within the active window or dialogbox; returns False otherwise.

Comments The EditExists function takes the following parameters:

Parameter Description

name$ String containing the name of the text box.

The name of a text box is determined by scanning the window list looking for atext control with the given name that is immediately followed by a text box.

id Integer specifying the ID of the text box.

A runtime error is generated if a text box control with the given name or IDcannot be found within the active window.

If there is no active window, False will be returned.

Note: The EditExists function is used to determine whether a text box existsin another application's dialog box. There is no equivalent function for use withdynamic dialog boxes.

Example 'This example adjusts the left margin if this control exists and is'enabled.

Sub Main()Menu "Format.Paragraph"If EditExists("Left:") Then

If EditEnabled("Left:") ThenSetEditText "Left:","5 pt"

End IfEnd If

End Sub

See Also EditEnabled (function); GetEditText$ (function); SetEditText (statement).

Page 220: Working Model 2D - User's Manual

216 Working Model Basic User's Manual

Platform(s) Windows.

Empty (constant)Description Constant representing a variant of type 0.

Comments The Empty value has special meaning indicating that a Variant isuninitialized.

When Empty is assigned to numbers, the value 0 is assigned. When Empty isassigned to a String, the string is assigned a zero-length string.

Example Sub Main()Dim a As Varianta = Empty

End Sub

See Also Null (constant); Variant (data type); VarType (function).

Platform(s) Windows and Macintosh.

End (statement)Syntax End

Description Terminates execution of the current script, closing all open files.

Example 'This example uses the End statement to stop execution.

Sub Main()MsgBox "The next line will terminate the script."End

End Sub

See Also Close (statement); Stop (statement); Exit For (statement); Exit Do(statement); Exit Function (statement); Exit Sub (function).

Platform(s) Windows and Macintosh.

Environ, Environ$ (functions)Syntax Environ[$](variable$ | VariableNumber)

Description Returns the value of the specified environment variable.

Page 221: Working Model 2D - User's Manual

Chapter 2 EOF (function) 217

Comments Environ$ returns a String, whereas Environ returns a String variant.

If variable$ is specified, then this function looks for that variable$ in theenvironment. If the variable$ name cannot be found, then a zero-length stringis returned.

If VariableNumber is specified, then this function looks for the Nth variablewithin the environment (the first variable being number 1). If there is no suchenvironment variable, then a zero-length string is returned. Otherwise, theentire 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$("COMSPEC")MsgBox "The DOS Comspec variable is set to: " & a$(1)

End Sub

See Also Command, Command$ (functions).

Platform(s) Windows and Macintosh.

EOF (function)Syntax EOF(filenumber)

Description Returns True if the end-of-file has been reached for the given file; returnsFalse otherwise.

Comments The filenumber parameter is an Integer used by WM Basic to refer to theopen file—the number passed to the Open statement.

With sequential files, EOF returns True when the end of the file has beenreached (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 beenmade to read beyond the end of the file. Thus, EOF will only return True whenGet was unable to read the entire record.

Page 222: Working Model 2D - User's Manual

218 Working Model Basic User's Manual

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()Dim s$Open "c:\autoexec.bat" For Input As #1Do While Not EOF(1)

Input #1,s$LoopClose

MsgBox "The last line was:" & crlf & s$End Sub

See Also Open (statement); LOF (function).

Platform(s) Windows and Macintosh.

Eqv (operator)Syntax expression1 Eqv expression2

Description Performs a logical or binary equivalence on two expressions.

Comments If both expressions are either Boolean, Boolean variants, or Null variants,then a logical equivalence is performed as follows:

If the first and the second then theexpression is expression is result is

True True TrueTrue False FalseFalse True FalseFalse False True

If either expression is Null, then Null is returned.

Binary Equivalence

If the two expressions are Integer, then a binary equivalence is performed,returning an Integer result. All other numeric types (including Emptyvariants) 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 thebinary representations of the two expressions, according to the following table:

1 Eqv1 = 1 Example:0 Eqv1 = 0 5 011010011 Eqv0 = 0 6 10101010 0 Eqv0 = 1 Eqv00101000

Page 223: Working Model 2D - User's Manual

Chapter 2 Erase (statement) 219

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 = FalseIf ((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 (topic); Or (operator); Xor (operator); Imp (operator); And(operator).

Platform(s) Windows and Macintosh.

Erase (statement)Syntax Erase array1 [,array2]...

Description Erases the elements of the specified arrays.

Comments For dynamic arrays, the elements are erased, and the array is redimensioned tohave no dimensions (and therefore no elements). For fixed arrays, only theelements are erased; the array dimensions are not changed.

After a dynamic array is erased, the array will contain no elements and nodimensions. Thus, before the array can be used by your program, thedimensions must be reestablished using the Redim statement.

Up to 32 parameters can be specified with the Erase statement.

Page 224: Working Model 2D - User's Manual

220 Working Model Basic User's Manual

The meaning of erasing an array element depends on the type of the elementbeing erased:

Element Type What Erase Does to That Element

Integer Sets the element to 0.

Boolean Sets the element to False.

Long Sets the element to 0.

Double Sets the element to 0.0.

Date Sets the element to December 30, 1899.

Single Sets the element to 0.0.

String (variable-length)Frees the string, then sets the element to a zero-lengthstring.

String (fixed-length) Sets every character of each element to zero(Chr$(0)).

Object Decrements the reference count and sets the elementto Nothing.

Variant Sets the element to Empty.

User-defined type Sets each structure element as a separate variable.

Example 'This example puts a value into an array and displays it.'Then it erases the value and displays it again.

Sub Main()Dim a$(10) 'Declare an array.a$(1) = Dir$("*") 'Fill element 1 with a filename.MsgBox "Array before Erase: " & a$(1) 'Display element 1.Erase a$ 'Erase all elements in the array.MsgBox "Array after Erase: " & a$(1) 'Display element 1 again

(should be erased).End Sub

See Also Redim (statement); Arrays (topic).

Platform(s) Windows and Macintosh.

Erl (function)Syntax Erl[()]

Description Returns the line number of the most recent error.

Page 225: Working Model 2D - User's Manual

Chapter 2 Err (function) 221

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 outsidean 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 IntegerOn Error Goto Trap1i = 32767 'Generate an error--overflow.i = i + 1Exit Sub

Trap1:MsgBox "Error on line: " & ErlExit Sub 'Reset the error handler.

End Sub

See Also Err (function); Error, Error$ (functions); Error Handling (topic).

Platform(s) Windows and Macintosh.

Err (function)Syntax Err[()]

Description Returns an Integer representing the error that caused the current error trap.

Comments The Err function can only be used while within an error trap.

The internal value of Err is reset to 0 with any of the following statements:Resume, Exit Sub, Exit Function. Thus, if you want to use this value outsidean error handler, you must assign it to a variable.

Page 226: Working Model 2D - User's Manual

222 Working Model Basic User's Manual

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 TestErrorError 10MsgBox "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 IfResume Next

End Sub

See Also Erl (function); Error, Error$ (functions); Error Handling (topic).

Platform(s) Windows and Macintosh.

Err (statement)Syntax Err = value

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 allowsyou to perform error trapping within an error handler. The ability to reset theerror handler while within an error trap is not standard Basic. Normally, theerror handler is reset only with the Resume, Exit Sub, or ExitFunction statement.

Page 227: Working Model 2D - User's Manual

Chapter 2 Error (statement) 223

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 TestErrorError 10MsgBox "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 IfResume Next

End Sub

See Also Error (statement); Error Handling (topic).

Platform(s) Windows and Macintosh.

Error (statement)Syntax Error errornumber

Description Simulates the occurrence of the given runtime error.

Comments The errornumber parameter is any Integer containing either a built-in errornumber or a user-defined error number. The Err function can be used withinthe 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 TestErrorError 10MsgBox "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 IfResume Next

End Sub

Page 228: Working Model 2D - User's Manual

224 Working Model Basic User's Manual

See Also Err (statement); Error Handling (topic).

Platform(s) Windows and Macintosh.

Error Handling (topic)Error Handlers

WM Basic supports nested error handlers. When an error occurs within asubroutine, WM Basic checks for an On Error handler within the currentlyexecuting subroutine or function. An error handler is defined as follows:

Sub foo()On Error Goto catch'Do something here.Exit Sub

catch:'Handle error here.

End Sub

Error handlers have a life local to the procedure in which they are defined. Theerror is reset when (1) another On Error statement is encountered, (2) anerror occurs, or (3) the procedure returns.

Cascading Errors

If a runtime error occurs and no On Error handler is defined within thecurrently executing procedure, then WM Basic returns to the calling procedureand executes the error handler there. This process repeats until a procedure isfound that contains an error handler or until there are no more procedures. If anerror is not trapped or if an error occurs within the error handler, then WMBasic displays an error message, halting execution of the script.

Once an error handler has control, it must address the condition that caused theerror and resume execution with the Resume statement. This statement resetsthe error handler, transferring execution to an appropriate place within thecurrent procedure. An error is displayed if a procedure exits without firstexecuting Resume or Exit.

Visual Basic Compatibility

Where possible, WM Basic has the same error numbers and error messages asVisual Basic. This is useful for porting scripts between environments.

Handling errors in WM Basic involves querying the error number or error textusing the Error$ or Err function. Since this is the only way to handle errorsin WM Basic, compatibility with Visual Basic's error numbers and messages isessential.

Page 229: Working Model 2D - User's Manual

Chapter 2 Error, Error$ (functions) 225

WM Basic errors fall into three categories:

1. Visual Basic–compatible errors: These errors, numbered between 0 and799, are numbered and named according to the errors supported by VisualBasic.

2. WM Basic errors: These errors, numbered from 800 to 999, are unique toWM Basic.

3. User-defined errors: These errors, equal to or greater than 1,000, areavailable for use by extensions or by the script itself.

You can intercept trappable errors using WM Basic's On Error construct.Almost all errors in WM Basic are trappable except for various system errors.

Error, Error$ (functions)Syntax Error[$][(errornumber)]

Description Returns a String containing the text corresponding to the given error numberor 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 errormessage to retrieve. If this parameter is omitted, then the function returns thetext corresponding to the most recent runtime error. If no runtime error hasoccurred, then a zero-length string is returned.

If the Error statement was used to generate a user-defined runtime error, thenthis function will return a zero-length string ("").

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 TestErrorError 10MsgBox "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 IfResume Next

End Sub

Page 230: Working Model 2D - User's Manual

226 Working Model Basic User's Manual

See Also Erl (function); Err (function); Error Handling (topic).

Platform(s) Windows and Macintosh.

Exit Do (statement)Syntax Exit Do

Description Causes execution to continue on the statement following the Loop clause.

Comments This statement can only appear within a Do...Loop statement.

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 Thena(i%) = Dir$("*")

Else a(i%) = Dir$End IfIf i% >= 10 Then Exit Do

Loop While (a(i%) <> "")

If i% = 10 ThenMsgBox i% & " entries processed!"

ElseMsgBox "Less than " & i% & " entries processed!"

End IfEnd Sub

See Also Stop (statement); Exit For (statement); Exit Function (statement); ExitSub (statement); End (function); Do...Loop (statement).

Platform(s) Windows and Macintosh.

Exit For (statement)Syntax Exit For

Description Causes execution to exit the innermost For loop, continuing execution on theline following the Next statement.

Comments This statement can only appear within a For...Next block.

Page 231: Working Model 2D - User's Manual

Chapter 2 Exit Function (statement) 227

Example 'This example will fill an array with directory entries until a null'entry is encountered or 100 entries have been processed--at which'time, the loop is terminated by an Exit For statement. The dialog box'displays a count of files found and then some entries from the array.

Const crlf = Chr$(13) + Chr$(10)

Sub Main()Dim a$(100)For i = 1 To 100

If i = 1 Thena$(i) = Dir$("*")

Elsea$(i) = Dir$

End IfIf (a$(i) = "") Or (i >= 100) Then Exit For

Next imsg = "There are " & i & " files found." & crlfMsgBox msg & a$(1) & crlf & a$(2) & crlf & a$(3) & crlf & a$(10)

End Sub

See Also Stop (statement); Exit Do (statement); Exit Function (statement); Exit Sub(statement); End (statement); For...Next (statement).

Platform(s) Windows and Macintosh.

Exit Function (statement)Syntax Exit Function

Description Causes execution to exit the current function, continuing execution on thestatement following the call to this function.

Comments This statement can only appear within a function.

Example 'This function displays a message and then terminates with Exit'Function.

Function Test_Exit() As IntegerMsgBox "Testing function exit, returning to Main()."Test_Exit = 0Exit FunctionMsgBox "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 (statement); Exit For (statement); Exit Do (statement); Exit Sub(statement); End (statement); Function...End Function (statement).

Platform(s) Windows and Macintosh.

Page 232: Working Model 2D - User's Manual

228 Working Model Basic User's Manual

Exit Sub (statement)Syntax Exit Sub

Description Causes execution to exit the current subroutine, continuing execution on thestatement following the call to this subroutine.

Comments This statement can appear anywhere within a subroutine. It cannot appearwithin a function.

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 SubMsgBox "Still here in Main()."

End Sub

See Also Stop (statement); Exit For (statement); Exit Do (statement); Exit Function(statement); End (function); Sub...End Sub (statement).

Platform(s) Windows and Macintosh.

Exp (function)Syntax Exp(value)

Description Returns the value of e raised to the power of value.

Comments The value parameter is a Double within the following range:

0 <= value <= 709.782712893.

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.40)MsgBox "e to the 12.4 power is: " & a#

End Sub

See Also Log (function).

Platform(s) Windows and Macintosh.

Page 233: Working Model 2D - User's Manual

Chapter 2 Expression Evaluation (topic) 229

Expression Evaluation (topic)WM Basic allows expressions to involve data of different types. When thisoccurs, the two arguments are converted to be of the same type by promotingthe less precise operand to the same type as the more precise operand. Forexample, WM Basic will promote the value of i% to a Double in thefollowing expression:

result# = i% * d#

In some cases, the data type to which each operand is promoted is different thanthat of the most precise operand. This is dependent on the operator and the datatypes of the two operands and is noted in the description of each operator.

If an operation is performed between a numeric expression and a Stringexpression, then the String expression is usually converted to be of the sametype as the numeric expression. For example, the following expression convertsthe String expression to an Integer before performing the multiplication:

result = 10 * "2" 'Result is equal to 20.

There are exceptions to this rule as noted in the description of the indicidualoperators.

Type Coercion

WM Basic performs numeric type conversion automatically. Automaticconversions sometimes result in overflow errors, as shown in the followingexample:

d# = 45354i% = d#

In this example, an overflow error is generated because the value contained ind# is larger than the maximum size of an Integer.

Page 234: Working Model 2D - User's Manual

230 Working Model Basic User's Manual

Rounding

When floating-point values (Single or Double) are converted to integervalues (Integer or Long), the fractional part of the floating-point number islost, rounding to the nearest integer value. WM Basic 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 oddand 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 numericaloperators such as addition or subtraction, then the default property of that obectis automatically retrieved. For example, consider the following:

Dim Excel As ObjectSet Excel = GetObject(,"Excel.Application")MsgBox "This application is " & Excel

The above example displays This application is Microsoft Excel in adialog box. When the variable Excel is used within the expression, the defaultproperty is automatically retrieved, which, in this case, is the string MicrosoftExcel. Considering that the default property of the Excel object is .Value,then the following two statements are equivalent:

MsgBox "This application is " & ExcelMsgBox "This application is " & Excel.Value

Page 235: Working Model 2D - User's Manual

231

False (constant)Description Boolean constant whose value is False.

Comments Used in conditionals and Boolean expressions.

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 = FalseIf ((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 (constant); Constants (topic); Boolean (data type).

Platform(s) Windows and Macintosh.

FileAttr (function)Syntax FileAttr(filenumber, attribute)

Description Returns an Integer specifying the file mode (if attribute is 1) or theoperating system file handle (if attribute is 2).

Comments The FileAttr function takes the following parameters:

Parameter Description

filenumber Integer value used by WM Basic to refer to the open file—the number passedto the Open statement.

attribute Integer specifying the type of value to be returned. If attribute is 1, then oneof the following values is returned:

1 Input2 Output4 Random8 Append32 Binary

If attribute is 2, then the operating system file handle is returned. On mostsystems, this is a special Integer value identifying the file.

Page 236: Working Model 2D - User's Manual

232 Working Model Basic User's Manual

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 #1a% = FileAttr(1,1)Select Case a%

Case 1MsgBox "Opened for input."

Case 2MsgBox "Opened for output."

Case 4MsgBox "Opened for random."

Case 8MsgBox "Opened for append."

Case 32MsgBox "Opened for binary."

Case ElseMsgBox "Unknown file mode."

End Selecta% = FileAttr(1,2)MsgBox "File handle is: " & a%Close

End Sub

See Also FileLen (function); GetAttr (function); FileType (function); FileExists(function); Open (statement); SetAttr (statement).

Platform(s) Windows and Macintosh.

FileCopy (statement)Syntax FileCopy source$, destination$

Description Copies a source$ file to a destination$ file.

Comments The FileCopy function takes the following parameters:

Parameter Description

source$ String containing the name of a single file to copy.

The source$ parameter cannot contain wildcards (? or *) but may contain pathinformation.

destination$ String containing a single, unique destination file, which may contain a driveand path specification.

The file will be copied and renamed if the source$ and destination$ filenamesare not the same.

Some platforms do not support drive letters and may not support dots toindicate current and parent directories.

Page 237: Working Model 2D - User's Manual

Chapter 2 FileDateTime (function) 233

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 ErrHandlerFileCopy "c:\autoexec.bat", "c:\autoexec.sav"Open "c:\autoexec.sav" For Input As # 1FileCopy "c:\autoexec.sav", "c:\autoexec.sv2"CloseExit 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 IfResume Next

End Sub

See Also Kill (statement); Name (statement).

Platform(s) Windows and Macintosh.

FileDateTime (function)Syntax FileDateTime(filename$)

Description Returns a Date variant representing the date and time of the last modificationof a file.

Comments This function retrieves the date and time of the last modification of the filespecified by filename$ (wildcards are not allowed). A runtime error results ifthe file does not exist. The value returned can be used with the date/timefunctions (i.e., Year, Month, Day, Weekday, Minute, Second, Hour) toextract 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 (function); GetAttr (function); FileType (function); FileAttr(function); FileExists (function).

Page 238: Working Model 2D - User's Manual

234 Working Model Basic User's Manual

Platform(s) Windows and Macintosh.

FileDirs (statement)Syntax FileDirs array() [,dirspec$]

Description Fills a String or Variant array with directory names from disk.

Comments The FileDirs statement takes the following parameters:

Parameter Description

array() Either a zero- or a one-dimensioned array of strings or variants. The array canbe either dynamic or fixed.

If array() is dynamic, then it will be redimensioned to exactly hold the newnumber of elements. If there are no elements, then the array will beredimensioned to contain no dimensions. You can use the LBound, UBound, andArrayDims functions to determine the number and size of the new array'sdimensions.

If the array is fixed, each array element is first erased, then the new elementsare 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 Stringarrays) or Empty (for Variant arrays). A runtime error results if the array is toosmall to hold the new elements.

dirspec$ String containing the file search mask, such as:t*.c:\*.*

If this parameter is omitted, then * is used, which fills the array with all thesubdirectory 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 (statement); Dir, Dir$ (functions); CurDir, CurDir$ (functions);ChDir (statement).

Platform(s) Windows and Macintosh.

FileExists (function)Syntax FileExists(filename$)

Page 239: Working Model 2D - User's Manual

Chapter 2 FileLen (function) 235

Description Returns True if filename$ exists; returns False otherwise.

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 date and'time of creation 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 (function); GetAttr (function); FileType (function); FileAttr(function); FileParse$ (function).

Platform(s) Windows and Macintosh.

FileLen (function)Syntax FileLen(filename$)

Description Returns a Long representing the length of filename$ in bytes.

Comments This function is used in place of the LOF function to retrieve the length of a filewithout 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()If (FileExists("c:\autoexec.bat") And (FileLen("c:\autoexec.bat")

<> 0)) Thenb% = FileLen("c:\autoexec.bat")MsgBox "The length of autoexec.bat is: " & b%

ElseMsgBox "File does not exist."

End IfEnd Sub

See Also GetAttr (function); FileType (function); FileAttr (function); FileParse$(function); FileExists (function); Loc (function).

Platform(s) Windows and Macintosh.

FileList (statement)Syntax FileList array() [,[ filespec$] [,[include_attr] [,exclude_attr]]]

Page 240: Working Model 2D - User's Manual

236 Working Model Basic User's Manual

Description Fills a String or Variant array with filenames from disk.

Comments The FileList function takes the following parameters:

Parameter Description

array() Either a zero- or a one-dimensioned array of strings or variants. The array canbe either dynamic or fixed.

If array() is dynamic, then it will be redimensioned to exactly hold the newnumber of elements. If there are no elements, then the array will beredimensioned to contain no dimensions. You can use the LBound, UBound, andArrayDims functions to determine the number and size of the new array'sdimensions.

If the array is fixed, each array element is first erased, then the new elementsare 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 Stringarrays) or Empty (for Variant arrays). A runtime error results if the array is toosmall 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 thisparameter is omitted, then * is used.

include_attr Integer specifying attributes of files you want included in the list. It can beany combination of the attributes listed below.

If this parameter is omitted, then the value 97 is used (ebReadOnly OrebArchive Or ebNone).

exclude_attr Integer specifying attributes of files you want excluded from the list. It can beany combination of the attributes listed below.

If this parameter is omitted, then the value 18 is used (ebHidden OrebDirectory). In other words, hidden files and subdirectories are excludedfrom the list.

Page 241: Working Model 2D - User's Manual

Chapter 2 FileList (statement) 237

Wildcards

The * character matches any sequence of zero or more characters, whereas the? character matches any single character. Multiple *'s and ?'s can appearwithin the expression to form complete searching patterns. The following tableshows some examples:

This Pattern Matches These Files Doesn't Match These Files

*S*.TXT SAMPLE.TXT SAMPLEGOOSE.TXT SAMPLE.DATSAMS.TXT

C*T.TXT CAT.TXT CAP.TXTACATS.TXT

C*T CAT CAT.DOCCAP.TXT

C?T CAT CAT.TXTCUT CAPIT

CT

* (All files)

File Attributes

These numbers can be any combination of the following:

Constant Value Includes

ebNormal 0 Read-only, archive, subdir, noneebReadOnly 1 Read-only filesebHidden 2 Hidden filesebSystem 4 System filesebVolume 8 Volume labelebDirectory 16 DOS subdirectoriesebArchive 32 Files that have changed since the lastbackupebNone 64 Files with no attributes

Page 242: Working Model 2D - User's Manual

238 Working Model Basic User's Manual

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), ebSystemIf ArrayDims(a$) > 0 Then

MsgBox a$(1) & crlf & a$(2) & crlf & a$(3) & crlf & a$(4)Else

MsgBox "No files found."End If

End Sub

See Also FileDirs (statement); Dir, Dir$ (functions).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Notice that WM Basic’s filename matching is different than DOS's. The pattern"*.*" under DOS matches all files. With WM Basic, this pattern matches onlyfiles that have file extensions.

FileParse$ (function)Syntax FileParse$(filename$[, operation])

Description Returns a String containing a portion of filename$ such as the path, drive, orfile extension.

Page 243: Working Model 2D - User's Manual

Chapter 2 FileParse$ (function) 239

Comments The filename$ parameter can specify any valid filename (it does not have toexist). For example:

..\test.datc:\sheets\test.dattest.dat

A runtime error is generated if filename$ is a zero-length string.

The optional operation parameter is an Integer specifying which portion ofthe filename$ to extract. It can be any of the following values.

Value Meaning Example

0 Full name c:\sheets\test.dat1 Drive c2 Path c:\sheets3 Name test.dat4 Root test5 Extension dat

If operation is not specified, then the full name is returned. A runtime error willresult 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:\testsub\autoexec.bat" into its'component parts and displays them in a dialog box.

Const crlf = Chr$(13) + Chr$(10)

Sub Main()Dim a$(6)For i = 1 To 5

a$(i) = FileParse$("c:\testsub\autoexec.bat",i - 1)Next iMsgBox a$(1) & crlf & a$(2) & crlf & a$(3) & crlf & a$(4) & crlf &

a$(5)End Sub

See Also FileLen (function); GetAttr (function); FileType (function); FileAttr(function); FileExists (function).

Platform(s) Windows and Macintosh.

PlatformNotes:

On systems that do not support drive letters, operation 1 will return a zero-length string.

The path separator is different on different platforms. Under Windows, thebackslash and forward slash can be used interchangeably. For example,"c:\test.dat" is the same as "c:/test.dat".

Page 244: Working Model 2D - User's Manual

240 Working Model Basic User's Manual

PlatformNotes:

Macintosh

On the Macintosh, all characters are valid within filenames except colons,which are seen as path separators.

FileType (function)Syntax FileType(filename$)

Description Returns the type of the specified file.

Comments One of the following Integer constants is returned:

Constant Value Description

ebDos 1 A DOS executable file (exe files only; comfiles are not recognized).

ebWindows 2 A Windows executable file.

If one of the above values is not returned, then the file type is unknown.

Example 'This example looks at c:\windows\winfile.exe and determines whether'it is a DOS or a Windows file. The result is displayed in a dialog'box.

Sub Main()a = FileType("c:\windows\winfile.exe")If a = ebDos Then

MsgBox "This is a DOS file."Else

MsgBox "This is a Windows file of type '" & a & "'"End If

End Sub

See Also FileLen (function); GetAttr (function); FileAttr (function); FileExists(function).

Platform(s) Windows.

PlatformNotes:

Windows

Currently, only files with a ".exe" extension can be used with this function.Files with a ".com" or ".bat" extension will return 3 (unknown).

Fix (function)Syntax Fix(number)

Description Returns the integer part of number.

Page 245: Working Model 2D - User's Manual

Chapter 2 For...Next (statement) 241

Comments This function returns the integer part of the given value by removing thefractional part. The sign is preserved.

The Fix function returns the same type as number, with the followingexceptions:

If number is Empty, then an Integer variant of value 0 is returned.

If number is a String, then a Double variant is returned.

If number contains no valid data, then a Null variant is returned.

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.45b% = Fix(a#)MsgBox "The fixed portion of -19923.45 is: " & b%

End Sub

See Also Int (function); CInt (function).

Platform(s) Windows and Macintosh.

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 loopcounter by a given increment each time through the loop.

Page 246: Working Model 2D - User's Manual

242 Working Model Basic User's Manual

Comments The For statement takes the following parameters:

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 assignedthis value.

end Final value for counter. The statements will continue executing until counter isequal to end.

increment Amount added to counter each time through the loop. If end is greater thanstart, then increment must be positive. If end is less than start, then incrementmust be negative.

If increment is not specified, then 1 is assumed. The expression given asincrement is evaluated only once. Changing the step during execution of theloop will have no effect.

statements Any number of WM Basic statements.

The For...Next statement continues executing until an Exit Forstatement 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 eachcounter with a comma. The ordering of the counters must be consistent with thenesting order (innermost counter appearing before outermost counter). Thefollowing example shows two equivalent For statements:

For i = 1 To 10 For i = 1 To 10For j = 1 To 10 For j = 1 To 10Next j Next j,i

Next i

A Next clause appearing by itself (with no counter variable) matches theinnermost For loop.

The counter variable can be changed within the loop but will have no effect onthe number of times the loop will execute.

Page 247: Working Model 2D - User's Manual

Chapter 2 Format, Format$ (functions) 243

Example Sub Main()'This example constructs a truth table for the OR statement 'using nested For...Next loops.For x = -1 To 0

For y = -1 To 0Z = x Or ymsg = msg & Format(Abs(x%),"0") & " Or "msg = msg & Format(Abs(y%),"0") & " = "msg = msg & Format(Z,"True/False") & Basic.Eoln$

Next yNext xMsgBox msg

End Sub

See Also Do...Loop (statement); While...WEnd (statement).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Due to errors in program logic, you can inadvertently create infinite loops inyour code. Under Windows, you can break out of infinite loops usingCtrl+Break.

PlatformNotes:

Macintosh

Due to errors in program logic, you can inadvertently create infinite loops inyour code. On the Macintosh, you can break out of infinite loops usingCommand+Period.

Format, Format$ (functions)Syntax Format[$](expression [,Userformat$])

Description

Returns a String formatted to user specification.

Page 248: Working Model 2D - User's Manual

244 Working Model Basic User's Manual

Comments Format$ returns a String, whereas Format returns a String variant.

The Format$/Format functions take the following parameters:

Parameter Description

expression String or numeric expression to be formatted.

Userformat$ Format expression that can be either one of the built-in WM Basic formats ora user-defined format consisting of characters that specify how the expressionshould be displayed.

String, numeric, and date/time formats cannot be mixed in a singleUserformat$ expression.

If Userformat$ is omitted and the expression is numeric, then these functionsperform the same function as the Str$ or Str statements, except that theydo not preserve a leading space for positive values.

If expression is Null, then a zero-length string is returned.

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 numericexpressions and the other with date/time values.The following tables list thebuilt-in numeric and date/time format strings, followed by an explanation ofwhat each does.

Numeric FormatsFormat Description

General number Display the numeric expression as is, with no additional formatting.

Currency Displays the numeric expression as currency, with thousands separator ifnecessary.

Fixed Displays at least one digit to the left of the decimal separator and two digitsto 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 digitsto the right.

Percent Displays the numeric expression multiplied by 100. A percent sign (%) willappear at the right of the formatted output. Two digits are displayed to theright of the decimal separator.

Scientific Displays the number using scientific notation. One digit appears before thedecimal separator and two after.

Yes/No Displays No if the numeric expression is 0. Displays Yes for all other values.

Page 249: Working Model 2D - User's Manual

Chapter 2 Format, Format$ (functions) 245

True/False Displays False if the numeric expression is 0. Displays True for all othervalues.

On/Off Displays Off if the numeric expression is 0. Displays On for all other values.

Date/Time FormatsFormat Description

General date Displays the date and time. If there is no fractional part in the numericexpression, then only the date is displayed. If there is no integral part in thenumeric expression, then only the time is displayed. Output is in thefollowing form: 1/1/95 01:00:00 AM.

Long date Displays a long date.

Medium date Displays a medium date—prints out only the abbreviated name of the month.

Short date Displays a short date.

Long time Displays the long time. The default is: h:mm:ss.

Medium time Displays the time using a 12-hour clock. Hours and minutes are displayed,and the AM/PM 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 byusing characters that have special meaning when used in a format expression.The following tables list the characters you can use for numeric, string, anddate/time formats and explain their functions.

Numeric FormatsCharacter Meaning

Empty string Displays the numeric expression as is, with no additional formatting.

0 This is a digit placeholder.

Displays a number or a 0. If a number exists in the numeric expression in theposition where the 0 appears, the number will be displayed. Otherwise, a 0will be displayed. If there are more 0s in the format string than there aredigits, the leading and trailing 0s are displayed without modification.

# This is a digit placeholder.

Displays a number or nothing. If a number exists in the numeric expression inthe position where the number sign appears, the number will be displayed.Otherwise, nothing will be displayed. Leading and trailing 0s are notdisplayed.

Page 250: Working Model 2D - User's Manual

246 Working Model Basic User's Manual

. This is the decimal placeholder.

Designates the number of digits to the left of the decimal and the number ofdigits to the right. The character used in the formatted string depends on thedecimal placeholder, as specified by your locale.

% This is the percentage operator.

The numeric expression is multiplied by 100, and the percent character isinserted in the same position as it appears in the user-defined format string.

, This is the thousand separator.

The common use for the thousands separator is to separate thousands fromhundreds. To specify this use, the thousands separator must be surrounded bydigit placeholders. Commas appearing before any digit placeholders arespecified are just displayed. Adjacent commas with no digit placeholdersspecified between them and the decimal mean that the number should bedivided by 1,000 for each adjacent comma in the format string. A commaimmediately to the left of the decimal has the same function. The actualthousands separator character used depends on the character specified byyour locale.

E-E+e-e+ These are the scientific notation operators, which display the number inscientific 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 negativeexponents. Using E- or e- places a – in front of negative exponents andnothing in front of positive exponents.

: This is the time separator.

Separates hours, minutes, and seconds when time values are being formatted.The actual character used depends on the character specified by your locale.

/ This is the date separator.

Separates months, days, and years when date values are being formatted. Theactual character used depends on the character specified by your locale.

-+$()space These are the literal characters you can display.

To display any other character, you should precede it with a backslash orenclose it in quotes.

\ This designates the next character as a displayed character.

To display characters, precede them with a backslash. To display a backslash,use two backslashes. Double quotation marks can also be used to displaycharacters. Numeric formatting characters, date/time formatting characters,and string formatting characters cannot be displayed without a precedingbackslash.

Page 251: Working Model 2D - User's Manual

Chapter 2 Format, Format$ (functions) 247

"ABC" Displays the text between the quotation marks, but not the quotation marks.To designate a double quotation mark within a format string, use twoadjacent double quotation marks.

* This will display the next character as the fill character.

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 asemicolon. If you specify one format, it applies to all values. If you specifytwo formats, the first applies to positive values and the second to negativevalues. If you specify three formats, the first applies to positive values, thesecond to negative values, and the third to 0s. If you include semicolons withno format between them, the format for positive values is used.

String FormatsCharacter 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 unlessthe 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 unlessthe 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 defaultis right to left.

Date/Time FormatsCharacter Meaning

c Displays the date as ddddd and the time as ttttt. Only the date is displayedif no fractional part exists in the numeric expression. Only the time isdisplayed if no integral portion exists in the numeric expression.

d Displays the day without a leading 0 (1–31).

dd Displays the day with a leading 0 (01–31).

ddd Displays the day of the week abbreviated (Sun–Sat).

Page 252: Working Model 2D - User's Manual

248 Working Model Basic User's Manual

dddd Displays the day of the week (Sunday–Saturday).

ddddd Displays the date as a short date.

dddddd Displays the date as a long date.

w Displays the number of the day of the week (1–7). Sunday is 1; Saturday is 7.

ww Displays the week of the year (1–53).

m Displays the month without a leading 0 (1–12). If m immediately follows h orhh, m is treated as minutes (0–59).

mm Displays the month with a leading 0 (01–12). If mm immediately follows h orhh, mm is treated as minutes with a leading 0 (00–59).

mmm Displays the month abbreviated (Jan–Dec).

mmmm Displays the month (January–December).

q Displays the quarter of the year (1–4).

y Displays the day of the year (1–366).

yy Displays the year, not the century (00–99).

yyyy Displays the year (1000–9999).

h Displays the hour without a leading 0 (0–24).

hh Displays the hour with a leading 0 (00–24).

n Displays the minute without a leading 0 (0–59).

nn Displays the minute with a leading 0 (00–59).

s Displays the second without a leading 0 (0–59).

ss Displays the second with a leading 0 (00–59).

ttttt Displays the time. A leading 0 is displayed if specified by your locale.

AM/PM Displays the time using a 12-hour clock. Displays an uppercase AM for timevalues before 12 noon. Displays an uppercase PM for time values after 12noon and before 12 midnight.

am/pm Displays the time using a 12-hour clock. Displays a lowercase am or pm at theend.

A/P Displays the time using a 12-hour clock. Displays an uppercase A or P at theend.

a/p Displays the time using a 12-hour clock. Displays a lowercase a or p at theend.

Page 253: Working Model 2D - User's Manual

Chapter 2 FreeFile (function) 249

AMPM Displays the time using a 12-hour clock. Displays the string s1159 for valuesbefore 12 noon and s2359 for values after 12 noon and before 12 midnight.

Example Const crlf = Chr$(13) + Chr$(10)

Sub Main()a# = 1199.234msg = "Some general formats for '" & a# & "' are:"msg = msg & Format$(a#,"General Number") & crlfmsg = msg & Format$(a#,"Currency") & crlfmsg = msg & Format$(a#,"Standard") & crlfmsg = msg & Format$(a#,"Fixed") & crlfmsg = msg & Format$(a#,"Percent") & crlfmsg = msg & Format$(a#,"Scientific") & crlfmsg = msg & Format$(True,"Yes/No") & crlfmsg = msg & Format$(True,"True/False") & crlfmsg = msg & Format$(True,"On/Off") & crlfmsg = msg & Format$(a#,"0,0.00") & crlfmsg = msg & Format$(a#,"##,###,###.###") & crlfMsgBox msg

da$ = Date$msg = "Some date formats for '" & da$ & "' are:"msg = msg & Format$(da$,"General Date") & crlfmsg = msg & Format$(da$,"Long Date") & crlfmsg = msg & Format$(da$,"Medium Date") & crlfmsg = msg & Format$(da$,"Short Date") & crlfMsgBox msg

ti$ = Time$msg = "Some time formats for '" & ti$ & "' are:"msg = msg & Format$(ti$,"Long Time") & crlfmsg = msg & Format$(ti$,"Medium Time") & crlfmsg = msg & Format$(ti$,"Short Time") & crlfMsgBox msg

End Sub

See Also Str, Str$ (functions); CStr (function).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Under Windows, default date/time formats are read from the [Intl]section of the win.ini file.

FreeFile (function)Syntax FreeFile[()]

Description Returns an Integer containing the next available file number.

Comments The number returned is suitable for use in the Open statement and will alwaysbe between 1 and 255 inclusive.

Page 254: Working Model 2D - User's Manual

250 Working Model Basic User's Manual

Example 'This example assigns A to the next free file number and displays it'in a dialog box.

Sub Main()a = FreeFileMsgBox "The next free file number is: " & a

End Sub

See Also FileAttr (function); Open (statement).

Platform(s) Windows and Macintosh.

Function...End Function (statement)Syntax [Private | Public] [Static] Function name[(arglist)] [As ReturnType]

[statements]End Sub

where arglist is a comma-separated list of the following (up to 30 argumentsare allowed):

[Optional] [ByVal | ByRef] parameter [()] [As type]

Description Creates a user-defined function.

Page 255: Working Model 2D - User's Manual

Chapter 2 Function...End Function (statement) 251

Comments The Function statement has the following parts:

Part Description

Private Indicates that the function being defined cannot be called from other scripts.

Public Indicates that the function being defined can be called from other scripts. Ifboth the Private and Public keywords are missing, then Public is assumed.

Static Recognized by the compiler but currently has no effect.

name Name of the function, which must follow WM Basic naming conventions:

1. Must start with a letter.

2. May contain letters, digits, and the underscore character(_). Punctuation and type-declaration characters are notallowed. The exclamation point (!) can appear within thename as long as it is not the last character, in which caseit is interpreted as a type-declaration character.

3. Must not exceed 80 characters in length.

Additionally, the name parameter can end with an optional type-declarationcharacter specifying the type of data returned by the function (i.e., any of thefollowing characters: %, &, !, #, @).

Optional Keyword indicating that the parameter is optional. All optional parameters mustbe of type Variant. Furthermore, all parameters that follow the first optionalparameter must also be optional.

If this keyword is omitted, then the parameter is required.

Note: You can use the IsMissing function to determine if an optionalparameter was actually passed by the caller.

ByVal Keyword indicating that parameter is passed by value.

Page 256: Working Model 2D - User's Manual

252 Working Model Basic User's Manual

ByRef Keyword indicating that parameter is passed by reference. If neither the ByValnor the ByRef keyword is given, then ByRef is assumed.

parameter Name of the parameter, which must follow the same naming conventions asthose used by variables. This name can include a type-declaration character,appearing in place of As type.

type Type of the parameter (i.e., Integer, String, and so on). Arrays are indicatedwith parentheses. For example, an array of integers would be declared asfollows:

Function Test(a() As Integer)End Function

ReturnType Type of data returned by the function. If the return type is not given, thenVariant is assumed. The ReturnType can only be specified if the functionname (i.e., the name parameter) does not contain an explicit type-declarationcharacter.

A function returns to the caller when either of the following statements isencountered:

End FunctionExit Function

Functions can be recursive.

Returning Values from Functions

To assign a return value, an expression must be assigned to the name of thefunction, as shown below:

Function TimesTwo(a As Integer) As IntegerTimesTwo = a * 2

End Function

If no assignment is encountered before the function exits, then one of thefollowing values is returned:

Value Data Type Returned by the Function

0 Integer, Long, Single, Double, Currency

Zero-length string String

Nothing Object (or any data object)

Empty Variant

December 30, 1899 Date

False Boolean

Page 257: Working Model 2D - User's Manual

Chapter 2 Function...End Function (statement) 253

The type of the return value is determined by the As ReturnType clause on theFunction statement itself. As an alternative, a type-declaration character canbe added to the Function name. For example, the following two definitionsof Test both return String values:

Function Test() As StringTest = "Hello, world"

End Function

Function Test$()Test = "Hello, world"

End Function

Passing Parameters to Functions

Parameters are passed to a function either by value or by reference, dependingon the declaration of that parameter in arglist. If the parameter is declared usingthe ByRef keyword, then any modifications to that passed parameter within thefunction change the value of that variable in the caller. If the parameter isdeclared using the ByVal keyword, then the value of that variable cannot bechanged in the called function. If neither the ByRef or ByVal keywords arespecified, then the parameter is passed by reference.

You can override passing a parameter by reference by enclosing that parameterwithin parentheses. For instance, the following example passes the variable jby reference, regardless of how the third parameter is declared in the arglist ofUserFunction:

i = UserFunction(10,12,(j))

Page 258: Working Model 2D - User's Manual

254 Working Model Basic User's Manual

Optional Parameters

WM Basic allows you to skip parameters when calling functions, as shown inthe following example:

Function Test(a%,b%,c%) As VariantEnd Function

Sub Maina = Test(1,,4) 'Parameter 2 was skipped.

End Sub

You can skip any parameter with the following restrictions:

1. The call cannot end with a comma. For instance, using the above example,the following is not valid:

a = Test(1,,)

2. The call must contain the minimum number of parameters as requred by thecalled function. For instance, using the above example, the following areinvalid:

a = Test(,1) 'Only passes two out of three required parameters.a = Test(1,2)'Only passes two out of three required parameters.

When you skip a parameter in this manner, WM Basic creates a temporaryvariable and passes this variable instead. The value of this temporary variabledepends on the data type of the corresponding parameter in the argument list ofthe called function, as described in the following table:

Value Data Type

0 Integer, Long, Single, Double, Currency

Zero-length string String

Nothing Object (or any data object)

Error Variant

December 30, 1899 Date

False Boolean

Within the called function, you will be unable to determine if a parameter wasskipped unless the parameter was declared as a variant in the argument list ofthe function. In this case, you can use the IsMissing function to determine ifthe parameter was skipped:

Function Test(a,b,c)If IsMissing(a) Or IsMissing(b) Then Exit Sub

End Function

Page 259: Working Model 2D - User's Manual

Chapter 2 Fv (function) 255

Example Function Factorial(n%) As Integer'This function calculates N! (N-factoral).f% = 1For i = n To 2 Step -1

f = f * iNext iFactorial = f

End Function

Sub Main()'This example calls user-defined function Factoral and displays the'result in a dialog box.a% = 0Do While a% < 2

a% = Val(InputBox$("Enter an integer number greater than2.","Compute Factorial"))

Loopb# = Factorial(a%)MsgBox "The factoral of " & a% & " is: " & b#

End Sub

See Also Sub...End Sub (statement)

Platform(s) Windows and Macintosh.

Fv (function)Syntax Fv(Rate, Nper, Pmt,Pv,Due)

Description Calculates the future value of an annuity based on periodic fixed payments anda constant rate of interest.

Page 260: Working Model 2D - User's Manual

256 Working Model Basic User's Manual

Comments An annuity is a series of fixed payments made to an insurance company orother investment company over a period of time. Examples of annuities aremortgages 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 arenormalized 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 areentered 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, thepresent value would be the amount of the loan, whereas in the case of aretirement annuity, the present value would be the amount of the fund.

Due Integer indicating when payments are due for each payment period. A 0specifies payment at the end of each period, whereas a 1 indicates payment atthe start of each period.

Rate and NPer values must be expressed in the same units. If Rate is expressedas a percentage per month, then NPer must also be expressed in months. If Rateis an annual rate, then the NPer must also be given in years.

Positive numbers represent cash received, whereas negative numbers representcash 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 (function); MIRR (function); Npv (function); Pv (function).

Platform(s) Windows and Macintosh.

Get (statement)Syntax Get [#] filenumber, [recordnumber], variable

Description Retrieves data from a random or binary file and stores that data into thespecified variable.

Page 261: Working Model 2D - User's Manual

Chapter 2 Get (statement) 257

Comments The Get statement accepts the following parameters:

Parameter Description

filenumber Integer used by WM Basic to identify the file. This is the same number passedto 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 withthe beginning of the file (the first byte is 1). For random files, this numberrepresents the record number starting with the beginning of the file (the firstrecord 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). Whenthis parameter is omitted, the commas must still appear, as in the followingexample:

Get #1,,recvar

If recordnumber is specified, it overrides any previous change in file positionspecified with the Seek statement.

variable Variable into which data will be read. The type of the variable determines howthe data is read from the file, as described below.

With random files, a runtime error will occur if the length of the data being readexceeds the reclen parameter specified with the Open statement. If the lengthof the data being read is less than the record length, the file pointer is advancedto the start of the next record. With binary files, the data elements being readare contiguousthe file pointer is never advanced.

Variable Types

The type of the variable parameter determines how data will be read from thefile. It can be any of the following types:

Variable Type File Storage Description

Integer 2 bytes are read from the file.

Long 4 bytes are read from the file.

Page 262: Working Model 2D - User's Manual

258 Working Model Basic User's Manual

String (variable-length)In binary files, variable-length strings are read by firstdetermining the specified string variable's length andthen reading that many bytes from the file. Forexample, to read a string of eight characters:

s$ = String$(8," ")Get #1,,s$

In random files, variable-length strings are read byfirst reading a 2-byte length and then reading thatmany characters from the file.

String (fixed-length) Fixed-length strings are read by reading a fixednumber of characters from the file equal to the string'sdeclared length.

Double 8 bytes are read from the file (IEEE format).

Single 4 bytes are read from the file (IEEE format).

Date 8 bytes are read from the file (IEEE double format).

Boolean 2 bytes are read from the file. Nonzero values areTrue, and zero values are False.

Variant A 2-byte VarType is read from the file, whichdetermines the format of the data that follows. Oncethe VarType is known, the data is read individually, asdescribed above. With user-defined errors, after the 2-byte VarType, a 2-byte unsigned integer is read andassigned as the value of the user-defined error,followed by 2 additional bytes of information aboutthe error.

The exception is with strings, which are alwayspreceded by a 2-byte string length.

User-defined types Each member of a user-defined data type is readindividually.

In binary files, variable-length strings within user-defined types are read by first reading a 2-byte lengthfollowed by the string's content. This storage isdifferent from variable-length strings outside of user-defined types.

When reading user-defined types, the record lengthmust be greater than or equal to the combined size ofeach element within the data type.

Arrays Arrays cannot be read from a file using the Getstatement.

Page 263: Working Model 2D - User's Manual

Chapter 2 GetAttr (function) 259

Objects Object variables cannot be read from a file using theGet 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 #1For x = 1 to 10

y% = x * 10Put #1,x,y

Next xClose

Open "test.dat" For Random Access Read As #1For y = 1 to 5

Get #1,y,x%msg = msg & "Record " & y & ": " & x% & Basic.Eoln$

Next y

MsgBox msgClose

End Sub

See Also Open (statement); Put (statement); Input# (statement); Line Input#(statement); Input, Input$ (functions).

Platform(s) Windows and Macintosh.

GetAttr (function)Syntax GetAttr(filename$)

Description Returns an Integer containing the attributes of the specified file.

Page 264: Working Model 2D - User's Manual

260 Working Model Basic User's Manual

Comments The attribute value returned is the sum of the attributes set for the file. Thevalue of each attribute is as follows:

Constant Value Includes

ebNormal 0 Read-only files, archive files,subdirectories,

and files with no attributes.ebReadOnly 1 Read-only filesebHidden 2 Hidden filesebSystem 4 System filesebVolume 8 Volume labelebDirectory 16 DOS subdirectoriesebArchive 32 Files that have changed since the lastbackupebNone 64 Files with no attributes

To deterimine whether a particular attribute is set, you can And the valuesshown above with the value returned by GetAttr. If the result is True, theattribute is set, as shown below:

Dim w As Integerw = GetAttr("sample.txt")If w And ebReadOnly Then MsgBox "This file is read-only."

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()If Not FileExists("test.dat") Then

Open "test.dat" For Random Access Write As #1Close

End If

y% = GetAttr("test.dat")If y% And ebNone Then msg = msg & "No archive bit is set." & crlfIf y% And ebReadOnly Then msg = msg & "The read-only bit is set." &

crlfIf y% And ebHidden Then msg = msg & "The hidden bit is set." & crlfIf y% And ebSystem Then msg = msg & "The system bit is set." & crlfIf y% And ebVolume Then msg = msg & "The volume bit is set." & crlfIf y% And ebDirectory Then msg = msg & "The directory bit is set."

& crlfIf y% And ebArchive Then msg = msg & "The archive bit is set."

MsgBox msgKill "test.dat"

End Sub

Page 265: Working Model 2D - User's Manual

Chapter 2 GetCheckBox (function) 261

See Also SetAttr (statement); FileAttr (function).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Under Windows, these attributes are the same as those used by DOS.

GetCheckBox (function)Syntax GetCheckBox(name$ | id)

Description Returns an Integer representing the state of the specified check box.

Comments This function is used to determine the state of a check box, given its name orID. The returned value will be one of the following:

Returned Value Description

0 Check box contains no check.

1 Check box contains a check.

2 Check box is grayed.

The GetCheckBox function takes the following parameters:

Parameter Description

name$ String containing the name of the check box.

id Integer specifying the ID of the check box.

Note: The GetCheckBox function is used to retrieve the state of a check box inanother application's dialog box. Use the DlgValue function to retrieve the stateof a check box in a dynamic dialog box.

Example 'This example toggles the Match Case check box in the Find dialog box.

Sub Main()Menu "Search.Find"If GetCheckBox("Match Case") = 0 Then

SetCheckBox "Match Case",1Else

SetCheckBox "Match Case",0End If

End Sub

See Also CheckBoxExists (function); CheckBoxEnabled (function); SetCheckBox(statement); DlgValue (function).

Platform(s) Windows.

Page 266: Working Model 2D - User's Manual

262 Working Model Basic User's Manual

GetComboBoxItem$ (function)Syntax GetComboBoxItem$(name$ | id [,ItemNumber])

Description Returns a String containing the text of an item within a combo box.

Comments The GetComboBoxItem$ function takes the following parameters:

Parameter Description

name$ String specifying the name of the combo box containing the item to bereturned.

The name of a combo box is determined by scanning the window list lookingfor a text control with the given name that is immediately followed by a combobox. A runtime error is generated if a combo box with that name cannot befound within the active window.

id Integer specifying the ID of the combo box containing the item to be returned.

ItemNumber Integer containing the line number of the desired combo box item to bereturned. If omitted, then the currently selected item in the combo box isreturned.

The combo box must exist within the current window or dialog box; otherwise,a runtime error is generated.

A zero-length string will be returned if the combo box does not contain textualitems.

Note: The GetComboBoxItem$ function is used to retrieve the current item of acombo box in another application's dialog box. Use the DlgText function toretrieve the current item of a combo box in a dynamic dialog box.

Example 'This example retrieves the last item from a combo box.

Sub Main()last% = GetComboBoxItemCount("Directories:")s$ = GetComboBoxItem$("Directories:",last% - 1) 'Number is 0-

basedMsgBox "The last item in the combo box is " & s$

End Sub

See Also ComboBoxEnabled (function); ComboBoxExists (function);GetComboBoxItemCount (function); SelectComboBoxItem (statement).

Platform(s) Windows.

GetComboBoxItemCount (function)Syntax GetComboBoxItemCount(name$ | id)

Page 267: Working Model 2D - User's Manual

Chapter 2 GetEditText$ (function) 263

Description Returns an Integer containing the number of items in the specified combobox.

Comments The GetComboBoxItemCount function takes the following parameters:

Parameter Description

name$ String containing the name of the combo box.

The name of a combo box is determined by scanning the window list lookingfor a text control with the given name that is immediately followed by a combobox. A runtime error is generated if a combo box with that name cannot befound within the active window.

id Integer specifying the ID of the combo box.

A runtime error is generated if the specified combo box does not exist withinthe current window or dialog box.

Note: The GetComboBoxItemCount function is used to determine the numberof items in a combo box in another application's dialog box. There is noequivalent function for use with dynamic dialog boxes.

Example 'This example copies all the items out of a combo box and into an'array.

Sub Main()Dim MyList$()last% = GetComboBoxItemCount("Directories:")ReDim MyList$(0 To last - 1)For i = 0 To last - 1

MyList$(i) = GetComboBoxItem$("Directories:",i)Next i

End Sub

See Also ComboBoxEnabled (function); ComboBoxExists (function); GetComboBoxItem$(function); SelectComboBoxItem (statement).

Platform(s) Windows.

GetEditText$ (function)Syntax GetEditText$(name$ | id)

Description Returns a String containing the content of the specified text box control.

Page 268: Working Model 2D - User's Manual

264 Working Model Basic User's Manual

Comments The GetEditText$ function takes the following parameters:

Parameter Description

name$ String containing the name of the text box whose content will be returned.

The name of a text box is determined by scanning the window list looking for atext control with the given name that is immediately followed by a text box. Aruntime error is generated if a text box with that name cannot be found withinthe active window.

id Integer specifying the ID of the text box whose content will be returned.

A runtime error is generated if a text box control with the given name or IDcannot be found within the active window.

Note: The GetEditText$ function is used to retrieve the content of a text boxin another application's dialog box. Use the DlgText$ function to retrieve thecontent of a text box in a dynamic dialog box.

Example 'This example retrieves the filename and prepends it with the current'directory.

Sub Main()s$ = GetEditText$("Filename:") 'Retrieve the content of

the edit control.s$ = CurDir$ & Basic.PathSeparator & s$ 'Prepend the current

directory.SetEditText "Filename:",s$ 'Put it back.

End Sub

See Also EditEnabled (function); EditExists (function); SetEditText (statement).

Platform(s) Windows.

GetListBoxItem$ (function)Syntax GetListBoxItem$(name$ | id,[item])

Description Returns a String containing the specified item in a list box.

Page 269: Working Model 2D - User's Manual

Chapter 2 GetListBoxItemCount (function) 265

Comments The GetListBoxItem$ function takes the following parameters:

Parameter Description

name$ String specifying the name of the list box containing the item to be returned.

The name of a list box is determined by scanning the window list looking for atext control with the given name that is immediately followed by a list box. Aruntime error is generated if a list box with that name cannot be found withinthe active window.

id Integer specifying the ID of the list box containing the item to be returned.

item Integer containing the line number of the desired list box item to be returned.This number must be between 1 and the number of items in the list box.

If omitted, then the currently selected item in the list box is returned.

A runtime error is generated if the specified list box cannot be found within theactive window.

Note: The GetListBoxItem$ function is used to retreive an item from a listbox in another application's dialog box. There is no equivalent function for usewith dynamic dialog boxes.

Example 'This example sees whether my name appears as an item in the "Users"'list box.

Sub Main()last% = GetListBoxItemCount("Users")IsThere = FalseFor i = 0 To last% - 1 'Number is zero-based.

If GetListBoxItem$("Users",i) = Net.User$ Then isThere = TrueNext iIf IsThere Then MsgBox "I am a member!",ebOKOnly

End Sub

See Also GetListBoxItemCount (function); ListBoxEnabled (function);ListBoxExists (function); SelectListBoxItem (statement).

Platform(s) Windows.

GetListBoxItemCount (function)Syntax GetListBoxItemCount(name$ | id)

Description Returns an Integer containing the number of items in a specified list box.

Page 270: Working Model 2D - User's Manual

266 Working Model Basic User's Manual

Comments The GetListBoxItemCount function takes the following parameters:

Parameter Description

name$ String containing the name of the list box.

The name of a list box is determined by scanning the window list looking for atext control with the given name that is immediately followed by a list box. Aruntime error is generated if a list box with that name cannot be found withinthe active window.

id Integer specifying the ID of the list box.

A runtime error is generated if the specified list box cannot be found within theactive window.

Note: The GetListBoxItemCount function is used to retrieve the number ofitems in a list box in another application's dialog box. There is no equivalentfunction for use with dynamic dialog boxes.

Example See GetListBoxItem$ (function).

See Also GetListBoxItem$ (function); ListBoxEnabled (function); ListBoxExists(function); SelectListBoxItem (statement).

Platform(s) Windows.

GetObject (function)Syntax GetObject(filename$ [,class$])

Description Returns the object specified by filename$ or returns a previously instantiatedobject of the given class$.

Page 271: Working Model 2D - User's Manual

Chapter 2 GetObject (function) 267

Comments This function is used to retrieve an existing OLE automation object, either onethat comes from a file or one that has previously been instantiated.

The filename$ argument specifies the full pathname of the file containing theobject to be activated. The application associated with the file is determined byOLE at runtime. For example, suppose that a file calledc:\docs\resume.doc was created by a word processor calledwordproc.exe. The following statement would invoke wordproc.exe,load the file called c:\docs\resume.doc, and assign that object to avariable:

Dim doc As ObjectSet doc = GetObject("c:\docs\resume.doc")

To activate a part of an object, add an exclamation point to the filenamefollowed 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 previousexample:

Dim doc As ObjectSet doc = GetObject("c:\docs\resume.doc!P1-P3")

The GetObject function behaves differently depending on whether the firstparameter is omitted. The following table summarizes the different beheviors ofGetObject:

Filename$ Class$ GetObject Returns

Omitted Specified Reference to an existing instance of the specifiedobject. A runtime error results if the object is notalready loaded.

"" Specified Reference to a new object (as specified byclass$). A runtime error occurs if an object ofthe specified class cannot be found.

This is the same as CreateObject.

Specified Omitted Default object from filename$. The applicationto activate is determined by OLE based on thegiven filename.

Specified Specified Object given by class$ from the file given byfilename$. A runtime error occurs if an object ofthe given class cannot be found in the given file.

Page 272: Working Model 2D - User's Manual

268 Working Model Basic User's Manual

Examples 'This first example instantiates the existing copy of Excel.

Dim Excel As ObjectSet Excel = GetObject(,"Excel.Application")

'This second example loads the OLE server associated with a document.

Dim MyObject As ObjectSet MyObject = GetObject("c:\documents\resume.doc",)

See Also CreateObject (function); Object (data type).

Platform(s) Windows and Macintosh.

GetOption (function)Syntax GetOption(name$ | id)

Description Returns True if the option is set; returns False otherwise.

Comments The GetOption function takes the following parameters:

Parameter Description

name$ String containing the name of the option button.

id Integer containing the ID of the option button. The id must be used when thename of the option button is not known in advance.

The option button must exist within the current window or dialog box.

A runtime error will be generated if the specified option button does not exist.

Note: The GetOption function is used to retrieve the state of an option buttonin another application's dialog box. Use the DlgValue function to retrieve thestate of an option button in a dynamic dialog box.

Example 'This example figures out which option is set in the Desktop dialog'box of the Control Panel.

Sub Main()id = Shell("control",7) 'Run the Control Panel.WinActivate "Control Panel" 'Activate the Control Panel

window.Menu "Settings.Desktop" 'Select Desktop dialog box.WinActivate "Control Panel|Desktop" 'Activate it.If GetOption("Tile") Then 'Retrieve which option is

set.MsgBox "Your wallpaper is tiled." 'The Tile option is

currently set.Else

MsgBox "Your wallpaper is centered." 'The Centered option iscurrently set.

End IfEnd Sub

Page 273: Working Model 2D - User's Manual

Chapter 2 Global (statement) 269

See Also OptionEnabled (function); OptionExists (function); SetOption (statement).

Platform(s) Windows.

Global (statement)DescriptionSee Public (statement).

Platform(s) Windows and Macintosh.

GoSub (statement)Syntax GoSub label

Description Causes execution to continue at the specified label.

Comments Execution can later be returned to the statement following the GoSub by usingthe 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.

Page 274: Working Model 2D - User's Manual

270 Working Model Basic User's Manual

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 CheckNameMsgBox "Hello, " & uname$Exit Sub

CheckName:If (uname$ = "") Then

GoSub BlankNameElseIf uname$ = "MICHAEL" Then

GoSub RightNameElse

GoSub OtherNameEnd IfReturn

BlankName:MsgBox "No name? Clicked Cancel? I'm shutting down."Exit Sub

RightName:Return

OtherName:MsgBox "I am renaming you MICHAEL!"uname$ = "MICHAEL"Return

End Sub

See Also Goto (statement); Return (statement).

Platform(s) Windows and Macintosh.

Goto (statement)Syntax Goto label

Description Transfers execution to the line containing the specified label.

Page 275: Working Model 2D - User's Manual

Chapter 2 Goto (statement) 271

Comments 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:

1. Must begin with a letter.

2. May contain letters, digits, and the underscore character.

3. Must not exceed 80 characters in length.

4. Must be followed by a colon (:).

Labels are not case-sensitive.

Example 'This example gets a name from the user and then branches to a'statement, depending on the input name. If the name is not MICHAEL,'it is reset to MICHAEL unless it is null or the user clicks Cancel--'in which case, the program displays a message and terminates.

Sub Main()uname$ = Ucase$(InputBox$("Enter your name:","Enter Name"))If uname$ = "MICHAEL" Then

Goto RightNameElse

Goto WrongNameEnd If

WrongName:If (uname$ = "") Then

MsgBox "No name? Clicked Cancel? I'm shutting down."Else

MsgBox "I am renaming you MICHAEL!"uname$ = "MICHAEL"Goto RightName

End IfExit Sub

RightName:MsgBox "Hello, MICHAEL!"

End Sub

See Also GoSub (statement); Call (statement).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

To break out of an infinite loop, press Ctrl+Break.

PlatformNotes:

Macintosh

To break out of an infinite loop, press Ctrl+Period.

Page 276: Working Model 2D - User's Manual

272 Working Model Basic User's Manual

GroupBox (statement)Syntax GroupBox X,Y,width,height,title$ [,.Identifier]

Description Defines a group box within a dialog box template.

Comments This statement can only appear within a dialog box template (i.e., between theBegin Dialog and End Dialog statements).

The group box control is used for static display onlythe user cannot interactwith a group box control.

Separator lines can be created using group box controls. This is accomplishedby creating a group box that is wider than the width of the dialog box andextends below the bottom of the dialog boxi.e., three sides of the group boxare not visible.

If title$ is a zero-length string, then the group box is drawn as a solid rectanglewith no title.

The GroupBox statement requires the following parameters:

Parameter Description

X, Y Integer coordinates specifying the position of the control (in dialog units)relative to the upper left corner of the dialog box.

width, height Integer coordinates specifying the dimensions of the control in dialog units.

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 bereferenced by statements in a dialog function (such as DlgFocus andDlgEnable). 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",.ShowToolbarCheckBox 12,28,68,8,"Show &Status Bar",.ShowStatusBarGroupBox -12,52,152,48," ",.SeparatorLineOKButton 16,64,40,14,.OKCancelButton 68,64,40,14,.Cancel

End DialogDim OptionsDialog As OptionsTemplateDialog OptionsDialog

End Sub

Page 277: Working Model 2D - User's Manual

Chapter 2 Hex, Hex$ (functions) 273

See Also CancelButton (statement); CheckBox (statement); ComboBox (statement);Dialog (function); Dialog (statement); DropListBox (statement); ListBox(statement); OKButton (statement); OptionButton (statement); OptionGroup(statement); Picture (statement); PushButton (statement); Text (statement);TextBox (statement); Begin Dialog (statement), PictureButton (statement).

Platform(s) Windows and Macintosh.

Hex, Hex$ (functions)Syntax Hex[$](number)

Description Returns a String containing the hexadecimal equivalent of number.

Comments Hex$ returns a String, whereas Hex returns a String variant.

The returned string contains only the number of hexadecimal digits necessary torepresent the number, up to a maximum of eight.

The number parameter can be any type but is rounded to the nearest wholenumber before converting to hex. If the passed number is an integer, then amaximum of four digits are returned; otherwise, up to eight digits can bereturned.

The number parameter can be any expression convertible to a number. Ifnumber is Null, then Null is returned. Empty is treated as 0.

Example 'This example inputs a number and displays it in decimal and'hex until the input number is 0 or an invalid input.

Sub Main()Do

xs$ = InputBox$("Enter a number to convert:","Hex Convert")x = Val(xs$)If x <> 0 Then

MsgBox "Dec: " & x & " Hex: " & Hex$(x)Else

MsgBox "Goodbye."End If

Loop While x <> 0End Sub

See Also Oct, Oct$ (functions).

Platform(s) Windows and Macintosh.

HLine (statement)Syntax HLine [lines]

Description Scrolls the window with the focus left or right by the specified number of lines.

Page 278: Working Model 2D - User's Manual

274 Working Model Basic User's Manual

Comments The lines parameter is an Integer specifying the number of lines to scroll. Ifthis 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 (statement); HScroll (statement).

Platform(s) Windows.

Hour (function)Syntax Hour(time)

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.

Example 'This example takes the current time; extracts the hour,'minute, and second; and displays them as the current time.

Sub Main()xt# = TimeValue(Time$())xh# = Hour(xt#)xm# = Minute(xt#)xs# = Second(xt#)MsgBox "The current time is: " & xh# & ":" & xm# & ":" & xs#

End Sub

See Also Day (function); Minute (function); Second (function); Month (function); Year(function); Weekday (function); DatePart (function).

Platform(s) Windows and Macintosh.

HPage (statement)Syntax HPage [pages]

Description Scrolls the window with the focus left or right by the specified number ofpages.

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.

Page 279: Working Model 2D - User's Manual

Chapter 2 HScroll (statement) 275

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 (statement); HScroll (statement).

Platform(s) Windows.

HScroll (statement)Syntax HScroll percentage

Description Sets the thumb mark on the horizontal scroll bar attached to the currentwindow.

Comments The position is given as a percentage of the total range associated with thatscroll bar. For example, if the percentage parameter is 50, then the thumb markis 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 (statement); HPage (statement).

Platform(s) Windows.

HWND (object)Syntax Dim name As HWND

Description A data type used to hold window objects.

Comments This data type is used to hold references to physical windows in the operatingenvironment. The following commands operate on HWND objects:

WinActivate WinClose WinFind WinListWinMaximize WinMinimize WinMove WinRestoreWinSize

The above language elements support both string and HWND windowspecifications.

Page 280: Working Model 2D - User's Manual

276 Working Model Basic User's Manual

Example 'This example activates the "Main" MDI window within Program Manager.

Sub Main()Dim ProgramManager As HWNDDim ProgramManagerMain As HWNDSet ProgramManager = WinFind("Program Manager")If ProgramManager Is Not Nothing Then

WinActivate ProgramManagerWinMaximize ProgramManagerSet ProgramManagerMain = WinFind("Program Manager|Main")If ProgramManagerMain Is Not Nothing Then

WinActivate ProgramManagerMainWinRestore ProgramManagerMain

ElseMsgBox "Your Program Manager doesn't have a Main group."

End IfElse

MsgBox "Program Manager is not running."End If

End Sub

See Also HWND.Value (property); WinFind (function); WinActivate (function).

Platform(s) Windows.

HWND.Value (property)Syntax window.Value

Description The default property of an HWND object that returns a Variant containing aHANDLE to the physical window of an HWND object variable.

Comments The Value property is used to retrieve the operating environment–specificvalue of a given HWND object. The size of this value depends on the operatingenvironment in which the script is executing and thus should always be placedinto a Variant variable.

This property is read-only.

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$,ByValClsNameLen%)

Sub Main()Dim ProgramManager As HWNDSet ProgramManager = WinFind("Program Manager")ClassName$ = Space(40)GetClassName ProgramManager.Value,ClassName$,Len(ClassName$)MsgBox "The program classname is: " & ClassName$

End Sub

Page 281: Working Model 2D - User's Manual

Chapter 2 If...Then...Else (statement) 277

See Also HWND (data type).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, this value is an Integer.

If...Then...Else (statement)Syntax 1 If condition Then statements [Else else_statements]

Syntax 2 If condition Then [statements][ElseIf else_condition Then [elseif_statements]][Else [else_statements]]End If

Description Conditionally executes a statement or group of statements.

Comments The single-line conditional statement (syntax 1) has the following parameters:

Parameter Description

condition Any expression evaluating to a Boolean value.

statements One or more statements separated with colons. This group of statements isexecuted when condition is True.

else_statements One or more statements separated with colons. This group of statements isexecuted when condition is False.

Page 282: Working Model 2D - User's Manual

278 Working Model Basic User's Manual

The multiline conditional statement (syntax 2) has the following parameters:

Parameter Description

condition Any expression evaluating to a Boolean value.

statements One or more statements to be executed when condition is True.

else_condition Any expression evaluating to a Boolean value. The else_condition is evaluatedif condition is False.

elseif_statements One or more statements to be exected when condition is False andelse_condition is True.

else_statements One or more statements to be executed when both condition and else_conditionare False.

There can be as many ElseIf conditions as required.

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" ThenGoSub MikeNameExit Sub

End If

If uname$ = "" ThenMsgBox "Since you don't have a name, I'll call you MIKE!"uname$ = "MIKE"GoSub MikeName

ElseIf uname$ = "MICHAEL" ThenGoSub MikeName

ElseGoSub OtherName

End IfExit Sub

MikeName:MsgBox "Hello, MICHAEL!"Return

OtherName:MsgBox "Hello, " & uname$ & "!"Return

End Sub

See Also Choose (function); Switch (function); IIf (function); Select...Case(statement).

Page 283: Working Model 2D - User's Manual

Chapter 2 IIf (function) 279

Platform(s) Windows and Macintosh.

IIf (function)Syntax IIf(condition,TrueExpression,FalseExpression)

Description Returns TrueExpression if condition is True; otherwise, returnsFalseExpression.

Comments Both expressions are calculated before IIf returns.

The IIf function is shorthand for the following construct:

If condition Thenvariable = TrueExpression

Elsevariable = FalseExpression

End If

Example Sub Main()s$ = "Car"MsgBox IIf(s$ = "Car","Nice Car","Nice Automobile")

End Sub

See Also Choose (function); Switch (function); If...Then...Else (statement);Select...Case (statement).

Platform(s) Windows and Macintosh.

Imp (operator)Syntax expression1 Imp expression2

Description Performs a logical or binary implication on two expressions.

Page 284: Working Model 2D - User's Manual

280 Working Model Basic User's Manual

Comments If both expressions are either Boolean, Boolean variants, or Null variants,then a logical implication is performed as follows:

If the first and the second then theexpression is expression is result is

True True TrueTrue False FalseTrue Null NullFalse True TrueFalse False TrueFalse Null TrueNull True TrueNull False NullNull Null Null

Binary Implication

If the two expressions are Integer, then a binary implication is performed,returning an Integer result. All other numeric types (including Emptyvariants) 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 thebinary representations of the two expressions, according to the following table:

1 Imp1 = 1 Example:0 Imp1 = 1 5 011010011 Imp0 = 0 6 10101010 0 Imp0 = 1 Imp10111110

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) ThenMsgBox "a is less than b implies that c is less than d."

ElseMsgBox "a is less than b does not imply that c is less than d."

End If

If (a < b) Imp (c > d) ThenMsgBox "a is less than b implies that c is greater than d."

ElseMsgBox "a is less than b does not imply that c is greater than

d."End If

End Sub

Page 285: Working Model 2D - User's Manual

Chapter 2 Inline (statement) 281

See Also Operator Precedence (topic); Or (operator); Xor (operator); Eqv (operator); And(operator).

Platform(s) Windows and Macintosh.

Inline (statement)Syntax Inline name [parameters]

anytextEnd Inline

Description Allows execution or interpretation of a block of text.

Comments The Inline statement takes the following parameters:

Parameter Description

name Identifier specifying the type of inline statement.

parameters Comma-separated list of parameters.

anytext Text to be executed by the Inline statement. This text must be in a formatappropriate for execution by the Inline statement.

The end of the text is assumed to be the first occurrence of the words EndInline appearing on a line.

Example Sub Main()Inline MacScript

-- This is an AppleScript comment.BeepDisplay Dialog "AppleScript" buttons "OK" default button "OK"Display Dialog Current Date

End InlineEnd Sub

See Also MacScript (statement).

Platform(s) Windows and Macintosh.

Input# (statement)Syntax Input [#]filenumber%,variable[,variable]...

Description Reads data from the file referenced by filenumber into the given variables.

Comments Each variable must be type-matched to the data in the file. For example, aString variable must be matched to a string in the file.

The following parsing rules are observed while reading each variable in thevariable list:

1. Leading white space is ignored (spaces and tabs).

Page 286: Working Model 2D - User's Manual

282 Working Model Basic User's Manual

2. When reading String variables, if the first character on the line is aquotation mark, then characters are read up to the next quoation mark or theend of the line, whichever comes first. Blank lines are read as empty strings.If the first character read is not a quoation mark, then characters are read upto the first comma or the end of the line, whichever comes first. Stringdelimiters (quotes, comma, end-of-line) are not included in the returnedstring.

3. When reading numeric variables, scanning of the number stops when thefirst nonnumber character (such as a comma, a letter, or any otherunexpected character) is encountered. Numeric errors are ignored whilereading numbers from a file. The resultant number is automaticallyconverted to the same type as the variable into which the value will beplaced. If there is an error in conversion, then 0 is stored into the variable.

After reading the number, input is skipped up to the next delimiter—acomma, an end-of-line, or an end-of-file.

Numbers must adhere to any of the following syntaxes:

[-|+]digits[.digits][E[-|+]digits][!|#|%|&|@]

&Hhexdigits[!|#|%|&]

&[O]octaldigits[!|#|%|&|@]

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 tothe next delimiter (a comma, an end-of-line, or an end-of-file). If the inputmatches #FALSE#, then False is stored in the Boolean; otherwise Trueis stored.

5. When reading Date variables, the first character must be #; otherwise, aruntime error occurs. If the first character is #, then the input is scanned upto the next delimiter (a comma, an end-of-line, or an end-of-file). If theinput ends in a # and the text between the #'s can be correctly interpreted asa date, then the date is stored; otherwise, December 31, 1899, is stored.

Normally, dates that follow the universal date format are input fromsequential 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 and12, DD is a day between 1 and 31, HH is an hour between 0 and 23, MM isa minute between 0 and 59, and SS is a second between 0 and 59.

Page 287: Working Model 2D - User's Manual

Chapter 2 Input# (statement) 283

6. When reading Variant variables, if the data begins with a quotationmark, then a string is read consisting of the characters between the openingquotation mark and the closing quoation mark, end-of-line, or end-of-file.

If the input does not begin with a quotation mark, then input is scanned upto the next comma, end-of-line, or end-of-file and a determination is madeas to what data is being represented. If the data cannot be represented as anumber, Date, Error, Boolean, or Null, then it is read as a string.

The following table describes how special data is interpreted as variants:

Blank line Read as an Empty variant.

#NULL# Read as a Null variant.

#TRUE# Read as a Boolean variant.

#FALSE# Read as a Boolean variant.

#ERROR code# Read as a user-defined error.

#date# Read as a Date variant.

"text" Read as a String variant.

If an error occurs in interpretation of the data as a particular type, then thatdata is read as a String variant.

When reading numbers into variants, the optional type-declaration characterdetermines the VarType of the resulting variant. If no type-declarationcharacter is specified, then WM Basic will read the number according to thefollowing rules:

Rule 1: If the number contains a decimal point or an exponent, then thenumber is read as Currency. If there is an error converting to Currency,then the number is treated as a Double.

Rule 2: If the number does not contain a decimal point or an exponent, thenthe number is stored in the smallest of the following data types that mostaccurately represents that value: Integer, Long, Currency, Double.

7. End-of-line is interpreted as either a single line feed, a single carriagereturn, or a carriage-return/line-feed pair. Thus, text files from any platformcan be interpreted using this command.

Page 288: Working Model 2D - User's Manual

284 Working Model Basic User's Manual

The filenumber parameter is a number that is used by WM Basic to refer to theopen filethe number passed to the Open statement.

The filenumber must reference a file opened in Input mode. It is goodpractice to use the Write statement to write date elements to files read withthe Input statement to ensure that the variable list is consistent between theinput and output routines.

Example 'This example creates a file called test.dat and writes a series of'variables into it. Then the variables are read using the Input#'function.

Const crlf = Chr$(13) + Chr$(10)

Sub Main()Open "test.dat" For Output As #1Write #1,2112,"David","McCue","123-45-6789"Close

Open "test.dat" For Input As #1Input #1,x%,st1$,st2$,st3$msg = "Employee " & x% & " Information" & crlf & crlfmsg = msg & "First Name: " & st1$ & crlfmsg = msg & "Last Name: "& st2$ & crlfmsg = msg & "Social Security Number: " & sy3$MsgBox msgClose

Kill "test.dat"End Sub

See Also Open (statement); Get (statement); Line Input# (statement); Input, Input$(functions).

Platform(s) Windows and Macintosh.

Input, Input$ (functions)Syntax Input[$](numbytes,[#] filenumber)

Description Returns numbytes characters read from a given sequential file.

Page 289: Working Model 2D - User's Manual

Chapter 2 InputBox, InputBox$ (functions) 285

Comments Input$ returns a String, whereas Input returns a String variant.

The Input/Input$ functions require the following parameters:

Parameter Description

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 thesame number passed to the Open statement.

This function reads all characters, including spaces and end-of-lines.

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 #1Else

MsgBox "File not found or empty."Exit Sub

End If

If x& > 80 Thenins = Input(80,#1)

Elseins = Input(x,#1)

End IfCloseMsgBox "File length: " & x& & crlf & ins

End Sub

See Also Open (statement); Get (statement); Input# (statement); Line Input#(statement).

Platform(s) Windows and Macintosh.

InputBox, InputBox$ (functions)Syntax InputBox[$](prompt [,[title] [,[default] [,X,Y]]])

Description Displays a dialog box with a text box into which the user can type.

Page 290: Working Model 2D - User's Manual

286 Working Model Basic User's Manual

Comments The content of the text box is returned as a String (in the case ofInputBox$) 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 parameters:

Parameter Description

prompt Text to be displayed above the text box. The prompt parameter can containmultiple 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 isNull.

title Caption of the dialog box. If this parameter is omitted, then no title appears asthe 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 runtimeerror is generated if default is Null.

X, Y Integer coordinates, given in twips (twentieths of a point), specifying theupper left corner of the dialog box relative to the upper left corner of the screen.If the position is omitted, then the dialog box is positioned on or near theapplication executing the script.

Example Sub Main()s$ = InputBox$("File to copy:","Copy","sample.txt")

End Sub

See Also MsgBox (statement); AskBox$ (function); AskPassword$ (function);OpenFilename$ (function); SaveFilename$ (function); SelectBox (function);AnswerBox (function).

Platform(s) Windows and Macintosh.

InStr (function)Syntax InStr([start,] search, find [,compare])

Description Returns the first character position of string find within string search.

Page 291: Working Model 2D - User's Manual

Chapter 2 Int (function) 287

Comments The InStr function takes the following parameters:

Parameter Description

start Integer specifying the character position where searching begins. The startparameter must be between 1 and 32767.

If this parameter is omitted, then the search starts at the beginning (start = 1).

search Text to search. This can be any expression convertible to a String.

find Text for which to search. This can be any expression convertible to a String.

compare Integer controlling how string comparisons are performed:

0 String comparisons are case-sensitive.

1 String comparisons are case-insensitive.

Any other value A runtime error is produced.

If this parameter is omitted, then string comparisons use the current OptionCompare setting. If no Option Compare statement has been encountered, thenBinary is used (i.e., string comparisons are case-sensitive).

If the string is found, then its character position within search is returned, with1 being the character position of the first character. If find is not found, or startis greater than the length of search, or search is zero-length, then 0 is returned.

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(a$,"Stuart",1)If x% <> 0 Then

b$ = Mid$(a$,x%,6)MsgBox b$ & " was found."Exit Sub

ElseMsgBox "Stuart not found."

End IfEnd Sub

See Also Mid, Mid$ (functions); Option Compare (statement); Item$ (function); Word$(function); Line$ (function).

Platform(s) Windows and Macintosh.

Int (function)

Page 292: Working Model 2D - User's Manual

288 Working Model Basic User's Manual

Syntax Int(number)

Description Returns the integer part of number.

Comments This function returns the integer part of a given value by returning the firstinteger less than the number. The sign is preserved.

The Int function returns the same type as number, with the followingexceptions:

If number is Empty, then an Integer variant of value 0 is returned.

If number is a String, then a Double variant is returned.

If number is Null, then a Null variant is returned.

Example 'This example extracts the integer part of a number.

Sub Main()a# = -1234.5224b% = Int(a#)MsgBox "The integer part of -1234.5224 is: " & b%

End Sub

See Also Fix (function); CInt (function).

Platform(s) Windows and Macintosh.

Integer (data type)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 astructure, integers require 2 bytes of storage. When used with binary or randomfiles, 2 bytes of storage are required.

When passed to external routines, Integer values are sign-extended to thesize of an integer on that platform (either 16 or 32 bits) before pushing onto thestack.

The type-declaration character for Integer is %.

See Also Currency (data type); Date (data type); Double (data type); Long (data type),Object (data type), Single (data type), String (data type), Variant (datatype), Boolean (data type), DefType (statement), CInt (function).

Platform(s) Windows and Macintosh.

Page 293: Working Model 2D - User's Manual

Chapter 2 IPmt (function) 289

IPmt (function)Syntax IPmt(Rate, Per, Nper, Pv, Fv, Due)

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 orother investment company over a period of time. Examples of annuities aremortgages, 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 aremonthly, 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 theinterest payment. If you want to know the interest paid or received duringperiod 20 of an annuity, this value would be 20.

Nper Double representing the total number of payments in the annuity. This isusually expressed in months, and you should be sure that the interest rate givenabove is for the same period that you enter here.

Pv Double representing the present value of your annuity. In the case of a loan, thepresent value would be the amount of the loan because that is the amount ofcash you have in the present. In the case of a retirement plan, this value wouldbe the current value of the fund because you have a set amount of principal inthe plan.

Fv Double representing the future value of your annuity. In the case of a loan, thefuture value would be zero because you will have paid it off. In the case of asavings plan, the future value would be the balance of the account after allpayments are made.

Due Integer indicating when payments are due. If this parameter is 0, thenpayments are due at the end of each period (usually, the end of the month). Ifthis value is 1, then payments are due at the start of each period (the beginningof the month).

Rate and Nper must be in expressed in the same units. If Rate is expressed inpercentage paid per month, then Nper must also be expressed in months. If Rateis an annual rate, then the period given in Nper should also be in years or theannual 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.

Page 294: Working Model 2D - User's Manual

290 Working Model Basic User's Manual

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()For x = 1 to 10

ipm# = IPmt((.10/12),x,36,1000,0,1)msg = msg & Format(x,"00") & " : " & Format(ipm#," 0,0.00") &

crlfNext xMsgBox msg

End Sub

See Also NPer (function); Pmt (function); PPmt (function); Rate (function).

Platform(s) Windows and Macintosh.

IRR (function)Syntax IRR(ValueArray(),Guess)

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 investmentconsisting of a series of positive and/or negative cash flows over a period ofregular intervals. It is usually used to project the rate of return on a businessinvestment that requires a capital investment up front and a series ofinvestments 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 valuesare payments, and negative values are receipts.

There must be at least one positive and one negative value to indicate the initialinvestment (negative value) and the amount earned by the investment (positivevalue).

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 andcycles through the calculation adjusting Guess until the result is accurate within0.00001 percent. After 20 tries, if a result cannot be found, IRR fails, and theuser must pick a better guess.

Page 295: Working Model 2D - User's Manual

Chapter 2 Is (operator) 291

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 investmentmsg = valu#(1) & ", "

'Calculate the second through fifth months' sales.For x = 2 To 5

valu(x) = 100 + (x * 2) msg = msg & valu(x) & ", "

Next x

'Calcluate the sixth through twelfth months' sales.For x = 6 To 12

valu(x) = 100 + (x * 10)msg = msg & valu(x) & ", "

Next x

'Calcluate the equivalent investment return rate.retrn# = IRR(valu,.1)msg = "The values: " & crlf & msg & crlf & crlfMsgBox msg & "Return rate: " & Format(retrn#,"Percent")

End Sub

See Also Fv (function); MIRR (function); Npv (function); Pv (function).

Platform(s) Windows and Macintosh.

Is (operator)Syntax object Is [object | Nothing]

Description Returns True if the two operands refer to the same object; returns Falseotherwise.

Comments This operator is used to determine whether two object variables refer to thesame object. Both operands must be object variables of the same type (i.e., thesame data object type or both of type Object).

The Nothing constant can be used to determine whether an object variable isuninitialized:

If MyObject Is Nothing Then MsgBox "MyObject is uninitialized."

Uninitialized object variables reference no object.

Page 296: Working Model 2D - User's Manual

292 Working Model Basic User's Manual

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 ObjectOn Error Resume NextWinWord = CreateObject("word.basic")InsertDate WinWord

End Sub

See Also Operator Precedence (topic); Like (operator).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows,Macintosh

When comparing OLE automation objects, the Is operator will only returnTrue if the operands reference the same OLE automation object. This isdifferent from data objects. For example, the following use of Is (using theobject class called excel.application) returns True:

Dim a As ObjectDim b As Objecta = CreateObject("excel.application")b = aIf a Is b Then Beep

The following use of Is will return False, even though the actual objects maybe the same:

Dim a As ObjectDim b As Objecta = 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 aand b reference the same object, they may be treated as different objects byOLE 2.0 (this is dependent on the OLE 2.0 server application).

IsDate (function)Syntax IsDate(expression)

Description Returns True if expression can be legally converted to a date; returns Falseotherwise.

Page 297: Working Model 2D - User's Manual

Chapter 2 IsEmpty (function) 293

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 IfEnd Sub

See Also Variant (data type); IsEmpty (function); IsError (function); IsObject(function); VarType (function); IsNull (function).

Platform(s) Windows and Macintosh.

IsEmpty (function)Syntax IsEmpty(expression)

Description Returns True if expression is a Variant variable that has never beeninitialized; returns False otherwise.

Comments The IsEmpty function is the same as the following:

(VarType(expression) = ebEmpty)

Example Sub Main()Dim a As VariantIf IsEmpty(a) Then

a = 1.0# 'Give uninitialized data a Double value 0.0.MsgBox "The variable has been initialized to: " & a

ElseMsgBox "The variable was already initialized!"

End IfEnd Sub

See Also Variant (data type); IsDate (function); IsError (function); IsObject(function); VarType (function); IsNull (function).

Platform(s) Windows and Macintosh.

IsError (function)Syntax IsError(expression)

Description Returns True if expression is a user-defined error value; returns Falseotherwise.

Page 298: Working Model 2D - User's Manual

294 Working Model Basic User's Manual

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 VariantIf 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 Varianta = Div(10,12)If IsError(a) Then

MsgBox "The following error occurred: " & CStr(a)Else

MsgBox "The result is: " & aEnd If

End Sub

See Also Variant (data type); IsEmpty (function); IsDate (function); IsObject(function); VarType (function); IsNull (function).

Platform(s) Windows and Macintosh.

IsMissing (function)Syntax IsMissing(variable)

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 Optionalkeyword, IsMissing will always return True.

Page 299: Working Model 2D - User's Manual

Chapter 2 IsNull (function) 295

Example 'The following function runs an application and optionally minimizesit. If'the optional isMinimize parameter is not specified by the caller, thenthe'application is not minimized.

Sub Test(AppName As String,Optional isMinimize As Variant)app = Shell(AppName)If Not IsMissing(isMinimize) Then

AppMinimize appElse

AppMaximize appEnd If

End Sub

Sub MainTest "Notepad" 'Maximize this applicationTest "Notepad",True 'Mimimize this application

End Sub

See Also Declare (statement), Sub...End Sub (statement), Function...End Function(statement)

Platform(s) Windows and Macintosh.

IsNull (function)Syntax IsNull(expression)

Description Returns True if expression is a Variant variable that contains no valid data;returns False otherwise.

Comments The IsNull function is the same as the following:

(VarType(expression) = ebNull)

Example Sub Main()Dim a As Variant 'Initialized as EmptyIf IsNull(a) Then MsgBox "The variable contains no valid data."a = Empty * NullIf IsNull(a) Then MsgBox "Null propagated through the expression."

End Sub

See Also Empty (constant); Variant (data type); IsEmpty (function); IsDate (function);IsError (function); IsObject (function); VarType (function).

Platform(s) Windows and Macintosh.

IsNumeric (function)Syntax IsNumeric(expression)

Description Returns True if expression can be converted to a number; returns Falseotherwise.

Page 300: Working Model 2D - User's Manual

296 Working Model Basic User's Manual

Comments If passed a number or a variant containing a number, then IsNumeric alwaysreturns True.

If a String or String variant is passed, then IsNumeric will return Trueonly if the string can be converted to a number. The following syntaxes arerecognized as valid numbers:

&Hhexdigits[&|%|!|#|@]

&[O]octaldigits[&|%|!|#|@]

[-|+]digits[.[digits]][E[-|+]digits][!|%|&|#|@]

If an Object variant is passed, then the default property of that object isretrieved and one of the above rules is applied.

IsNumeric returns False if expression is a Date.

Example Sub Main()Dim s$ As Strings$ = InputBox("Enter a number.","Enter Number")

If IsNumeric(s$) ThenMsgBox "You did good!"

ElseMsgBox "You didn't do so good!"

End IfEnd Sub

See Also Variant (data type); IsEmpty (function); IsDate (function); IsError(function); IsObject (function); VarType (function); IsNull (function).

Platform(s) Windows and Macintosh.

IsObject (function)Syntax IsObject(expression)

Description Returns True if expression is a Variant variable containing an Object;returns False otherwise.

Page 301: Working Model 2D - User's Manual

Chapter 2 Item$ (function) 297

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 'WMBasic.

Sub Main()Dim v As VariantOn Error Resume NextSet v = GetObject(,"Excel.Application")

If IsObject(v) ThenMsgBox "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 (data type); IsEmpty (function); IsDate (function); IsError(function); VarType (function); IsNull (function).

Platform(s) Windows and Macintosh.

Item$ (function)Syntax Item$(text$,first,last [,delimiters$])

Description Returns all the items between first and last within the specified formatted textlist.

Comments The Item$ function takes the following parameters:

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 greaterthan 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 itemsbetween first and last are returned. If last is greater than the number of items intext$, 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 bechanged by specifying different delimiters in the delimiters$ parameter.

Page 302: Working Model 2D - User's Manual

298 Working Model Basic User's Manual

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 (function); Line$ (function); LineCount (function); Word$(function); WordCount (function).

Platform(s) Windows and Macintosh.

ItemCount (function)Syntax ItemCount(text$ [,delimiters$])

Description Returns an Integer containing the number of items in the specified delimitedtext.

Comments Items are substrings of a delimited text string. Items, by default, are separatedby commas and/or end-of-lines. This can be changed by specifying differentdelimiters in the delimiters$ parameter. For example, to parse items using abackslash:

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$,"/")msg = "The first lists contains: " & l1% & " items." & crlfmsg = msg & "The second list contains: " & l2% & " items."MsgBox msg

End Sub

See Also Item$ (function); Line$ (function); LineCount (function); Word$ (function);WordCount (function).

Platform(s) Windows and Macintosh.

Page 303: Working Model 2D - User's Manual

299

Keywords (topic)A keyword is any word or symbol recognized by WM Basic as part of thelanguage. All of the following are keywords:

Built-in subroutine names, such as MsgBox and Print.

Built-in function names, such as Str$, CDbl, and Mid$.

Special keywords, such as To, Next, Case, and Binary.

Names of any extended language elements.

Restrictions

All keywords are reserved by WM Basic, 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.

Platform(s) Windows and Macintosh.

Kill (statement)Syntax Kill filespec$

Description Deletes all files matching filespec$.

Page 304: Working Model 2D - User's Manual

300 Working Model Basic User's Manual

Comments The filespec$ argument can include wildcards, such as * and ?. The * charactermatches any sequence of zero or more characters, whereas the ? charactermatches any single character. Multiple *'s and ?'s can appear within theexpression to form complex searching patterns. The following table showssome examples.

This Pattern Matches These Files Doesn't Match These Files

*S*.TXT SAMPLE.TXT SAMPLEGOOSE.TXT SAMPLE.DATSAMS.TXT

C*T.TXT CAT.TXT CAP.TXTACATS.TXT

C*T CAT CAT.DOCCAP.TXT

C?T CAT CAT.TXTCUT CAPIT

CT

* (All files)

Example 'This example looks to see whether file test1.dat exists. If it doesnot,'then it creates both test1.dat and test2.dat. The existence of thefiles'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 #1Open "test2.dat" For Output As #2Close

End If

If FileExists ("test1.dat") ThenMsgBox "File test1.dat exists."Kill "test?.dat"

End If

If FileExists ("test1.dat") ThenMsgBox "File test1.dat still exists."

ElseMsgBox "test?.dat sucessfully deleted."

End IfEnd Sub

See Also Name (statement).

Page 305: Working Model 2D - User's Manual

Chapter 2 LBound (function) 301

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Notice that WM Basic’s filename matching is different than DOS's. The pattern"*.*" under DOS matches all files. With WM Basic, this pattern matches onlyfiles that have file extensions.

This function behaves the same as the "del" command in DOS.

PlatformNotes:

Macintosh

The Macintosh does not support wildcard characters such as * and ?. These arevalid filename characters. Instead of wildcards, the Macintosh uses the MacIDfunction to specify a collection of files of the same type. The syntax for thisfunction is:

Kill MacID(text$)

The text$ parameter is a four-character string containing a file type, a resourcetype, an application signature, or an Apple event. A runtime error occurs if theMacID function is used on platforms other than the Macintosh.

LBound (function)Syntax LBound(ArrayVariable() [,dimension])

Description Returns an Integer containing the lower bound of the specified dimension ofthe specified array variable.

Comments The dimension parameter is an integer specifying the desired dimension. If thisparameter is not specified, then the lower bound of the first dimension isreturned.

The LBound function can be used to find the lower bound of a dimension of anarray returned by an OLE automation method or property:

LBound(object.property [,dimension])

LBound(object.method [,dimension])

Page 306: Working Model 2D - User's Manual

302 Working Model Basic User's Manual

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

'This example uses LBound and UBound to dimension a dynamic arrayto

'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 xMsgBox "The last element of the new array is: " & nl$(count)

End IfEnd Sub

See Also UBound (function); ArrayDims (function); Arrays (topic).

Platform(s) Windows and Macintosh.

LCase, LCase$ (functions)Syntax LCase[$](text)

Description Returns the lowercase equivalent of the specified string.

Comments LCase$ returns a String, whereas LCase returns a String variant.

Null is returned if text is Null.

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

See Also UCase, UCase$ (functions).

Platform(s) Windows and Macintosh.

Page 307: Working Model 2D - User's Manual

Chapter 2 Left, Left$ (functions) 303

Left, Left$ (functions)Syntax Left[$](text,NumChars)

Description Returns the leftmost NumChars characters from a given string.

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 greaterthan or equal to the number of characters in the specified string, then the entirestring 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

See Also Right, Right$ (functions).

Platform(s) Windows and Macintosh.

Len (function)Syntax Len(expression)

Description Returns the number of characters in expression or the number of bytes requiredto store the specified variable.

Comments If expression evaluates to a string, then Len returns the number of characters ina 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 expressionis a Null, then Len returns a Null variant.

If used with a non-String or non-Variant variable, the function returns thenumber of bytes occupied by that data element.

Page 308: Working Model 2D - User's Manual

304 Working Model Basic User's Manual

When used with user-defined data types, the function returns the combined sizeof each member within the structure. Since variable-length strings are storedelsewhere, 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 Element Size

Integer 2 bytes.

Long 4 bytes.

Float 4 bytes.

Double 8 bytes.

Currency 8 bytes.

String (variable-length)Number of characters in the string.

String (fixed-length) The length of the string as it appears in the string'sdeclaration.

Objects 0 bytes. Both data object variables and variables oftype Object are always returned as 0 size.

User-defined type Combined size of each structure member.

Variable-length strings within structures require 2bytes of storage.

Arrays within structures are fixed in their dimensions.The elements for fixed arrays are stored within thestructure and therefore require the number of bytes foreach array element multiplied by the size of each arraydimension:

element_size * dimension1 * dimension2...

The Len function always returns 0 with object variables or any data objectvariable.

Page 309: Working Model 2D - User's Manual

Chapter 2 Let (statement) 305

Examples Const crlf = Chr$(13) + Chr$(10)

Sub Main()'This example shows the Len function used in a routine to change'uppercase names to lowercase with an uppercase first letter.

lname$ = "WILLIAMS"fl$ = Left$(lname$,1)ln% = Len(lname$)rest$ = Mid$(lname$,2,ln%)lname$ = fl$ & LCase$(rest$)MsgBox "The converted name is: " & lname$

'This example returns a table of lengths for standard numerictypes.

Dim lns(4)a% = 100 : b& = 200 : c! = 200.22 : d# = 300.22lns(1) = Len(a%)lns(2) = Len(b&)lns(3) = Len(c!)lns(4) = Len(d#)msg = "Lengths of standard types:" & crlfmsg = msg & "Integer: " & lns(1) & crlfmsg = msg & "Long: " & lns(2) & crlfmsg = msg & "Single: " & lns(3) & crlfmsg = msg & "Double: " & lns(4) & crlfMsgBox msg

End Sub

See Also InStr (function).

Platform(s) Windows and Macintosh.

Let (statement)Syntax [Let] variable = expression

Description Assigns the result of an expression to a variable.

Page 310: Working Model 2D - User's Manual

306 Working Model Basic User's Manual

Comments The use of the word Let is supported for compatibility with otherimplementations of WM Basic. Normally, this word is dropped.

When assigning expressions to variables, internal type conversions areperformed automatically between any two numeric quantities. Thus, you canfreely assign numeric quantities without regard to type conversions. However,it is possible for an overflow error to occur when converting from larger tosmaller types. This happens when the larger type contains a numeric quantitythat cannot be represented by the smaller type. For example, the following codewill produce a runtime error:

Dim amount As LongDim 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.

Example Sub Main()Let a$ = "This is a string."Let b% = 100Let c# = 1213.3443

End Sub

See Also = (keyword); Expression Evaluation (topic).

Platform(s) Windows and Macintosh.

Like (operator)Syntax expression Like pattern

Description Compares two strings and returns True if the expression matches the givenpattern; returns False otherwise.

Comments Case sensitivity is controlled by the Option Compare setting.

The pattern expression can contain special characters that allow more flexiblematching:

Character Evaluates To

? Matches a single character.

* Matches one or more characters.

# Matches any digit.

[range] Matches if the character in question is within the specified range.

[!range] Matches if the character in question is not within the specified range.

Page 311: Working Model 2D - User's Manual

Chapter 2 Line Input# (statement) 307

A range specifies a grouping of characters. To specify a match of any of agroup 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 areconverted to String variants and compared, returning a Boolean variant. Ifeither variant is Null, then Null is returned.

The following table shows some examples:

expression True If pattern Is False If pattern Is

"EBW" "E*W", "E*" "E*B"

"Version" "V[e]?s*n" "V[r]?s*N"

"2.0" "#.#", "#?#" "###", "#?[!0-9]"

"[ABC]" "[[]*]" "[ABC]", "[*]"

Example 'This example demonstrates various uses of the Like function.

Sub Main()a$ = "This is a string variable of 123456 characters"b$ = "123.45"If a$ Like "[A-Z][g-i]*" Then MsgBox "The first comparison is

True."If b$ Like "##3.##" Then MsgBox "The second comparison is True."If a$ Like "*variable*" Then MsgBox "The third comparison is True."

End Sub

See Also Operator Precedence (topic); Is (operator); Option Compare (statement).

Platform(s) Windows and Macintosh.

Line Input# (statement)Syntax Line Input [#]filenumber,variable

Description Reads an entire line into the given variable.

Page 312: Working Model 2D - User's Manual

308 Working Model Basic User's Manual

Comments The filenumber parameter is a number that is used by WM Basic to refer to theopen filethe number passed to the Open statement. The filenumber mustreference 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 theterminating end-of-line.

The variable parameter is any string or variant variable reference. Thisstatement will automatically declare the variable if the specified variable hasnot yet been used or dimensioned.

This statement recognizes either a single line feed or a carriage-return/line-feedpair 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()Open "c:\autoexec.bat" For Input As #1For x = 1 To 5

Line Input #1,lin$msg = msg & lin$ & crlf

Next xMsgBox "The first 5 lines of your autoexec.bat are:" & crlf & Msg

End Sub

See Also Open (statement); Get (statement); Input# (statement); Input, Input$(functions).

Platform(s) Windows and Macintosh.

Line Numbers (topic)Line numbers are not supported by WM Basic.

As an alternative to line numbers, you can use meaningful labels as targets forabsolute jumps, as shown below:

Sub Main()Dim i As IntegerOn Error Goto MyErrorTrap

i = 0LoopTop:

i = i + 1If i < 10 Then Goto LoopTop

MyErrorTrap:MsgBox "An error occurred."

End Sub

Page 313: Working Model 2D - User's Manual

Chapter 2 Line$ (function) 309

Line$ (function)Syntax Line$(text$,first[,last])

Description Returns a String containing a single line or a group of lines between first andlast.

Comments Lines are delimited by carriage return, line feed, or carriage-return/line-feedpairs.

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, thenthis line will be returned. If first is greater than the number of lines in text$,then a zero-length string is returned.

last Integer representing the index of the last line to return.

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()

Open "c:\autoexec.bat" For Input As #1For x = 1 To 5

Line Input #1,lin$txt = txt & lin$ & crlf

Next xlines$ = Line$(txt,3,4)MsgBox lines$

End Sub

See Also Item$ (function); ItemCount (function); LineCount (function); Word$(function); WordCount (function).

Platform(s) Windows and Macintosh.

LineCount (function)Syntax LineCount(text$)

Description Returns an Integer representing the number of lines in text$.

Comments Lines are delimited by carriage return, line feed, or both.

Page 314: Working Model 2D - User's Manual

310 Working Model Basic User's Manual

Example 'This example reads the first ten lines of your autoexec.bat file,'uses the LineCount function to determine the number of lines,'and then displays them in a message box.

Const crlf = Chr$(13) + Chr$(10)

Sub Main()x = 1Open "c:\autoexec.bat" For Input As #1While (x < 10) And Not EOF(1)

Line Input #1,lin$txt = txt & lin$ & crlfx = x + 1

Wendlines! = LineCount(txt)MsgBox "The number of lines in txt is: " & lines! & crlf & crlf &

txtEnd Sub

See Also Item$ (function); ItemCount (function); Line$ (function); Word$ (function);WordCount (function).

Platform(s) Windows and Macintosh.

ListBox (statement)Syntax ListBox X,Y,width,height,ArrayVariable,.Identifier

Description Creates a list box within a dialog box template.

Page 315: Working Model 2D - User's Manual

Chapter 2 ListBox (statement) 311

Comments When the dialog box is invoked, the list box will be filled with the elementscontained in ArrayVariable.

This statement can only appear within a dialog box template (i.e., between theBegin 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)relative 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 ofthe list box. If this array has no dimensions, then the list box will be initializedwith no elements. A runtime error results if the specified array contains morethan one dimension.

ArrayVariable can specify an array of any fundamental data type (structures arenot allowed). Null and Empty values are treated as zero-length strings.

.Identifier Name by which this control can be referenced by statements in a dialogfunction (such as DlgFocus and DlgEnable). This parameter also creates aninteger 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 accessedusing 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 StringDim dirs() As StringBegin Dialog ListBoxTemplate 16,32,184,96,"Sample"

Text 8,4,24,8,"&Files:"ListBox 8,16,60,72,files$,.FilesText 76,4,21,8,"&Dirs:"ListBox 76,16,56,72,dirs$,.DirsOKButton 140,4,40,14CancelButton 140,24,40,14

End DialogFileList filesFileDirs dirs

Dim ListBoxDialog As ListBoxTemplaterc% = Dialog(ListBoxDialog)

End Sub

Page 316: Working Model 2D - User's Manual

312 Working Model Basic User's Manual

See Also CancelButton (statement); CheckBox (statement); ComboBox (statement);Dialog (function); Dialog (statement); DropListBox (statement); GroupBox(statement); OKButton (statement); OptionButton (statement); OptionGroup(statement); Picture (statement); PushButton (statement); Text (statement);TextBox (statement); Begin Dialog (statement), PictureButton (statement).

Platform(s) Windows and Macintosh.

ListBoxEnabled (function)Syntax ListBoxEnabled(name$ | id)

Description Returns True if the given list box is enabled within the active window ordialog box; returns False otherwise.

Comments This function is used to determine whether a list box is enabled within thecurrent window or dialog box. If there is no active window, False will bereturned.

The ListBoxEnabled function takes the following parameters:

Parameter Description

name$ String containing the name of the list box.

The name of a list box is determined by scanning the window list looking for atext control with the given name that is immediately followed by a list box. Aruntime error is generated if a list box with that name cannot be found withinthe active window.

id Integer specifying the ID of the list box.

Note: The ListBoxEnabled function is used to determine whether a list box isenabled in another application's dialog box. Use the DlgEnable function indynamic dialog boxes.

Example 'This example checks to see whether the list box is enabled before'setting the focus to it.

Sub Main()If ListBoxEnabled("Files:") Then ActivateControl "Files:"

End Sub

See Also GetListBoxItem$ (function); GetListBoxItemCount (function);ListBoxExists (function); SelectListBoxItem (statement).

Platform(s) Windows.

ListBoxExists (function)Syntax ListBoxExists(name$ | id)

Page 317: Working Model 2D - User's Manual

Chapter 2 ListBoxExists (function) 313

Description Returns True if the given list box exists within the active window or dialogbox; returns False otherwise.

Comments This function is used to determine whether a list box exists within the currentwindow or dialog box. If there is no active window, False will be returned.

The ListBoxExists function takes the following parameters:

Parameter Description

name$ String containing the name of the list box.

The name of a list box is determined by scanning the window list looking for atext control with the given name that is immediately followed by a list box. Aruntime error is generated if a list box with that name cannot be found withinthe active window.

id Integer specifying the ID of the list box.

Note: The ListBoxExists function is used to determine whether a list boxexists in another application's dialog box. There is no equivalent function foruse with dynamic dialog boxes.

Example 'This example checks to see whether the list box exists and is enabled'before setting the focus to it.

Sub Main()If ListBoxExists("Files:") Then

If ListBoxEnabled("Files:") ThenActivateControl "Files:"

End IfEnd If

End Sub

See Also GetListBoxItem$ (function); GetListBoxItemCount (function);ListBoxEnabled (function); SelectListBoxItem (statement).

Platform(s) Windows.

Page 318: Working Model 2D - User's Manual

314 Working Model Basic User's Manual

Literals (topic)Literals are values of a specific type. The following table shows the differenttypes of literals supported by WM Basic:

Literal Description

10 Integer whose value is 10.

43265 Long whose value is 43,265.

5# Double whose value is 5.0. A number's type can be explicitly set using any ofthe following type-declaration characters:

% Integer

& Long

# Double

! Single

5.5 Double whose value is 5.5. Any number with decimal point is considered adouble.

5.4E100 Double expressed in scientific notation.

&HFF Integer expressed in hexadecimal.

&O47 Integer expressed in octal.

&HFF# Double expressed in hexadecimal.

"hello" String of five characters: hello.

"""hello""" String of seven characters: "hello". Quotation marks can be embeddedwithin strings by using two consecutive quotation marks.

#1/1/1994# Date value whose internal representation is 34335.0. Any valid date can appearwith #'s. Date literals are interpreted at execution time using the locale settingsof the host environment. To ensure that date literals are correctly interpreted forall locales, use the international date format:

#YYYY-MM-DD HH:MM:SS#

Page 319: Working Model 2D - User's Manual

Chapter 2 Loc (function) 315

Constant Folding

WM Basic supports constant folding where constant expressions are calculatedby 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" + Chr(46)

is the same as:

s$ = "Hello, there."

Loc (function)Syntax Loc(filenumber)

Description Returns a Long representing the position of the file pointer in the given file.

Comments The filenumber parameter is an Integer used by WM Basic to refer to thenumber passed by the Open statement to WM Basic.

The Loc function returns different values depending on the mode in which thefile was opened:

File Mode Returns

Input Current byte position divided by 128Output Current byte position divided by 128Append Current byte position divided by 128Binary Position of the last byte read or writtenRandom Number of the last record read or written

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()Open "c:\autoexec.bat" For Input As #1For x = 1 To 5

If Not EOF(1) Then Line Input #1,lin$Next xlc% = Loc(1)CloseMsgBox "The file location is: " & lc%

End Sub

Page 320: Working Model 2D - User's Manual

316 Working Model Basic User's Manual

See Also Seek (function); Seek (statement); FileLen (function).

Platform(s) Windows and Macintosh.

Lock (statement)Syntax Lock [#] filenumber [,{record | [start] To end}]

Description Locks a section of the specified file, preventing other processes from accessingthat section of the file until the Unlock statement is issued.

Comments The Lock statement requires the following parameters:

Parameter Description

filenumber Integer used by WM Basic to refer to the open file—the number passed to theOpen statement.

record Long specifying which record to lock.

start Long specifying the first record within a range to be locked.

end Long specifying the last record within a range to be locked.

For sequential files, the record, start, and end parameters are ignored. Theentire file is locked.

The section of the file is specified using one of the following:

Syntax Description

No parameters Locks the entire file (no record specification is given).

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) orbyte (for Binary files).

start to end Locks the specified range of records (for Random files) or bytes (for Binaryfiles).

The lock range must be the same as that used to subsequently unlock the filerange, and all locked ranges must be unlocked before the file is closed. Rangeswithin files are not unlocked automatically by WM Basic when your scriptterminates, which can cause file access problems for other processes. It is agood idea to group the Lock and Unlock statements close together in thecode, both for readability and so subsequent readers can see that the lock andunlock are performed on the same range. This practice also reduces errors infile locks.

Page 321: Working Model 2D - User's Manual

Chapter 2 Lof (function) 317

Example 'This example creates test.dat and fills it with ten string variable'records. These are displayed in a dialog box. The file is thenreopened'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$ = ""

msg = ""Open "test.dat" For Random Access Write Shared As #1For x = 1 To 10

rec$ = a$ & xLock #1,xPut #1,,rec$Unlock #1,xmsg = msg & rec$ & crlf

Next xCloseMsgBox "The records are:" & crlf & msg

msg = ""Open "test.dat" For Random Access Read Write Shared As #1For x = 1 To 10

rec$ = Mid$(rec$,1,23) & (11 - x)Lock #1,xPut #1,x,rec$Unlock #1,xmsg = msg & rec$ & crlf

Next xMsgBox "The records are: " & crlf & msgClose

Kill "test.dat"End Sub

See Also Unlock (statement); Open (statement).

Platform(s) Windows and Macintosh.

Lof (function)Syntax Lof(filenumber)

Description Returns a Long representing the number of bytes in the given file.

Comments The filenumber parameter is an Integer used by WM Basic to refer to the

open filethe number passed to the Open statement.

The file must currently be open.

Page 322: Working Model 2D - User's Manual

318 Working Model Basic User's Manual

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: "

Open "test.dat" For Random Access Write Shared As #1For x = 1 To 10

rec$ = a$ & xput #1,,rec$msg = msg & rec$ & crlf

Next xClose

Open "test.dat" For Random Access Read Write Shared As #1r% = Lof(1)CloseMsgBox "The length of test.dat is: " & r%

End Sub

See Also Loc (function); Open (statement); FileLen (function).

Platform(s) Windows and Macintosh.

Log (function)Syntax Log(number)

Description Returns a Double representing the natural logarithm of a given number.

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

See Also Exp (function).

Platform(s) Windows and Macintosh.

Long (data type)Syntax Long

Page 323: Working Model 2D - User's Manual

Chapter 2 LSet (statement) 319

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, 4bytes of storage are required.

The type-declaration character for Long is &.

See Also Currency (data type); Date (data type); Double (data type); Integer (datatype); Object (data type); Single (data type); String (data type); Variant(data type); Boolean (data type); DefType (statement); CLng (function).

Platform(s) Windows and Macintosh.

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-definedtype to another.

Comments Syntax 1

The LSet statement copies the source string source into the destination stringdest. The dest parameter must be the name of either a String or Variantvariable. 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 inlength than dest, then source is truncated, copying only the leftmost number ofcharacters that will fit in dest.

The destvariable parameter specifies a String or Variant variable. Ifdestvariable is a Variant containing Empty, then no characters are copied. Ifdestvariable is not convertible to a String, then a runtime error occurs. Aruntime error results if destvariable is Null.

Syntax 2

The source structure is copied byte for byte into the destination structure. Thisis useful for copying structures of different types. Only the number of bytes ofthe smaller of the two structures is copied. Neither the source structure nor thedestination structure can contain strings.

Page 324: Working Model 2D - User's Manual

320 Working Model Basic User's Manual

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, "*")msg = "Here are two strings that have been right-" + crlfmsg = msg & "and left-justified in a 40-character string."msg = msg & crlf & crlfRSet tmpstr$ = "Right->"msg = msg & tmpstr$ & crlfLSet tmpstr$ = "<-Left"msg = msg & tmpstr$ & crlfMsgBox msg

End Sub

See Also RSet (function).

Platform(s) Windows and Macintosh.

LTrim, LTrim$ (functions)Syntax LTrim[$](text)

Description Returns text with the leading spaces removed.

Comments LTrim$ returns a String, whereas LTrim returns a String variant.

Null is returned if text is Null.

Example 'This 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

See Also RTrim, RTrim$ (functions); Trim, Trim$ (functions).

Platform(s) Windows and Macintosh.

MacID (function)Syntax MacID(text$)

Description Returns a value representing a collection of same-type files on the Macintosh.

Page 325: Working Model 2D - User's Manual

Chapter 2 MacScript (statement) 321

Comments Since this platform does not support wildcards (i.e., * or ?), this function is theonly way to specify a group of files. This function can only be used with thefollowing statements:

Kill Dir$ Shell AppActivate

The text$ parameter is a four-character string containing a file type, a resourcetype, an application signature, or an Apple event. A runtime error occurs if theMacID function is used on platforms other than the Macintosh.

Example 'This example retrieves the names of all the text files.

Sub Main()s$ = Dir$(MacID("TEXT")) 'Get the first text file.While s$ <> ""

MsgBox s$ 'Display it.s$ = Dir$ 'Get the next text file in the list.

Wend

'Delete all the text files.Kill MacID("TEXT")

End Sub

See Also Kill (statement); Dir, Dir$ (functions); Shell (statement); AppActivate(statement).

Platform(s) Macintosh.

MacScript (statement)Syntax MacScript script$

Description Executes the specified AppleScript script.

Comments When using the MacScript statement, you can separate multiple lines byembedding carriage returns:

MacScript "Beep" + Chr(13) + "Display Dialog ""Hello"""

If embedding carriage returns proves cumbersome, you can use the Inlinestatement. The following Inline statement is equivalent to the above example:

Inline MacScriptBeepDisplay Dialog "Hello"

End Inline

Example Sub Main()MacScript "display dialog ""AppleScript"""

End Sub

See Also Inline (statement).

Platform(s) Macintosh.

Page 326: Working Model 2D - User's Manual

322 Working Model Basic User's Manual

PlatformNotes:

Macintosh

Requires Macintosh System 7.0 or later.

Main (statement)Syntax Sub Main()

End Sub

Description Defines the subroutine where execution begins.

Example Sub Main()MsgBox "This is the Main() subroutine and entry point."

End Sub

Platform(s) Windows and Macintosh.

Mci (function)Syntax Mci(command$,result$ [,error$])

Description Executes an Mci command, returning an Integer indicating whether thecommand was successful.

Comments The Mci function takes the following parameters:

Parameter Description

command$ String containing the command to be executed.

result$ String variable into which the result is placed. If the command doesn't returnanything, then a zero-length string is returned.

To ignore the returned string, pass a zero-length string: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.

Page 327: Working Model 2D - User's Manual

Chapter 2 Mci (function) 323

Example 'This first example plays a wave file. The wave file is played to'completion before execution can continue.

Sub Main()Dim result As StringDim ErrorMessage As StringDim Filename As StringDim 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 ErrorMessageExit Sub

End If

rc = Mci("play CoolSound wait","","") 'Wait for sound tofinish.

rc = Mci("close CoolSound","","") 'Close driver and file.End Sub

Page 328: Working Model 2D - User's Manual

324 Working Model Basic User's Manual

Example 'This next example shows how to query an Mci device and play an MIDIfile in'the background.

Sub Main()Dim result As StringDim ErrMsg As StringDim Filename As StringDim 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 ErrorMessageExit 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")

'Open the driver and file.rc = Mci("open " & Filename & " type sequencer alias

song",result$,ErrMsg)If rc Then

MsgBox ErrMsgExit Sub

End If

rc = Mci("play song","","") 'Play in the background.MsgBox "Press OK to stop the music.",ebOKOnlyrc = Mci("close song","","")

End Sub

See Also Beep (statement).

Platform(s) Windows.

PlatformNotes:

Windows

The Mci function accepts any Mci command as defined in the MultimediaProgrammers Reference in the Windows 3.1 SDK.

Menu (statement)Syntax Menu MenuItem$

Description Issues the specified menu command from the active window of the activeapplication.

Page 329: Working Model 2D - User's Manual

Chapter 2 MenuItemChecked (function) 325

Comments The MenuItem$ parameter specifies the complete menu item name, with eachmenu level being separated by a period. For example, the "Open" command onthe "File" menu is represented by "File.Open". Cascading menu itemsmay have multiple periods, one for each pop-up menu, such as"File.Layout.Vertical". Menu items can also be specified usingnumeric index values. For example, to select the third menu item from the Filemenu, use "File.#3". To select the fourth item from the third menu, use"#3.#4".

Items from an application's system menu can be selected by beginning themenu item specification with a period, such as ".Restore" or".Minimize".

A runtime error will result if the menu item specification does not specify amenu item. For example, "File" specifies a menu pop-up rather than a menuitem, and "File.Blah Blah" is not a valid menu item.

When comparing menu item names, this statement removes periods (.), spaces,and the ampersand. Furthermore, all characters after a backspace or tab areremoved. Thus, the menu item "&Open...\aCtrl+F12" translates simply to"Open".

A runtime error is generated if the menu item cannot be found or is not enabledat the time that this statement is encountered.

Examples Sub Main()Menu "File.Open"Menu "Format.Character.Bold"Menu ".Restore" 'Command from system menuMenu "File.#2"

End Sub

See Also MenuItemChecked (function); MenuItemEnabled (function); MenuItemExists(function).

Platform(s) Windows.

MenuItemChecked (function)Syntax MenuItemChecked(MenuItemName$)

Description Returns True if the given menu item exists and is checked; returns Falseotherwise.

Comments The MenuItemName$ parameter specifies a complete menu item or menu itempop-up following the same format as that used by the Menu statement.

Page 330: Working Model 2D - User's Manual

326 Working Model Basic User's Manual

Example 'This example turns the ruler off if it is on.

Sub Main()If MenuItemChecked("View.Ruler") Then Menu "View.Ruler"

End Sub

See Also Menu (statement); MenuItemEnabled (function); MenuItemExists (function).

Platform(s) Windows.

MenuItemEnabled (function)Syntax MenuItemEnabled(MenuItemName$)

Description Returns True if the given menu item exists and is enabled; returns Falseotherwise.

Comments The MenuItemName$ parameter specifies a complete menu item or menu itempop-up following the same format as that used by the Menu statement.

Example 'This example only pastes if there is something in the Clipboard.

Sub Main()If MenuItemEnabled("Edit.Paste") Then

Menu "Edit.Paste"Else

MsgBox "There is nothing in the Clipboard.",ebOKOnlyEnd If

End Sub

See Also Menu (statement); MenuItemChecked (function); MenuItemExists (function).

Platform(s) Windows.

MenuItemExists (function)Syntax MenuItemExists(MenuItemName$)

Description Returns True if the given menu item exists; returns False otherwise.

Comments The MenuItemName$ parameter specifies a complete menu item or menu itempop-up following the same format as that used by the Menu statement.

Examples Sub Main()If MenuItemExists("File.Open") Then BeepIf MenuItemExists("File") Then MsgBox "There is a File menu."

End Sub

See Also Menu (statement); MenuItemChecked (function); MenuItemEnabled (function).

Platform(s) Windows.

Page 331: Working Model 2D - User's Manual

Chapter 2 Mid, Mid$ (functions) 327

Mid, Mid$ (functions)Syntax Mid[$](text,start [,length])

Description Returns a substring of the specified string, beginning with start, for lengthcharacters.

Comments The returned substring starts at character position start and will be lengthcharacters long.

Mid$ returns a String, whereas Mid returns a String variant.

The Mid/Mid$ functions take the following parameters:

Parameter Description

text Any String expression containing the text from which characters are returned.

start Integer specifying the character position where the substring begins. If start isgreater than the length of text$, then a zero-length string is returned.

length Integer specifying the number of characters to return. If this parameter isomitted, then the entire string is returned, starting at start.

The Mid function will return Null text is Null.

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 (function); Option Compare (statement); Mid, Mid$ (statements).

Platform(s) Windows and Macintosh.

Mid, Mid$ (statements)Syntax Mid[$](variable,start[,length]) = newvalue

Description Replaces one part of a string with another.

Page 332: Working Model 2D - User's Manual

328 Working Model Basic User's Manual

Comments The Mid/Mid$ statements take the following parameters:

Parameter Description

variable String or Variant variable to be changed.

start Integer specifying the character position within variable where replacementbegins. If start is greater than the length of variable, then variable remainsunchanged.

length Integer specifying the number of characters to change. If this parameter isomitted, then the entire string is changed, starting at start.

newvalue Expression used as the replacement. This expression must be convertible to aString.

The resultant string is never longer than the original length of variable.

With Mid, variable must be a Variant variable convertible to a String,and newvalue is any expression convertible to a string. A runtime error isgenerated if either variant is Null.

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 "MsgBox a$ & crlf & b$

End Sub

See Also Mid, Mid$ (functions); Option Compare (statement).

Platform(s) Windows and Macintosh.

Minute (function)Syntax Minute(time)

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.

Page 333: Working Model 2D - User's Manual

Chapter 2 MIRR (function) 329

Example 'This example takes the current time; extracts the hour, minute,'and second; and displays them as the current time.

Sub Main()xt# = TimeValue(Time$())xh# = Hour(xt#)xm# = Minute(xt#)xs# = Second(xt#)MsgBox "The current time is: " & xh# & ":" & xm# & ":" & xs#

End Sub

See Also Day (function); Second (function); Month (function); Year (function); Hour(function); Weekday (function); DatePart (function).

Platform(s) Windows and Macintosh.

MIRR (function)Syntax MIRR(ValueArray(),FinanceRate,ReinvestRate)

Description Returns a Double representing the modified internal rate of return for a seriesof periodic payments and receipts.

Comments The modified internal rate of return is the equivalent rate of return on aninvestment in which payments and receipts are financed at different rates. Theinterest cost of investment and the rate of interest received on the returns oninvestment 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. Positivevalues are payments (invested capital), and negative values are receipts (returnson 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).

ReinvestRate Double representing the rate of interest received on incomes from theinvestment (receipts).

FinanceRate and ReinvestRate should be expressed as percentages. Forexample, 11 percent should be expressed as 0.11.

To return the correct value, be sure to order your payments and receipts in thecorrect sequence.

Page 334: Working Model 2D - User's Manual

330 Working Model Basic User's Manual

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 returnis'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 investmentmsg = valu(1) & ", "For x = 2 To 5

valu(x) = 100 + (x * 2) 'Incomes months 2-5msg = msg & valu(x) & ", "

Next xFor x = 6 To 12

valu(x) = 100 + (x * 10) 'Incomes months 6-12msg = msg & valu(x) & ", "

Next xretrn# = MIRR(valu,.1/12,.09/12) 'Note: normalized annual

rates

msg = "The values: " & crlf & msg & crlf & crlfMsgBox msg & "Modified rate: " & Format(retrn#,"Percent")

End Sub

See Also Fv (function); IRR (function); Npv (function); Pv (function).

Platform(s) Windows and Macintosh.

MkDir (statement)Syntax MkDir dir$

Description Creates a new directory as specified by dir$.

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 NextMkDir "TestDir"If Err <> 0 Then

MsgBox "The following error occurred: " & Error(Err)Else

MsgBox "Directory was created and is about to be removed."RmDir "TestDir"

End IfEnd Sub

Page 335: Working Model 2D - User's Manual

Chapter 2 Mod (operator) 331

See Also ChDir (statement); ChDrive (statement); CurDir, CurDir$ (functions); Dir,Dir$ (functions); RmDir (statement).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

This command behaves the same as the DOS "mkdir" command.

Mod (operator)Syntax expression1 Mod expression2

Description Returns the remainder of expression1 / expression2 as a whole number.

Comments If both expressions are integers, then the result is an integer. Otherwise, eachexpression is converted to a Long before performing the operation, returning aLong.

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 arandomly'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"Randomizecard% = Random(1,52)value = card% Mod 13If value = 0 Then value = 13CardNum$ = 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"msg = "Card number " & card% & " is the "msg = msg & CardNum & " of " & suit$MsgBox msg

End Sub

See Also / (operator); \ (operator).

Platform(s) Windows and Macintosh.

Page 336: Working Model 2D - User's Manual

332 Working Model Basic User's Manual

Month (function)Syntax Month(date)

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.

Example 'This example returns the current month in a dialog box.

Sub Main()mons$ = "Jan., Feb., Mar., Apr., May, Jun., Jul., Aug., Sep., Oct.,

Nov., Dec."tdate$ = Date$tmonth! = Month(DateValue(tdate$))MsgBox "The current month is: " & Item$(mons$,tmonth!)

End Sub

See Also Day (function); Minute (function); Second (function); Year (function); Hour(function); Weekday (function); DatePart (function).

Platform(s) Windows and Macintosh.

MsgBox (function)Syntax MsgBox(msg [,[type] [, title]])

Description Displays a message in a dialog box with a set of predefined buttons, returningan Integer representing which button was selected.

Comments The MsgBox function takes the following parameters:

Parameter Description

msg Message to be displayed—any expression convertible to a String.

End-of-lines can be used to separate lines (either a carriage return, line feed, orboth). If a given line is too long, it will be word-wrapped. If msg containscharacter 0, then only the characters up to the character 0 will be displayed.

The width and height of the dialog box are sized to hold the entire contents ofmsg.

A runtime error is generated if msg is Null.

type Integer specifying the type of dialog box (see below).

title Caption of the dialog box. This parameter is any expression convertible to aString. If it is omitted, then BasicScript is used.

A runtime error is generated if title is Null.

Page 337: Working Model 2D - User's Manual

Chapter 2 MsgBox (function) 333

The MsgBox function returns one of the following values:

Constant Value Description

ebOK 1 OK was clicked.

ebCancel 2 Cancel was clicked.

ebAbort 3 Abort was clicked.

ebRetry 4 Retry was clicked.

ebIgnore 5 Ignore was clicked.

ebYes 6 Yes was clicked.

ebNo 7 No was clicked.

Page 338: Working Model 2D - User's Manual

334 Working Model Basic User's Manual

The type parameter is the sub of any of the following values:

Constant Value Description

ebOKOnly 0 Displays OK button only.

ebOKCancel 1 Displays OK and Cancel buttons.

ebAbortRetryIgnore 2 DisplaysAbort, Retry, and Ignore buttons.

ebYesNoCancel 3 Displays Yes, No, and Cancel buttons.

ebYesNo 4 Displays Yes and No buttons.

ebRetryCancel 5 Displays Retry and Cancel buttons.

ebCritical 16 Displays "stop" icon.

ebQuestion 32 Displays "question mark" icon.

ebExclamation 48 Displays "exclamation point" icon.

ebInformation 64 Displays "information" icon.

ebDefaultButton1 0 First button is the default button.

ebDefaultButton2 256 Second button is the default button.

ebDefaultButton3 512 Third button is the default button.

ebApplicationModal 0Applicati

on modal—the current application issuspended until the dialog box is closed.

ebSystemModal 4096 System modal—all applications aresuspended until the dialog box is closed.

The default value for type is 0 (display only the OK button, making it thedefault).

Page 339: Working Model 2D - User's Manual

Chapter 2 MsgBox (function) 335

Breaking Text across Lines

The msg parameter can contain end-of-line characters, forcing the text thatfollows to start on a new line. The following example shows how to display astring on two lines:

MsgBox "This is on" + Chr(13) + Chr(10) + "two lines."

The carriage-return or line-feed characters can be used by themselves todesignate an end-of-line.

r = MsgBox("Hello, World")

r = MsgBox("Hello, World",ebYesNoCancel Or ebDefaultButton1)

r = MsgBox("Hello, World",ebYesNoCancel Or ebDefaultButton1 OrebCritical)

Example Sub MainMsgBox "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

Page 340: Working Model 2D - User's Manual

336 Working Model Basic User's Manual

See Also AskBox$ (function); AskPassword$ (function); InputBox, InputBox$(functions); OpenFilename$ (function); SaveFilename$ (function); SelectBox(function); AnswerBox (function).

Platform(s) Windows and Macintosh.

PlatformNotes:

The appearance of the MsgBox dialog box and its icons differs slightlydepending on the platform.

PlatformNotes:

Windows

MsgBox displays all text in its dialog box in 8-point MS Sans Serif.

MsgBox (statement)Syntax MsgBox msg [,[type] [, title]]

Description This command is the same as the MsgBox function, except that the statementform 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

See Also AskBox$ (function); AskPassword$ (function); InputBox, InputBox$(functions); OpenFilename$ (function); SaveFilename$ (function); SelectBox(function); AnswerBox (function).

Platform(s) Windows and Macintosh.

MsgClose (statement)Syntax MsgClose

Description Closes the modeless message dialog box.

Comments Nothing will happen if there is no open message dialog box.

Example Sub Main()MsgOpen "Printing. Please wait...",0,True,TrueSleep 3000MsgClose

End Sub

See Also MsgOpen (statement); MsgSetThermometer (statement); MsgSetText(statement).

Platform(s) Windows.

Page 341: Working Model 2D - User's Manual

Chapter 2 MsgOpen (statement) 337

MsgOpen (statement)Syntax MsgOpen msg$,timeout,isCancel,isThermometer [,X,Y]

Description This statement displays a message in a dialog box with an optional Cancelbutton and thermometer.

Comments The MsgOpen statement takes the following parameters:

Parameter Description

msg$ String containing the text to be displayed.

The text can be changed using the MsgSetText statement.

timeout Integer specifying the number of seconds before the dialog box isautomatically removed. The timeout parameter has no effect if its value is 0.

isCancel Boolean controlling whether or not a Cancel button appears within the dialogbox beneath the displayed message. If this parameter is True, then a Cancelbutton 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 isgenerated (error number 809). In this manner, a message dialog box can bedisplayed and processing can continue as normal, aborting only when the usercancels the process by choosing the Cancel button.

isThermometer Boolean controlling whether the dialog box contains a thermometer. If thisparameter is True, then a thermometer is created between the text and theoptional Cancel button. The thermometer initially indicates 0% complete andcan be changed using the MsgSetThermometer statement.

X, Y Integer coordinates specifying the location of the upper left corner of themessage box, in twips (twentieths of a point). If these parameters are notspecified, then the window is centered on top of the application.

Unlike other dialog boxes, a message dialog box remains open until the userselects Cancel, the timeout has expired, or the MsgClose statement isexecuted (this is sometimes referred to as modeless).

Only a single message window can be opened at any one time. The messagewindow is removed automatically when a script terminates.

Page 342: Working Model 2D - User's Manual

338 Working Model Basic User's Manual

MsgOpen "Printing. Please wait...",0,False,False

MsgOpen "Printing. Please wait...",0,True,False

MsgOpen "Printing. Please wait...",0,True,TrueMsgSetThermometer 75

Example 'The following example displays several types of message boxes.

Sub Main()MsgOpen "Printing. Please wait...",0,True,FalseSleep 3000MsgCloseMsgOpen "Printing. Please wait...",0,True,TrueFor x = 1 to 100

MsgSetThermometer xNext xSleep 1000Msgclose

End Sub

See Also MsgClose (statement); MsgSetThermometer (statement); MsgSetText(statement).

Platform(s) Windows.

MsgSetText (statement)Syntax MsgSetText newtext$

Description Changes the text within an open message dialog box (one that was previouslyopened with the MsgOpen statement).

Page 343: Working Model 2D - User's Manual

Chapter 2 MsgSetThermometer (statement) 339

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 (usingMsgOpen).

Example 'This example creates a modeless message box, leaving room in themessage'text for the record number. This box contains a Cancel button.

Sub Main()MsgOpen "Reading Record",0,True,FalseFor i = 1 To 100

'Read a record here.'Update the modeless message box.Sleep 100MsgSetText "Reading record " & i

Next iMsgClose

End Sub

See Also MsgClose (statement); MsgOpen (statement); MsgSetThermometer (statement).

Platform(s) Windows.

MsgSetThermometer (statement)Syntax MsgSetThermometer percentage

Description Changes the percentage filled indicated within the thermometer of a messagedialog box (one that was previously opened with the MsgOpen statement).

Comments A runtime error will result if a message box is not currently open (usingMsgOpen) or if the value of percentage is not between 0 and 100 inclusive.

Page 344: Working Model 2D - User's Manual

340 Working Model Basic User's Manual

Example 'This example create a modeless message box with a thermometer and aCancel'button. This example also shows how to process the clicking of theCancel'button.

Sub Main()On Error Goto ErrorTrapMsgOpen "Reading records from file...",0,True,TrueFor i = 1 To 100

'Read a record here.'Update the modeless message box.MsgSetThermometer iDoEventsSleep 50

Next iMsgCloseOn Error Goto 0 'Turn error trap off.Exit Sub

ErrorTrap:If Err = 809 Then

MsgBox "Cancel was pressed!"Exit Sub 'Reset error handler.

End IfEnd Sub

See Also MsgClose (statement); MsgOpen (statement); MsgSetText (statement).

Platform(s) Windows.

Name (statement)Syntax Name oldfile$ As newfile$

Description Renames a file.

Page 345: Working Model 2D - User's Manual

Chapter 2 Net.AddCon (method) 341

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 samephysical disk volume. For example, the following rename will work underWindows:

Name "c:\samples\mydoc.txt" As "c:\backup\doc\mydoc.bak"

You cannot rename files across physical disk volumes. For example, thefollowing 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, thenerase the original:

FileCopy "c:\samples\mydoc.txt","a:\mydoc.bak" 'Make a copyKill "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()On Error Resume NextIf FileExists("test.dat") Then

Name "test.dat" As "test2.dat"If Err <> 0 Then

msg = "File exists and cannot be renamed! Error: " & ErrElse

msg = "File exists and renamed to test2.dat."End If

ElseOpen "test.dat" For Output As #1CloseName "test.dat" As "test2.dat"If Err <> 0 Then

msg = "File created but not renamed! Error: " & ErrElse

msg = "File created and renamed to test2.dat."End If

End IfMsgBox msg

End Sub

See Also Kill (statement), FileCopy (statement).

Platform(s) Windows and Macintosh.

Net.AddCon (method)Syntax Net.AddCon netpath$,password$,localname$

Description Redirects a local device (a disk drive or printer queue) to the specified shareddevice or remote server.

Page 346: Working Model 2D - User's Manual

342 Working Model Basic User's Manual

Comments The Net.AddCon method takes the following parameters:

Parameter Description

netpath$ String containing the name of the shared device or the name of a remoteserver. This parameter can contain the name of a shared printer queue (such asthat returned by Net.Browse[1]) or the name of a network path (such as thatreturned by Net.Browse[0]).

password$ String containing the password for the given device or server. This parameteris 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:".

A runtime error will result if no network is present.

Example 'This example sets N: so that it refers to the network pathSYS:\PUBLIC.

Sub Main()Net.AddCon "SYS:\PUBLIC","","N:"

End Sub

See Also Net.CancelCon (method); Net.GetCon$ (method).

Platform(s) Windows.

Net.Browse$ (method)Syntax Net.Browse$(type)

Description Calls the currently installed network's browse dialog box, requesting aparticular type of information.

Comments The type parameter is an Integer specifying the type of dialog box todisplay:

Type Description

0 If type is 0, then this method displays a dialog box that allows the user tobrowse network volumes and directories. Choosing OK returns the completedpathname as a String.

1 If type is 1, then this function displays a dialog box that allows the user tobrowse the network's printer queues. Choosing OK returns the complete nameof that printer queue as a String. This string is the same format as required bythe Net.AddCon method.

This dialog box differs depending on the type of network installed.

A runtime error will result if no network is present.

Page 347: Working Model 2D - User's Manual

Chapter 2 Net.CancelCon (method) 343

Example 'This second example retrieves a valid network path.

Sub Main()s$ = Net.Browse$(0)If s$ <> "" Then

MsgBox "The following network path was selected: " & s$Else

MsgBox "Dialog box was canceled."End If

End Sub

See Also Net.Dialog (method).

Platform(s) Windows.

Net.CancelCon (method)Syntax Net.CancelCon connection$ [,isForce]

Description Cancels a network connection.

Comments The Net.CancelCon method takes the following parameters:

Parameter Description

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 thereare open files or open print jobs. If this parameter is True, then this method willclose all open files and open print jobs before the connection is closed. If thisparameter is False, this the method will issue a runtime error if there are anyopen files or open print jobs.

A runtime error will result if no network is present.

Example 'This example deletes the drive mapping associated with drive N:.

Sub Main()Net.CancelCon "N:"

End Sub

See Also Net.AddCon (method); Net.GetCon$ (method).

Platform(s) Windows.

Net.Dialog (method)Syntax Net.Dialog

Description Displays the dialog box that allows configuration of the currently installednetwork.

Page 348: Working Model 2D - User's Manual

344 Working Model Basic User's Manual

Comments The displayed dialog box depends on the currently installed network. Thedialog box is modal—script execution will be paused until the dialog box iscompleted.

A runtime error will result if no network is present.

Example 'This example invokes the network driver dialog box.

Sub Main()Net.Dialog

End Sub

See Also Net.Browse$ (method).

Platform(s) Windows.

Net.GetCaps (method)Syntax Net.GetCaps(type)

Description Returns an Integer specifying information about the network and itscapabilities.

Comments The type parameter specifies what type of information to retrieve:

Value of type Description

1 Returns the version of the driver specification to which the currently installednetwork driver conforms. The high byte of the returned value contains themajor version number and the low byte contains the minor version number.These values can be retrieved using the following code:

MajorVersionNumber = Net.GetCaps(1) \ 256MinorVersionNumber = Net.GetCaps(1) And &H00FF

2 Returns the type of network. The network type is returned in the high byte andthe sub-network type is returned in the low byte. These values can be obtainedusing the following code:

NetType = Net.GetCaps(2) \ 256SubNetType = Net.GetCaps(2) And &H00FF

Page 349: Working Model 2D - User's Manual

Chapter 2 Net.GetCaps (method) 345

Using the above values, NetType can be any of the following values:

0 No network is installed.1 Microsoft Network.2 Microsoft LAN Manager.3 Novell NetWare.4 Banyan Vines.5 10Net.6 Locus.7 SunSoft PC NFS.8 LanStep.9 9 Titles.10 Articom Lantastic.11 IBM AS/400.12 FTP Software FTP NFS.13 DEC Pathworks.

If NetType is is 128, then SubNetType is any of the following values (you cantest for any of these values using the And operator):

0 None.bit &H0001 Microsoft Network.bit &H0002 Microsoft LAN Manager.bit &H0004 Windows for Workgroups.bit &H0008 Novell NetWare.bit &H0010 Banyan Vines.bit &H0080 Other unspecified network.

3 Returns the network driver version number.

4 Returns 1 if the Net.User$ property is supported, 0 otherwise.

6 Returns any of the following values indicating which connections are supported(you can test for these values using the And operator):

bit &H0001 Driver supports Net.AddCon.bit &H0002 Driver supports Net.CancelCon.bit &H0004 Driver supports Net.GetCon.bit &H0008 Driver supports auto connect.bit &H0010 Driver supports Net.Browse$.

Page 350: Working Model 2D - User's Manual

346 Working Model Basic User's Manual

7 Returns a value indicating which printer function are available (you can test forthese values using the And operator):

bit &H0002 Driver supports open print job.bit &H0004 Driver supports close print job.bit &H0010 Driver supports hold print job.bit &H0020 Driver supports release print job.bit &H0040 Driver supports cancel print job.bit &H0080 Driver supports setting the number of printcopies.bit &H0100 Driver supports watch print queue.bit &H0200 Driver supports unwatch print queue.bit &H0400 Driver supports locking queue data.bit &H0800 Driver supports unlocking queue data.bit &H1000 Driver supports queue change message.bit &H2000 Driver supports abort print job.bit &H4000 Driver supports no arbitrary lock.bit &H8000 Driver supports write print job.

8 Returns a value indicating which dialog functions are available (you can test forthese values using the And operator):

bit &H0001 Driver supports device mode dialog.bit &H0002 Driver supports the Browse dialog.bit &H0004 Driver supports the Connect dialog.bit &H0008 Driver supports the Disconnect dialog.bit &H0010 Driver supports the View Queue dialog.bit &H0020 Driver supports the Property dialog.bit &H0040 Driver supports the Connection dialog.bit &H0080 Driver supports the Printer Connect dialog.bit &H0100 Driver supports the Shares dialog.bit &H0200 Driver supports the Share As dialog.

A runtime error will result if no network is present.

Examples 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

Platform(s) Windows.

Net.GetCon$ (method)Syntax Net.GetCon$(localname$)

Page 351: Working Model 2D - User's Manual

Chapter 2 Net.User$ (property) 347

Description Returns the name of the network resource associated with the specifiedredirected 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 notredirected.

A runtime error will result if no network is present.

Example 'This example finds out where drive Z is mapped.

Sub Main()NetPath$ = Net.GetCon$("Z:")MsgBox "Drive Z is mapped as " & NetPath$

End Sub

See Also Net.CancelCon (method); Net.AddCon (method).

Platform(s) Windows.

Net.User$ (property)Syntax Net.User$

Description Returns the name of the user on the network.

Comments A runtime error is generated if the network is not installed.

Examples 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

Platform(s) Windows.

New (keyword)Syntax 1 Dim ObjectVariable As New ObjectType

Syntax 2 Set ObjectVariable = New ObjectType

Description Creates a new instance of the specified object type, assigning it to the specifiedobject variable.

Page 352: Working Model 2D - User's Manual

348 Working Model Basic User's Manual

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 notifiedthat a new object is being defined. The application responds by creating a newphysical object (within the appropriate context) and returning a reference to thatobject, which is immediately assigned to the variable being declared.

When that variable goes out of scope (i.e., the Sub or Function procedure inwhich the variable is declared ends), the application is notified. The applicationthen performs some appropriate action, such as destroying the physical object.

See Also Dim (statement); Set (statement).

Platform(s) Windows and Macintosh.

Not (operator)Syntax Not expression

Description Returns either a logical or binary negation of expression.

Comments The result is determined as shown in the following table:

If the Expression Is Then the Result Is

True False

False True

Null Null

Any numeric type A binary negation of the number. If the number is an Integer, then an Integeris returned. Otherwise, the expression is first converted to a Long, then a binarynegation is performed, returning a Long.

Empty Treated as a Long value 0.

Page 353: Working Model 2D - User's Manual

Chapter 2 Nothing (constant) 349

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 = Falseb = TrueIf (Not a and b) Then msg = "a = False, b = True" & crlf

toggle% = Truemsg = msg & "toggle% is now " & Format(toggle%,"True/False") & crlftoggle% = Not toggle%msg = msg & "toggle% is now " & Format(toggle%,"True/False") & crlftoggle% = Not toggle%msg = msg & "toggle% is now " & Format(toggle%,"True/False")MsgBox msg

End Sub

See Also Boolean (data type); Comparison Operators (topic).

Platform(s) Windows and Macintosh.

Nothing (constant)Description A value indicating that an object variable no longer references a valid object.

Example Sub Main()Dim a As ObjectIf a Is Nothing Then

MsgBox "The object variable references no object."Else

MsgBox "The object variable references: " & a.ValueEnd If

End Sub

See Also Set (statement); Object (data type).

Platform(s) Windows and Macintosh.

Now (function)Syntax Now[()]

Description Returns a Date variant representing the current date and time.

Page 354: Working Model 2D - User's Manual

350 Working Model Basic User's Manual

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

See Also Date, Date$ (functions); Time, Time$ (functions).

Platform(s) Windows and Macintosh.

NPer (function)Syntax NPer(Rate,Pmt,Pv,Fv,Due)

Description Returns the number of periods for an annuity based on periodic fixed paymentsand a constant rate of interest.

Comments An annuity is a series of fixed payments paid to or received from an investmentover 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, besure to normalize annual rates by dividing them by 12.

Pmt Double representing the amount of each payment or income. Income isrepresented by positive values, whereas payments are represented by negativevalues.

Pv Double representing the present value of your annuity. In the case of a loan, thepresent 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, thefuture value would be zero, and the present value would be the amount of theloan.

Due Integer indicating when payments are due for each payment period. A 0specifies payment at the end of each period, whereas a 1 indicates payment atthe start of each period.

Positive numbers represent cash received, whereas negative numbers representcash paid out.

Page 355: Working Model 2D - User's Manual

Chapter 2 Npv (function) 351

Example 'This example calculates the number of $100.00 monthly paymentsnecessary'to accumulate $10,000.00 at an annual rate of 10%. Payments are madeat 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 (function); Pmt (function); PPmt (function); Rate (function).

Platform(s) Windows and Macintosh.

Npv (function)Syntax Npv(Rate,ValueArray())

Description Returns the net present value of an annuity based on periodic payments andreceipts, and a discount rate.

Comments The Npv function requires the following parameters:

Parameter Description

Rate Double that represents the interest rate over the length of the period. If thevalues are monthly, annual rates must be divided by 12 to normalize them tomonthly rates.

ValueArray() Array of Double numbers representing the payments and receipts. Positivevalues 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 representcash paid out.

For accurate results, be sure to enter your payments and receipts in the correctorder because Npv uses the order of the array values to interpret the order ofthe payments and receipts.

If your first cash flow occurs at the beginning of the first period, that valuemust be added to the return value of the Npv function. It should not be includedin the array of cash flows.

Npv differs from the Pv function in that the payments are due at the end of theperiod and the cash flows are variable. Pv's cash flows are constant, andpayment may be made at either the beginning or end of the period.

Page 356: Working Model 2D - User's Manual

352 Working Model Basic User's Manual

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 annual10%'rate.

Const crlf = Chr$(13) + Chr$(10)

Sub Main()Dim valu#(12)valu(1) = -800 'Initial investmentmsg = valu(1) & ", "For x = 2 To 5 'Months 2-5

valu(x) = 100 + (x * 2)msg = msg & valu(x) & ", "

Next xFor x = 6 To 12 'Months 6-12

valu(x) = 100 + (x * 10) 'Accelerated incomemsg = msg & valu(x) & ", "

Next xNetVal# = NPV((.10/12),valu)msg = "The values:" & crlf & msg & crlf & crlfMsgBox msg & "Net present value: " & Format(NetVal#,"Currency")

End Sub

See Also Fv (function); IRR (function); MIRR (function); Pv (function).

Platform(s) Windows and Macintosh.

Null (constant)Description Represents a variant of VarType 1.

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 errorvalues through a complex expression. For example, you can write functions thatreturn 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 anerror occurred during calculation.

Since variants are Empty by default, the only way for Null to appear within avariant is for you to explicitly place it there. Only a few BasicScript functionsreturn this value.

Page 357: Working Model 2D - User's Manual

Chapter 2 Object (data type) 353

Example Sub Main()Dim a As Varianta = NullIf IsNull(a) Then MsgBox "The variable is Null."MsgBox "The VarType of a is: " & VarType(a)'Should display 1.

End Sub

Platform(s) Windows and Macintosh.

Object (data type)Syntax Object

Description A data type used to declare OLE automation variables.

Comments The Object type is used to declare variables that reference objects within anapplication using OLE automation.

Each object is a 4-byte (32-bit) value that references the object internally. Thevalue 0 (or Nothing) indicates that the variable does not reference a validobject, as is the case when the object has not yet been given a value. Accessingproperties or methods of such Object variables generates a runtime error.

Using Objects

Object variables are declared using the Dim, Public, or Privatestatement:

Dim MyApp As Object

Object variables can be assigned values (thereby referencing a real physicalobject) using the Set statement:

Set MyApp = CreateObject("phantom.application")Set MyApp = Nothing

Properties of an Object are accessed using the dot (.) separator:

MyApp.Color = 10i% = MyApp.Color

Methods of an Object are also accessed using the dot (.) separator:

MyApp.Open "sample.txt"isSuccess = MyApp.Save("new.txt",15)

Page 358: Working Model 2D - User's Manual

354 Working Model Basic User's Manual

Automatic Destruction

BasicScript keeps track of the number of variables that reference a given objectso that the object can be destroyed when there are no longer any references toit:

Sub Main() 'Number of references to objectDim a As Object '0Dim b As Object '0Set a = CreateObject("phantom.application) '1Set b = a '2Set a = Nothing '1

End Sub '0 (object destroyed)

Note: An OLE automation object is instructed by BasicScript to destroy itselfwhen no variables reference that object. However, it is the responsibility of theOLE automation server to destroy it. Some servers do not destroy theirobjects—usually when the objects have a visual component and can bedestroyed manually by the user.

See Also Currency (data type); Date (data type); Double (data type); Integer (datatype); Long (data type); Single (data type); String (data type); Variant (datatype); Boolean (data type); DefType (statement).

Platform(s) Windows and Macintosh.

Objects (topic)BasicScript defines two types of objects: data objects and OLE automationobjects.

Syntactically, these are referenced in the same way.

What Is an Object

An object in BasicScript is an encapsulation of data and routines into a singleunit. The use of objects in WM Basic has the effect of grouping together a setof 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. InWM Basic, an object method can take the form of a function or a subroutine.For example, a OLE automation object called MyApp may contain a methodsubroutine called Open that takes a single argument (a filename), as shownbelow:

MyApp.Open "c:\files\sample.txt"

Page 359: Working Model 2D - User's Manual

Chapter 2 Objects (topic) 355

Declaring Object Variables

In order to gain access to an object, you must first declare an object variableusing either Dim, Public, or Private:

Dim o As Object 'OLE automation object

Initially, objects are given the value 0 (or Nothing). Before an object can beaccessed, it must be associated with a physical object.

Assigning a Value to an Object Variable

An object variable must reference a real physical object before accessing anyproperties or methods of that object. To instantiate an object, use the Setstatement.

Dim MyApp As ObjectSet MyApp = CreateObject("Server.Application")

Accessing Object Properties

Once an object variable has been declared and associated with a physicalobject, it can be modified using WM Basic code. Properties are syntacticallyaccessible using the dot operator, which separates an object name from theproperty being accessed:

MyApp.BackgroundColor = 10i% = MyApp.DocumentCount

Properties are set using WM Basic's normal assignment statement:

MyApp.BackgroundColor = 10

Object properties can be retrieved and used within expressions:

i% = MyApp.DocumentCount + 10MsgBox "Number of documents = " & MyApp.DocumentCount

Accessing Object Methods

Like properties, methods are accessed via the dot operator. Object methods thatdo not return values behave like subroutines in WM Basic (i.e., the argumentsare not enclosed within parentheses):

MyApp.Open "c:\files\sample.txt",True,15

Object methods that return a value behave like function calls in WM Basic.Any arguments must be enclosed in parentheses:

If MyApp.DocumentCount = 0 Then MsgBox "No open documents."NumDocs = app.count(4,5)

There is no syntactic difference between calling a method function andretrieving a property value, as shown below:

variable = object.property(arg1,arg2)variable = object.method(arg1,arg2)

Page 360: Working Model 2D - User's Manual

356 Working Model Basic User's Manual

Comparing Object Variables

The values used to represent objects are meaningless to the script in which theyare used, with the following exceptions:

Objects can be compared to each other to determine whether they refer tothe same object.

Objects can be compared with Nothing to determine whether the objectvariable refers to a valid object.

Object comparisons are accomplished using the Is operator:

If a Is b Then MsgBox "a and b are the same object."If a Is Nothing Then MsgBox "a is not initialized."If b Is Not Nothing Then MsgBox "b is in use."

Collections

A collection is a set of related object variables. Each element in the set is calleda member and is accessed via an index, either numeric or text, as shown below:

MyApp.Toolbar.Buttons(0)MyApp.Toolbar.Buttons("Tuesday")

It is typical for collection indexes to begin with 0.

Each element of a collection is itself an object, as shown in the followingexamples:

Dim MyToolbarButton As Object

Set MyToolbarButton = MyApp.Toolbar.Buttons("Save")MyAppp.Toolbar.Buttons(1).Caption = "Open"

The collection itself contains properties that provide you with informationabout the collection and methods that allow navigation within that collection:

Dim MyToolbarButton As Object

NumButtons% = MyApp.Toolbar.Buttons.CountMyApp.Toolbar.Buttons.MoveNextMyApp.Toolbar.Buttons.FindNext "Save"

For i = 1 To MyApp.Toolbar.Buttons.CountSet MyToolbarButton = MyApp.Toolbar.Buttons(i)MyToolbarButton.Caption = "Copy"

Next i

Page 361: Working Model 2D - User's Manual

Chapter 2 Oct, Oct$ (functions) 357

Predefined Objects

WM Basic predefines a few objects for use in all scripts. These are:

Clipboard System Desktop HWNDNet Basic Screen

In addition, WM Basic has objects defined specifically for Working Model.Please see Chapter 1 and Chapter 3 for more information.

Note: Some of these objects are not available on all platforms.

Oct, Oct$ (functions)Syntax Oct[$](number)

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 torepresent 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 isrounded to the nearest whole number before converting to the octal equivalent.

Example 'This example displays the octal equivalent of several numbers.

Const crlf = Chr$(13) + Chr$(10)

Sub Main()st$ = "The octal values are: " & crlfFor x = 1 To 5

y% = x * 10st$ = st$ & y% & " : " & Oct$(y%) & crlf

Next xMsgBox st$

End Sub

See Also Hex, Hex$ (functions).

Platform(s) Windows and Macintosh.

OKButton (statement)Syntax OKButton X,Y,width,height [,.Identifier]

Description Creates an OK button within a dialog box template.

Page 362: Working Model 2D - User's Manual

358 Working Model Basic User's Manual

Comments This statement can only appear within a dialog box template (i.e., between theBegin 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)relative to the upper left corner of the dialog box.

width, height Integer coordinates specifying the dimensions of the control in dialog units.

.Identifier Name by which this control can be referenced by statements in a dialogfunction (such as DlgFocus and DlgEnable).

If the DefaultButton parameter is not specified in the Dialog statement, theOK button will be used as the default button. In this case, the OK button can beselected 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 ButtonTemplate 17,33,104,23,"Buttons"

OKButton 8,4,40,14,.OKCancelButton 56,4,40,14,.Cancel

End DialogDim ButtonDialog As ButtonTemplateWhichButton = Dialog(ButtonDialog)If WhichButton = -1 Then

MsgBox "OK was pressed."ElseIf WhichButton = 0 Then

MsgBox "Cancel was pressed."End If

End Sub

See Also CancelButton (statement); CheckBox (statement); ComboBox (statement);Dialog (function); Dialog (statement); DropListBox (statement); GroupBox(statement); ListBox (statement); OptionButton (statement); OptionGroup(statement); Picture (statement); PushButton (statement); Text (statement);TextBox (statement); Begin Dialog (statement), PictureButton (statement).

Platform(s) Windows and Macintosh.

On Error (statement)Syntax On Error {Goto label | Resume Next | Goto 0}

Description Defines the action taken when a trappable runtime error occurs.

Page 363: Working Model 2D - User's Manual

Chapter 2 On Error (statement) 359

Comments The form On Error Goto label causes execution to transfer to thespecified label when a runtime error occurs.

The form On Error Resume Next causes execution to continue on theline 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 itappears.

Once an error trap has gained control, appropriate action should be taken, andthen control should be resumed using the Resume statement. The Resumestatement resets the error handler and continues execution. If a procedure endswhile an error is pending, then an error will be generated. (The Exit Sub orExit Function statement also resets the error handler, allowing aprocedure to end without displaying an error message.)

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 errorhandler, then the error is fatal, causing the script to stop executing. Thefollowing statements reset the error state (i.e., these statements turn off the factthat an error occurred):

ResumeErr=-1

The Resume statement forces execution to continue either on the same line oron the line following the line that generated the error. The Err=-1 statementallows explicit resetting of the error state so that the script can continue normalexecution without resuming at the statement that caused the error condition.

The On Error statement will not reset the error. Thus, if an On Errorstatement occurs within an error handler, it has the effect of changing thelocation of a new error handler for any new errors that may occur once the errorhas been reset.

Page 364: Working Model 2D - User's Manual

360 Working Model Basic User's Manual

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 = 10000b = 10000

On Error Goto Pass 'Branch to this label on error.Do

x% = a * bLoop

Pass:Err = -1 'Clear error status.MsgBox "Cleared error status and continued."

On Error Goto Overflow 'Branch to new error routine on anyx% = 1000 'subsequent errors.x% = a * bx% = a / 0

On Error Goto 0 'Clear error branching.x% = a * b 'Program will stop here.Exit Sub 'Exit before common error routine.

Overflow: 'Beginning of common error routine.If Err = 6 then

MsgBox "Overflow Branch."Else

MsgBox Error(Err)End If

Resume NextEnd Sub

See Also Error Handling (topic); Error (statement); Resume (statement).

Platform(s) Windows and Macintosh.

Open (statement)Syntax Open filename$ [For mode] [Access accessmode] [lock] As [#] filenumber _

[Len = reclen]

Description Opens a file for a given mode, assigning the open file to the suppliedfilenumber.

Page 365: Working Model 2D - User's Manual

Chapter 2 Open (statement) 361

Comments The filename$ parameter is a string expression that contains a valid filename.

The filenumber parameter is a number between 1 and 255. The FreeFilefunction can be used to determine an available file number.

The mode parameter determines the type of operations that can be performed onthat file:

File Mode Description

Input Opens an existing file for sequential input (filename$ must exist). The value ofaccessmode, if specified, must be Read.

Output Opens an existing file for sequential output, truncating its length to zero, orcreates a new file. The value of accessmode, if specified, must be Write.

Append Opens an existing file for sequential output, positioning the file pointer at theend of the file, or creates a new file. The value of accessmode, if specified,must be Read Write.

Binary Opens an existing file for binary I/O or creates a new file. Existing binary filesare never truncated in length. The value of accessmode, if specified, determineshow the file can subsequently be accessed.

Random Opens an existing file for record I/O or creates a new file. Existing random filesare truncated only if accessmode is Write. The reclen parameter determines therecord length for I/O operations.

If the mode parameter is missing, then Random is used.

The accessmode parameter determines what type of I/O operations can beperformed on the file:

Access Description

Read Opens the file for reading only. This value is valid only for files opened inBinary, Random, or Input mode.

Write Opens the file for writing only. This value is valid only for files opened inBinary, Random, or Output mode.

Read Write Opens the file for both reading and writing. This value is valid only for filesopened in Binary, Random, or Append mode.

Page 366: Working Model 2D - User's Manual

362 Working Model Basic User's Manual

If the accessmode parameter is not specified, the following defaults are used:

File Mode Default Value for accessmode

Input Read

Output Write

Append Read Write

Binary When the file is initially opened, access is attempted three times in thefollowing order:

1. Read Write2. Write3. Read

Random Same as Binary files

The lock parameter determines what access rights are granted to other processesthat attempt to open the same file. The following table describes the values forlock:

lock Value Description

Shared Another process can both read this file and write to it. (Deny none.)

Lock Read Another process can write to this file but not read it. (Deny read.)

Lock Write Another process can read this file but not write to it. (Deny write.)

Lock Read Write Another process is prevented both from readingthis file and from writing to it. (Exclusive.)

If lock is not specified, then the file is opened in Shared mode.

If the file does not exist and the lock parameter is specified, the file is openedtwiceonce to create the file and again to establish the correct sharing mode.

Files opened in Random mode are divided up into a sequence of records, eachof the length specified by the reclen parameter. If this parameter is missing,then 128 is used. For files opened for sequential I/O, the reclen parameterspecifies the size of the internal buffer used by WM Basic when performingI/O. Larger buffers mean faster file access. For Binary files, the reclenparameter is ignored.

Page 367: Working Model 2D - User's Manual

Chapter 2 OpenFilename$ (function) 363

Example 'This example opens several files in various configurations.

Sub Main()Open "test.dat" For Output Access Write Lock Write As #2CloseOpen "test.dat" For Input Access Read Shared As #1CloseOpen "test.dat" For Append Access Write Lock Read Write as #3CloseOpen "test.dat" For Binary Access Read Write Shared As #4CloseOpen "test.dat" For Random Access Read Write Lock Read As #5CloseOpen "test.dat" For Input Access Read Shared As #6CloseKill "test.dat"

End Sub

See Also Close (statement); Reset (statement); FreeFile (function).

Platform(s) Windows and Macintosh.

OpenFilename$ (function)Syntax OpenFilename$[([title$ [,extensions$]])]

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 ifthe user selects Cancel.

Comments This function displays the standard file open dialog box, which allows the userto 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 thisparameter is omitted, then "Open" is used.

extension$ String specifying the available file types. The format for this string depends onthe platform on which WM Basic is running. If this parameter is omitted, thenall files are displayed.

Page 368: Working Model 2D - User's Manual

364 Working Model Basic User's Manual

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 toread the'first line from that file.Sub Main

Dim f As String,s As Stringf$ = OpenFilename$("Open Picture","Text Files:*.TXT")If f$ <> "" Then

Open f$ For Input As #1Line Input #1,s$Close #1MsgBox "First line from " & f$ & " is " & s$

End IfEnd Sub

See Also MsgBox (statement); AskBox$ (function); AskPassword$ (function); InputBox,InputBox$ (functions); SaveFilename$ (function); SelectBox (function);AnswerBox (function).

Platform(s) Windows and Macintosh.

Page 369: Working Model 2D - User's Manual

Chapter 2 OpenFilename$ (function) 365

PlatformNotes:

Windows

The extensions$ parameter must be in the following format:

type:ext[,ext][;type:ext[,ext]]...

Placeholder Description

type Specifies the name of the grouping of files, such as All Files.

ext Specifies a valid file extension, such as *.BAT or *.?F?.

For example, the following are valid extensions$ specifications:

"All Files:*.*""Documents:*.TXT,*.DOC""All Files:*.*;Documents:*.TXT,*.DOC"

PlatformNotes:

Macintosh

On the Macintosh, the extensions$ parameter contains a comma-separated listof four-character file types. For example:

"TEXT,XLS4,MSWD"

On the Macintosh, the title$ parameter is ignored.

Page 370: Working Model 2D - User's Manual

366 Working Model Basic User's Manual

Operator Precedence (topic)The following table shows the precedence of the operators supported by WMBasic. Operations involving operators of higher precedence occur beforeoperations involving operators of lower precedence. When operators of equalprecedence occur together, they are evaluated from left to right.

Operator Description Precedence Order

() Parentheses Highest^ Exponentiation- Unary minus/, * Division and multiplication\ Integer divisionMod Modulo+, - Addition and subtraction& String concatenation=, <>, >, <, <=, >= RelationalLike, Is String and object comparisonNot Logical negationAnd Logical or binary conjunctionOr Logical or binary disjunctionXor, Eqv, Imp Logical or binary operators Lowest

The precedence order can be controlled using parentheses, as shown below:

a = 4 + 3 * 2 'a becomes 10.a = (4 + 3) * 2 'a becomes 14.

Page 371: Working Model 2D - User's Manual

Chapter 2 Operator Precision (topic) 367

Operator Precision (topic)When numeric, binary, logical or comparison operators are used, the data typeof 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 Integeroperand to a Long, then preforms a long addition, overflowing only if theresult cannot be contained with a Long. The order of precision is shown in thefollowing table:

Empty Least precise

Boolean

Integer

Long

Single

Date

Double

Currency Most precise

There are exceptions noted in the descriptions of each operator.

The rules for operand conversion are further complicated when an operator isused with variant data. In many cases, an overflow causes automatic promotionof the result to the next highest precise data type. For example, adding twoInteger variants results in an Integer variant unless it overflows, in whichcase the result is automatically promoted to a Long variant.

Option Base (statement)Syntax Option Base {0 | 1}

Description Sets the lower bound for array declarations.

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).

End Sub

See Also Dim (statement); Public (statement); Private (statement).

Platform(s) Windows and Macintosh.

Page 372: Working Model 2D - User's Manual

368 Working Model Basic User's Manual

Option Compare (statement)Syntax Option Compare [Binary | Text]

Description Controls how strings are compared.

Comments When Option Compare is set to Binary, then string comparisons are case-sensitive (e.g., "A" does not equal "a"). When it is set to Text, stringcomparisons are case-insensitive (e.g., "A" is equal to "a").

The default value for Option Compare is Binary.

The Option Compare statement affects all string comparisons in anystatements that follow the Option Compare statement. Additionally, thesetting affects the default behavior of Instr, StrComp, and the Likeoperator. The following table shows the types of string comparisons affected bythis setting:

> < <><= >= InstrStrComp Like

The Option Compare statement must appear outside the scope of allsubroutines and functions. In other words, it cannot appear within a Sub orFunction block.

Page 373: Working Model 2D - User's Manual

Chapter 2 Option CStrings (statement) 369

Example 'This example shows the use of Option Compare.

Option Compare BinarySub CompareBinary

a$ = "This String Contains UPPERCASE."b$ = "this string contains uppercase."If a$ = b$ Then

MsgBox "The two strings were compared case-insensitive."Else

MsgBox "The two strings were compared case-sensitive."End If

End Sub

Option Compare TextSub CompareText

a$ = "This String Contains UPPERCASE."b$ = "this string contains uppercase."If a$ = b$ Then

MsgBox "The two strings were compared case-insensitive."Else

MsgBox "The two strings were compared case-sensitive."End If

End Sub

Sub Main()CompareBinary 'Calls subroutine above.CompareText 'Calls subroutine above.

End Sub

See Also Like (operator); InStr (function); StrComp (function); Comparison Operators(topic).

Platform(s) Windows and Macintosh.

Option CStrings (statement)Syntax Option CStrings {On | Off}

Description Turns on or off the ability to use C-style escape sequences within strings.

Page 374: Working Model 2D - User's Manual

370 Working Model Basic User's Manual

Comments When Option CStrings On is in effect, the compiler treats the backslashcharacter as an escape character when it appears within strings. An escapecharacter is simply a special character that cannot otherwise be ordinarily typedby the computer keyboard.

Escape Description Equivalent Expression

\r Carriage return Chr$(13)\n Line feed Chr$(10)\a Bell Chr$(7)\b Backspace Chr$(8)\f Form feed Chr$(12)\t Tab Chr$(9)\v Vertical tab Chr$(11)\0 Null Chr$(0)\" Double quotation mark "" or Chr$(34)\\ Backslash Chr$(92)\? Question mark ?\' Single quotation mark'\xhh Hexadecimal number Chr$(Val("&Hhh))\ooo Octal number Chr$(Val("&Oooo"))\anycharacter Any character anycharacter

With hexadecimal values, WM Basic stops scanning for digits when itencounters a nonhexadecimal digit or two digits, whichever comes first.Similarly, with octal values, WM Basic stops scanning when it encounters anonoctal digit or three digits, whichever comes first.

When Option CStrings Off is in effect, then the backslash character has nospecial 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

Platform(s) Windows and Macintosh.

OptionButton (statement)Syntax OptionButton X,Y,width,height,title$ [,.Identifier]

Description Defines an option button within a dialog box template.

Page 375: Working Model 2D - User's Manual

Chapter 2 OptionEnabled (function) 371

Comments This statement can only appear within a dialog box template (i.e., between theBegin 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)relative to the upper left corner of the dialog box.

width, height Integer coordinates specifying the dimensions of the control in dialog units.

title$ String containing text that appears within the option button. This text maycontain an ampersand character to denote an accelerator letter, such as"&Portrait" for Portrait, which can be selected by pressing the Paccelerator.

.Identifier Name by which this control can be referenced by statements in a dialogfunction (such as DlgFocus and DlgEnable).

Example See OptionGroup (statement).

See Also CancelButton (statement); CheckBox (statement); ComboBox (statement);Dialog (function); Dialog (statement); DropListBox (statement); GroupBox(statement); ListBox (statement); OKButton (statement); OptionGroup(statement); Picture (statement); PushButton (statement); Text (statement);TextBox (statement); Begin Dialog (statement), PictureButton (statement).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

On Windows, accelerators are underlined, and the accelerator combinationAlt+letter is used.

PlatformNotes:

Macintosh

On the Macintosh, accelerators are normal in appearance, and the acceleratorcombination Command+letter is used.

OptionEnabled (function)Syntax OptionEnabled(name$ | id)

Description Returns True if the specified option button is enabled within the currentwindow or dialog box; returns False otherwise.

Page 376: Working Model 2D - User's Manual

372 Working Model Basic User's Manual

Comments This function is used to determine whether a given option button is enabledwithin the current window or dialog box. If an option button is enabled, then itsvalue can be set using the SetOption statement.

The OptionEnabled statement takes the following parameters:

Parameter Description

name$ String containing the name of the option button.

id Integer specifying the ID of the option button.

Note: The OptionEnabled function is used to determine whether an optionbutton is enabled in another application's dialog box. Use the DlgEnablefunction with dynamic dialog boxes.

Example 'This example checks to see whether the option button is enabled before'setting it.

If OptionEnabled("Tile") ThenSetOption "Tile"

End If

See Also GetOption (function); OptionExists (function); SetOption (statement).

Platform(s) Windows.

OptionExists (function)Syntax OptionExists(name$ | id)

Description Returns True if the specified option button exists within the current window ordialog box; returns False otherwise.

Comments This function is used to determine whether a given option button exists withinthe current window or dialog box.

The OptionExists statement takes the following parameters:

Parameter Description

name$ String containing the name of the option button.

id Integer specifying the ID of the option button.

Note: The OptionExists function is used to determine whether an optionbutton exists in another application's dialog box. There is no equivalentfunction for use with dynamic dialog boxes.

Page 377: Working Model 2D - User's Manual

Chapter 2 OptionGroup (statement) 373

Example 'This example checks to see whether the option button exists and isenabled'before setting it.

If OptionExists("Tile") ThenIf OptionEnabled("Tile") Then

SetOption("Tile")End If

End If

See Also GetOption (function); OptionEnabled (function); SetOption (statement).

Platform(s) Windows.

OptionGroup (statement)Syntax OptionGroup .Identifier

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 optionbuttons can be referenced by statements in a dialog function (such asDlgFocus and DlgEnable). This parameter also creates an integer variablewhose value corresponds to the index of the selected option button within thegroup (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 (i.e., between theBegin Dialog and End Dialog statements).

When the dialog box is created, the option button specified by .Identifier will beon; all other option buttons in the group will be off. When the dialog box isdismissed, the .Identifier will contain the selected option button.

Example 'This example creates a group of option buttons.

Sub Main()Begin Dialog PrintTemplate 16,31,128,65,"Print"

GroupBox 8,8,64,52,"Orientation",.JunkOptionGroup .Orientation

OptionButton 16,20,37,8,"Portrait",.PortraitOptionButton 16,32,51,8,"Landscape",.LandscapeOptionButton 16,44,49,8,"Don't Care",.DontCare

OKButton 80,8,40,14End DialogDim PrintDialog As PrintTemplateDialog PrintDialog

End Sub

Page 378: Working Model 2D - User's Manual

374 Working Model Basic User's Manual

See Also CancelButton (statement); CheckBox (statement); ComboBox (statement);Dialog (function); Dialog (statement); DropListBox (statement); GroupBox(statement); ListBox (statement); OKButton (statement); OptionButton(statement); Picture (statement); PushButton (statement); Text (statement);TextBox (statement); Begin Dialog (statement), PictureButton (statement).

Platform(s) Windows and Macintosh.

Or (operator)Syntax expression1 Or expression2

Description Performs a logical or binary disjunction on two expressions.

Comments If both expressions are either Boolean, Boolean variants, or Null variants,then a logical disjunction is performed as follows:

If the first and the second then theexpression is expression is result is

True True TrueTrue False TrueTrue Null TrueFalse True TrueFalse False FalseFalse Null NullNull True TrueNull False NullNull Null Null

Binary Disjunction

If the two expressions are Integer, then a binary disjunction is performed,returning an Integer result. All other numeric types (including Emptyvariants) 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 thebinary representations of the two expressions according to the following table:

1 Or 1 = 1 Example:0 Or 1 = 1 5 101010011 Or 0 = 1 6 01101010 0 Or 0 = 0 Or 11101011

Page 379: Working Model 2D - User's Manual

Chapter 2 Pi (constant) 375

Examples 'This first example shows the use of logical Or.

Dim s$ As String

s$ = InputBox$("Enter a string.")If s$ = "" Or Mid$(s$,1,1) = "A" Then

s$ = LCase$(s$)End If

'This second example shows the use of binary Or.

Dim w As Integer

TryAgain:s$ = InputBox$("Enter a hex number (four digits max).")If Mid$(s$,1,1) <> "&" Then

s$ = "&H" & s$End IfIf Not IsNumeric(s$) Then Goto TryAgain

w = CInt(s$)MsgBox "Your number is &H" & Hex$(w)w = w Or &H8000MsgBox "Your number with the high bit set is &H" & Hex$(w)

See Also Operator Precedence (topic); Xor (operator); Eqv (operator); Imp (operator);And (operator).

Platform(s) Windows and Macintosh.

Pi (constant)Syntax Pi

Description The Double value 3.141592653589793238462643383279.

Comments Pi can also be determined using the following formula:

4 * Atn(1)

Example 'This example illustrates the use of the Pi constant.

Const crlf = Chr$(13) + Chr$(10)

Sub Main()dia# = 5circ# = Pi * dia#area# = Pi * ((dia# / 2) ^ 2)msg = "Diameter: 5" & crlfmsg = msg & "Circumference: " & Format(circ#,"Standard") & crlfmsg = msg & "Area: " & Format(area#,"Standard")MsgBox msg

End Sub

See Also Tan (function); Atn (function); Cos (function); Sin (function).

Platform(s) Windows and Macintosh.

Page 380: Working Model 2D - User's Manual

376 Working Model Basic User's Manual

Picture (statement)Syntax Picture X,Y,width,height,PictureName$,PictureType [,[.Identifier] [,style]]

Description Creates a picture control in a dialog box template.

Comments Picture controls are used for the display of graphics images only. The usercannot 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)relative 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 namespecifies the name of the file containing the image. If PictureType is 10, thenPictureName$ specifies the name of the image within the resource of thepicture library.

If PictureName$ is empty, then no picture will be associated with the control. Apicture can later be placed into the picture control using the DlgSetPicturestatement.

PictureType Integer specifying the source for the image. The following sources aresupported:

0 The image is contained in a file on disk.

10 The image is contained in a picture library asspecified by the PicName$ parameter on theBegin Dialog statement.

.Identifier Name by which this control can be referenced by statements in a dialogfunction (such as DlgFocus and DlgEnable). If omitted, then the first twowords of PictureName$ are used.

style Specifies whether the picture is drawn within a 3D frame. It can be any of thefollowing values:

0 Draw the picture control with a normal frame.

1 Draw the picture control with a 3D frame.

If omitted, then the picture control is drawn with a normal frame.

Page 381: Working Model 2D - User's Manual

Chapter 2 Picture (statement) 377

The picture control extracts the actual image from either a disk file or a picturelibrary. In the case of bitmaps, both 2- and 16-color bitmaps are supported. Inthe case of WMFs, WM Basic supports the Placeable Windows Metafile.

If PictureName$ is a zero-length string, then the picture is removed from thepicture control, freeing any memory associated with that picture.

Examples '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,14Picture 8,8,224,64,"c:\bitmaps\logo.bmp",0,.Logo

End DialogDim LogoDialog As LogoDialogTemplateDialog LogoDialog

End Sub

'This second example shows how to use a picture from a picture librarywith'a 3D frame.

Sub Main()Begin Dialog LogoDialogTemplate

16,31,288,76,"Introduction",,"pictures.dll"OKButton 240,8,40,14Picture 8,8,224,64,"CompanyLogo",10,.Logo,1

End DialogDim LogoDialog As LogoDialogTemplateDialog LogoDialog

End Sub

See Also CancelButton (statement); CheckBox (statement); ComboBox (statement);Dialog (function); Dialog (statement); DropListBox (statement); GroupBox(statement); ListBox (statement); OKButton (statement); OptionButton(statement); OptionGroup (statement); PushButton (statement); Text(statement); TextBox (statement); Begin Dialog (statement), PictureButton(statement) , DlgSetPicture (statement).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Picture controls can contain either a bitmap or a WMF (Windows metafile).When extracting images from a picture library, WM Basic assumes that theresource type for metafiles is 256.

Picture libraries are implemented as DLLs on Windows.

PlatformNotes:

Macintosh

Picture controls on the Macintosh can contain only PICT images. These arecontained in files of type PICT.

Picture libraries on the Macintosh are files with collections of named PICTresources. The PictureName$ parameter corresponds to the name of one theresources as it appears within the file.

Page 382: Working Model 2D - User's Manual

378 Working Model Basic User's Manual

PictureButton (statement)Syntax PictureButton X,Y,width,height,PictureName$,PictureType [,.Identifier]

Description Creates a picture button control in a dialog box template.

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 graphicimage 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)relative 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 namespecifies the name of the file containing the image. If PictureType is 10, thenPictureName$ specifies the name of the image within the resource of thepicture library.

If PictureName$ is empty, then no picture will be associated with the control. Apicture can later be placed into the picture control using the DlgSetPicturestatement.

PictureType Integer specifying the source for the image. The following sources aresupported:

0 The image is contained in a file on disk.

10 The image is contained in a picture library asspecified by the PicName$ parameter on theBegin Dialog statement.

.Identifier Name by which this control can be referenced by statements in a dialogfunction (such as DlgFocus and DlgEnable).

The picture button control extracts the actual image from either a disk file or apicture library, depending on the value of PictureType. The supported pictureformats vary from platform to platform.

If PictureName$ is a zero-length string, then the picture is removed from thepicture button control, freeing any memory associated with that picture.

Page 383: Working Model 2D - User's Manual

Chapter 2 Pmt (function) 379

Examples '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,14PictureButton 8,4,224,64,"c:\bitmaps\logo.bmp",0,.Logo

End DialogDim LogoDialog As LogoDialogTemplateDialog LogoDialog

End Sub

'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,14PictureButton 8,4,224,64,"CompanyLogo",10,.Logo

End DialogDim LogoDialog As LogoDialogTemplateDialog LogoDialog

End Sub

See Also CancelButton (statement); CheckBox (statement); ComboBox (statement);Dialog (function); Dialog (statement); DropListBox (statement); GroupBox(statement); ListBox (statement); OKButton (statement); OptionButton(statement); OptionGroup (statement); PushButton (statement); Text(statement); TextBox (statement); Begin Dialog (statement), Picture(statement), DlgSetPicture (statement).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Picture controls can contain either a bitmap or a WMF (Windows metafile).When extracting images from a picture library, WM Basic assumes that theresource type for metafiles is 256.

Picture libraries are implemented as DLLs on Windows.

PlatformNotes:

Macintosh

Picture controls on the Macintosh can contain only PICT images. These arecontained in files of type PICT.

Picture libraries on the Macintosh are files with collections of named PICTresources. The PictureName$ parameter corresponds to the name of one theresources as it appears within the file.

Pmt (function)Syntax Pmt(Rate,NPer,Pv,Fv,Due)

Description Returns the payment for an annuity based on periodic fixed payments and aconstant rate of interest.

Page 384: Working Model 2D - User's Manual

380 Working Model Basic User's Manual

Comments An annuity is a series of fixed payments made to an insurance company orother investment company over a period of time. Examples of annuities aremortgages and monthly savings plans.

The Pmt function requires the following parameters:

Parameter Description

Rate Double representing the interest rate per period. If the periods are given inmonths, be sure to normalize annual rates by dividing them by 12.

NPer Double representing the total number of payments in the annuity.

Pv Double representing the present value of your annuity. In the case of a loan, thepresent value would be the amount of the loan.

Fv Double representing the future value of your annuity. In the case of a loan, thefuture value would be 0.

Due Integer indicating when payments are due for each payment period. A 0specifies payment at the end of each period, whereas a 1 specifies payment atthe start of each period.

Rate and NPer must be expressed in the same units. If Rate is expressed inmonths, then NPer must also be expressed in months.

Positive numbers represent cash received, whereas negative numbers representcash paid out.

Example 'This example calculates the payment necessary to repay a $1,000.00loan'over 36 months at an annual rate of 10%. Payments are due at thebeginning'of the period.

Sub Main()x = Pmt((.1/12),36,1000.00,0,1)msg = "The payment to amortize $1,000 over 36 months @ 10% is: "MsgBox msg & Format(x,"Currency")

End Sub

See Also IPmt (function); NPer (function); PPmt (function); Rate (function).

Platform(s) Windows and Macintosh.

PopupMenu (function)Syntax PopupMenu(MenuItems$())

Description Displays a pop-up menu containing the specified items, returning an Integerrepresenting the index of the selected item.

Page 385: Working Model 2D - User's Manual

Chapter 2 PPmt (function) 381

Comments If no item is selected (i.e., the pop-up menu is canceled), then a value of 1 lessthan the lower bound is returned (normally, –1).

This function creates a pop-up menu using the string elements in the givenarray. Each array element is used as a menu item. A zero-length string results ina separator bar in the menu.

The pop-up menu is created with the upper left corner at the current mouseposition.

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 ifanother script executes this function while a pop-up menu is visible.

Example Sub Main()Dim a$()AppList a$w% = PopupMenu(a$)

End Sub

See Also SelectBox (function).

Platform(s) Windows.

PPmt (function)Syntax PPmt(Rate,Per,NPer,Pv,Fv,Due)

Description Calculates the principal payment for a given period of an annuity based onperiodic, fixed payments and a fixed interest rate.

Page 386: Working Model 2D - User's Manual

382 Working Model Basic User's Manual

Comments An annuity is a series of fixed payments made to an insurance company orother investment company over a period of time. Examples of annuities aremortgages and monthly savings plans.

The PPmt function requires the following parameters:

Parameter Description

Rate Double representing the interest rate per period.

Per Double representing the number of payment periods. Per can be no less than 1and no greater than NPer.

NPer Double representing the total number of payments in your annuity.

Pv Double representing the present value of your annuity. In the case of a loan, thepresent value would be the amount of the loan.

Fv Double representing the future value of your annuity. In the case of a loan, thefuture value would be 0.

Due Integer indicating when payments are due. If this parameter is 0, thenpayments are due at the end of each period; if it is 1, then payments are due atthe start of each period.

Rate and NPer must be in the same units to calculate correctly. If Rate isexpressed in months, then NPer must also be expressed in months.

Negative values represent payments paid out, whereas positive values representpayments received.

Page 387: Working Model 2D - User's Manual

Chapter 2 Print (statement) 383

Example 'This example calculates the principal paid during each year on a loanof'$1,000.00 with an annual rate of 10% for a period of 10 years. Theresult'is displayed as a table containing the following information: payment,'principal payment, principal balance.

Const crlf = Chr$(13) + Chr$(10)

Sub Main()pay = Pmt(.1,10,1000.00,0,1)msg = "Amortization table for 1,000" & crlf & "at 10% annually for"msg = msg & " 10 years: " & crlf & crlfbal = 1000.00For per = 1 to 10

prn = PPmt(.1,per,10,1000,0,0)bal = bal + prnmsg = msg & Format(pay,"Currency") & " " &

Format$(Prn,"Currency")msg = msg & " " & Format(bal,"Currency") & crlf

Next perMsgBox msg

End Sub

See Also IPmt (function); NPer (function); Pmt (function); Rate (function).

Platform(s) Windows and Macintosh.

Print (statement)Syntax Print [[{Spc(n) | Tab(n)}][expressionlist][{; | ,}]]

Description Prints data to an output device.

Page 388: Working Model 2D - User's Manual

384 Working Model Basic User's Manual

Comments The actual output device depends on the platform on which WM Basic isrunning.

The following table describes how data of different types is written:

Data Type Description

String Printed in its literal form, with no enclosing quotes.

Any numeric type Printed with an initial space reserved for the sign (space = positive).Additionally, there is a space following each number.

Boolean Printed as "True" or "False".

Date Printed using the short date format. If either the date or time component ismissing, only the provided portion is printed (this is consistent with the"general date" format understood by the Format/Format$ functions).

Empty Nothing is printed.

Null Prints "Null".

User-defined errors Printed as "Error code", where code is thevalue of the user-defined error. The word "Error" is not translated.

Each expression in expressionlist is separated with either a comma (,) or asemicolon (;). A comma means that the next expression is output in the nextprint zone. A semicolon means that the next expression is output immediatelyafter 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, thena carriage return is printed to the file. If the last expression ends with asemicolon, no carriage return is printedthe next Print statement will outputinformation immediately following the expression. If the last expression in thelist ends with a comma, the file pointer is positioned at the start of the next printzone on the current line.

The Tab and Spc functions provide additional control over the columnposition. The Tab function moves the file position to the specified column,whereas the Spc function outputs the specified number of spaces.

Page 389: Working Model 2D - User's Manual

Chapter 2 Print# (statement) 385

Examples Sub Main()i% = 10s$ = "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$ inprint

'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 column30.

Print i%;Tab(30);s$

'This example prints the value of i% and s$.Print i%;s$,Print 67

End Sub

See Also ViewportOpen (statement).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Under Windows, this statement writes data to a viewport window.

If no viewport window is open, then the statement is ignored. Printinginformation to a viewport window is a convenient way to output debugginginformation. To open a viewport window, use the following statement:

ViewportOpen

PlatformNotes:

Macintosh

On the Macintosh, the Print statement prints data to stdout.

Print# (statement)Syntax Print [#]filenumber, [[{Spc(n) | Tab(n)}][expressionlist][{;|,}]]

Description Writes data to a sequential disk file.

Page 390: Working Model 2D - User's Manual

386 Working Model Basic User's Manual

Comments The filenumber parameter is a number that is used by WM Basic to refer to theopen file—the number passed to the Open statement.

The following table describes how data of different types is written:

Data Type Description

String Printed in its literal form, with no enclosing quotes.

Any numeric type Printed with an initial space reserved for the sign (space = positive).Additionally, there is a space following each number.

Boolean Printed as "True" or "False".

Date Printed using the short date format. If either the date or time component ismissing, only the provided portion is printed (this is concistent with the"general date" format understood by the Format/Format$ functions).

Empty Nothing is printed.

Null Prints "Null".

User-defined errors Printed to files as "Error code", wherecode is the value of the user-defined error. The word "Error" is not translated.

Each expression in expressionlist is separated with either a comma (,) or asemicolon (;). A comma means that the next expression is output in the nextprint zone. A semicolon means that the next expression is output immediatelyafter 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, thenan end-of-line is printed to the file. If the last expression ends with a semicolon,no end-of-line is printedthe next Print statement will output informationimmediately following the expression. If the last expression in the list ends witha comma, the file pointer is positioned at the start of the next print zone on thecurrent 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 pointeris positioned on a new line.

The Print statement can only be used with files that are opened in Outputor 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 theSpc function outputs the specified number of spaces.

In order to correctly read the data using the Input# statement, you shouldwrite the data using the Write statement.

Page 391: Working Model 2D - User's Manual

Chapter 2 PrinterGetOrientation (function) 387

Examples Sub Main()'This example opens a file and prints some data.Open "test.dat" For Output As #1i% = 10s$ = "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 tenspaces.

Print #1,i%;Spc(10);s$

'This example prints the value of i in column 1 and s$ in column30.

Print #1,i%;Tab(30);s$

'This example prints the value of i% and s$.Print #1,i%;s$,Print #1,67

Close #1Kill "test.dat"

End Sub

See Also Open (statement); Put (statement); Write# (statement).

Platform(s) Windows and Macintosh.

PlatformNotes:

The end-of-line character is different on many platforms. On some platforms, itis defined as a carriage-return/line-feed pair, and on other platforms, it isdefined as only a line feed. The WM Basic statements that read sequential filesdo not care about the end-of-line character—either will work.

PrinterGetOrientation (function)Syntax PrinterGetOrientation[()]

Description Returns an Integer representing the current orientation of paper in thedefault printer.

Comments PrinterGetOrientation returns ebPortrait if the printer orientationis set to portrait; otherwise, it returns ebLandscape.

This function loads the printer driver and therefore may be slow.

Page 392: Working Model 2D - User's Manual

388 Working Model Basic User's Manual

Example 'This example toggles the printer orientation.

Sub Main()If PrinterGetOrientation = ebLandscape Then

PrinterSetOrientation ebPortraitElse

PrinterSetOrientation ebLandscapeEnd If

End Sub

See Also PrinterSetOrientation (statement).

Platform(s) Windows.

PlatformNotes:

Windows

The default printer is determined by examining the device= line in the[windows] section of the win.ini file.

PrinterSetOrientation (statement)Syntax PrinterSetOrientation NewSetting

Description Sets the orientation of the default printer to NewSetting.

Comments The possible values for NewSetting are as follows

Setting Description

ebLandscape Sets printer orientation to landscape.

ebPortrait Sets printer orientation to portrait.

This function loads the printer driver for the default printer and therefore maybe slow.

Example See PrinterGetOrientation (function).

See Also PrinterGetOrientation (function).

Platform(s) Windows.

PlatformNotes:

Windows

The default printer is determined by examining the device= line in the[windows] section of the win.ini file.

PrintFile (function)Syntax PrintFile(filename$)

Description Prints the filename$ using the application to which the file belongs.

Page 393: Working Model 2D - User's Manual

Chapter 2 Private (statement) 389

Comments PrintFile returns an Integer indicating success or failure.

If an error occurs executing the associated application, then PrintFilegenerates a trappable runtime error, returning 0 for the result. Otherwise,PrintFile returns a value representing that application to the system. Thisvalue is suitable for calling the AppActivate statement.

Example 'This example asks the user for the name of a text file, then printsit.

Sub Main()f$ = OpenFilename$("Print Text File","Text Files:*.txt")If f$ <> "" Then

rc% = PrintFile(f$)If rc% > 32 Then

MsgBox "File is printing."End If

End IfEnd Sub

See Also Shell (function).

Platform(s) Windows.

PlatformNotes:

Windows

This function invokes the Windows 3.1 shell functions that cause an applicationto execute and print a file. The application executed by PrintFile depends onyour system's file associations.

Private (statement)Syntax Private name [(subscripts)] [As type] [,name [(subscripts)] [As type]]...

Description Declares a list of private variables and their corresponding types and sizes.

Page 394: Working Model 2D - User's Manual

390 Working Model Basic User's Manual

Comments Private variables are global to every Sub and Function within the currentlyexecuting script.

If a type-declaration character is used when specifying name (such as %, @, &, $,or !), the optional [As type] expression is not allowed. For example, thefollowing are allowed:

Private foo As IntegerPrivate foo%

The subscripts parameter allows the declaration of arrays. This parameter usesthe following syntax:

[lower To] upper [,[lower To] upper]...

The lower and upper parameters are integers specifying the lower and upperbounds of the array. If lower is not specified, then the lower bound as specifiedby Option Base is used (or 1 if no Option Base statement has beenencountered). 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 beany of the following data types: String, Integer, Long, Single, Double,Currency, Object, data object, built-in data type, or any user-defined datatype.

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 inwhich 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.

Page 395: Working Model 2D - User's Manual

Chapter 2 Public (statement) 391

Initial Values

All declared variables are given initial values, as described in the followingtable:

Data Type Initial Value

Integer 0

Long 0

Double 0.0

Single 0.0

Currency 0.0

Object Nothing

Date December 31, 1899 00:00:00

Boolean False

Variant Empty

String "" (zero-length string)

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.

Example See Public (statement).

See Also Dim (statement); Redim (statement); Public (statement); Option Base(statement).

Platform(s) Windows and Macintosh.

Public (statement)Syntax Public name [(subscripts)] [As type] [,name [(subscripts)] [As type]]...

Description Declares a list of public variables and their corresponding types and sizes.

Page 396: Working Model 2D - User's Manual

392 Working Model Basic User's Manual

Comments Public variables are global to all Subs and Functions 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, thefollowing are allowed:

Public foo As integerPublic foo%

The subscripts parameter allows the declaration of arrays. This parameter usesthe following syntax:

[lower To] upper [,[lower To] upper]...

The lower and upper parameters are integers specifying the lower and upperbounds of the array. If lower is not specified, then the lower bound as specifiedby Option Base is used (or 1 if no Option Base statement has beenencountered). 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 beany of the following data types: String, Integer, Long, Single, Double,Currency, Object, data object, built-in data type, or any user-defined datatype.

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 inwhich it is used.

For compatibility, the keyword Global is also supported. It has the samemeaning 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.

Page 397: Working Model 2D - User's Manual

Chapter 2 Public (statement) 393

Initial Values

All declared variables are given initial values, as described in the followingtable:

Data Type Initial Value

Integer 0

Long 0

Double 0.0

Single 0.0

Currency 0.0

Date December 31, 1899 00:00:00

Object Nothing

Boolean False

Variant Empty

String "" (zero-length string)

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 sharedvariables are the same in each script that uses those variables. If the publicvariable being shared is a user-defined structure, then the structure definitionsmust 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 andArea.

Const crlf = Chr$(13) + Chr$(10)

Public x#, ar#

Sub Area()ar# = (x# ^ 2) * Pi

End Sub

Sub Main()msg = "The area of the ten circles are:" & crlfFor x# = 1 To 10

Areamsg = msg & x# & ": " & ar# & Basic.Eoln$

Next x#MsgBox msg

End Sub

Page 398: Working Model 2D - User's Manual

394 Working Model Basic User's Manual

See Also Dim (statement); Redim (statement); Private (statement); Option Base(statement).

Platform(s) Windows and Macintosh.

PushButton (statement)Syntax PushButton X,Y,width,height,title$ [,.Identifier]

Description Defines a push button within a dialog box template.

Comments Choosing a push button causes the dialog box to close (unless the dialogfunction redefines this behavior).

This statement can only appear within a dialog box template (i.e., between theBegin 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)relative to the upper left corner of the dialog box.

width, height Integer coordinates specifying the dimensions of the control in dialog units.

title$ String containing the text that appears within the push button. This text maycontain 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 dialogfunction (such as DlgFocus and DlgEnable).

If a push button is the default button, it can be selected by pressing Enter on anonbutton control.

A dialog box template must contain at least one OKButton, CancelButton,or PushButton statement (otherwise, the dialog box cannot be dismissed).

Page 399: Working Model 2D - User's Manual

Chapter 2 Put (statement) 395

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,.OKCancelButton 8,24,40,14,.CancelPushButton 8,44,40,14,"1",.Button1PushButton 8,64,40,14,"2",.Button2PushButton 56,4,40,14,"3",.Button3PushButton 56,24,40,14,"4",.Button4PushButton 56,44,40,14,"5",.Button5PushButton 56,64,40,14,"6",.Button6

End DialogDim ButtonDialog As ButtonTemplateWhichButton% = Dialog(ButtonDialog)MsgBox "You pushed button " & WhichButton%

End Sub

See Also CancelButton (statement); CheckBox (statement); ComboBox (statement);Dialog (function); Dialog (statement); DropListBox (statement); GroupBox(statement); ListBox (statement); OKButton (statement); OptionButton(statement); OptionGroup (statement); Picture (statement); Text (statement);TextBox (statement); Begin Dialog (statement), PictureButton (statement).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

On Windows, accelerators are underlined, and the accelerator combinationAlt+letter is used.

PlatformNotes:

Macintosh

On the Macintosh, accelerators are normal in appearance, and the acceleratorcombination Command+letter is used.

Put (statement)Syntax Put [#]filenumber, [recordnumber], variable

Description Writes data from the specified variable to a Random or Binary file.

Page 400: Working Model 2D - User's Manual

396 Working Model Basic User's Manual

Comments The Put statement accepts the following parameters:

Parameter Description

filenumber Integer representing the file to be written to. This is the same value asreturned 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 withthe beginning of the file (the first byte is 1). For Random files, this numberrepresents the record number starting with the beginning of the file (the firstrecord 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 thefollowing example:

Put #1,,recvar

If recordlength is specified, it overrides any previous change in file positionspecified with the Seek statement.

Page 401: Working Model 2D - User's Manual

Chapter 2 Put (statement) 397

The variable parameter is the name of any variable of any of the followingtypes:

Variable Type File Storage Description

Integer 2 bytes are written to the file.

Long 4 bytes are written to the file.

String (variable-length)In Binary files, variable-length strings are written byfirst determining the specified string variable's length,then writing that many bytes to the file.

In Random files, variable-length strings are written byfirst writing a 2-byte length, then writing that manycharacters to the file.

String (fixed-length) Fixed-length strings are written to Random and Binaryfiles in the same way: the number of characters equalto the string's declared length are written.

Double 8 bytes are written to the file (IEEE format).

Single 4 bytes are written to the file (IEEE format).

Date 8 bytes are written to the file (IEEE double format).

Boolean 2 bytes are written to the file (either –1 for True or 0for False).

Variant A 2-byte VarType is written to the file followed by thedata as described above. With variants of type 10(user-defined errors), the 2-byte VarType is followedby a 2-byte unsigned integer (the error value), which isthen followed by 2 additional bytes of information.

The exception is with strings, which are alwayspreceded by a 2-byte string length.

Page 402: Working Model 2D - User's Manual

398 Working Model Basic User's Manual

User-defined types Each member of a user-defined data type is writtenindividually.

In Binary files, variable-length strings within user-defined types are written by first writing a 2-bytelength followed by the string's content. This storage isdifferent than variable-length strings outside of user-defined types.

When writing user-defined types, the record lengthmust be greater than or equal to the combined size ofeach element within the data type.

Arrays Arrays cannot be written to a file using the Putstatement.

Objects Object variables cannot be written to a file using thePut statement.

With Random files, a runtime error will occur if the length of the data beingwritten exceeds the record length (specified as the reclen parameter with theOpen statement). If the length of the data being written is less than the recordlength, the entire record is written along with padding (whatever data happensto be in the I/O buffer at that time). With Binary files, the data elements arewritten 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 #1For x = 1 To 10

r% = x * 10Put #1,x,r%

Next xClose

Open "test.dat" For Random Access Read As #1For x = 1 To 10

Get #1,x,r%msg = msg & "Record " & x & " is: " & r% & Basic.Eoln$

Next x

MsgBox msgCloseKill "test.dat"

End Sub

See Also Open (statement); Put (statement); Write# (statement); Print# (statement).

Page 403: Working Model 2D - User's Manual

Chapter 2 Pv (function) 399

Platform(s) Windows and Macintosh.

Pv (function)Syntax Pv(Rate,NPer,Pmt,Fv,Due)

Description Calculates the present value of an annuity based on future periodic fixedpayments and a constant rate of interest.

Comments The Pv function requires the following parameters:

Parameter Description

Rate Double representing the interest rate per period. When used with monthlypayments, be sure to normalize annual percentage rates by dividing them by 12.

NPer Double representing the total number of payments in the annuity.

Pmt Double representing the amount of each payment per period.

Fv Double representing the future value of the annuity after the last payment hasbeen 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 0specifies payment at the end of each period, whereas a 1 specifies payment atthe start of each period.

Rate and NPer must be expressed in the same units. If Rate is expressed inmonths, then NPer must also be expressed in months.

Positive numbers represent cash received, whereas negative numbers representcash paid out.

Example 'This example demonstrates the present value (the amount you'd have topay'now) for a $100,000 annuity that pays an annual income of $5,000 over20'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 (function); IRR (function); MIRR (function); Npv (function).

Platform(s) Windows and Macintosh.

QueEmpty (statement)Syntax QueEmpty

Page 404: Working Model 2D - User's Manual

400 Working Model Basic User's Manual

Description Empties the current event queue.

Comments After this statement, QueFlush will do nothing.

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,1393QueMouseUp ebLeftButton,4147,2363QueFlush True

End Sub

Platform(s) Windows.

QueFlush (statement)Syntax QueFlush isSaveState

Description Plays back events that are stored in the current event queue.

Comments After QueFlush is finished, the queue is empty.

If isSaveState is True, then QueFlush saves the state of the Caps Lock, NumLock, Scroll Lock, and Insert and restores the state after the QueFlush iscomplete. If this parameter is False, these states are not restored.

The function does not return until the entire queue has been played.

Example 'This example pumps some keys into Notepad.

Sub Main()AppActivate "Notepad"QueKeys "This is a test{Enter}"QueFlush True 'Play back the queue.

End Sub

Platform(s) Windows.

PlatformNotes:

Windows

The QueFlush statement uses the Windows journaling mechanism to replaythe mouse and keyboard events stored in the queue. As a result, the mouseposition may be changed. Furthermore, events can be played into any Windowsapplication, including DOS applications running in a window.

QueKeyDn (statement)Syntax QueKeyDn KeyString$ [,time]

Description Appends key-down events for the specified keys to the end of the current eventqueue.

Page 405: Working Model 2D - User's Manual

Chapter 2 QueKeys (statement) 401

Comments The QueKeyDn statement accepts the following parameters:

Parameter Description

KeyString$ String containing the keys to be sent. The format for KeyString$ is describedunder the SendKeys statement.

time Integer specifying the number of milliseconds devoted for the output of theentire KeyString$ parameter. It must be within the following range:

0 <= time <= 32767

For example, if time is 5000 (5 seconds) and the KeyString$ parameter containsten keys, then a key will be output every 1/2 second. If unspecified (or 0), thekeys will play back at full speed.

The QueFlush command is used to play back the events stored in the currentevent queue.

Example 'This example plays back a Ctrl + mouse click.

Sub Main()QueEmptyQueKeyDn "^"QueMouseClick ebLeftButton 1024,792QueKeyUp "^"QueFlush True

End Sub

See Also DoKeys (statement); SendKeys (statement); QueKeys (statement); QueKeyUp(statement); QueFlush (statement).

Platform(s) Windows.

QueKeys (statement)Syntax QueKeys KeyString$ [,time]

Description Appends keystroke information to the current event queue.

Comments The QueKeys statement accepts the following parameters:

Parameter Description

KeyString$ String containing the keys to be sent. The format for KeyString$ is describedunder the SendKeys statement.

Page 406: Working Model 2D - User's Manual

402 Working Model Basic User's Manual

time Integer specifying the number of milliseconds devoted for the output of theentire KeyString$ parameter. It must be within the following range:

0 <= time <= 32767

For example, if time is 5000 (5 seconds) and the KeyString$ parameter containsten keys, then a key will be output every 1/2 second. If unspecified (or 0), thekeys will play back at full speed.

The QueFlush command is used to play back the events stored in the currentevent queue.

Example Sub Main()WinActivate "Notepad"QueEmptyQueKeys "This is a test.{Enter}This is on a new line.{Enter}"QueKeys "{Tab 3}This is indented with three tabs."QueKeys "Some special characters: {~}{^}{%}{+}~"QueKeys "Invoking the Find dialog.%Sf" 'Alt+S,FQueFlush True

End Sub

See Also DoKeys (statement); SendKeys (statement); QueKeyDn (statement); QueKeyUp(statement); QueFlush (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, you cannot send keystrokes to MS-DOS applications runningin a window.

QueKeyUp (statement)Syntax QueKeyUp KeyString$ [,time]

Description Appends key-up events for the specified keys to the end of the current eventqueue.

Comments The QueKeyUp statement accepts the following parameters:

Parameter Description

KeyString$ String containing the keys to be sent. The format for KeyString$ is describedunder the SendKeys statement.

Page 407: Working Model 2D - User's Manual

Chapter 2 QueMouseClick (statement) 403

time Integer specifying the number of milliseconds devoted for the output of theentire KeyString$ parameter. It must be within the following range:

0 <= time <= 32767

For example, if time is 5000 (5 seconds) and the KeyString$ parameter containsten keys, then a key will be output every 1/2 second. If unspecified (or 0), thekeys will play back at full speed.

The QueFlush command is used to play back the events stored in the currentevent queue.

Example See QueKeyDn (statement).

See Also DoKeys (statement); SendKeys (statement); QueKeys (statement); QueKeyDn(statement); QueFlush (statement).

Platform(s) Windows.

QueMouseClick (statement)Syntax QueMouseClick button,X,Y [,time]

Description Adds a mouse click to the current event queue.

Comments The QueMouseClick statement takes the following parameters:

Parameter Description

button Integer specifying which mouse button to click:

ebLeftButton Click the left mouse button.

ebRightButton Click the right mouse button.

X, Y Integer coordinates, in twips, where the mouse click is to be recorded.

time Integer specifying the delay in milliseconds between this event and theprevious event in the queue. If this parameter is omitted (or 0), the mouse clickwill play back at full speed.

A mouse click consists of a mouse button down at position X, Y, immediatelyfollowed by a mouse button up.

The QueFlush command is used to play back the events stored in the currentevent queue.

Page 408: Working Model 2D - User's Manual

404 Working Model Basic User's Manual

Example 'This example acvivates Notepad and invokes the Find dialog box. Itthen'uses the QueMouseClick command to click the Cancel button.

Sub Main()AppActivate "Notepad" 'Activate Notepad.QueKeys "%Sf" 'Invoke the Find dialog box.QueFlush True 'Play this back (allow dialog box to open).QueSetRelativeWindow 'Set mouse relative to Find dialog box.QueMouseClick ebLeftButton,7059,1486 'Click the Cancel button.QueFlush True 'Play back the queue.

End Sub

See Also QueMouseDn (statement); QueMouseUp (statement); QueMouseDblClk(statement); QueMouseDblDn (statement); QueMouseMove (statement);QueMouseMoveBatch (statement); QueFlush (statement).

Platform(s) Windows.

QueMouseDblClk (statement)Syntax QueMouseDblClk button,X,Y [,time]

Description Adds a mouse double click to the current event queue.

Comments The QueMouseDblClk statement takes the following parameters:

Parameter Description

button Integer specifying which mouse button to double-click:

ebLeftButton Double-click the left mouse button.

ebRightButton Double-click the right mousebutton.

X, Y Integer coordinates, in twips, where the mouse double click is to be recorded.

time Integer specifying the delay in milliseconds between this event and theprevious event in the queue. If this parameter is omitted (or 0), the mousedouble click will play back at full speed.

A mouse double click consists of a mouse down/up/down/up at position X, Y.The events are queued in such a way that a double click is registered duringqueue playback.

The QueFlush command is used to play back the events stored in the currentevent queue.

Example 'This example double-clicks the left mouse button.

QueMouseDblClk ebLeftButton,344,360

Page 409: Working Model 2D - User's Manual

Chapter 2 QueMouseDblDn (statement) 405

See Also QueMouseClick (statement); QueMouseDn (statement); QueMouseUp (statement);QueMouseDblDn (statement); QueMouseMove (statement); QueMouseMoveBatch(statement); QueFlush (statement).

Platform(s) Windows.

QueMouseDblDn (statement)Syntax QueMouseDblDn button, X, Y [,time]

Description Adds a mouse double down to the end of the current event queue.

Comments The QueMouseDblDn statement takes the following parameters:

Parameter Description

button Integer specifying which mouse button to press:

ebLeftButton Click the left mouse button.

ebRightButton Click the right mouse button.

x,y Integer coordinates, in twips, where the mouse double down is to be recorded.

time Integer specifying the delay in milliseconds between this event and theprevious event in the queue. If this parameter is omitted (or 0), the mousedouble down will play back at full speed.

This statement adds a mouse double down to the current event queue. A doubledown consists of a mouse down/up/down at position X, Y.

The QueFlush command is used to play back the events stored in the currentevent queue.

Example 'This example double-clicks a word, then drags it to a new location.

Sub Main()QueFlush 'Start with empty queue.QueMouseDblDn ebLeftButton,356,4931 'Double-click, mouse still

down.QueMouseMove 600,4931 'Drag to new spot.QueMouseUp ebLeftButton 'Now release the mouse.QueFlush True 'Play back the queue.

End Sub

See Also QueMouseClick (statement); QueMouseDn (statement); QueMouseUp (statement);QueMouseDblClk (statement); QueMouseMove (statement); QueMouseMoveBatch(statement); QueFlush (statement).

Platform(s) Windows.

Page 410: Working Model 2D - User's Manual

406 Working Model Basic User's Manual

QueMouseDn (statement)Syntax QueMouseDn button,X,Y [,time]

Description Adds a mouse down to the current event queue.

Comments The QueMouseDn statement takes the following parameters:

Parameter Description

button Integer specifying which mouse button to press:

ebLeftButton Click the left mouse button.

ebRightButton Click the right mouse button.

X, Y Integer coordinates, in twips, where the mouse down is to be recorded.

time Integer specifying the delay in milliseconds between this event and theprevious event in the queue. If this parameter is omitted (or 0), the mouse downwill play back at full speed.

The QueFlush command is used to play back the events stored in the currentevent queue.

Example See QueEmpty (statement).

See Also QueMouseClick (statement); QueMouseUp (statement); QueMouseDblClk(statement); QueMouseDblDn (statement); QueMouseMove (statement);QueMouseMoveBatch (statement); QueFlush (statement).

Platform(s) Windows.

QueMouseMove (statement)Syntax QueMouseMove X,Y [,time]

Description Adds a mouse move to the current event queue.

Comments The QueMouseMove statement takes the following parameters:

Parameter Description

X, Y Integer coordinates, in twips, where the mouse is to be moved.

time Integer specifying the delay in milliseconds between this event and theprevious event in the queue. If this parameter is omitted (or 0), the mouse movewill play back at full speed.

The QueFlush command is used to play back the events stored in the currentevent queue.

Page 411: Working Model 2D - User's Manual

Chapter 2 QueMouseMoveBatch (statement) 407

Example See QueMouseDblDn (statement).

See Also QueMouseClick (statement); QueMouseDn (statement); QueMouseUp (statement);QueMouseDblClk (statement); QueMouseDblDn (statement);QueMouseMoveBatch (statement); QueFlush (statement).

Platform(s) Windows.

QueMouseMoveBatch (statement)Syntax QueMouseMoveBatch ManyMoves$

Description Adds a series of mouse-move events to the current event queue.

Comments The ManyMoves$ parameter is a string containing positional and timinginformation in the following format:

X,Y,time [,X,Y,time]...

The X and Y parameters specify a mouse position in twips. The time parameterspecifies the delay in milliseconds between the current mouse move and theprevious event in the queue. If time is 0, then the mouse move will play back asfast as possible.

The QueMouseMoveBatch command should be used in place of a series ofQueMouseMove statements to reduce the number of lines in your script. Afurther advantage is that, since the mouse-move information is contained withina literal string, the storage for the data is placed in the constant segment insteadof the code segment, reducing the size of the code.

The QueFlush command is used to play back the events stored in the currentevent queue.

Page 412: Working Model 2D - User's Manual

408 Working Model Basic User's Manual

Example 'This example activates PaintBrush, then paints the word "Hi".

Sub Main()AppActivate "Paintbrush"AppMaximizeQueMouseDn ebLeftButton,2175,3412QueMouseMoveBatch

"2488,3224,0,2833,2786,0,3114,2347,0,3208,2160,0,3240,2097,0"QueMouseMoveBatch

"3255,2034,0,3255,1987,0,3255,1956,0,3255,1940,0,3224,1956,0"QueMouseMoveBatch

"3193,1987,0,3114,2019,0,3036,2066,0,3005,2113,0,2973,2175,0"QueMouseMoveBatch

"2942,2332,0,2926,2394,0,2926,2582,0,2911,2739,0,2911,2801,0"QueMouseMoveBatch

"2911,2958,0,2911,3020,0,2911,3052,0,2911,3083,0,2911,3114,0"QueMouseMoveBatch

"2911,3130,0,2895,3161,0,2895,3193,0,2895,3208,0,2895,3193,0"QueMouseMoveBatch

"2895,3146,0,2911,3083,0,2926,3020,0,2942,2958,0,2973,2895,0"QueMouseMoveBatch

"3005,2848,0,3020,2817,0,3036,2801,0,3052,2770,0,3083,2770,0"QueMouseMoveBatch

"3114,2754,0,3130,2754,0,3146,2770,0,3161,2786,0,3161,2848,0"QueMouseMoveBatch

"3193,3005,0,3193,3193,0,3208,3255,0,3224,3318,0,3240,3349,0"QueMouseMoveBatch

"3255,3349,0,3286,3318,0,3380,3271,0,3474,3208,0,3553,3052,0"QueMouseMoveBatch

"3584,2895,0,3615,2739,0,3631,2692,0,3631,2645,0,3646,2645,0"QueMouseMoveBatch

"3646,2660,0,3646,2723,0,3646,2880,0,3662,2942,0,3693,2989,0"QueMouseMoveBatch "3709,3005,0,3725,3005,0,3756,2989,0,3787,2973,0"QueMouseUp ebLeftButton,3787,2973QueMouseDn ebLeftButton,3678,2535QueMouseMove 3678,2520QueMouseMove 3678,2535QueMouseUp ebLeftButton,3678,2535QueFlush True

End Sub

See Also QueMouseClick (statement); QueMouseDn (statement); QueMouseUp (statement);QueMouseDblClk (statement); QueMouseDblDn (statement); QueMouseMove(statement); QueFlush (statement).

Platform(s) Windows.

QueMouseUp (statement)Syntax QueMouseUp button,X,Y [,time]

Description Adds a mouse up to the current event queue.

Page 413: Working Model 2D - User's Manual

Chapter 2 QueSetRelativeWindow (statement) 409

Comments The QueMouseUp statement takes the following parameters:

Parameter Description

button Integer specifying the mouse buttton to be released:

ebLeftButton Release the left mouse button.

ebRightButton Release the right mouse button.

X, Y Integer coordinates, in twips, where the mouse button is to be released.

time Integer specifying the delay in milliseconds between this event and theprevious event in the queue. If this parameter is omitted (or 0), the mouse upwill play back at full speed.

The QueFlush command is used to play back the events stored in the currentevent queue.

Example See QueEmpty (statement).

See Also QueMouseClick (statement); QueMouseDn (statement); QueMouseDblClk(statement); QueMouseDblDn (statement); QueMouseMove (statement);QueMouseMoveBatch (statement); QueFlush (statement).

Platform(s) Windows.

QueSetRelativeWindow (statement)Syntax QueSetRelativeWindow [window_object]

Description Forces all subsequent QueX commands to adjust the mouse positions relative tothe specified window.

Comments The window_object parameter is an object of type HWND. If window_object isNothing or omitted, then the window with the focus is used (i.e., the activewindow).

The QueFlush command is used to play back the events stored in the currentevent queue.

Example Sub Main()'Adjust mouse coordinates relative to Notepad.Dim a As HWNDSet a = WinFind("Notepad")QueSetRelativeWindow a

End Sub

Platform(s) Windows.

Page 414: Working Model 2D - User's Manual

410 Working Model Basic User's Manual

Random (function)Syntax Random(min,max)

Description Returns a Long value greater than or equal to min and less than or equal tomax.

Comments Both the min and max parameters are rounded to Long. A runtime error isgenerated if min is greater than max.

Example 'This example uses the random number generator to generate ten'lottery numbers.

Const crlf = Chr$(13) + Chr$(10)

Sub Main()Randomize 'Start with new random seed.For x = 1 To 10

y = Random(0,100) 'Generate numbers.msg = msg & y & crlf

Next xMsgBox "Ten numbers for the lottery: " & crlf & msg

End Sub

See Also Randomize (statement); Random (function).

Platform(s) Windows and Macintosh.

Randomize (statement)Syntax Randomize [seed]

Description Initializes the random number generator with a new seed.

Comments If seed is not specified, then the current value of the system clock is used.

Example 'This example sets the randomize seed to a random number between'100 and 1000, then generates ten random numbers for the lottery.

Const crlf = Chr$(13) + Chr$(10)

Sub Main()Randomize 'Start with new random seed.For x = 1 To 10

y = Random(0,100) 'Generate numbers.msg = msg + Str(y) + crlf

Next xMsgBox "Ten numbers for the lottery: " & crlf & msg

End Sub

See Also Random (function); Rnd (function).

Platform(s) Windows and Macintosh.

Page 415: Working Model 2D - User's Manual

Chapter 2 Rate (function) 411

Rate (function)Syntax Rate(NPer,Pmt,Pv,Fv,Due,Guess)

Description Returns the rate of interest for each period of an annuity.

Comments An annuity is a series of fixed payments made to an insurance company orother investment company over a period of time. Examples of annuities aremortgages and monthly savings plans.

The Rate function requires the following parameters:

Parameter Description

NPer Double representing the total number of payments in the annuity.

Pmt Double representing the amount of each payment per period.

Pv Double representing the present value of your annuity. In a loan situation, thepresent value would be the amount of the loan.

Fv Double representing the future value of the annuity after the last payment hasbeen 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 0indicates payment at the end of each period, whereas a 1 indicates payment atthe start of each period.

Guess Double specifying a guess as to the value the Rate function will return. Themost common guess is .1 (10 percent).

Positive numbers represent cash received, whereas negative values representcash paid out.

The value of Rate is found by iteration. It starts with the value of Guess andcycles through the calculation adjusting Guess until the result is accurate within0.00001 percent. After 20 tries, if a result cannot be found, Rate fails, and theuser must pick a better guess.

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 (function); NPer (function); Pmt (function); PPmt (function).

Platform(s) Windows and Macintosh.

Page 416: Working Model 2D - User's Manual

412 Working Model Basic User's Manual

ReadIni$ (function)Syntax ReadIni$(section$,item$[,filename$])

Description Returns a String containing the specified item from an ini file.

Comments The ReadIni$ function takes the following parameters:

Parameter Description

section$ String specifying the section that contains the desired variable, such as"windows". Section names are specified without the enclosing brackets.

item$ String specifying the item whose value is to be retrieved.

filename$ String containing the name of the ini file to read.

See Also WriteIni (statement); ReadIniSection (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, if the name of the ini file is not specified, then win.ini isassumed.

If the filename$ parameter does not include a path, then this statement looks forini files in the Windows directory.

ReadIniSection (statement)Syntax ReadIniSection section$,ArrayOfItems()[,filename$]

Description Fills an array with the item names from a given section of the specified ini file.

Page 417: Working Model 2D - User's Manual

Chapter 2 Redim (statement) 413

Comments The ReadIniSection statement takes the following parameters:

Parameter Description

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. Thearray can be either dynamic or fixed.

If ArrayOfItems() is dynamic, then it will be redimensioned to exactly hold thenew number of elements. If there are no elements, then the array will beredimensioned to contain no dimensions. You can use the LBound, UBound, andArrayDims functions to determine the number and size of the new array'sdimensions.

If the array is fixed, each array element is first erased, then the new elementsare 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 Stringarrays) or Empty (for Variant arrays). A runtime error results if the array is toosmall to hold the new elements.

filename$ String containing the name of an ini file.

On return, the ArrayOfItems() parameter will contain one array element foreach variable in the specified ini section.

Example Sub Main()Dim items() As StringReadIniSection "windows",items$r% = SelectBox("INI Items",,items$)

End Sub

See Also ReadIni$ (function); WriteIni (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, if the name of the ini file is not specified, then win.ini isassumed.

If the filename$ parameter does not include a path, then this statement looks forini files in the Windows directory.

Redim (statement)Syntax Redim [Preserve] variablename (subscriptRange) [As type],...

Description Redimensions an array, specifying a new upper and lower bound for eachdimension of the array.

Page 418: Working Model 2D - User's Manual

414 Working Model Basic User's Manual

Comments The variablename parameter specifies the name of an existing array (previouslydeclared using the Dim statement) or the name of a new array variable. If thearray variable already exists, then it must previously have been declared withthe 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 foreach 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 Basestatement). A runtime error is generated if lower is less than upper. Arraydimensions must be within the following range:

–32768 <= lower <= upper <= 32767

The type parameter can be used to specify the array element type. Arrays can bedeclared using any fundamental data type, user-defined data types, and objects.

Redimensioning an array erases all elements of that array unless the Preservekeyword is specified. When this keyword is specified, existing data in the arrayis preserved where possible. If the number of elements in an array dimension isincreased, the new elements are initialized to 0 (or empty string). If the numberof elements in an array dimension is decreased, then the extra elements will bedeleted. If the Preserve keyword is specified, then the number of dimensionsof the array being redimensioned must either be zero or the same as the newnumber of dimensions.

Example 'This example uses the FileList statement to redim an array and fill it'with filename strings. A new array is then redimmed 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 xMsgBox "The last element of the new array is: " & nl$(count)

End Sub

See Also Dim (statement); Public (statement); Private (statement); ArrayDims(function); LBound (function); UBound (function).

Platform(s) Windows and Macintosh.

Page 419: Working Model 2D - User's Manual

Chapter 2 Rem (statement) 415

Rem (statement)Syntax Rem text

Description Causes the compiler to skip all characters on that line.

Example Sub Main()Rem This is a line of comments that serves to illustrate theRem workings of the code. You can insert comments to make it moreRem readable and maintainable in the future.

End Sub

See Also ' (keyword); Comments (topic).

Platform(s) Windows and Macintosh.

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 Resetstatement,'then deletes it with the Kill statement.

Sub Main()Open "test.dat" for Output Access Write as # 1ResetKill "test.dat"

If FileExists("test.dat") ThenMsgBox "The file was not deleted."

ElseMsgBox "The file was deleted."

End IfEnd Sub

See Also Close (statement); Open (statement).

Platform(s) Windows and Macintosh.

Resume (statement)Syntax Resume {[0] | Next | label}

Description Ends an error handler and continues execution.

Page 420: Working Model 2D - User's Manual

416 Working Model Basic User's Manual

Comments The form Resume 0 (or simply Resume by itself) causes execution tocontinue with the statement that caused the error.

The form Resume Next causes execution to continue with the statementfollowing 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 executingthis 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 Overflowa% = InputBox("Enter 1st integer to multiply","Enter Number")b% = InputBox("Enter 2nd integer to multiply","Enter Number")

On Error Resume Next 'Continue program execution at next line x% = a% * b%

if err = 0 thenMsgBox x%

elseMsgbox a% & " * " & b% & " cause an overflow!"

end if

Exit Sub

Overflow: 'Error handler.MsgBox "You've entered a non-integer value, try again!"Resume Again

End Sub

See Also Error Handling (topic); On Error (statement).

Platform(s) Windows and Macintosh.

Return (statement)Syntax Return

Description Transfers execution control to the statement following the most recent GoSub.

Page 421: Working Model 2D - User's Manual

Chapter 2 Right, Right$ (functions) 417

Comments A runtime error results if a Return statement is encountered without acorresponding GoSub statement.

Example 'This example calls a subroutine and then returns execution to the Main'routine by the Return statement.

Sub Main()GoSub SubTrueMsgBox "The Main routine continues here."Exit Sub

SubTrue:MsgBox "This message is generated in the subroutine."ReturnExit Sub

End Sub

See Also GoSub (statement).

Platform(s) Windows and Macintosh.

Right, Right$ (functions)Syntax Right[$](text,NumChars)

Description Returns the rightmost NumChars characters from a specified string.

Comments Right$ returns a String, whereas Right returns a String variant.

The Right function takes the following parameters:

Parameter Description

text String from which characters are returned. A runtime error is generated if textis Null.

NumChars Integer specifying the number of characters to return. If NumChars is greaterthan or equal to the length of the string, then the entire string is returned. IfNumChars is 0, then a zero-length string is returned.

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

See Also Left, Left$ (functions).

Page 422: Working Model 2D - User's Manual

418 Working Model Basic User's Manual

Platform(s) Windows and Macintosh.

RmDir (statement)Syntax RmDir dir$

Comments Removes the directory specified by the String contained in dir$.

Example 'This routine creates a directory and then deletes it with RmDir.

Sub Main()On Error Goto ErrMakeMkDir("test01")On Error Goto ErrRemoveRmDir("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 (statement); ChDrive (statement); CurDir, CurDir$ (functions); Dir,Dir$ (functions); MkDir (statement).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Under Windows, this command behaves the same as the DOS "rd" command.

Rnd (function)Syntax Rnd[(number)]

Description Returns a random Single number between 0 and 1.

Comments If number is omitted, the next random number is returned. Otherwise, thenumber parameter has the following meaning:

If Then

number < 0 Always returns the same number.

number = 0 Returns the last number generated.

number > 0 Returns the next random number.

Page 423: Working Model 2D - User's Manual

Chapter 2 RSet (statement) 419

Example 'This routine generates a list of random numbers and displays them.

Const crlf = Chr$(13) + Chr$(10)

Sub Main()For x = -1 To 8

y! = Rnd(1) * 100msg = msg & x & " : " & y! & crlf

Next xMsgBox msg & "Last form: " & Rnd

End Sub

See Also Randomize (statement); Random (function).

Platform(s) Windows and Macintosh.

RSet (statement)Syntax RSet destvariable = source

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-alignedwithin destvariable and the remaining characters are padded with spaces. Ifsource is longer in length than destvariable, then source is truncated, copyingonly the leftmost number of characters that will fit in destvariable. A runtimeerror is generated if source is Null.

The destvariable parameter specifies a String or Variant variable. Ifdestvariable is a Variant containing Empty, then no characters are copied. Ifdestvariable is not convertible to a String, then a runtime error occurs. Aruntime 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 msg,tmpstr$tmpstr$ = String$(40, "*")msg = "Here are two strings that have been right-" & crlfmsg = msg & "and left-justified in a 40-character string."msg = msg & crlf & crlfRSet tmpstr$ = "Right->"msg = msg & tmpstr$ & crlfLSet tmpstr$ = "<-Left"msg = msg & tmpstr$ & crlfMsgBox msg

End Sub

See Also LSet (statement).

Page 424: Working Model 2D - User's Manual

420 Working Model Basic User's Manual

Platform(s) Windows and Macintosh.

RTrim, RTrim$ (functions)Syntax RTrim[$](text)

Description Returns a string with the trailing spaces removed.

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()a$ = "This is a left-justified string. "b$ = RTrim$(a$)MsgBox a$ & "<=" & crlf & b$ & "<="

End Sub

See Also LTrim, LTrim$ (functions); Trim, Trim$ (functions).

Platform(s) Windows and Macintosh.

Page 425: Working Model 2D - User's Manual

421

SaveFilename$ (function)Syntax SaveFilename$[([title$ [,extensions$]])]

Description Displays a dialog box that prompts the user to select from a list of files andreturns a String containing the full path of the selected file.

Comments The SaveFilename$ function accepts the following parameters:

Parameter Description

title$ String containing the title that appears on the dialog box's caption. If thisstring is omitted, then "Save As" is used.

extensions$ String containing the available file types. Its format depends on the platformon which WM Basic is running. If this string is omitted, then all files are used.

The SaveFilename$ function returns a full pathname of the file that the userselects. A zero-length string is returned if the user selects Cancel. If the filealready exists, then the user is prompted to overwrite it.

e$ = "All Files:*.BMP,*.WMF;Bitmaps:*.BMP;Metafiles:*.WMF"f$ = SaveFilename$("Save Picture",e$)

Page 426: Working Model 2D - User's Manual

422 Working Model Basic User's Manual

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 (statement); AskBox$ (function); AskPassword$ (function); InputBox,InputBox$ (functions); OpenFilename$ (function); SelectBox (function);AnswerBox (function).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Under Windows, the extensions$ parameter must be in the following format:

description:ext[,ext][;description:ext[,ext]]...

Placeholder Description

description Specifies the grouping of files for the user, such as All Files.

ext Specifies a valid file extension, such as *.BAT or *.?F?.

For example, the following are valid extensions$ specifications:

"All Files:*""Documents:*.TXT,*.DOC""All Files:*;Documents:*.TXT,*.DOC"

PlatformNotes:

Macintosh

On the Macintosh, the extensions$ parameter contains a comma-separated listof four-character file types. For example:

"TEXT,XLS4,MSWD"

On the Macintosh, the title$ parameter is ignored.

Screen.DlgBaseUnitsX (property)Syntax Screen.DlgBaseUnitsX

Description Returns an Integer used to convert horizontal pixels to and from dialogunits.

Page 427: Working Model 2D - User's Manual

Chapter 2 Screen.DlgBaseUnitsY (property) 423

Comments The number returned depends on the name and size of the font used to displaydialog 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.Widthconv% = Screen.DlgBaseUnitsXXDlgUnits = (XPixels * 4) + (conv% -1) / conv%MsgBox "The screen width is " & XDlgUnits & " dialog units."

End Sub

See Also Screen.DlgBaseUnitsY (property).

Platform(s) Windows.

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 displaydialog 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.Heightconv% = Screen.DlgBaseUnitsYYDlgUnits = (YPixels * 8) + (conv% -1) / conv%MsgBox "The screen width is " & YDlgUnits & " dialog units."

End Sub

See Also Screen.DlgBaseUnitsX (property).

Platform(s) Windows.

Screen.Height (property)Syntax Screen.Height

Page 428: Working Model 2D - User's Manual

424 Working Model Basic User's Manual

Description Returns the height of the screen in pixels as an Integer.

Comments This property is used to retrieve the height of the screen in pixels. This valuewill differ depending on the display resolution.

This property is read-only.

Example 'This example displays the screen height in pixels.

Sub Main()MsgBox "The Screen height is " & Screen.Height & " pixels."

End Sub

See Also Screen.Width (property).

Platform(s) Windows.

Screen.TwipsPerPixelX (property)Syntax Screen.TwipsPerPixelX

Description Returns an Integer representing the number of twips per pixel in thehorizontal direction of the installed display driver.

Comments This property is read-only.

Example 'This example displays the number of twips across the screenhorizontally.

Sub Main()XScreenTwips = Screen.Width * Screen.TwipsPerPixelXMsgBox "Total horizontal screen twips = " & XScreenTwips

End Sub

See Also Screen.TwipsPerPixelY (property).

Platform(s) Windows.

Screen.TwipsPerPixelY (property)Syntax Screen.TwipsPerPixelY

Description Returns an Integer representing the number of twips per pixel in the verticaldirection of the installed display driver.

Comments This property is read-only.

Example 'This example displays the number of twips across the screenvertically.

Sub Main()YScreenTwips = Screen.Height * Screen.TwipsPerPixelYMsgBox "Total vertical screen twips = " & YScreenTwips

End Sub

Page 429: Working Model 2D - User's Manual

Chapter 2 Screen.Width (property) 425

See Also Screen.TwipsPerPixelX (property).

Platform(s) Windows.

Screen.Width (property)Syntax Screen.Width

Description Returns the width of the screen in pixels as an Integer.

Comments This property is used to retrieve the width of the screen in pixels. This valuewill differ depending on the display resolution.

This property is read-only.

Example 'This example displays the screen width in pixelsSub Main()

MsgBox "The screen width is " & Screen.Width & " pixels."End Sub

See Also Screen.Height (property).

Platform(s) Windows.

Second (function)Syntax Second(time)

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 takes the current time; extracts the hour,'minute, and second; and displays them as the current time.

Sub Main()xt# = TimeValue(Time$())xh# = Hour(xt#)xm# = Minute(xt#)xs# = Second(xt#)Msgbox "The current time is: " & CStr(xh#) & ":" & CStr(xm#) & ":"

& CStr(xs#)End Sub

See Also Day (function); Minute (function); Month (function); Year (function); Hour(function); Weekday (function); DatePart (function).

Platform(s) Windows and Macintosh.

Page 430: Working Model 2D - User's Manual

426 Working Model Basic User's Manual

Seek (function)Syntax Seek(filenumber)

Description Returns the position of the file pointer in a file relative to the beginning of thefile.

Comments The filenumber parameter is a number that WM Basic uses to refer to the openfile—the number passed to the Open statement.

The value returned depends on the mode in which the file was opened:

File Mode Returns

Input Byte position for the next readOutput Byte position for the next writeAppend Byte position for the next writeRandom Number of the next record to be written or readBinary Byte position for the next read or write

The value returned is a Long between 1 and 2147483647, where the first byte(or first record) in the file is 1.

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 #1For x = 1 To 10

r% = x * 10Put #1,x,r%

Next xy = Seek(1)MsgBox "The current file position is: " & yClose

End Sub

See Also Seek (statement); Loc (function).

Platform(s) Windows and Macintosh.

Seek (statement)Syntax Seek [#] filenumber,position

Description Sets the position of the file pointer within a given file such that the next read orwrite operation will occur at the specified position.

Page 431: Working Model 2D - User's Manual

Chapter 2 Select...Case (statement) 427

Comments The Seek statement accepts the following parameters:

Parameter Description

filenumber Integer used by WM Basic to refer to the open file—the number passed to theOpen statement.

position Long that specifies the location within the file at which to position the filepointer. The value must be between 1 and 2147483647, where the first byte (orrecord 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. ForRandom files, position is the record number.

A file can be extended by seeking beyond the end of the file and writing datathere.

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 #1For x = 1 To 10

rec$ = "Record#: " & xPut #1,x,rec$

Next xClose

Open "test.dat" For Random Access Read As #1Seek #1,9Get #1,,rec$MsgBox "The ninth record = " & xCloseKill "test.dat"

End Sub

See Also Seek (function); Loc (function).

Platform(s) Windows and Macintosh.

Select...Case (statement)Syntax Select Case testexpression

[Case expressionlist [statement_block]][Case expressionlist [statement_block]]

.

.[Case Else [statement_block]]End Select

Page 432: Working Model 2D - User's Manual

428 Working Model Basic User's Manual

Description Used to execute a block of WM Basic statements depending on the value of agiven expression.

Comments The Select Case statement has the following parts:

Part Description

testexpression Any numeric or string expression.

statement_block Any group of WM Basic statements. If the testexpression matches any of theexpressions contained in expressionlist, then this statement block will beexecuted.

expressionlist A comma separated list of expressions to be compared against testexpressionusing any of the following syntaxes:

expression [,expression]...expression to expressionis relational_operator expression

The resultant type of expression in expressionlist must be the same as that oftestexpression.

Multiple expression ranges can be used within a single Case clause. Forexample:

Case 1 to 10,12,15, Is > 40

Only the statement_block associated with the first matching expression will beexecuted. If no matching statement_block is found, then the statementsfollowing the Case Else will be executed.

A Select...End Select expression can also be represented with theIf...Then expression. The use of the Select statement, however, may bemore readable.

Example 'This example uses the Select...Case statement to output the'current operating system.

Sub Main()OpSystem% = Basic.OSSelect Case OpSystem%

Case 0s = "Microsoft Windows"

Case 10s = "Macintosh"

Case Elses = "Other"

End SelectMsgBox "This version of WM Basic is running on: " & s

End Sub

Page 433: Working Model 2D - User's Manual

Chapter 2 SelectBox (function) 429

See Also Choose (function); Switch (function); IIf (function); If...Then...Else(statement).

Platform(s) Windows and Macintosh.

SelectBox (function)Syntax SelectBox(title,prompt,ArrayOfItems)

Description Displays a dialog box that allows the user to select from a list of choices andreturns an Integer containing the index of the item that was selected.

Comments The SelectBox statement accepts the following parameters:

Parameter Description

title Title of the dialog box. This can be an expression convertible to a String. Aruntime error is generated if title is Null.

prompt Text to appear immediately above the list box containing the items. This can bean expression convertible to a String. A runtime error is generated if prompt isNull.

ArrayOfItems Single-dimensioned array. Each item from the array will occupy a single entryin 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 arenot 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 listbox that was selected, with 0 being the first item. If the user selects Cancel, –1is returned.

result% = SelectBox("Picker","Pick an application:",a$)

Page 434: Working Model 2D - User's Manual

430 Working Model Basic User's Manual

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 (statement); AskBox$ (function); AskPassword$ (function); InputBox,InputBox$ (functions); OpenFilename$ (function); SaveFilename$ (function);AnswerBox (function).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Under Windows, SelectBox displays all text in its dialog box in 8-point MSSans Serif.

SelectButton (statement)Syntax SelectButton name$ | id

Description Simulates a mouse click on the a push button given the push button's name (thename$ parameter) or ID (the id parameter).

Comments The SelectButton statement accepts the following parameters:

Parameter Description

name$ String containing the name of the push button to be selected.

id Integer representing the ID of the push button to be selected.

A runtime error is generated if a push button with the given name or ID cannotbe found in the active window.

Note: The SelectButton statement is used to select a button in anotherapplication's dialog box. This command is not intended for use with built-in ordynamic dialog boxes.

Example This example simulates the selection of several buttons in a dialog.

Sub Main()SelectButton "OK"SelectButton 2SelectButton "Close"

End Sub

Page 435: Working Model 2D - User's Manual

Chapter 2 SelectComboBoxItem (statement) 431

See Also ButtonEnabled (function), ButtonExists (function)

Platform(s) Windows.

SelectComboBoxItem (statement)Syntax SelectComboBoxItem {name$ | id},{ItemName$ | ItemNumber} [,isDoubleClick]

Description Selects an item from a combo box given the name or ID of the combo box andthe name or line number of the item.

Comments The SelectComboBoxItem statement accepts the following parameters:

Parameter Description

name$ String indicating the name of the combo box containing the item to beselected.

The name of a combo box is determined by scanning the window list lookingfor a text control with the given name that is immediately followed by a combobox. A runtime error is generated if a combo box with that name cannot befound within the active window.

id Integer specifying the ID of the combo box containing the item to be selected.

ItemName$ String specifying which item is to be selected. The string is compared withoutregard to case. If ItemName$ is a zero-length string, then all currently selecteditems are deselected. A runtime error results if ItemName$ cannot be found inthe combo box.

ItemNumber Integer containing the index of the item to be selected. A runtime error isgenerated if ItemNumber is not within the correct range.

isDoubleClick Boolean value indicating whether a double click of that item is to be simulated.

Note: The SelectComboBoxItem statement is used to set the item of a combobox in another application's dialog box. Use the DlgText statement to changethe content of the text box part of a list box in a dynamic dialog box.

Example This example simulates the selection of a couple of comboboxes

Sub Main()SelectComboBoxItem "ComboBox1","Item4"SelectComboBoxItem 1,2,TRUE

End Sub

See Also ComboBoxEnabled (function); ComboBoxExists (function); GetComboBoxItem$(function); GetComboBoxItemCount (function).

Platform(s) Windows.

Page 436: Working Model 2D - User's Manual

432 Working Model Basic User's Manual

SelectListBoxItem (statement)Syntax SelectListBoxItem {name$ | id},{ItemName$ | ItemNumber} [,isDoubleClick]

Description Selects an item from a list box given the name or ID of the list box and thename or line number of the item.

Comments The SelectListBoxItem statement accepts the following parameters:

Parameter Description

name$ String indicating the name of the list box containing the item to be selected.

The name of a list box is determined by scanning the window list looking for atext control with the given name that is immediately followed by a list box. Aruntime error is generated if a list box with that name cannot be found withinthe active window.

id Integer specifying the ID of the list box containing the item to be selected.

ItemName$ String specifying which item is to be selected. The string is compared withoutregard to case. If ItemName$ is a zero-length string, then all currently selecteditems are deselected. A runtime error results if ItemName$ cannot be found inthe list box.

ItemNumber Integer containing the index of the item to be selected. A runtime error isgenerated if ItemNumber is not within the correct range.

isDoubleClick Boolean value indicating whether a double click of that item is to be simulated.

The list box must exist within the current window or dialog box; otherwise, aruntime error will be generated.

For multiselect list boxes, SelectListBoxItem will select additionalitems (i.e., it will not remove the selection from the currently selected items).

Note: The SelectListBoxItem statement is used to select an item in a list boxof another application's dialog box. Use the DlgText statement to change theselected item in a list box within a dynamic dialog box.

Example 'This example simulates a double click on the first item in list box 1.

Sub Main()SelectListBoxItem "ListBox1",1,TRUE

End Sub

See Also GetListBoxItem$ (function); GetListBoxItemCount (function);ListBoxEnabled (function); ListBoxExists (function).

Platform(s) Windows.

Page 437: Working Model 2D - User's Manual

Chapter 2 SendKeys (statement) 433

SendKeys (statement)Syntax SendKeys KeyString$ [,[isWait] [,time]]

Description Sends the specified keys to the active application, optionally waiting for thekeys to be processed before continuing.

Comments The SendKeys statement accepts the following parameters:

Parameter Description

KeyString$ String containing the keys to be sent. The format for KeyString$ is describedbelow.

isWait Boolean value. If True (or not specified), then WM Basic waits for the keys tobe completely processed before continuing.

time Integer specifying the number of milliseconds devoted for the output of theentire KeyString$ parameter. It must be within the following range:

0 <= time <= 32767

For example, if time is 5000 (5 seconds) and the KeyString$ parameter containsten keys, then a key will be output every 1/2 second. If unspecified (or 0), thekeys will play back at full speed.

Specifying Keys

To specify any key on the keyboard, simply use that key, such as "a" forlowercase 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:

Key Special Meaning Example+ Shift "+{F1}" 'Shift+F1

^ Ctrl "^a" 'Ctrl+A

~ Shortcut for Enter "~" 'Enter

% Alt "%F" 'Alt+F

[] No special meaning "{[}" 'Open bracket

{} Used to enclose special keys "{Up}" 'Up Arrow

() Used to specify grouping "^(ab)" 'Ctrl+A,Ctrl+B

Page 438: Working Model 2D - User's Manual

434 Working Model Basic User's Manual

Keys that are not displayed when you press them are also specified withinbraces, such as {Enter} or {Up}. A list of these keys follows:

{BkSp} {BS} {Break} {CapsLock}{Clear}{Delete} {Del} {Down} {End} {Enter}{Escape} {Esc} {Help} {Home}{Insert}{Left} {NumLock} {NumPad0} {NumPad1} {NumPad2}{NumPad3} {NumPad4} {NumPad5} {NumPad6} {NumPad7}{NumPad8} {NumPad9} {NumPad/} {NumPad*} {NumPad-}{NumPad+} {NumPad.} {PgDn} {PgUp}{PrtSc}{Right} {Tab} {Up} {F1} {ScrollLock}{F2} {F3} {F4} {F5} {F6}{F7} {F8} {F9} {F10} {F11}{F12} {F13} {F14} {F15} {F16}

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 "~~"

Page 439: Working Model 2D - User's Manual

Chapter 2 Set (statement) 435

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}"

Eample 'This example runs Notepad, writes to Notepad, and saves the new fileusing'the SendKeys statement.

Sub Main()id = Shell("Notepad.exe")AppActivate "Notepad"SendKeys "Hello, Notepad." 'Write some text.Sleep 2000SendKeys "%fs" 'Save file (simulate Alt+F, S keys).Sleep 2000SendKeys "name.txt{ENTER}" 'Enter name of new file to save.AppClose "Notepad"

End Sub

See Also DoKeys (statement); QueKeys (statement); QueKeyDn (statement); QueKeyUp(statement).

Platform(s) Windows.

Set (statement)Syntax 1 Set object_var = object_expression

Syntax 2 Set object_var = New object_type

Syntax 3 Set object_var = Nothing

Description Assigns a value to an object variable.

Page 440: Working Model 2D - User's Manual

436 Working Model Basic User's Manual

Comments Syntax 1

The first syntax assigns the result of an expression to an object variable. Thisstatement does not duplicate the object being assigned but rather copies areference of an existing object to an object variable.

The object_expression is any expression that evaluates to an object of the sametype as the object_var.

With data objects, Set performs additional processing. When the Set isperformed, the object is notified that a reference to it is being made anddestroyed. For example, the following statement deletes a reference to object A,then adds a new reference to B.

Set a = b

In this way, an object that is no longer being referenced can be destroyed.

Syntax 2

In the second syntax, the object variable is being assigned to a new instance ofan existing object type. This syntax is valid only for data objects.

When an object created using the New keyword goes out of scope (i.e., the Subor 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 referenceno object. At a later time, the object variable can be compared to Nothing totest 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 ObjectDim page As ObjectSet document = GetObject("c:\resume.doc")Set page = Document.ActivePageMsgBox page.name

End Sub

See Also = (statement); Let (statement); CreateObject (function); GetObject(function); Nothing (constant).

Platform(s) Windows and Macintosh.

SetAttr (statement)Syntax SetAttr filename$,attribute

Page 441: Working Model 2D - User's Manual

Chapter 2 SetCheckBox (statement) 437

Description Changes the attribute filename$ to the given attribute. A runtime error results ifthe file cannot be found.

Comments The SetAttr statement accepts the following parameters:

Parameter Description

filename$ String containing the name of the file.

attribute Integer specifying the new attribute of the file.

The attribute parameter can contain any combination of the following values:

Constant Value Description

ebNormal 0 Turns off all attributesebReadOnly 1 Read-only filesebHidden 2 Hidden filesebSystem 4 System filesebVolume 8 Volume labelebArchive 32 Files that have changed since the lastbackupebNone 64 Turns off all attributes

The attributes can be combined using the + operator or the binary Or operator.

Example 'This example creates a file and sets its attributes to Read-Only and'System.

Sub Main()Open "test.dat" For Output Access Write As #1CloseMsgBox "The current file attribute is: " & GetAttr("test.dat")SetAttr "test.dat",ebReadOnly Or ebSystemMsgBox "The file attribute was set to: " & GetAttr("test.dat")

End Sub

See Also GetAttr (function); FileAttr (function).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Under Windows, these attributes are the same as those used by DOS.

SetCheckBox (statement)Syntax SetCheckBox {name$ | id},state

Description Sets the state of the check box with the given name or ID.

Page 442: Working Model 2D - User's Manual

438 Working Model Basic User's Manual

Comments The SetCheckBox statement accepts the following parameters:

Parameter Description

name$ String containing the name of the check box to be set.

id Integer specifying the ID of the check box to be set.

state Integer indicating the new state of the check box. If state is 1, then the box ischecked. If state is 0, then the check is removed. If state is 2, then the box isdimmed (only applicable for three-state check boxes).

A runtime error is generated if a check box with the specified name cannot befound in the active window.

This statement has the side effect of setting the focus to the given check box.

Note: The SetCheckBox statement is used to set the state of a check box inanother application's dialog box. Use the DlgValue statement to modify thestate of a check box within a dynamic dialog box.

Example 'This example sets a factious checkbox

Sub Main()SetCheckBox "CheckBox1",1

End Sub

See Also CheckBoxExists (function); CheckBoxEnabled (function); GetCheckBox(function); DlgValue (statement).

Platform(s) Windows.

SetEditText (statement)Syntax SetEditText {name$ | id},content$

Description Sets the content of an edit control given its name or ID.

Page 443: Working Model 2D - User's Manual

Chapter 2 SetOption (statement) 439

Comments The SetEditText statement accepts the following parameters:

Parameter Description

name$ String containing the name of the text box to be set.

The name of a text box control is determined by scanning the window listlooking for a text control with the given name that is immediately followed byan edit control. A runtime error is generated if a text box control with that namecannot be found within the active window.

id Integer specifying the ID of the text box to be set.

For text boxes that do not have a preceding text control, the id can be used toabsolutely reference the control. The id is determined by examining the dialogbox with a resource editor or using an application such as Spy.

content$ String containing the new content for the text box.

This statement has the side effect of setting the focus to the given text box.

Note: The SetEditText statement is used to set the content of a text box inanother application's dialog box. Use the DlgText statement to set the text of atext box within a dynamic dialog box.

Example 'This example sets the content of the filename text box of the'current window to "test.dat".

Sub Main()SetEditText "Filename:","test.dat"

End Sub

See Also EditEnabled (function); EditExists (function); GetEditText$ (function).

Platform(s) Windows.

SetOption (statement)Syntax SetOption name$ | id

Description Selects the specified option button given its name or ID.

Page 444: Working Model 2D - User's Manual

440 Working Model Basic User's Manual

Comments The SetOption statement accepts the following parameters:

Parameter Description

name$ String containing the name of the option button to be selected.

id Integer containing the ID of the option button to be selected.

A runtime error is generated if the option button cannot be found within theactive window.

Note: The SetOption statement is used to select an option button in anotherapplication's dialog box. Use the DlgValue statement to select an option buttonwithin a dynamic dialog box.

Example 'This example selects the Continue option button.

Sub Main()SetOption "Continue"

End Sub

See Also GetOption (function); OptionEnabled (function); OptionExists (function).

Platform(s) Windows.

Sgn (function)Syntax Sgn(number)

Description Returns an Integer indicating whether a number is less than, greater than, orequal 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.

Page 445: Working Model 2D - User's Manual

Chapter 2 Shell (function) 441

Example 'This example tests the product of two numbers and displays'a message based on the sign of the result.

Sub Main()a% = -100b% = 100c% = a% * b%Select Case Sgn(c%)

Case -1MsgBox "The product is negative " & Sgn(c%)

Case 0MsgBox "The product is 0 " & Sgn(c%)

Case 1MsgBox "The product is positive " & Sgn(c%)

End SelectEnd Sub

See Also Abs (function).

Platform(s) Windows and Macintosh.

Shell (function)Syntax Shell(command$ [,WindowStyle])

Description Executes another application, returning the task ID if successful.

Page 446: Working Model 2D - User's Manual

442 Working Model Basic User's Manual

Comments The Shell statement accepts the following parameters:

Parameter Description

command$ String containing the name of the application and any parameters.

WindowStyle Optional Integer specifying the state of the application window afterexecution. It can be any of the following values:

1 Normal window with focus

2 Minimized with focus (default)

3 Maximized with focus

4 Normal window without focus

7 Minimized without focus

An error is generated if unsuccessful running command$.

The Shell command runs programs asynchronously: the statement followingthe Shell statement will execute before the child application has exited. Onsome platforms, the next statement will run before the child application hasfinished loading.

The Shell function returns a value suitable for activating the application usingthe AppActivate statement. It is important that this value be placed into aVariant, as its type depends on the platform.

Example 'This example displays the Windows Clock, delays awhile, then closesit.

Sub Main()id = Shell("clock.exe",1)AppActivate "Clock"Sleep(2000)AppClose "Clock"

End Sub

See Also PrintFile (function); SendKeys (statement); AppActivate (statement).

Platform(s) Windows and Macintosh.

Page 447: Working Model 2D - User's Manual

Chapter 2 Sin (function) 443

PlatformNotes:

Macintosh

The Macintosh does not support wildcard characters such as * and ?. These arevalid filename characters. Instead of wildcards, the Macintosh uses the MacIDfunction to specify a collection of files of the same type. The syntax for thisfunction is:

Shell(MacID(text$) [,WindowStyle])

The text$ parameter is a four-character string containing an applicationsignature. A runtime error occurs if the MacID function is used on platformsother than the Macintosh.

On the Macintosh, the WindowStyle parameter only specifies whether theapplication receives the focus.

PlatformNotes:

Windows

Under Windows, this function returns the hInstance of the application.Since this value is only a WORD in size, the upper WORD of the result is alwayszero.

Sin (function)Syntax Sin(angle)

Description Returns a Double value specifying the sine of angle.

Comments The angle parameter is a Double specifying an angle in radians.

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 (function); Cos (function); Atn (function).

Platform(s) Windows and Macintosh.

Single (data type)Syntax Single

Description A data type used to declare variables capable of holding real numbers with upto seven digits of precision.

Page 448: Working Model 2D - User's Manual

444 Working Model Basic User's Manual

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, whenappearing within a structure, singles require 4 bytes of storage. When used withbinary 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 (data type); Date (data type); Double (data type); Integer (datatype); Long (data type); Object (data type); String (data type); Variant (datatype); Boolean (data type); DefType (statement); CSng (function).

Platform(s) Windows and Macintosh.

Sleep (statement)Syntax Sleep milliseconds

Description Causes the script to pause for a specified number of milliseconds.

Comments The milliseconds parameter is a Long in the following range:

0 <= milliseconds <= 2,147,483,647

Example 'This example displays a message for 2 seconds.

Sub Main()MsgOpen "Waiting 2 seconds",0,False,FalseSleep(2000)MsgClose

End Sub

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Under Windows, the accuracy of the system clock is modulo 55 milliseconds.The value of milliseconds will, in the worst case, be rounded up to the nearestmultiple of 55. In other words, if milliseconds is 1, it will be rounded to 55 inthe worst case.

Page 449: Working Model 2D - User's Manual

Chapter 2 Sln (function) 445

Sln (function)Syntax Sln(Cost,Salvage,Life)

Description Returns the straight-line depreciation of an asset assuming constant benefitfrom 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

The Sln function requires the following parameters:

Parameter Description

Cost Double representing the initial cost of the asset.

Salvage Double representing the estimated value of the asset at the end of its useful life.

Life Double representing the length of the asset's useful life.

The unit of time used to express the useful life of the asset is the same as theunit 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 (function); DDB (function).

Platform(s) Windows and Macintosh.

Space, Space$ (functions)Syntax Space[$](NumSpaces)

Description Returns a string containing the specified number of spaces.

Comments Space$ returns a String, whereas Space returns a String variant.

NumSpaces is an Integer between 0 and 32767.

Page 450: Working Model 2D - User's Manual

446 Working Model Basic User's Manual

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$ (functions); Spc (function).

Platform(s) Windows and Macintosh.

Spc (function)Syntax Spc(numspaces)

Description Prints out the specified number of spaces. This function can only be used withthe Print and Print# statements.

Comments The numspaces parameter is an Integer specifying the number of spaces tobe printed. It can be any value between 0 and 32767.

If a line width has been specified (using the Width statement), then thenumber 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 theline length. Furthermore, with a large value for column and a small line width,the file pointer will never advance more than one line.

Example 'This example displays 20 spaces between the arrows.

Sub Main()ViewportOpenPrint "I am"; Spc(20); "20 spaces apart!"Sleep (10000)'Wait 10 seconds.ViewportClose

End Sub

See Also Tab (function); Print (statement); Print# (statement).

Platform(s) Windows and Macintosh.

SQLBind (function)Syntax SQLBind(ID,array,column)

Description Specifies which fields are returned when results are requested using theSQLRetrieve or SQLRetrieveToFile function.

Page 451: Working Model 2D - User's Manual

Chapter 2 SQLBind (function) 447

Comments The following table describes the parameters to the SQLBind function:

Parameter Description

ID Long parameter specifying a valid connection.

array Any array of variants. Each call to SQLBind adds a new column number (anInteger) in the appropriate slot in the array. Thus, as you bind additionalcolumns, the array parameter grows, accumulating a sorted list (in ascendingorder) of bound columns.

If array is fixed, then it must be a one-dimensional variant array with sufficientspace to hold all the bound column numbers. A runtime error is generated ifarray is too small.

If array is dynamic, then it will be resized to exactly hold all the bound columnnumbers.

column Optional Long parameter that specifies the column to which to bind data. If thisparameter is omitted, all bindings for the connection are dropped.

This function returns the number of bound columns on the connection. If nocolumns are bound, then 0 is returned. If there are no pending queries, thencalling SQLBind will cause an error (queries are initiated using theSQLExecQuery function).

If supported by the driver, row numbers can be returned by binding column 0.

WM Basic generates a trappable runtime error if SQLBind fails. Additionalerror information can then be retrieved using the SQLError function.

Example 'This example binds columns to data.

Sub Main()Dim columns() As Variantid& = SQLOpen("dsn=SAMPLE",,3)t& = SQLExecQuery(id&,"Select * From c:\sample.dbf")i% = SQLBind(id&,columns,3)i% = SQLBind(id&,columns,1)i% = SQLBind(id&,columns,2)i% = SQLBind(id&,columns,6)For x = 0 To (i% - 1)

MsgBox columns(x)Next xid& = SQLClose(id&)

End Sub

See Also SQLRetrieve (function); SQLRetrieveToFile (function).

Platform(s) Windows.

Page 452: Working Model 2D - User's Manual

448 Working Model Basic User's Manual

SQLClose (function)Syntax SQLClose(connectionID)

Description Closes the connection to the specified data source.

Comments The unique connection ID (connectionID) is a Long value representing a validconnection as returned by SQLOpen. After SQLClose is called, any subsequentcalls made with the connectionID will generate runtime errors.

The SQLClose function returns 0 if successful; otherwise, it returns the passedconnection ID and generates a trappable runtime error. Additional errorinformation can then be retrieved using the SQLError function.

WM Basic automatically closes all open SQL connections when either thescript or the application terminates. You should use the SQLClose functionrather than relying on WM Basic to automatically close connections in order toensure that your connections are closed at the proper time.

Example 'This example disconnects the the data source sample.

Sub Main()id& = SQLOpen("dsn=SAMPLE",,3)id& = SQLClose(id&)

End Sub

See Also SQLOpen (function).

Platform(s) Windows.

SQLError (function)Syntax SQLError(ErrArray [, ID])

Description Retrieves driver-specific error information for the most recent SQL functionsthat failed.

Page 453: Working Model 2D - User's Manual

Chapter 2 SQLError (function) 449

Comments This function is called after any other SQL function fails. Error information isreturned in a two-dimensional array (ErrArray). The following table describesthe 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 wantreturned. If x is too small to hold all the errors, then the extra error informationis discarded. If x is greater than the number of errors available, all errors arereturned, 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 isomitted, error information is returned for the most recent SQL function call.

Each array entry in the ErrArray parameter describes one error. The threeelements in each array entry contain the following information:

Element Value

(entry,0) The ODBC error state, indicated by a Long containing the error class andsubclass.

(entry,1) The ODBC native error code, indicated by a Long.

(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 returnederror, the array is referenced as:

ErrArray(0,2)

The SQLError function returns the number of errors found.

WM Basic generates a runtime error if SQLError fails. (You cannot use theSQLError function to gather additional error information in this case.)

Page 454: Working Model 2D - User's Manual

450 Working Model Basic User's Manual

Example 'This example forces a connection error and traps it for use with'the SQLError function.

Sub Main()Dim a() As VariantOn Error Goto Trapid& = SQLOpen("",,4)id& = SQLClose(id&)Exit Sub

Trap:rc% = SQLError(a)If (rc%) Then

For x = 0 To (rc% - 1)MsgBox "The SQLState returned was: " & a(x,0)MsgBox "The native error code returned was: " & a(x,1)MsgBox a(x,2)

Next xEnd If

End Sub

Platform(s) Windows.

SQLExecQuery (function)Syntax SQLExecQuery(ID, query$)

Description Executes an SQL statement query on a data source.

Comments This function is called after a connection to a data source is established usingthe SQLOpen function. The SQLExecQuery function may be called multipletimes 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 bythe SQLOpen function.

query$ String specifying an SQL query statement. The SQL syntax of the string muststrictly follow that of the driver.

Page 455: Working Model 2D - User's Manual

Chapter 2 SQLGetSchema (function) 451

The return value of this function depends on the result returned by the SQLstatement:

SQL Statement Value

SELECT...FROM The value returned is the number of columns returnedby the SQL statement.

DELETE,INSERT,UPDATEThe value returned is the number of rows affected bythe SQL statement.

WM Basic generates a runtime error if SQLExecQuery fails. Additional errorinformation can then be retrieved using the SQLError function.

Example 'This example executes a query on the connected data source.

Sub Main()Dim s As StringDim qry As LongDim a() As Variant

On Error Goto Trapid& = SQLOpen("dsn=SAMPLE", s$, 3)qry = SQLExecQuery(id&,"Select * From c:\sample.dbf")MsgBox "There are " & qry & " columns in the result set."id& = SQLClose(id&)Exit Sub

Trap:rc% = SQLError(a)If (rc%) Then

For x = 0 To (rc% - 1)MsgBox "The SQLState returned was: " & a(x,0)MsgBox "The native error code returned was: " & a(x,1)MsgBox a(x,2)

Next xEnd If

End Sub

See Also SQLOpen (function); SQLClose (function); SQLRetrieve (function);SQLRetrieveToFile (function).

Platform(s) Windows.

SQLGetSchema (function)Syntax SQLGetSchema(ID, action, [,[array] [,qualifier$]])

Description Returns information about the data source associated with the specifiedconnection.

Page 456: Working Model 2D - User's Manual

452 Working Model Basic User's Manual

Comments The following table describes the parameters to the SQLGetSchema function:

Parameter Description

ID Long parameter identifying a valid connected data source. This parameter isreturned by the SQLOpen function.

action Integer parameter specifying the results to be returned. The following tablelists values for this parameter:

Value Meaning

1 Returns a one-dimensional array of availabledata sources. The array is returned in thearray parameter.

2 Returns a one-dimensional array of databases(either directory names or database names,depending on the driver) associated with thecurrent connection. The array is returned inthe array parameter.

3 Returns a one-dimensional array of owners(user IDs) of the database associated with thecurrent connection. The array is returned inthe array parameter.

4 Returns a one-dimensional array of tablenames for a specified owner and databaseassociated with the current connection. Thearray is returned in the array parameter.

5 Returns a two-dimentional array (n by 2)containing information about a specifiedtable. The array is configured as follows:

(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,0) Nth column name(n,1) ODBC SQL data type(Integer)

6 Returns a string containing the ID of thecurrent user.

Page 457: Working Model 2D - User's Manual

Chapter 2 SQLGetSchema (function) 453

7 Returns a string containing the name (eitherthe directory name or the database name,depending on the driver) of the currentdatabase.

8 Returns a string containing the name of thedata source on the current connection.

9 Returns a string containing the name of theDBMS of the data source on the currentconnection (e.g., "FoxPro 2.5" or "ExcelFiles").

10 Returns a string containing the name of theserver for the data source.

11 Returns a string containing the ownerqualifier used by the data source (e.g.,"owner," "Authorization ID," "Schema").

12 Returns a string containing the table qualifierused by the data source (e.g., "table," "file").

13 Returns a string containing the databasequalifier used by the data source (e.g.,"database," "directory").

14 Returns a string containing the procedurequalifier used by the data source (e.g.,"database procedure," "stored procedure,""procedure").

array Optional Variant array parameter. This parameter is only required for actionvalues 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 requestedinformation, 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 ofelements requested.

Page 458: Working Model 2D - User's Manual

454 Working Model Basic User's Manual

qualifier Optional String parameter required for actions 3, 4, or 5. The values are listedin the following table:

Action Qualifier

3 The qualifier parameter must be the name ofthe database represented by ID.

4 The qualifier parameter specifies a databasename and an owner name. The syntax for thisstring is:

DatabaseName.OwnerName

5 The qualifier parameter specifies the name ofa table on the current connection.

WM Basic generates a runtime error if SQLGetSchema fails. Additional errorinformation can then be retrieved using the SQLError function.

If you want to retrieve the available data sources (where action = 1) beforeestablishing a connection, you can pass 0 as the ID parameter. This is the onlyaction that will execute successfully without a valid connection.

This function calls the ODBC functions SQLGetInfo and SQLTables in order toretrieve the requested information. Some database drivers do not support thesecalls and will therefore cause the SQLGetSchema function to fail.

Example 'This example gets all available data sources.

Const crlf = Chr$(13) + Chr$(10)

Sub Main()Dim dsn() As Variantnumdims% = SQLGetSchema(0,1,dsn)If (numdims%) Then

msg = "Valid data sources are:" & crlfFor x = 0 To numdims% - 1

msg = msg & dsn(x) & crlfNext x

Elsemsg = "There are no available data sources."

End IfMsgBox msg

End Sub

See Also SQLOpen (function).

Platform(s) Windows.

Page 459: Working Model 2D - User's Manual

Chapter 2 SQLOpen (function) 455

SQLOpen (function)Syntax SQLOpen(login$ [,[completed$] [,prompt]])

Description Establishes a connection to the specified data source, returning a Longrepresenting the unique connection ID.

Comments This function connects to a data source using a login string (login$) andoptionally sets the completed login string (completed$) that was used by thedriver. The following table describes the parameters to the SQLOpen function:

Parameter Description

login$ String expression containing information required by the driver to connect tothe requested data source. The syntax must strictly follow the driver's SQLsyntax.

completed$ Optional String variable that will recieve a completed connection stringreturned by the driver. If this parameter is missing, then no connection stringwill be returned.

prompt Integer expression specifying any of the following values:

Value Meaning

1 The driver's login dialog box is alwaysdisplayed.

2 The driver's dialog box is only displayed ifthe connection string does not contain enoughinformation to make the connection. This isthe default behavior.

3 The driver's dialog box is only displayed ifthe connection string does not contain enoughinformation to make the connection. Dialogbox options that were passed as validparameters are dimmed and unavailable.

4 The driver's login dialog box is neverdisplayed.

The SQLOpen function will never return an invalid connection ID. Thefollowing example establishes a connection using the driver's login dialog box:

id& = SQLOpen("",,1)

WM Basic returns 0 and generates a trappable runtime error if SQLOpen fails.Additional error information can then be retrieved using the SQLError function.

Page 460: Working Model 2D - User's Manual

456 Working Model Basic User's Manual

Before you can use any SQL statements, you must set up a data source andrelate an existing database to it. This is accomplished using the odbcadm.exeprogram.

Example 'This example connects the data source called "sample," returning the'completed connction string, and then displays it.

Sub Main()Dim s As Stringid& = SQLOpen("dsn=SAMPLE",s$,3)MsgBox "The completed connection string is: " & s$id& = SQLClose(id&)

End Sub

See Also SQLClose (function).

Platform(s) Windows.

SQLRequest (function)Syntax SQLRequest(connection$,query$,array [,[output$] [,[prompt] [,isColumnNames]]])

Description Opens a connection, runs a query, and returns the results as an array.

Comments The SQLRequest function takes the following parameters:

Parameter Description

connection String specifying the connection information required to connect to the datasource.

query String specifying the query to execute. The syntax of this string must strictlyfollow 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 exactnumber of records and fields.

output Optional String to receive the completed connection string as returned by thedriver.

prompt Optional Integer specifying the behavior of the driver's dialog box.

isColumnNames Optional Boolean specifying whether the column names are returned as thefirst row of results. The default is False.

WM Basic generates a runtime error if SQLRequest fails. Additional errorinformation can then be retrieved using the SQLError function.

Page 461: Working Model 2D - User's Manual

Chapter 2 SQLRetrieve (function) 457

The SQLRequest function performs one of the following actions, depending onthe type of query being performed:

Type of Query Action

SELECT The SQLRequest function fills array with the resultsof the query, returning a Long containing the numberof results placed in the array. The array is filled asfollows (assuming an x by y query):

(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, UPDATE The SQLRequest function erases array andreturns a Long containing the 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 Variantl& = SQLRequest("dsn=SAMPLE;","Select * From

c:\sample.dbf",a,,3,True)For x = 0 To Ubound(a)

For y = 0 To l - 1MsgBox a(x,y)

Next yNext x

End Sub

Platform(s) Windows.

SQLRetrieve (function)Syntax SQLRetrieve(ID,array[,[maxcolumns] [,[ maxrows] [,[isColumnNames] [,

isFetchFirst]]]])

Description Retrieves the results of a query.

Page 462: Working Model 2D - User's Manual

458 Working Model Basic User's Manual

Comments This function is called after a connection to a data source is established, a queryis executed, and the desired columns are bound. The following table describesthe 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 rowsby y columns. The number of columns is determined by the number of bindingson the connection.

maxcolumns Optional Integer expression specifying the maximum number of columns tobe returned. If maxcolumns is greater than the number of columns bound, theadditional columns are set to empty. If maxcolumns is less than the number ofbound results, the rightmost result columns are discarded until the result fits.

maxrows Optional Integer specifying the maximum number of rows to be returned. Ifmaxrows 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 ofrows available, the array is filled, and additional results are placed in memoryfor subsequent calls to SQLRetrieve.

isColumnNames Optional Boolean specifying whether column names should be returned as thefirst row of results. The default is False.

isFetchFirst Optional Boolean expression specifying whether results are retrieved from thebeginning of the result set. The default is False.

Before you can retrieve the results from a query, you must (1) initiate a queryby calling the SQLExecQuery function and (2) specify the fields to retrieve bycalling the SQLBind function.

This function returns a Long specifying the number of columns available in thearray.

WM Basic generates a runtime error if SQLRetrieve fails. Additional errorinformation is placed in memory.

Page 463: Working Model 2D - User's Manual

Chapter 2 SQLRetrieveToFile (function) 459

Example 'This example executes a query on the connected data source, binds'columns, and retrieves them.

Sub Main()Dim a() As VariantDim b() As VariantDim c() As Variant

On Error Goto Trapid& = 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 l& - 1MsgBox c(x,y)

Next yNext xid& = SQLClose(id&)Exit Sub

Trap:rc% = SQLError(a)If (rc%) Then

For x = 0 To (rc% - 1)MsgBox "The SQLState returned was: " & a(x,0)MsgBox "The native error code returned was: " & a(x,1)MsgBox a(x,2)

Next xEnd If

End Sub

See Also SQLOpen (function); SQLExecQuery (function); SQLClose (function); SQLBind(function); SQLRetrieveToFile (function).

Platform(s) Windows.

SQLRetrieveToFile (function)Syntax SQLRetrieveToFile(ID,destination$ [,[isColumnNames] [,delimiter$]])

Description Retrieves the results of a query and writes them to the specified file.

Page 464: Working Model 2D - User's Manual

460 Working Model Basic User's Manual

Comments The following table describes the parameters to the SQLRetrieveToFilefunction:

Parameter Description

ID Long specifying a valid connection ID.

destination String specifying the file where the results are written.

isColumnNames Optional Boolean specifying whether the first row of results returned are thebound column names. By default, the column names are not returned.

delimiter Optional String specifying the column separator. A tab (Chr$(9)) is used asthe default.

Before you can retrieve the results from a query, you must (1) initiate a queryby calling the SQLExecQuery function and (2) specify the fields to retrieve bycalling the SQLBind function.

This function returns the number of rows written to the file. A runtime error isgenerated if there are no pending results or if WM Basic is unable to open thespecified file.

WM Basic generates a runtime error if SQLRetrieveToFile fails. Additionalerror information may be placed in memory for later use with the SQLErrorfunction.

Page 465: Working Model 2D - User's Manual

Chapter 2 Sqr (function) 461

Example 'This example opens a connection, runs a query, binds columns, and'writes the results to a file.

Sub Main()Dim a() As VariantDim b() As Variant

On Error Goto Trapid& = 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&)Exit Sub

Trap:rc% = SQLError(a)If (rc%) Then

For x = 0 To (rc-1)MsgBox "The SQLState returned was: " & a(x,0)MsgBox "The native error code returned was: " & a(x,1)MsgBox a(x,2)

Next xEnd If

End Sub

See Also SQLOpen (function); SQLExecQuery (function); SQLClose (function); SQLBind(function); SQLRetrieve (function).

Platform(s) Windows.

Sqr (function)Syntax Sqr(number)

Description Returns a Double representing the square root of number.

Comments The number parameter is a Double greater than or equal to 0.

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()For x = 1 To 10

sx# = Sqr(x)msg = msg & Format(x,"Fixed") & " - " & Format(sx#,"Fixed") &

crlfNext xMsgBox msg

End Sub

Page 466: Working Model 2D - User's Manual

462 Working Model Basic User's Manual

Platform(s) Windows and Macintosh.

Stop (statement)Syntax Stop

Description Suspends execution of the current script, returning control to a debugger if oneis present. If a debugger is not present, this command will have the same effectas End.

Example 'The Stop statement can be used for debugging. In this example, it isused'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 Stopy = x / z

Next xEnd Sub

See Also Exit For (statement); Exit Do (statement); Exit Function (statement); ExitSub (statement); End (statement).

Platform(s) Windows and Macintosh.

Str, Str$ (functions)Syntax Str[$](number)

Description Returns a string representation of the given number.

Comments The number parameter is any numeric expression or expression convertible to anumber. If number is negative, then the returned string will contain a leadingminus sign. If number is positive, then the returned string will contain a leadingspace.

Singles are printed using only 7 significant digits. Doubles are printed using15–16 significant digits.

These functions only output the period as the decimal separator and do notoutput thousands separators. Use the CStr, Format, or Format$ functionfor this purpose.

Example 'In this example, the Str$ function is used to display the value of a'numeric variable.

Sub Main()x# = 100.22MsgBox "The string value is: " + Str(x#)

End Sub

Page 467: Working Model 2D - User's Manual

Chapter 2 StrComp (function) 463

See Also Format, Format$ (functions); CStr (function).

Platform(s) Windows and Macintosh.

StrComp (function)Syntax StrComp(string1,string2 [,compare])

DescriptionReturns an Integer indicating the result of comparing the two string arguments.

Comments Any of the following values are returned:

0 string1 = string2

1 string1 > string2

_1 string1 < string2

Null string1 or string2 is Null

The StrComp function accepts the following parameters:

Parameter Description

string1 First string to be compared, which can be any expression convertible to aString.

string2 Second string to be compared, which can be any expression convertible to aString.

compare Optional Integer specifying how the comparison is to be performed. It can beeither of the following values:

0 Case-sensitive comparison

1 Case-insensitive comparison

If compare is not specified, then the current Option Compare setting isused. If no Option Compare statement has been encountered, then Binaryis used (i.e., string comparison is case-sensitive).

Page 468: Working Model 2D - User's Manual

464 Working Model Basic User's Manual

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()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"abc = StrComp(a$,b$,0)msg = msg & "a and c (sensitive) : " & Format(abc,"True/False") &

crlfabi = StrComp(a$,b$,1)msg = msg & "a and b (insensitive): " & Format(abi,"True/False") &

crlfaci = StrComp(a$,c$,1)msg = msg & "a and c (insensitive): " & Format(aci,"True/False") &

crlfbdi = StrComp(b$,d$,1)msg = msg & "b and d (sensitive) : " & Format(bdi,"True/False") &

crlfMsgBox msg

End Sub

See Also Comparison Operators (topic); Like (operator); Option Compare (statement).

Platform(s) Windows and Macintosh.

String (data type)Syntax String

Description A data type capable of holding a number of characters.

Comments Strings are used to hold sequences of characters, each character having a valuebetween 0 and 255. Strings can be any length up to a maximum length of 32767characters.

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 functionreturns the number of characters that have been stored in the string, includingunprintable characters.

The type-declaration character for String is $.

String variables that have not yet been assigned are set to zero-length bydefault.

Page 469: Working Model 2D - User's Manual

Chapter 2 String, String$ (functions) 465

Strings are normally declared as variable-length, meaning that the memoryrequired for storage of the string depends on the size of its content. Thefollowing WM Basic statements declare a variable-length string and assign it avalue of length 5:

Dim s As Strings = "Hello" 'String has length 5.

Fixed-length strings are given a length in their declaration:

Dim s As String * 20s = "Hello" 'String has length 20 (internally pads with

spaces).

When a string expression is assigned to a fixed-length string, the followingrules apply:

If the string expression is less than the length of the fixed-length string, thenthe 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-lengthstring.

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, asdescribed in the following table:

Strings Declared Are Stored

In structures In the same data area as that of the structure. Local structures are on the stack;public structures are stored in the public data space; and private structures arestored in the private data space. Local structures should be used sparingly asstack space is limited.

In arrays In the global string space along with all the other array elements.

Local routines On the stack. The stack is limited in size, so local fixed-length strings should beused sparingly.

See Also Currency (data type); Date (data type); Double (data type); Integer (datatype); Long (data type); Object (data type); Single (data type); Variant (datatype); Boolean (data type); DefType (statement); CStr (function).

Platform(s) Windows and Macintosh.

String, String$ (functions)Syntax String[$](number,[CharCode | text$])

Page 470: Working Model 2D - User's Manual

466 Working Model Basic User's Manual

Description Returns a string of length number consisting of a repetition of the specifiedfiller character.

Comments String$ returns a String, whereas String returns a String variant.

These functions take the following parameters:

Parameter Description

number Integer specifying the number of repetitions.

CharCode Integer specifying the character code to be used as the filler character. IfCharCode is greater than 255 (the largest character value), then WM Basicconverts 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 fillercharacter.

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

See Also Space, Space$ (functions).

Platform(s) Windows and Macintosh.

Sub...End Sub (statement)Syntax [Private | Public] [Static] Sub name[(arglist)]

[statements]End Sub

Where arglist is a comma-separated list of the following (up to 30 argumentsare allowed):

[Optional] [ByVal | ByRef] parameter[()] [As type]

Description Declares a subroutine.

Page 471: Working Model 2D - User's Manual

Chapter 2 Sub...End Sub (statement) 467

Comments The Sub statement has the following parts:

Part Description

Private Indicates that the subroutine being defined cannot be called from other scripts.

Public Indicates that the subroutine being defined can be called from other scripts. Ifthe Private and Public keywords are both missing, then Public is assumed.

Static Recognized by the compiler but currently has no effect.

name Name of the subroutine, which must follow WM Basic naming conventions:

1. Must start with a letter.

2. May contain letters, digits, and the underscore character(_). Punctuation and type-declaration characters are notallowed. The exclamation point (!) can appear within thename as long as it is not the last character.

3. Must not exceed 80 characters in length.

Optional Keyword indicating that the parameter is optional. All optional parameters mustbe of type Variant. Furthermore, all parameters that follow the first optionalparameter must also be optional.

If this keyword is omitted, then the parameter is required.

Note: You can use the IsMissing function to determine if an optionalparameter was actually passed by the caller.

ByVal Keyword indicating that the parameter is passed by value.

ByRef Keyword indicating that the parameter is passed by reference. If neither theByVal nor the ByRef keyword is given, then ByRef is assumed.

parameter Name of the parameter, which must follow the same naming conventions asthose used by variables. This name can include a type-declaration character,appearing in place of As type.

type Type of the parameter (i.e., Integer, String, and so on). Arrays are indicatedwith parentheses. For example, an array of integers would be declared asfollows:

Sub Test(a() As Integer)End Sub

A subroutine terminates when one of the following statements is encountered:End SubExit Sub

Subroutines can be recursive.

Page 472: Working Model 2D - User's Manual

468 Working Model Basic User's Manual

Passing Parameters to Subroutines

Parameters are passed to a subroutine either by value or by reference,depending on the declaration of that parameter in arglist. If the parameter isdeclared using the ByRef keyword, then any modifications to that passedparameter within the subroutine change the value of that variable in the caller.If the parameter is declared using the ByVal keyword, then the value of thatvariable cannot be changed in the called subroutine. If neither the ByRef orByVal keywords are specified, then the parameter is passed by reference.

You can override passing a parameter by reference by enclosing that parameterwithin parentheses. For instance, the following example passes the variable jby reference, regardless of how the third parameter is declared in the arglist ofUserSub:

UserSub 10,12,(j)

Optional Parameters

WM Basic allows you to skip parameters when calling subroutines, as shown inthe following example:

Sub Test(a%,b%,c%)End Sub

Sub MainTest 1,,4 'Parameter 2 was skipped.

End Sub

You can skip any parameter with the following restrictions:

1. The call cannot end with a comma. For instance, using the above example,the following is not valid:

Test 1,,

2. The call must contain the minimum number of parameters as requred by thecalled subroutine. For instance, using the above example, the following areinvalid:

Test ,1 'Only passes two out of three requiredparameters.

Test 1,2 'Only passes two out of three required parameters.

Page 473: Working Model 2D - User's Manual

Chapter 2 Switch (function) 469

When you skip a parameter in this manner, WM Basic creates a temporaryvariable and passes this variable instead. The value of this temporary variabledepends on the data type of the corresponding parameter in the argument list ofthe called subroutine, as described in the following table:

Value Data type

0 Integer, Long, Single, Double, Currency

Zero-length string String

Nothing Object (or any data object)

Error Variant

December 30, 1899 Date

False Boolean

Within the called subroutine, you will be unable to determine if a parameterwas skipped unless the parameter was declared as a variant in the argument listof the subroutine. In this case, you can use the IsMissing function to determineif the parameter was skipped:

Sub Test(a,b,c)If IsMissing(a) Or IsMissing(b) Then Exit Sub

End Sub

Example 'This example uses a subroutine to calculate the area of a circle.

Sub Main()r! = 10PrintArea r!

End Sub

Sub PrintArea(r as single)area! = (r! ^ 2) * PiMsgBox "The area of a circle with radius " & r! & " = " & area!

End Sub

See Also Main (keyword); Function...End Function (statement).

Platform(s) Windows and Macintosh.

Switch (function)Syntax Switch(condition1,expression1 [,condition2,expression2 ... [,condition7,expression7]])

Description Returns the expression corresponding to the first True condition.

Page 474: Working Model 2D - User's Manual

470 Working Model Basic User's Manual

Comments The Switch function evaluates each condition and expression, returning theexpression that corresponds to the first condition (starting from the left) thatevaluates to True. Up to seven condition/expression pairs can be specified.

A runtime error is generated it there is an odd number of parameters (i.e., thereis a condition without a corresponding expression).

The Switch function returns Null if no condition evaluates to True.

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 Varianta = Switch(Basic.OS = 0,"Windows 3.1",Basic.OS = 10,"Mac")MsgBox "The current platforms is: " & IIf(IsNull(a),"Unknown",a)

End Sub

See Also Choose (function); IIf (function); If...Then...Else (statement);Select...Case (statement).

Platform(s) Windows and Macintosh.

SYD (function)Syntax SYD(Cost,Salvage,Life,Period)

Description Returns the sum of years' digits depreciation of an asset over a specific periodof 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

The SYD function requires the following parameters:

Parameter Description

Cost Double representing the initial cost of the asset.

Salvage Double representing the estimated value of the asset at the end of its useful life.

Life Double representing the length of the asset's useful life.

Period Double representing the period for which the depreciation is to be calculated. Itcannot exceed the life of the asset.

To receive accurate results, the parameters Life and Period must be expressedin the same units. If Life is expressed in terms of months, for example, thenPeriod must also be expressed in terms of months.

Page 475: Working Model 2D - User's Manual

Chapter 2 System.Exit (method) 471

Example 'In this example, an asset that cost $1,000.00 is depreciated over tenyears.'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()For x = 1 To 10

dep# = SYD(1000,100,10,x)msg = msg & "Year: " & x & " Dep: " & Format(dep#,"Currency") &

crlfNext xMsgBox msg

End Sub

See Also Sln (function); DDB (function).

Platform(s) Windows and Macintosh.

System.Exit (method)Syntax System.Exit

Description Exits the operating environment.

Example 'This example asks whether the user would like to restart Windows'after exiting.

Sub Mainbutton = 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

See Also System.Restart (method).

Platform(s) Windows.

System.FreeMemory (property)Syntax System.FreeMemory

Description Returns a Long indicating the number of bytes of free memory.

Example 'The following example gets the free memory and converts it to'kilobytes

Sub Main()FreeMem& = System.FreeMemoryFreeKBytes$ = Format(FreeMem& / 1000,"##,###")MsgBox FreeKbytes$ & " Kbytes of free memory"

End Sub

Page 476: Working Model 2D - User's Manual

472 Working Model Basic User's Manual

See Also System.TotalMemory (property); System.FreeResources (property);Basic.FreeMemory (property).

Platform(s) Windows.

System.FreeResources (property)Syntax System.FreeResources

Description Returns an Integer representing the percentage of free system resources.

Comments The returned value is between 0 and 100.

Example 'This example gets the percentage of free resources.

Sub Main()FreeRes% = System.FreeResourcesMsgBox FreeRes% & "% of memory resources available."

End Sub

See Also System.TotalMemory (property); System.FreeMemory (property);Basic.FreeMemory (property).

Platform(s) Windows.

System.MouseTrails (method)Syntax System.MouseTrails isOn

Description Toggles mouse trails on or off.

Comments If isOn is True, then mouse trails are turned on; otherwise, mouse trails areturned off.

A runtime error is generated if mouse trails is not supported on your system.

Example 'This example turns on mouse trails.Sub Main

System.MouseTrails 1End Sub

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the setting is saved in the INI file permanently.

System.Restart (method)Syntax System.Restart

Description Restarts the operating environment.

Page 477: Working Model 2D - User's Manual

Chapter 2 System.TotalMemory (property) 473

Example 'This example asks whether the user would like to restart Windows after'exiting.

Sub Mainbutton = 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

See Also System.Exit (method).

Platform(s) Windows.

System.TotalMemory (property)Syntax System.TotalMemory

Description Returns a Long representing the number of bytes of available free memory inWindows.

Example 'This example displays the total system memory.

Sub Main()TotMem& = System.TotalMemoryTotKBytes$ = Format(TotMem& / 1000,"##,###")MsgBox TotKbytes$ & " Kbytes of total system memory exist"

End Sub

See Also System.FreeMemory (property); System.FreeResources (property);Basic.FreeMemory (property).

Platform(s) Windows.

System.WindowsDirectory$ (property)Syntax System.WindowsDirectory$

Description Returns the home directory of the operating environment.

Example 'This example displays the windows directory.

Sub MainMsgBox "Windows directory = " & System.WindowsDirectory$

End Sub

See Also Basic.HomeDir$ (property).

Platform(s) Windows.

System.WindowsVersion$ (property)Syntax System.WindowsVersion$

Description Returns the version of the operating environment, such as "3.0" or "3.1."

Page 478: Working Model 2D - User's Manual

474 Working Model Basic User's Manual

Example 'This example sets the UseWin31 variable to True if the Windows versionis'greater than or equal to 3.1; otherwise, it sets the UseWin31 variable'to False.

Sub Main()If Val(System.WindowsVersion$) > 3.1 Then

MsgBox "You are running a Windows version later than 3.1"Else

MsgBox "You are running Windows version 3.1 or earlier"End If

End Sub

See Also Basic.Version$ (property).

Platform(s) Windows.

Page 479: Working Model 2D - User's Manual

475

Tab (function)Syntax Tab(column)

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 positionto 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 thenumber of spaces is calculated as:

column – print_position

Rule 2: If the current print position is greater than column, then column – 1spaces are printed on the next line.

If a line width is specified (using the Width statement), then the columnposition 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 givencolumn position, regardless of the length of the data already printed on that line.

Example 'This example prints three column headers and three numbers'alligned below the column headers.

Sub Main()ViewportOpenPrint "Column1";Tab(10);"Column2";Tab(20);"Column3"Print Tab(3);"1";Tab(14);"2";Tab(24);"3"Sleep(10000) 'Wait 10 seconds.ViewportClose

End Sub

See Also Spc (function); Print (statement); Print# (statement).

Platform(s) Windows and Macintosh.

Tan (function)Syntax Tan(angle)

Description Returns a Double representing the tangent of angle.

Comments The angle parameter is a Double value given in radians.

Page 480: Working Model 2D - User's Manual

476 Working Model Basic User's Manual

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

See Also Sin (function); Cos (function); Atn (function).

Platform(s) Windows and Macintosh.

Text (statement)Syntax Text x,y,width,height,title$ [,[.Identifier] [,[FontName$] [,[size] [,style]]]]

Description Defines a text control within a dialog box template. The text control onlydisplays text; the user cannot set the focus to a text control or otherwise interactwith it.

Comments The text within a text control word-wraps. Text controls can be used to displayup to 32K of text.

The Text statement accepts the following parameters:

Parameter Description

x, y Integer positions of the control (in dialog units) relative to the upper leftcorner of the dialog box.

width, height Integer dimensions of the control in dialog units.

title$ String containing the text that appears within the text control. This text maycontain an ampersand character to denote an accelerator letter, such as "&Save"for Save. Pressing this accelerator letter sets the focus to the control followingthe Text statement in the dialog box template.

Identifier Name by which this control can be referenced by statements in a dialogfunction (such as DlgFocus and DlgEnable). If omitted, then the first twowords 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.

Page 481: Working Model 2D - User's Manual

Chapter 2 TextBox (statement) 477

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 beany of the following values:

ebRegular Normal font (i.e., neither bold nor italic)

ebBold Bold font

ebItalic Italic font

ebBoldItalic Bold-italic font

If omitted, then ebRegular is used.

Example Begin Dialog UserDialog3 81,64,128,60,"Untitled"CancelButton 80,32,40,14OKButton 80,8,40,14Text 4,8,68,44,"This text is displayed in the dialog box."

End Dialog

See Also CancelButton (statement); CheckBox (statement); ComboBox (statement);Dialog (function); Dialog (statement); DropListBox (statement); GroupBox(statement); ListBox (statement); OKButton (statement); OptionButton(statement); OptionGroup (statement); Picture (statement); PushButton(statement); TextBox (statement); Begin Dialog (statement), PictureButton(statement).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Under Windows, accelerators are underlined, and the Alt+letter acceleratorcombination is used.

Under Windows, 8-point MS Sans Serif is the default font used within userdialogs.

PlatformNotes:

Macintosh

On the Macintosh, accelerators are normal in appearance, and theCommand+letter accelerator combination is used.

On the Macintosh, 10-point Geneva is the default font used within user dialogs.

TextBox (statement)Syntax TextBox x,y,width,height,.Identifier [,[isMultiline] [,[FontName$] [,[size] [,style]]]]

Description Defines a single or multiline text-entry field within a dialog box template.

Page 482: Working Model 2D - User's Manual

478 Working Model Basic User's Manual

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 newline rather than selecting the default button.

This statement can only appear within a dialog box template (i.e., between theBegin Dialog and End Dialog statements).

The TextBox statement requires the following parameters:

Parameter Description

x, y Integer position of the control (in dialog units) relative to the upper left cornerof the dialog box.

width, height Integer dimensions of the control in dialog units.

Identifier Name by which this control can be referenced by statements in a dialogfunction (such as DlgFocus and DlgEnable). This parameter also creates astring variable whose value corresponds to the content of the text box. Thisvariable 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. Ifomitted, 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. Ifomitted, 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. Thiscan be any of the following values:

ebRegular Normal font (i.e., neither bold nor italic)

ebBold Bold font

ebItalic Italic font

ebBoldItalic Bold-italic font

If omitted, then ebRegular is used.

When the dialog box is created, the Identifier variable is used to set the initialcontent of the text box. When the dialog box is dismissed, the variable willcontain the new content of the text box.

A single-line text box can contain up to 256 characters. The length of text in amultiline text box is not limited by WM Basic; the default memory limitspecified by the given platform is used instead.

Page 483: Working Model 2D - User's Manual

Chapter 2 Time, Time$ (functions) 479

Example Begin Dialog UserDialog3 81,64,128,60,"Untitled"CancelButton 80,32,40,14OKButton 80,8,40,14TextBox 4,8,68,44,.TextBox1,1

End Dialog

See Also CancelButton (statement); CheckBox (statement); ComboBox (statement);Dialog (function); Dialog (statement); DropListBox (statement); GroupBox(statement); ListBox (statement); OKButton (statement); OptionButton(statement); OptionGroup (statement); Picture (statement); PushButton(statement); Text (statement); Begin Dialog (statement), PictureButton(statement).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Under Windows, 8-point MS Sans Serif is the default font used within user dialogs.

PlatformNotes:

Macintosh

On the Macintosh, 10-point Geneva is the default font used within user dialogs.

Time, Time$ (functions)Syntax Time[$][()]

Description Returns the system time as a String or as a Date variant.

Comments The Time$ function returns a String contains the time in 24-hour timeformat, 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$msg = "Time was: " & oldtime$ & crlfTime$ = "10:30:54"msg = msg & "Time set to: " & Time$ & crlfTime$ = oldtime$msg = msg & "Time restored to: " & Time$MsgBox msg

End Sub

See Also Time, Time$ (statements); Date, Date$ (functions); Date, Date$(statements); Now (function).

Platform(s) Windows and Macintosh.

Page 484: Working Model 2D - User's Manual

480 Working Model Basic User's Manual

Time, Time$ (statements)Syntax Time[$] = newtime

Description Sets the system time to the time contained in the specified string.

Comments The Time$ statement requres a string variable in one of the following formats:

HHHH:MMHH:MM:SS

where HH is between 0 and 23, MM is between 0 and 59, and SS is between 0and 59.

The Time statement converts any valid expression to a time, including stringand numeric values. Unlike the Time$ statement, Time recognizes manydifferent 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$msg = "Time was: " & oldtime$ & crlfTime$ = "10:30:54"msg = msg & "Time set to: " & Time$ & crlfTime$ = oldtime$msg = msg & "Time restored to: " & Time$MsgBox msg

End Sub

See Also Time, Time$ (functions); Date, Date$ (functions); Date, Date$(statements).

Platform(s) Windows and Macintosh.

Timer (function)Syntax Timer

Description Returns a Single representing the number of seconds that have elapsed sincemidnight.

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& = TimerMsgBox "Click the OK button, please."total& = Timer - start&MsgBox "The elapsed time was: " & total& & " seconds."

End Sub

Page 485: Working Model 2D - User's Manual

Chapter 2 TimeSerial (function) 481

See Also Time, Time$ (functions); Now (function).

Platform(s) Windows and Macintosh.

TimeSerial (function)Syntax TimeSerial(hour,minute,second)

Description Returns a Date variant representing the given time with a date of zero.

Comments The TimeSerial function requires the following parameters:

Parameter Description

hour Integer between 0 and 23.

minute Integer between 0 and 59.

second Integer between 0 and 59.

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 (function); TimeValue (function); DateSerial (function).

Platform(s) Windows and Macintosh.

TimeValue (function)Syntax TimeValue(time_string$)

Description Returns a Date variant representing the time contained in the specified stringargument.

Comments This function interprets the passed time_string$ parameter looking for a validtime specification.

The time_string$ parameter can contain valid time items separated by timeseparators such as colon (:) or period (.).

Time strings can contain an optional date specification, but this is not used inthe 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."

Page 486: Working Model 2D - User's Manual

482 Working Model Basic User's Manual

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 (function); TimeSerial (function); DateSerial (function).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Under Windows, time specifications vary, depending on the internationalsettings contained in the [intl] section of the win.ini file.

Trim, Trim$ (functions)Syntax Trim[$](text)

Description Returns a copy of the passed string expression (text) with leading and trailingspaces removed.

Comments Trim$ returns a String, whereas Trim returns a String variant.

Null is returned if text is Null.

Example 'This 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

See Also LTrim, LTrim$ (functions); RTrim, RTrim$ (functions).

Platform(s) Windows and Macintosh.

True (constant)Description Boolean constant whose value is True.

Comments Used in conditionals and Boolean expressions.

Page 487: Working Model 2D - User's Manual

Chapter 2 Type (statement) 483

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 = TrueIf ((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 (constant); Constants (topic); Boolean (data type).

Platform(s) Windows and Macintosh.

Type (statement)Syntax Type username

variable As typevariable As typevariable As type:

End Type

Description The Type statement creates a structure definition that can then be used with theDim statement to declare variables of that type. The username field specifiesthe name of the structure that is used later with the Dim statement.

Comments Within a structure definition appear field descriptions in the format:

variable As type

where variable is the name of a field of the structure, and type is the data typefor that variable. Any fundamental data type or previously declared user-defined data type can be used within the structure definition (structures withinstructures are allowed). Only fixed arrays can appear within structuredefinitions.

The Type statement can only appear outside of subroutine and functiondeclarations.

Page 488: Working Model 2D - User's Manual

484 Working Model Basic User's Manual

When declaring strings within fixed-size types, it is useful to declare the stringsas fixed-length. Fixed-length strings are stored within the structure itself ratherthan in the string space. For example, the following structure will alwaysrequire 62 bytes of storage:

Type PersonFirstName As String * 20LastName As String * 40Age As Integer

End Type

Note: Fixed-length strings within structures are size-adjusted upward to aneven byte boundary. Thus, a fixed-length string of length 5 will occupy 6 bytesof 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 Circmsg As Stringrad As Integerdia As Integerare As Doublecir As Double

End Type

Sub Main()Dim circle As Circcircle.rad = 5circle.dia = circle.rad * 2circle.are = (circle.rad ^ 2) * Picircle.cir = circle.dia * Picircle.msg = "The area of the circle is: " & circle.areMsgBox circle.msg

End Sub

See Also Dim (statement); Public (statement); Private (statement).

Platform(s) Windows and Macintosh.

UBound (function)Syntax UBound(ArrayVariable() [,dimension])

Description Returns an Integer containing the upper bound of the specified dimension ofthe specified array variable.

Page 489: Working Model 2D - User's Manual

Chapter 2 UCase, UCase$ (functions) 485

Comments The dimension parameter is an integer that specifies the desired dimension. Ifnot 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 anarray 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.

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 & " 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 xMsgBox "The last element of the new array is: " & nl$(count)

End IfEnd Sub

See Also LBound (function); ArrayDims (function); Arrays (topic).

Platform(s) Windows and Macintosh.

UCase, UCase$ (functions)Syntax UCase[$](text)

Description Returns the uppercase equivalent of the specified string.

Comments UCase$ returns a String, whereas UCase returns a String variant.

Null is returned if text is Null.

Page 490: Working Model 2D - User's Manual

486 Working Model Basic User's Manual

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

See Also LCase, LCase$ (functions).

Platform(s) Windows and Macintosh.

Unlock (statement)Syntax Unlock [#] filenumber [,{record | [start] To end}]

Description Unlocks a section of the specified file, allowing other processes access to thatsection of the file.

Comments The Unlock statement requires the following parameters:

Parameter Description

filenumber Integer used by WM Basic to refer to the open file—the number passed to theOpen statement.

record Long specifying which record to unlock.

start Long specifying the first record within a range to be unlocked.

end Long specifying the last record within a range to be unlocked.

For sequential files, the record, start, and end parameters are ignored: the entirefile is unlocked.

Page 491: Working Model 2D - User's Manual

Chapter 2 Unlock (statement) 487

The section of the file is specified using one of the following:

Syntax Description

No record specification Unlock the entire file.

record Unlock the specified record number (forRandom files) or byte (for Binary files).

to end Unlock from the beginning of the file to thespecified record (for Random files) or byte (forBinary files).

start to end Unlock the specified range of records (forRandom files) or bytes (for Binary files).

The unlock range must be the same as that used by the Lock statement.

Page 492: Working Model 2D - User's Manual

488 Working Model Basic User's Manual

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 'displayedin a dialog box.

Const crlf = Chr$(13) + Chr$(10)

Sub Main()a$ = "This is record number: "b$ = "0"rec$ = ""

msg = ""Open "test.dat" For Random Access Write Shared As #1For x = 1 To 10

rec$ = a$ & xLock #1,xPut #1,,rec$Unlock #1,xmsg = msg & rec$ & crlf

Next xCloseMsgBox "The records are: " & crlf & msg

msg = ""Open "test.dat" For Random Access Read Write Shared As #1For 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,xmsg = msg & rec$ & crlf

Next xMsgBox "The records are: " & crlf & msgClose

Kill "test.dat"End Sub

See Also Lock (statement); Open (statement).

Platform(s) Windows and Macintosh.

PlatformNotes:

Macintosh

On the Macintosh, file locking will only succeed on volumes that are shared(i.e., file sharing is on).

Page 493: Working Model 2D - User's Manual

Chapter 2 User-Defined Types (topic) 489

User-Defined Types (topic)

User-defined types (UDTs) are structure definitions created using the Typestatement. UDTs are equivalent to C language structures.

Declaring Structures

The Type statement is used to create a structure definition. Type declarationsmust appear outside the body of all subroutines and functions within a scriptand are therefore global to an entire script.

Once defined, a UDT can be used to declare variables of that type using theDim, Public, or Private statement. The following example defines arectangle structure:

Type Rectleft As Integertop As Integerright As Integerbottom 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 otheruser-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. Noother standard operators can be applied to UDTs.

Dim r1 As RectDim r2 As Rect

:r1 = r2

When copying structures of the same type, all strings in the source UDT areduplicated and references are placed into the target UDT.

The LSet statement can be used to copy a UDT variable of one type toanother:

LSet variable1 = variable2

LSet cannot be used with UDTs containing variable-length strings. Thesmaller of the two structures determines how many bytes get copied.

Page 494: Working Model 2D - User's Manual

490 Working Model Basic User's Manual

Passing Structures

UDTs can be passed both to user-defined routines and to external routines, andthey can be assigned. UDTs are always passed by reference.

Since structures are always passed by reference, the ByVal keyword cannot beused when defining structure arguments passed to external routines (usingDeclare). The ByVal keyword can only be used with fundamental data typessuch as Integer and String.

Passing structures to external routines actually passes a far pointer to the datastructure.

Size of Structures

The Len function can be used to determine the number of bytes occupied by aUDT:

Len(udt_variable_name)

Since strings are stored in WM Basic's data space, only a reference (currently, 2bytes) is stored within a structure. Thus, the Len function may seem to returnincorrect information for structures containing strings.

Val (function)Syntax Val(number)

Description Converts a given string expression to a number.

Comments The number parameter can contain any of the following:

Leading minus sign (for nonhex or octal numbers only)

Hexadecimal number in the format &Hhexdigits

Octal number in the format &Ooctaldigits

Floating-point number, which can contain a decimal point and an optionalexponent

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 firstnonnumeric character.

The Val function always returns a double-precision floating-point value. Thisvalue is forced to the data type of the assigned variable.

Page 495: Working Model 2D - User's Manual

Chapter 2 Variant (data type) 491

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

'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 (function); Str, Str$ (functions).

Platform(s) Windows and Macintosh.

Variant (data type)Syntax Variant

Description A data type used to declare variables that can hold one of many different typesof data.

Comments During a variant's existence, the type of data contained within it can change.Variants can contain any of the following types of data:

Type of Data WM Basic Data Types

Numeric Integer, Long, Single, Double, Boolean, Date, Currency.

Logical Boolean.

Dates and times Date.

String String.

Object Object.

No valid data A variant with no valid data is considered Null.

Uninitialized An uninitialized variant is considered Empty.

There is no type-declaration character for variants.

The number of significant digits representable by a variant depends on the typeof data contained within the variant.

Variant is the default data type for WM Basic. If a variable is not explicitlydeclared with Dim, Public, or Private, and there is no type-declarationcharacter (i.e., #, @, !, %, or &), then the variable is assumed to be Variant.

Page 496: Working Model 2D - User's Manual

492 Working Model Basic User's Manual

Determining the Subtype of a Variant

The following functions are used to query the type of data contained within avariant:

Function Description

VarType Returns a number representing the type of data contained within the variant.

IsNumeric Returns True if a variant contains numeric data. The following are considerednumeric:

Integer, Long, Single, Double, Date, Boolean,Currency

If a variant contains a string, this function returns True if the string can beconverted to a number.

If a variant contains an Object whose default property is numeric, thenIsNumeric returns True.

IsObject Returns True if a variant contains an object.

IsNull Returns True if a variant contains no valid data.

IsEmpty Returns True if a variant is uninitialized.

IsDate Returns True if a variant contains a date. If the variant contains a string, thenthis function returns True if the string can be converted to a date. If the variantcontains an Object, then this function returns True if the default property ofthat object can be converted to a date.

Assigning to Variants

Before 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 valueis for that variant to be assigned to another Variant containing Empty, for itto be assigned explicitly to the constant Empty, or for it to be erased using theErase statement.

When a variant is assigned a value, it is also assigned that value's type. Thus, inall subsequent operations involving that variant, the variant will behave like thetype of data it contains.

Page 497: Working Model 2D - User's Manual

Chapter 2 Variant (data type) 493

Operations on Variants

Normally, a Variant behaves just like the data it contains. One exception tothis rule is that, in arithmetic operations, variants are automatically promotedwhen an overflow occurs. Consider the following statements:

Dim a As Integer,b As Integer,c As IntegerDim x As Variant,y As Variant,z As Variant

a% = 32767b% = 1c% = a% + b% 'This will overflow.

x = 32767y = 1z = x + y 'z becomes a Long because of Integer overflow.

In the above example, the addition involving Integer variables overflowsbecause the result (32768) overflows the legal range for integers. WithVariant variables, on the other hand, the addition operator recognizes theoverflow and automatically promotes the result to a Long.

Adding Variants

The + operator is defined as performing two functions: when passed strings, itconcatenates them; when passed numbers, it adds the numbers.

With variants, the rules are complicated because the types of the variants arenot known until execution time. If you use +, you may unintentionally performthe wrong operation.

It is recommended that you use the & operator if you intend to concatenate twoString variants. This guarantees that string concatenation will be performedand not addition.

Variants That Contain No Data

A Variant can be set to a special value indicating that it contains no validdata by assigning the Variant to Null:

Dim a As Varianta = Null

The only way that a Variant becomes Null is if you assign it as shownabove.

The Null value can be useful for catching errors since its value propagatesthrough an expression.

Page 498: Working Model 2D - User's Manual

494 Working Model Basic User's Manual

Variant Storage

Variants require 16 bytes of storage internally:

A 2-byte type

A 2-byte extended type for data objects

4 bytes of padding for alignment

An 8-byte value

Unlike other data types, writing variants to Binary or Random files does notwrite 16 bytes. With variants, a 2-byte type is written, followed by the data (2bytes for Integer and so on).

Disadvantages of Variants

The following list describes some disadvantages of variants:

1. Using variants is slower than using the other fundamental data types (i.e.,Integer, Long, Single, Double, Date, Object, String, Currency,and Boolean). Each operation involving a Variant requiresexamination of the variant's type.

2. Variants require more storage than other data types (16 bytes as opposed to8 bytes for a Double, 2 bytes for an Integer, and so on).

3. Unpredictable behavior. You may write code to expect an Integervariant. At runtime, the variant may be automatically promoted to a Longvariant, causing your code to break.

Passing Nonvariant Data to Routines Taking Variants

Passing nonvariant data to a routine that is declared to receive a variant byreference prevents that variant from changing type within that routine. Forexample:

Sub Foo(v As Variant)v = 50 'OK.v = "Hello, world." 'Get a type-mismatch error here!

End Sub

Sub Main()Dim i As IntegerFoo i 'Pass an integer by reference.

End Sub

In the above example, since an Integer is passed by reference (meaning thatthe caller can change the original value of the Integer), the caller mustensure that no attempt is made to change the variant's type.

Page 499: Working Model 2D - User's Manual

Chapter 2 VarType (function) 495

Passing Variants to Routines Taking Nonvariants

Variant variables cannot be passed to routines that accept nonvariant data byreference, as demonstrated in the following example:

Sub Foo(i as Integer)End Sub

Sub Main()Dim a As VariantFoo a 'Compiler gives type-mismatch error here.

End Sub

See Also Currency (data type); Date (data type); Double (data type); Integer (datatype); Long (data type); Object (data type); Single (data type); String (datatype); Boolean (data type); DefType (statement); CVar (function); Empty(constant); Null (constant); VarType (function).

Platform(s) Windows and Macintosh.

VarType (function)Syntax VarType(variable)

Description Returns an Integer representing the type of data in variable.

Comments The variable parameter is the name of any Variant.

The following table shows the different values that can be returned byVarType:

Value Constant Data Type

0 ebEmpty Uninitialized1 ebNull No valid data2 ebInteger Integer3 ebLong Long4 ebSingle Single5 ebDouble Double6 ebCurrency Currency7 ebDate Date8 ebString String9 ebObject Object (OLE automation object)

10 ebError User-defined error11 ebBoolean Boolean12 ebVariant Variant (not returned by this function)13 ebDataObject Non-OLE automation object

Page 500: Working Model 2D - User's Manual

496 Working Model Basic User's Manual

Comments When passed an cbject, the VarType function returns the type of the defaultproperty of that object. If the object has no default property, then eitherebObject or ebDataObject is returned, depending on the type of variable.

Example Sub Main()Dim v As Variantv = 5& 'Set v to a Long.

If VarType(v) = ebInteger ThenMsgbox "v is an Integer."

ElseIf VarType(v) = ebLong ThenMsgbox "v is a Long."

End IfEnd Sub

See Also Empty (constant); Null (constant); Variant (data type).

Platform(s) Windows and Macintosh.

ViewportClear (statement)Syntax ViewportClear

Description Clears the open viewport window.

Comments The statement has no effect if no viewport is open.

Example Sub Main()ViewportOpenPrint "This will be displayed in the viewport window."Sleep 2000ViewportClearPrint "This will replace the previous text."Sleep 2000ViewportClose

End Sub

See Also ViewportClose (statement); ViewportOpen (statement).

Platform(s) Windows.

ViewportClose (statement)Syntax ViewportClose

Description This statement closes an open viewport window.

Comments The statement has no effect if no viewport is opened.

Page 501: Working Model 2D - User's Manual

Chapter 2 ViewportOpen (statement) 497

Example Sub Main()ViewportOpenPrint "This will be displayed in the viewport window."Sleep 2000ViewportClose

End Sub

See Also ViewportOpen (statement).

Platform(s) Windows.

ViewportOpen (statement)Syntax ViewportOpen [title$ [,x,y [,width,height]]]

Description Opens a new viewport window or switches the focus to the existing viewportwindow.

Comments The ViewportOpen statement requires the following parameters:

Parameter Description

title$ Specifies a String containing the text to appear in the viewport's caption.

x,y Specifies Integer coordinates given in twips indicating the initial position ofthe upper left corner of the viewport.

width,height Specifies Integer values indicating the initial width and height of theviewport.

This statement has no effect if a viewport window is already open.

Combined with the Print statement, a viewport window is a convenient placeto output debugging information.

The viewport window is closed when the WM Basic host application isterminated.

Page 502: Working Model 2D - User's Manual

498 Working Model Basic User's Manual

The buffer size for the viewport is 32K. Information from the start of the bufferis removed to make room for additional information being appended to the endof the buffer.

The following keys work within a viewport window:

Up Scrolls up by one line.Down Scrolls down by one line.Home Scrolls to the first line in the viewport window.End Scrolls to the last line in the viewport window.PgDn Scrolls the viewport window down by one page.PgUp Scrolls the viewport window up by one page.Ctrl+PgUp Scrolls the viewport window left by one page.Ctrl+PgDn Scrolls the viewport window right by one page.

Only one viewport window can be open at any given time. Any scripts withPrint statements will output information into the same viewport window.

When printing to viewports, the end-of-line character can be any of thefollowing: a carriage return, a line feed, or a carriage-return/line-feed pair.

Example Sub Main()ViewportOpen "WM Basic Viewport",100,100,500,500Print "This will be displayed in the viewport window."Sleep 2000ViewportClose

End Sub

See Also ViewportClose (statement).

Platform(s) Windows.

VLine (statement)Syntax VLine [lines]

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. Ifthis parameter is omitted, then the window is scrolled down by one line.

Page 503: Working Model 2D - User's Manual

Chapter 2 VPage (statement) 499

Example 'This example prints a series of lines to the viewport, then 'scrollsback up the lines to the top using VLine.

Sub Main()ViewportOpen "WM Basic Viewport",100,100,500,200For i = 1 to 50

Print "This will be displayed on line#: " & iNext iMsgBox "We will now go back 40 lines..."VLine -40MsgBox "...and here we are!"ViewportClose

End Sub

See Also VPage (statement); VScroll (statement).

Platform(s) Windows.

VPage (statement)Syntax VPage [pages]

Description Scrolls the window with the focus up or down by the specified number ofpages.

Comments The pages parameter is an Integer specifying the number of lines to scroll. Ifthis parameter is omitted, then the window is scrolled down by one page.

Example 'This example scrolls the viewport window up five pages.

Sub Main()ViewportOpen "WM Basic Viewport",100,100,500,200For i = 1 to 500

Print "This will be displayed on line#: " & iNext iMsgBox "We will now go back 5 pages..."VLine -5MsgBox "...and here we are!"ViewportClose

End Sub

See Also VLine (statement); VScroll (statement).

Platform(s) Windows.

VScroll (statement)Syntax VScroll percentage

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 thatscroll bar. For example, if the percentage parameter is 50, then the thumb markis positioned in the middle of the scroll bar.

Page 504: Working Model 2D - User's Manual

500 Working Model Basic User's Manual

Example 'This example prints a bunch of lines to the viewport, then'scrolls back to the top using VScroll.

Sub Main()ViewportOpen "WM Basic Viewport",100,100,500,200For i = 1 to 50

Print "This will be displayed on line#: " & iNext iMsgBox "We will now go to the 0% thumb mark poisiton (the top)..."VScroll 0VScroll 0MsgBox "...and here we are!"ViewportClose

End Sub

See Also VLine (statement); VPage (statement).

Platform(s) Windows.

Weekday (function)Syntax Weekday(date)

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.

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 (function); Minute (function); Second (function); Month (function); Year(function); Hour (function); DatePart (function).

Platform(s) Windows and Macintosh.

Page 505: Working Model 2D - User's Manual

Chapter 2 While...Wend (statement) 501

While...Wend (statement)Syntax While condition

[statements]Wend

Description Repeats a statement or group of statements while a condition is True.

Comments The condition is initially and then checked at the top of each iteration throughthe loop.

Example 'This example executes a While loop until the random number generator'returns a value of 1.

Sub Main()x% = 0count% = 0While x% <> 1 And count% < 500

x% = Rnd(1)If count% > 1000 Then

Exit SubElse

count% = count% + 1End If

WendMsgBox "The loop executed " & count% & " times."

End Sub

See Also Do...Loop (statement); For...Next (statement).

Platform(s) Windows and Macintosh.

PlatformNotes:

Windows

Due to errors in program logic, you can inadvertantly create infinite loops inyour code. Under Windows, you can break out of infinite loops usingCtrl+Break.

PlatformNotes:

Macintosh

Due to errors in program logic, you can inadvertantly create infinite loops inyour code. On the Macintosh, you can break out of infinite loops usingCommand+Period.

Width# (statement)Syntax Width# filenumber,newwidth

Description Specifies the line width for sequential files opened in either Output orAppend mode.

Page 506: Working Model 2D - User's Manual

502 Working Model Basic User's Manual

Comments The Width# statement requires the following parameters:

Parameter Description

filenumber Integer used by WM Basic to refer to the open file—the number passed to theOpen 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 commandforces all subsequent output to the specified file to use the specified value as themaximum line length.

The Width statement affects output in the following manner: if the columnposition is greater than 1 and the length of the text to be written to the filecauses the column position to exceed the current line width, then the data iswritten on the next line.

The Width statement also affects output of the Print command when usedwith the Tab and Spc functions.

Example 'This statement sets the maximum line width for file number 1 to 80'columns.

Sub Main()Width #1,80

End Sub

See Also Print (statement); Print# (statement); Tab (function); Spc (function).

Platform(s) Windows and Macintosh.

WinActivate (statement)Syntax WinActivate [window_name$ | window_object] [,timeout]

Description Activates the window with the given name or object value.

Page 507: Working Model 2D - User's Manual

Chapter 2 WinClose (statement) 503

Comments The WinActivate 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 witha vertical bar (|), as in the following example:

WinActivate "Notepad|Find"

In this example, the top-level windows are searched for a window whose titlecontains the word "Notepad". If found, the windows owned by the top levelwindow 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 placeof the window_name$ parameter to indicate a specific window to activate.

timeout Integer specifying the number of milliseconds for which to attempt activationof the specified window. If not specified (or 0), then only one attempt will bemade to activate the window. This value is handy when you are not certain thatthe window you are attempting to activate has been created.

If window_name$ and window_object are omitted, then no action is performed.

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

See Also AppActivate (statement).

Platform(s) Windows.

WinClose (statement)Syntax WinClose [window_name$ | window_object]

Description Closes the given window.

Page 508: Working Model 2D - User's Manual

504 Working Model Basic User's Manual

Comments The WinClose 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 witha vertical bar (|), as in the following example:

WinActivate "Notepad|Find"

In this example, the top-level windows are searched for a window whose titlecontains the word "Notepad". If found, the windows owned by the top levelwindow 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 placeof the window_name$ parameter to indicate a specific window to activate.

If window_name$ and window_object are omitted, then the window with thefocus is closed.

This command differs from the AppClose command in that this commandoperates on the current window rather than the current top-level window (orapplication).

Example 'This example closes Microsoft Word if its object reference is found.

Sub Main()Dim WordHandle As HWNDSet WordHandle = WinFind("Word")If (WordHandle Is Not Nothing) Then WinClose WordHandle

End Sub

See Also WinFind (function)

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the current window can be an MDI child window, a pop-upwindow, or a top-level window.

WinFind (function)Syntax WinFind(name$) As HWND

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 theWinActivate statement.

Page 509: Working Model 2D - User's Manual

Chapter 2 WinList (statement) 505

Example 'This example closes Microsoft Word if its object reference is found.

Sub Main()Dim WordHandle As HWNDSet WordHandle = WinFind("Word")If (WordHandle Is Not Nothing) Then WinClose WordHandle

End Sub

See Also WinActivate (statement).

Platform(s) Windows.

WinList (statement)Syntax WinList ArrayOfWindows()

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 isdynamic, then it will be redimensioned to exactly hold the new number ofelements. For fixed arrays, each array element is first erased, then the newelements are placed into the array. If there are fewer elements than will fit inthe array, then the remaining elements are unused. A runtime error results if thearray is too small to hold the new elements.

After calling this function, use the LBound and UBound functions todetermine the new size of the array.

Examples 'This example minimizes all top-level windows.

Sub Main()Dim a() As HWNDWinList aFor i = 1 To UBound(a)

WinMinimize a(i)Next i

End Sub

See Also WinFind (function)

Platform(s) Windows.

WinMaximize (statement)Syntax WinMaximize [window_name$ | window_object]

Description Maximizes the given window.

Page 510: Working Model 2D - User's Manual

506 Working Model Basic User's Manual

Comments The WinMaximize 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 witha vertical bar (|), as in the following example:

WinActivate "Notepad|Find"

In this example, the top-level windows are searched for a window whose titlecontains the word "Notepad". If found, the windows owned by the top levelwindow 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 placeof the window_name$ parameter to indicate a specific window to activate.

If window_name$ and window_object are omitted, then the window with thefocus is maximized.

This command differs from the AppMaximize command in that thiscommand operates on the current window rather than the current top-levelwindow.

Example 'This example maximizes all top-level windows.

Sub Main()Dim a() As HWNDWinList aFor i = 1 To UBound(a)

WinMaximize a(i)Next i

End Sub

See Also WinMinimize (statement); WinRestore (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the current window can be an MDI child window, a pop-upwindow, or a top-level window.

WinMinimize (statement)Syntax WinMinimize [window_name$ | window_object]

Description Minimizes the given window.

Page 511: Working Model 2D - User's Manual

Chapter 2 WinMove (statement) 507

Comments The WinMinimize 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 witha vertical bar (|), as in the following example:

WinActivate "Notepad|Find"

In this example, the top-level windows are searched for a window whose titlecontains the word "Notepad". If found, the windows owned by the top levelwindow 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 placeof the window_name$ parameter to indicate a specific window to activate.

If window_name$ and window_object are omitted, then the window with thefocus is minimized.

This command differs from the AppMinimize command in that thiscommand operates on the current window rather than the current top-levelwindow.

Example See example for WinList (statement).

See Also WinMaximize (statement); WinRestore (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the current window can be an MDI child window, a pop-upwindow, or a top-level window.

WinMove (statement)Syntax WinMove x,y [window_name$ | window_object]

Description Moves the given window to the given x,y position.

Page 512: Working Model 2D - User's Manual

508 Working Model Basic User's Manual

Comments The WinMove statement requires the following parameters:

Parameter Description

x,y Integer coordinates given in twips that specify the new location for thewindow.

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 witha vertical bar (|), as in the following example:

WinActivate "Notepad|Find"

In this example, the top-level windows are searched for a window whose titlecontains the word "Notepad". If found, the windows owned by the top levelwindow 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 placeof the window_name$ parameter to indicate a specific window to activate.

If window_name$ and window_object are omitted, then the window with thefocus is moved.

This command differs from the AppMove command in that this commandoperates on the current window rather than the current top-level window. Whenmoving child windows, remember that the x and y coordinates are relative tothe client area of the parent window.

Example 'This example moves Program Manager to upper left corner of the screen.

WinMove 0,0,"Program Manager"

See Also WinSize (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the current window can be an MDI child window, a pop-upwindow, or a top-level window.

WinRestore (statement)Syntax WinRestore [window_name$ | window_object]

Description Restores the specified window to its restore state.

Page 513: Working Model 2D - User's Manual

Chapter 2 WinSize (statement) 509

Comments Restoring a minimized window restores that window to it screen position beforeit was minimized. Restoring a maximized window resizes the window to its sizeprevious 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 witha vertical bar (|), as in the following example:

WinActivate "Notepad|Find"

In this example, the top-level windows are searched for a window whose titlecontains the word "Notepad". If found, the windows owned by the top levelwindow 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 placeof the window_name$ parameter to indicate a specific window to activate.

If window_name$ and window_object are omitted, then the window with thefocus is restored.

This command differs from the AppRestore command in that this commandoperates 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 HWNDWinList aFor i = 0 To UBound(a) WinMinimize a(i)Next IWinRestore "Program Manager"

End Sub

See Also WinMaximize (statement); WinMinimize (statement.

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the current window can be an MDI child window, a pop-upwindow, or a top-level window.

WinSize (statement)Syntax WinSize width,height [,window_name$ | window_object]

Page 514: Working Model 2D - User's Manual

510 Working Model Basic User's Manual

Description Resizes the given window to the specified width and height.

Comments The WinSize statement requires the following parameters:

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 witha vertical bar (|), as in the following example:

WinActivate "Notepad|Find"

In this example, the top-level windows are searched for a window whose titlecontains the word "Notepad". If found, the windows owned by the top levelwindow 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 placeof the window_name$ parameter to indicate a specific window to activate.

If window_name$ and window_object are omitted, then the window with thefocus is resized.

This command differs from the AppSize command in that this commandoperates on the current window rather than the current top-level window.

Example 'This example runs and resizes Notepad.

Sub Main()Dim NotepadApp As HWNDid = Shell("Notepad.exe")set NotepadApp = WinFind("Notepad")WinSize 4400,8500,NotepadApp

End Sub

See Also WinMove (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, the current window can be an MDI child window, a pop-upwindow, or a top-level window.

Word$ (function)Syntax Word$(text$,first[,last])

Description Returns a String containing a single word or sequence of words between firstand last.

Page 515: Working Model 2D - User's Manual

Chapter 2 WordCount (function) 511

Comments The Word$ function requires the following parameters:

Parameter Description

text$ String from which the sequence of words will be extracted.

first Integer specifing the index of the first word in the sequence to return. If last isnot specified, then only that word is returned.

last Integer specifying the index of the last word in the sequence to return. If lastis specified, then all words between first and last will be returned, including allspaces, tabs, and end-of-lines that occur between those words.

Words are separated by any nonalphanumeric 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 isreturned.

If last is greater than the number of words in text$, then all words from first tothe 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$ (function); ItemCount (function); Line$ (function); LineCount(function); WordCount (function).

Platform(s) Windows and Macintosh.

WordCount (function)Syntax WordCount(text$)

Description Returns an Integer representing the number of words in the specified text.

Comments Words are separated by spaces, tabs, and end-of-lines.

Example 'This example counts the number of words in a particular string.

Sub Main()s$ = "My last name is Williams; Stuart is my surname."i% = WordCount(s$)MsgBox "'" & s$ & "' has " & i% & " words."

End Sub

Page 516: Working Model 2D - User's Manual

512 Working Model Basic User's Manual

See Also Item$ (function); ItemCount (function); Line$ (function); LineCount(function); Word$ (function).

Platform(s) Windows and Macintosh.

Write# (statement)Syntax Write [#]filenumber [,expressionlist]

Description Writes a list of expressions to a given sequential file.

Comments The file referenced by filenumber must be opened in either Output orAppend mode.

The filenumber parameter is an Integer used by WM Basic to refer to theopen file—the number passed to the Open statement.

The following table summarizes how variables of different types are written:

Data Type Description

Any numeric type Written as text. There is no leading space, and the period is always used as thedecimal separator.

String Written as text, enclosed within quotes.

Empty No data is written.

Null Written as #NULL#.

Boolean Written as #TRUE# or #FALSE#.

Date Written using the universal date format:

#YYYY-MM-DD HH:MM:SS#

user-defined errors Written as #ERROR ErrorNumber#, whereErrorNumber is the value of the user-defined error. The word ERROR is nottranslated.

The Write statement outputs variables separated with commas. After writingeach expression in the list, Write outputs an end-of-line.

The Write statement can only be used with files opened in Output orAppend mode.

Page 517: Working Model 2D - User's Manual

Chapter 2 WriteIni (statement) 513

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 #1For x = 1 To 10

r% = x * 10 Write #1,x,r%Next xClose

Open "test.dat" For Input Access Read As #1For x = 1 To 10

Input #1,a%,b%msg = msg & "Record " & a% & ": " & b% & Basic.Eoln$

Next x

MsgBox msgClose

End Sub

See Also Open (statement); Put (statement); Print# (statement).

Platform(s) Windows and Macintosh.

WriteIni (statement)Syntax WriteIni section$,ItemName$,value$[,filename$]

Description Writes a new value into an ini file.

Comments The WriteIni statement requires the following parameters:

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 tochange. If ItemName$ is a zero-length string (""), then the entire sectionspecified by section$ is deleted.

value$ String specifying the new value for the given item. If value$ is a zero-lengthstring (""), then the item specified by ItemName$ is deleted from the ini file.

filename$ String specifying the name of the ini file.

Page 518: Working Model 2D - User's Manual

514 Working Model Basic User's Manual

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

See Also ReadIni$ (function); ReadIniSection (statement).

Platform(s) Windows.

PlatformNotes:

Windows

Under Windows, if filename$ is not specified, the win.ini file is used.

If the filename$ parameter does not include a path, then this statement looks forini files in the Windows directory.

Xor (operator)Syntax expression1 Xor expression2

Description Performs a logical or binary exclusion on two expressions.

Comments If both expressions are either Boolean, Boolean variants, or Null variants,then a logical exclusion is performed as follows:

If the first and the second then theexpression is expression is result is

True True FalseTrue False TrueFalse True TrueFalse False False

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 Emptyvariants) 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 thebinary representations of the two expressions according to the following table:

1 Xor 1 = 0 Example:0 Xor 1 = 1 5 011010011 Xor 0 = 1 6 10101010 0 Xor 0 = 0 Xor 11000011

Page 519: Working Model 2D - User's Manual

Year (function) 515

Example 'This example builds a logic table for the XOR function and'displays it.

Sub Main()For x = -1 To 0

For y = -1 To 0z = x Xor ymsg = msg & Format(x,"True/False") & " Xor "msg = msg & Format(y,"True/False") & " = "msg = msg & Format(z,"True/False") & Basic.Eoln$

Next yNext xMsgBox msg

End Sub

See Also Operator Precedence (topic); Or (operator); Eqv (operator); Imp (operator); And(operator).

Platform(s) Windows and Macintosh.

Year (function)Syntax Year(date)

Description Returns the year of the date encoded in the specified date parameter. The valuereturned is between 100 and 9999 inclusive.

The date parameter is any expression representing a valid date.

Example 'This example returns the current year in a dialog box.

Sub Main()tdate$ = Date$tyear! = Year(DateValue(tdate$))MsgBox "The current year is: " & tyear$

End Sub

See Also Day (function); Minute (function); Second (function); Month (function); Hour(function); Weekday (function); DatePart (function).

Platform(s) Windows and Macintosh.

Page 520: Working Model 2D - User's Manual
Page 521: Working Model 2D - User's Manual

517

C H A P T E R 3

This chapter contains an alphabetical listing of objects, methods, and properties that arespecifically implemented to operate Working Model.The reader is strongly encouraged to keep Working Model User's Manual at his/her disposal,since most of the following API calls have equivalent implementation in Working Model'sgraphical user interface. The Working Model User's Manual provides far more extensivediscussions on features.

NotationsItalicized portions of headings (e.g., WMDocument.Body) indicate type names. Hence tomake use of the indicated syntax, you must substitute the name of a variable of that type.For example, you cannot write:

Dim aBody as WMBodySet aBody = WMDocument.Body(3) ' wrong usage: WMDocument isa type name

Instead, you must declare a variable of type WMDocument as follows:Dim aDoc as WMDocumentDim aBody as WMBodySet aDoc = WM.ActiveDocumentSet aBody = aDoc.Body(3) ' correct

Note that in the last line of the above example, WMDocument is replaced with aDoc, a variableof the type WMDocument in order to invoke the Body method.

Collection (topic)In Working Model Basic, some objects are called a Collection, becausethey contain a set of objects of a particular type. The following objectsare Collections defined in Working Model Basic.

Object Description

WM.Documents Collection of Working Model documents, or WMDocument objects.

WMDocument.Bodies Collection of all WMBody objects inthe document.

Working Model BasicExtensions Reference

Page 522: Working Model 2D - User's Manual

518 Working Model Basic User's Manual

Each Collection object has several common names for its properties andmethods, although the exact syntax, return types, and their actions differdepending on the type of objects that the Collection represents.

Common properties and methods are as follows:

Method/PropertyDescription

Count (property) The Integer property containing the current number of objects that theCollection represents.

Item (method) Returns the specific object within the Collection. For example,WMDocument.Bodies.Item returns a WMBody object.

Please refer to individual Collection objects for detailed information ondefinitions, syntax, and examples.

See Also WM.Documents (property), WMDocument.Selection (property)

WM (constant)Description The constant WM represents the Working Model application itself. WM is an

object with the following methods and properties. Please see individualsections for detailed information on syntax, return values, and examples.

Method/PropertyDescription

ActiveDocument Currently active Working Model document.

DeleteMenuItem Deletes a menu item from the Script menu.

Documents Set of documents that are open.

EnableMenuItem Enables or disables the user-definable menu item in the Script menu.

GetMenuItem Returns a String containing the name of the specified menu item in theScript menu.

InsertMenuItem Adds a new menu item in the Script menu and associates the item with thespecified script file.

LoadWMBLibrary Loads a file containing subroutines for use in other scripts.

New Opens a new (untitled) Working Model document.

Open Opens an existing Working Model document.

RunScript Executes a script/tool written in WM Basic.

ShowAppearanceWindow Opens/closes the Appearancewindow.

ShowGeometryWindow Opens/closes the Geometry window.

ShowPropertiesWindow Opens/closes the Properties window.

Page 523: Working Model 2D - User's Manual

Chapter 3 WM.ActiveDocument (property) 519

UnloadWMBLibrary Unloads a file containing subroutines used in other scripts.

Version Version number of Working Model.

Example (See WM.ActiveDocument)

See Also WM.ActiveDocument (property), WM.Documents (property), WM.New(method), WM.Open (method), WM.Version (property), WM.Quit (method),WM.Save (method), WM.SaveAs (method).

WM.ActiveDocument (property)Syntax WM.ActiveDocument

Description A WMDocument object which is currently active in the Working Modelapplication. You can set or get the WM.ActiveDocument property.

Comments Working Model can open and simulate several documents at a time, andyou need to make a document active in order to bring it to the foreground.WM.ActiveDocument returns an error if the given document is invalid. Ifno document is currently open, WM.ActiveDocument returns an errorcode.

Example Sub Main()

'opens a new document in the back layer.

Dim Doc1 as WMDocument

Dim Doc2 as WMDocument

Set Doc1 = WM.ActiveDocument

Set Doc2 = WM.New() 'opens a new document (becomes active).

If Doc1 is not Nothing then

Set WM.ActiveDocument = Doc1 'resurrects the previouslyactive document

End If

End Sub

See Also WMDocument (object), WM.ActiveDocument (statement)

WM.DeleteMenuItem (method)Syntax WM.DeleteMenuItem Index

Description Deletes a menu item from the Script menu.

Comments The WM.DeleteMenuItem method removes a menu item from WorkingModel's Script menu (located in the menu bar). The first two items in theScript menu, Run and Edit, are part of Working Model's standard menuand cannot be deleted. Any menu item added by WM.InsertMenuItem

Page 524: Working Model 2D - User's Manual

520 Working Model Basic User's Manual

can be removed using the WM.DeleteMenuItem method.

The WM.DeleteMenuItem method takes the following parameter:

Parameter Description

Index An Integer. The number (> 0) specifies the location of the menu item tobe removed.

For example, if three menu items exist below Editor, then Index can bebetween 1 and 3 (inclusive). Setting Index = 2 would remove the menuitem in the middle, for instance.

If Index is out of range, DeleteMenuItem neither removes any item norgenerates an error code.

Example Sub Main()

' Adds three menu items "Hop", "Step", and "Jump"

' in that order. The pathname is shown in Windows format.

WM.InsertMenuItem 1, "Hop", "C:\scripts\hop.wbs"

WM.InsertMenuItem 2, "Step", "C:\scripts\step.wbs"

WM.InsertMenuItem 3, "Jump", "C:\scripts\jump.wbs"

' Immediately deletes the "Step" menu.

WM.DeleteMenuItem 2

End Sub

See Also WM.InsertMenuItem (method), WM.EnableMenuItem (method)

WM.Documents (property)Syntax WM.Documents

Description Returns a collection object of currently open Working Modeldocuments.

Comments WM.Documents is a read-only property.

The WM.Documents property has the following property and method.

Method/PropertyDescription

Count An Integer property containing the number of documents inWM.Documents (= number of open documents).

Item(id) A method which returns the WMDocument object specified by the index id(Integer).

Example Sub Main()

Page 525: Working Model 2D - User's Manual

Chapter 3 WM.EnableMenuItem (method) 521

' Shows the name of the third document. Does nothing

' if no more than 2 documents are currently open

Dim WM1 as WMDocument

if WM.Documents.Count > 2 then

Set WM1 = WM.Documents.Item(3)

MsgBox "Document ID 3 is " + WM1.Name

end if

End Sub

See Also WMDocument (object), WM (constant)

WM.EnableMenuItem (method)Syntax WM.EnableMenuItem Index,EnableFlag

Description Enables or disables a menu item in the Script menu.

Comments The WM.EnableMenuItem method enables or disables a user-definableitem from Working Model's Script menu (located in the menu bar). Thefirst two items in the Script menu, Run and Edit, are part of WorkingModel’s standard menu and cannot be altered. Any menu item added byWM.InsertMenuItem can be enabled or disabled using theWM.EnableMenuItem method.

The disabled menu item remains in the Script menu but appears dimmed(shown in light-gray). The item remains as such until it is enabled by theEnableMenuItem method. While the menu item is disabled, the usercannot choose it and is prohibited from invoking the script or toolassociated with the menu item through the Script menu. The user can stillinvoke the script using the Run menu (as long as she or he is aware of thefilename and path).

The WM.EnableMenuItem method takes the following parameters:

Parameter Description

Index An Integer. The number (> 0) specifies the location of the menu item tobe enabled or disabled.

For example, if three menu items exist below Editor, then the Index canbe between 1 and 3 (inclusive). Setting Index = 2 would enable or disablethe menu item in the middle, for instance.

EnableFlag A Boolean specifying whether the menu item is to be enabled or disabled.When EnableFlag is set to True, the menu item will be enabled; if False,then the menu item will be disabled.

Page 526: Working Model 2D - User's Manual

522 Working Model Basic User's Manual

If Index is out of range, EnableMenuItem neither generates an error norperforms any action.

To remove a menu item that was inserted by EnableMenuItem, useWM.DeleteMenuItem method.

Example Sub Main()

' Adds three menu items "Hop", "Step", and "Jump"

' in that order, and disables Hop and Step menu items.

' The pathname is shown in Windows format.

WM.InsertMenuItem 1, "Hop", "C:\scripts\hop.wbs"

WM.InsertMenuItem 2, "Step", "C:\scripts\step.wbs"

WM.InsertMenuItem 3, "Jump", "C:\scripts\jump.wbs"

' Disable Hop and Step menus.

WM.EnableMenuItem 1, False ' corresponds to Hop menu item

WM.EnableMenuItem 2, False ' corresponds to Step menu item

End Sub

See Also WM.DeleteMenuItem (method), WM.InsertMenuItem (method)

WM.GetMenuItem (method)Syntax WM.GetMenuItem(Index [, PathString])

Description Returns a String containing the name of the specified menu item in theScript menu.

Comments The WM.GetMenuItem method returns the menu name of the specifiedmenu item from Working Model's Script menu (located in the menu bar).Further, you can obtain the pathname of the script that is invoked by themenu item. (The pathname is originally set by the WM.InsertMenuItemmethod.)

The first two items in the Script menu, Run and Edit, are part of WorkingModel's standard menu and cannot be accessed using WM.GetMenuItem.Any menu item added by WM.InsertMenuItem can be accessed using theWM.GetMenuItem method.

The WM.GetMenuItem method takes the following parameters:

Parameter Description

Index An Integer. The number (> 0) specifies the location of the menu item.

For example, if three menu items exist below Edit in the Script menu,then Index can be between 1 and 3 (inclusive). Setting Index = 2 would

Page 527: Working Model 2D - User's Manual

Chapter 3 WM.InsertMenuItem (method) 523

access the menu item in the middle, for instance.

PathString An optional String. This parameter receives the pathname of the scriptthat is originally set by the WM.InsertMenuItem method.

If Index is out of range, WM.GetMenuItem neither generates an error norperforms any action.

If you choose to replace the script/tool invoked by a menu item, you needto delete the menu item first(using WM.DeleteMenuItem) and add themenu item again using WM.InsertMenuItem, with the new scriptpathname as its parameter.

The script specified by PathString can be either object code or sourcecode. See Chapter 1 for more information on object code and source codefile types.

Example Sub Main()

Dim Path as String

Dim MenuName as String

' Adds three menu items "Hop", "Step", and "Jump"

' in that order. The pathname is shown in Windows format.

WM.InsertMenuItem 1, "Hop", "C:\scripts\hop.wbs"

WM.InsertMenuItem 2, "Step", "C:\scripts\step.wbs"

WM.InsertMenuItem 3, "Jump", "C:\scripts\jump.wbs"

' Report pathname for the Jump menu item.

MenuName = WM.GetMenuItem(3, Path)

MsgBox "Menu "+MenuName+" invokes the file "+Path

End Sub

See Also WM.InsertMenuItem (method), WM.DeleteMenuItem (method)

WM.InsertMenuItem (method)Syntax WM.InsertMenuItem Index, MenuName, ScriptFileName

Description Adds a new menu item in the Script menu, and associates the menu itemwith the specified script file.

Comments The InsertMenuItem method adds a new item in Working Model's Scriptmenu located in the menu bar. At the same time, the specified script isassociated with the new menu item. From then on, the user can simplychoose the menu item and invoke the script or tool written in WM Basic.The purpose of this method is to provide quick access to pre-writtenscripts by seamlessly integrating external scripts into Working Model's

Page 528: Working Model 2D - User's Manual

524 Working Model Basic User's Manual

user interface.

The WM.InsertMenuItem method takes the following parameters:

Parameter Description

Index An Integer specifying where the menu item will be added. The number (>0) specifies the order in which the menu items appear. The number Indexmust specify where the menu is to be located.

For example, the first addition should be Index = 1. For the second timearound, if you wish to add another menu item above the first, then setIndex = 1. If you wish to add it below the first, then set Index = 2.

MenuName A String specifying how the menu item appears in the Script menu.

ScriptFileName A String specifying the script or tool that is to be invoked by choosingthe menu item. Full pathname is required.

If Index is out of range, InsertMenuItem does not add any new item. IfScriptFileName is not found in the file system, InsertMenuItem still addsthe menu item. In either case, no error code is generated. Use theFileExists call to verify the existence of the script file, if so desired.

After a menu item is added, you can disable or enable the menu item usingWM.EnableMenuItem method. You can also remove the menu item usingWM.DeleteMenuItem method.

Example (See WM.EnableMenuItem)

See Also WM.DeleteMenuItem (method), WM.EnableMenuItem (method),FileExists (function)

WM.LoadWMBLibrary (method)Syntax WM.LoadWMBLibrary ScriptFileName

Description Loads a scripting code module.

Comments The LoadWMBLibrary method loads a library of WM Basic code so that itbecomes available to the user. In order to invoke functions andsubroutines implemented in a library code module, you have to use theLoadWMBLibrary method to load it first.

The WM.LoadWMBLibrary method takes the following parameters:

Parameter Description

ScriptFileName A String specifying the filename of the code module.

The file could be either a source script file or a compiled script file. If youloaded a source file, you can use the debugger to trace into the source

Page 529: Working Model 2D - User's Manual

Chapter 3 WM.New (method) 525

code of the library.

NOTE: After a code module is loaded with WM.LoadWMBLibrary, themodule will stay in memory until you explicitly unload it usingWM.UnloadWMBLibrary or quit Working Model. If you make a change inthe module, and if the module is already loaded, you must unload themodule and reload it to make the change effective.

In order to use memory efficiently, you should consider usingWM.UnloadWMBLibrary method, which unloads the code module.

If you wish to run a complete script or tool (i.e., script or tool that can runon its own), you should use the WM.RunScript method.

Example ' Suppose the following code is saved as "c:\testing\mod1.wbs".

Function TimesTwo(a as Integer)

' Defines the function TimesTwo

TimesTwo = a * 2

End Function

' The following code (the main module) makes a call.

Sub Main()

Dim I as Integer

WM.LoadWMBLibrary "c:\testing\mod1.wbs"

I = 2

MsgBox str$(TimesTwo(I)) ‘ Calls the function TimesTwo

WM.UnloadWMBLibrary "c:\testing\mod1.wbs"

End Sub

See Also WM.UnloadWMBLibrary (method), WM.DeleteMenuItem (method),WM.EnableMenuItem (method), FileExists (function), WM.RunScript(method)

WM.New (method)Syntax WM.New()

Description Opens a new (untitled) Working Model document and returns thecorresponding WMDocument object.

Comments WM.ActiveDocument will point to the new document.

Example Sub Main()

Dim WM1 as WMDocument

Page 530: Working Model 2D - User's Manual

526 Working Model Basic User's Manual

Set WM1 = WM.New() 'just opened a new document

End Sub

See Also WMDocument (object)

WM.Open (method)Syntax WM.Open(FileName)

Description Opens the specified Working Model document and returns thecorresponding WMDocument object.

Comments The String parameter FileName is the name of the Working Model fileyou wish to open. The parameter can contain pathnames.

WM.ActiveDocument will point to the opened document.

Example Sub Main()

Dim WM1 as WMDocument

If FileExists("demo1.wm") then

Set WM1 = WM.Open("demo1.wm")

End If

End Sub

See Also WMApplication (object), WMDocument (object)

WM.RunScript (method)Syntax WM.RunScript FileName

Description Executes a script written in Working Model Basic.

Comments The WM.RunScript method invokes and executes the specified script ortool written in Working Model Basic.

The WM.RunScript method takes the following parameter:

Parameter Description

FileName A String containing the full pathname of the file/script to be executed(target script).

If the target script does not exist, WM.RunScript neither generates an errornor performs any action. Use the FileExists call to verify the existenceof the target script to make your code robust.

The target script needs to be a complete program (a program that can beexecuted on its own). If you wish to invoke only functions or subroutinesdefined in a target script, consider using the WM.LoadWMBLibrary method.

Page 531: Working Model 2D - User's Manual

Chapter 3 WM.UnloadWMBLibrary (method) 527

The WM Basic Debugger cannot trace into the target script. If you wishto debug the target script, you should run the target script on its own.

Otherwise, you can turn the target script into a code module; in that case,you would need to rename Main() module to something else, such asMain_Dummy(). You can use WM.LoadWMBLibrary method to load themodule, and call the subroutine Main_Dummy(). The debugger will beable to step into the target script code.

If you wish to have quick access to scripts or tools that you would like torun frequently, you may consider using WM.InsertMenuItem, which addsspecified scripts or tools as menu items in the Script menu.

Example Sub Main()

' Executes a Script named "magic.wbs". Returns an

' error message if no such file is found.

Dim S as String

If Basic.OS = ebWin16 then

S = "c:\scripts\magic.wbs"

ElseIf Basic.OS = ebMacintosh then

S = "Macintosh HD:Scripts:magic.wbs"

Else

S = "" ' Null string

End If

If FileExists(S) then

WM.RunScript S

Else

MsgBox "Tool "+S+" cannot be found."

End If

End Sub

See Also WM.InsertMenuItem (method), FileExists (Function),WM.LoadWMBLibrary (method)

WM.UnloadWMBLibrary (method)Syntax WM.UnloadWMBLibrary ScriptFileName

Description Unloads a scripting code module.

Comments The UnloadWMBLibrary method unloads a library of WM Basic codemodule from memory. The code module must be loaded first (using the

Page 532: Working Model 2D - User's Manual

528 Working Model Basic User's Manual

WM.LoadWMBLibrary method) before being unloaded.

By unloading a code module that may not be used frequently, WorkingModel can maintain sufficient memory space to run. You can always loadthe code module back when necessary.

The WM.UnloadWMBLibrary method takes the following parameters:

Parameter Description

ScriptFileName A String specifying the filename of the code module.

The file could be either a source script file or a compiled script file.

Example (See WM.LoadWMBLibrary.)

See Also WM.LoadWMBLibrary (method), WM.DeleteMenuItem (method),WM.EnableMenuItem (method), FileExists (function)

WM.ShowAppearanceWindow (property)Syntax WM.ShowAppearanceWindow

Description A Boolean property to specify whether the Appearance window is open.

Comments When the ShowAppearanceWindow property is set to True, theAppearance window opens.

Example Sub Main()

' Opens the Appearance window

If WM.ShowAppearanceWindow = False Then

WM.ShowAppearanceWindow = True

End If

End Sub

See Also WM (constant), WM.ShowPropertiesWindow (property),WM.ShowGeometryWindow (property)

WM.ShowGeometryWindow (property)Syntax WM.ShowGeometryWindow

Description A Boolean property to specify whether the Geometry window is open.

Comments When the ShowGeometryWindow property is set to True, the Geometrywindow opens.

Example Sub Main()

' Opens the Geometry window

If WM.ShowGeometryWindow = False Then

Page 533: Working Model 2D - User's Manual

Chapter 3 WM.ShowPropertiesWindow (property) 529

WM.ShowGeometryWindow = True

End If

End Sub

See Also WM (constant), WM.ShowPropertiesWindow (property),WM.ShowGeometryWindow (property)

WM.ShowPropertiesWindow (property)Syntax WM.ShowPropertiesWindow

Description A Boolean property to specify whether the Properties window is open.

Comments When the ShowPropertiesWindow property is set to True, the Propertieswindow opens.

Example Sub Main()

' Opens the Properties window

If WM.ShowPropertiesWindow = False Then

WM.ShowPropertiesWindow = True

End If

End Sub

See Also WM (constant), WM.ShowPropertiesWindow (property),WM.ShowGeometryWindow (property)

WM.Version (property)Syntax WM.Version

Description Returns a String indicating the version number of the Working Modelapplication.

Comments WM.Version is read-only.

Example Sub Main()

MsgBox "Running Working Model ver. " + WM.Version

End Sub

See Also WM (topic)

WMBody (object)Syntax WMBody

Description An object which provides an interface to rigid bodies used in WorkingModel simulations.

Page 534: Working Model 2D - User's Manual

530 Working Model Basic User's Manual

Comments To create a WMBody object in a document, use the NewBody method of theWMDocument object.

A WMBody object has properties that are different depending on the Kind ofthe object. Shown below are properties common to all WMBody objects.Please refer to the Working Model User's Manual for detailed discussionson these properties.

Note: WMBody object also has properties available in WMObject objects.Please see the section on WMObject for details.

Property Description

Kind (String) type of the body (Circle, Rectangle, or Polygon) (read-only).

PX, PY (WMCell) x- and y-positions of the body's FOR.

PR (WMCell) orientation of the body.

VX, VY (WMCell) x- and y-velocities of the body's FOR.

VR (WMCell) angular velocity of the body.

COMOffsetX (WMCell)x-offset of the body's center of mass from the FOR.

COMOffsetY (WMCell) y-offset of the body's center of mass from the FOR.

Mass (WMCell) mass of the body. Changing Mass affects Density accordingly, as thebody area is fixed.

Area (double) area of the body (read-only).

Density (double) density of the body. Changing Density affects Massaccordingly, as the body area is fixed (read-only).

Moment (WMCell) mass moment of inertia of the body.

Charge (WMCell) electric charge of the body.

Elasticity (WMCell) elasticity of the body.

StaticFriction (WMCell) static friction coefficient of the body.

KineticFriction (WMCell) kinetic friction coefficientof the body.

ShowCenterOfMass (Boolean) 1 if shown, 0 otherwise.

ShowCharge (Boolean) 1 if shown, 0 otherwise.

Further, depending on the Kind, a WMBody object has the followingproperties.

For Kind = "Rectangle" and "Square":

Property Description

Page 535: Working Model 2D - User's Manual

Chapter 3 WMBody (object) 531

Width (WMCell) width of the rectangle.

Height (WMCell) height of the rectangle.

For Square, Width and Height are always equal. Any modification toeither property will automatically modify the other.

For Kind = "Circle":

Property Description

Radius (WMCell) radius of the circle.

For Kind = "Polygon":

Property/MethodDescription

VertexCount (Integer) the number of vertices that the polygon consists of.

GetVertex Given an index (Integer) and two parameters (Double), this method fillsthe parameters x and y with the (x, y) coordinates of the specified vertex.

Syntax: Body.GetVertex n, x, y

where n is the index of the vertex, and x and y are parameters of typeDouble, to be assigned to the coordinates of the vertex n upon return fromthe method. The (x, y) coordinates are given in terms of the polygon’sframe of reference (FOR).

AddVertex Given an index (Integer) and x, y coordinates, this method adds the vertexto the polygon at the specified index.

Syntax: Body.AddVertex n, x, y

where n is the index at which the new vertex (x, y) is added. The rest ofthe vertices will be pushed down in the list. The (x, y) coordinates aregiven in terms of the global coordinates.

DeleteVertex Given an index, this method deletes the vertex from the polygon.

Syntax: Body.DeleteVertex n

where n is the index of the vertex to be deleted, and Body is assumed to bea WMBody object. The rest of the vertices will be pushed up in the list.

Because a polygon must have at least 3 vertices, DeleteVertex fails ifVertexCount = 3. If you want to replace one of the three remainingvertices, you must first insert the replacement vertex, then delete the oldone.

Example Sub Main()

'Creates a circle and a polygon

Dim CircleBody as WMBody

Page 536: Working Model 2D - User's Manual

532 Working Model Basic User's Manual

Dim PolyBody as WMBody

Dim Doc as WMDocument

Set Doc = WM.ActiveDocument

Set CircleBody = Doc.NewBody("Circle")

CircleBody.PX.Value = 1.0: CircleBody.PY.Value = 2.5

CircleBody.Radius.Value = 1.5

Set PolyBody = Doc.NewBody("polygon")

PolyBody.PX.Value = 4.0: PolyBody.PY.Value = 2.5

' Form the square-shaped polygon

PolyBody.AddVertex 1, 0.5, 0.5

PolyBody.AddVertex 2, 0.5, -0.5

PolyBody.AddVertex 3, -0.5, 0.5

PolyBody.AddVertex 4, -0.5, -0.5

PolyBody.DeleteVertex 7 ' delete three default vertices

PolyBody.DeleteVertex 6

PolyBody.DeleteVertex 5

' Delete one of the vertices and turn it into a right triangle

PolyBody.DeleteVertex 3 'Delete one of the vertices

End Sub

See Also WMDocument.NewBody (method), WMConstraint (object), WMPoint(object), WMCell (object)

WMCell (object)Syntax WMCell

DescriptionAn object to declare formula cells used in Working Model simulations.

Comments WMCell is a placeholder for the properties available in Working Modelobjects. For example, a WMBody object has properties PX and PY, whichrepresent the position of the body. You can enter in these properties notonly numerical values but Working Model formulas (such asbody[5].v.x). These properties, PX and PY, are instances of WMCellobjects.

A WMCell object has the following properties.

Property Description

Formula A String that contains the formula string. The usage of formula language

Page 537: Working Model 2D - User's Manual

Chapter 3 WMCell (object) 533

is discussed in the Working Model User’s Manual.

Value A Double that contains a numerical value. If the Formula string is notempty, the Value property holds the result of the evaluation of theFormula string above.

To assign a formula language expression to a WMCell object, make sure tobracket the expression with double quotation marks ("). For example, inorder to set a position, initial velocity, and a dimension of a rectanglebody called Rect, you can assign numerical values and formulas asfollows:

Rect.PX.Formula = "time + 2" ' x-position

Rect.PY.Value = 15 ' y-position

Rect.Width.Value = 8 ' width of the rectangle

Rect.Height.Formula = "Input[5]" ' height of the rectangle

As soon as one of the WMCell fields is defined, the other follows suit. Forexample, if you define a valid formula expression in the Formula propertyof a WMCell object, its Value property will hold the result of theevaluation of the formula thereafter. Conversely, if you define anumerical value in the Value property of the WMCell object, the Formulaproperty will hold an empty string.

When the Formula property is specified, its value is evaluated at everyframe of the simulation step, including frame 0. The value of t or time isevaluated to 0 at frame 0.

For performance reasons, when a WMCell object is modified, theappearance on the screen does not update until the script is terminated orthe Update method is invoked (although internal computations use correctvalues). See WMDocument.Update for more information.

Note: WMCell objects are always associated with properties of otherobjects, such as WMBody and WMConstraint. Declaring a WMCell objectmeans nothing more than declaring a “pointer” and does not allocate theactual object. Therefore, you cannot use a WMCell object as a placeholderfor expressions and variables. For example, you cannot type:

Dim MyCell as WMCell

MyCell.Formula = "2.5 + sin(t)" ' you will get an error here

because the object MyCell is still only a pointer and has no substance.Meanwhile, the following usage is valid:

Dim MyBody as WMBody

Dim MyCell as WMCell

Set MyBody = WM.ActiveDocument.NewBody("square")

Page 538: Working Model 2D - User's Manual

534 Working Model Basic User's Manual

Set MyCell = MyBody.PX ' correct usage

because MyCell now points to the physical object, MyBody.PX, or the x-position of a square WMObject.

Example Sub Main()

' Creates a rectangle and an input, and

' links the two.

Dim D as WMDocument

Dim B as WMBody

Dim I as WMInput

Set D = WM.ActiveDocument

Set B = D.NewBody("Rectangle")

Set I = D.NewInput()

' Moves the slider. Note X and Y are simply

' integers and not WMCell objects.

I.X = 100

I.Y = 50

I.Value = 0.5

' Defines the rectangle's initial position and initial velocity

B.PX.Value = 1.0

B.PY.Value = 2.0

B.VX.Formula = "Input["+str$(I.ID)+"]"

' Defines the rectangle's dimension

B.Width.Value = 0.4

B.Height.Formula = "body["+str$(B.ID)+"].width*2"

End Sub

See Also WMBody (object), WMPoint (object), WMConstraint (object), WMInput(object), WMOutput (object), WMDocument (object), WMDocument.Update(object)

WMConstraint (object)Syntax WMConstraint

DescriptionAn object which provides an interface to constraints used in Working Model simulations.

Comments To create a new WMConstraint object in a Working Model document, usethe NewConstraint method of the WMDocument object.

Page 539: Working Model 2D - User's Manual

Chapter 3 WMConstraint (object) 535

All WMConstraint objects have the following methods and properties.The list shows the properties and methods applicable to each Kind. Notethat only Kind, ActiveWhen, and AlwaysActive are the commonproperties for all WMConstraint objects. Please refer to individualsections for these methods and properties for more information.

Note: WMConstraint object also has properties available in WMObjectobjects. Please see the section on WMObject for details.

Constraint Kind Applicable Properties and Methods

Pin, SquarePin Kind, ActiveWhen, AlwaysActive, Point, PointCount

Spring Kind, ActiveWhen, AlwaysActive, Point, K, Exponent, Length,CurrentLength, PointCount

Damper Kind, ActiveWhen, AlwaysActive, Point, K, Exponent, PointCount

SpringDamper Kind, ActiveWhen, AlwaysActive, K, DamperK, Length, CurrentLength,Point, PointCount

Rspring Kind, ActiveWhen, AlwaysActive, K, Exponent, Rotation,CurrentRotation, Point, PointCount

Rdamper Kind, ActiveWhen, AlwaysActive, K, Exponent, Point, PointCount

Slot Kind, ActiveWhen, AlwaysActive, Point, PointCount

CurvedSlot Kind, ActiveWhen, AlwaysActive, Point, VertexCount, GetVertex,AddVertex, DeleteVertex, ClosedSlot, PointCount

Rod Kind, ActiveWhen, AlwaysActive, Point, Length, CurrentLength,PointCount

Separator, Rope Kind, ActiveWhen, AlwaysActive, Point, Elasticity, Length,CurrentLength, PointCount

Force Kind, ActiveWhen, AlwaysActive, Point, FX, FY, FR, Ftheta,RotateWithBody, PointCount

Torque Kind, ActiveWhen, AlwaysActive, Point, Torque, PointCount

Actuator Kind, ActiveWhen, Field, AlwaysActive, Point, ActuatorType,PointCount

Motor Kind, ActiveWhen, Field, AlwaysActive, Point, MotorType, PointCount

Pulley AppendPoint, PointCount, Point

Gear Kind, ActiveWhen, AlwaysActive, GearRatio, AutoComputeGearRatio,RodActive, RodAlwaysActive, Internal, InternalBody, PointCount

Example Sub Main()

' Creates a box, spring, and attaches one endpoint of

Page 540: Working Model 2D - User's Manual

536 Working Model Basic User's Manual

' the spring to Box.

Dim Doc as WMDocument : Set Doc = WM.Activedocument

Dim Box as WMBody

Set Box = Doc.NewBody("square") : Box.Width.Value = 1.0

Dim MySpring as WMConstraint

Set MySpring = Doc.NewConstraint("spring")

Set MySpring.Point(1).Body = Box ' attaches an endpoint to Box

' point coordinates are relative to Box, since the point is

' already attached to it.

MySpring.Point(1).PX.Value = 0.2

MySpring.Point(1).PY.Value = 0.5

' Set the position of the other endpoint to (3, 0) (global)

MySpring.Point(2).PX.Value = 3.0

MySpring.Point(2).PY.Value = 0.0

End Sub

See Also WMDocument.NewConstraint (method), WMBody (object), WMPoint(object), WMObject (object), WMCell (object)

WMConstraint.ActiveWhen (property)Syntax WMConstraint.ActiveWhen

Description A WMCell that specifies the condition for which the constraint is active (i.e., exertsnecessary force/torque to maintain the constraint).

Comments The ActiveWhen property itself is read-only, but you can modify the Value andFormula properties of this WMCell object (see description of the WMCell object).The condition is overridden if AlwaysActive is True, in which case the constraint isalways active.

The ActiveWhen property is applicable to all WMConstraint objects.

Note: Since the property AlwaysActive is True by default, you must first set theproperty to False before modifying the ActiveWhen property; otherwise, WorkingModel will report a run-time error.

Example Sub Main()

' Sets the first constraint in the document's active condition

Dim Constr1 as WMConstraint

Set Constr1 = WM.ActiveDocument.Constraints.Item(1)

if Constr1 is not Nothing then

Page 541: Working Model 2D - User's Manual

Chapter 3 WMConstraint.ActuatorType (property) 537

' Required before modifying ActiveWhen.

Constr1.AlwaysActive = False

Constr1.ActiveWhen.Formula = "and(frame()<50, time<2.5)"

else

MsgBox "No constraint exists in the document"

end if

End Sub

See Also WMConstraint (object), WMConstraint.AlwaysActive (property)

WMConstraint.ActuatorType (property)Syntax WMConstraint.ActuatorType

Description A String object to specify the type of an actuator constraint.

Comments ActuatorType can be set to Force, Acceleration, Velocity, or Length.Applicable only when Kind is Actuator.

Example Sub Main()

' Sets the driver type to sinusoidal, velocity driver

Dim D as WMDocument : Set D = WM.Activedocument

Dim driver as WMConstraint

Dim Weight as WMBody

Set Weight = D.NewBody("circle")

Weight.radius.Value = 0.5

Weight.PY.value = -1.5

Set driver = D.NewConstraint("actuator")

Set driver.Point(2).Body = Weight

driver.ActuatorType = "Length"

driver.Field.Formula = str$(Driver.CurrentLength)+"+sin(t*5)"

D.Run 100

End Sub

See Also WMConstraint (object)

WMConstraint.AddVertex (method)Syntax WMConstraint.AddVertex index, x, y

Description A method to add a new control point to the curved slot.

Page 542: Working Model 2D - User's Manual

538 Working Model Basic User's Manual

Comments AddVertex is a method which, given the index of the curved slot controlpoint (specified in the Integer parameter index), adds the new controlpoint (x, y) (Double parameters) at the index counter index. VertexCountwill be updated, and the remaining control points will be shiftedaccordingly (i.e. their index will increment by one).

The (x, y) coordinates of the control points are measured with respect tothe FOR of the curved slot (can be accessed using the Point method).Currently, WM Basic does not provide a direct way to enter polarcoordinates for curved slots.

To access the existing control points, use GetVertex method.

Applicable only when Kind is CurvedSlot.

Example Sub Main()

' Creates a closed curved slot and creates a polygon that hasthe

' save vertices

Dim Slot as WMConstraint

Dim Poly as WMBody

Dim x as Double, y as Double

Set Slot = WM.ActiveDocument.NewConstraint("curvedslot")

' By default, slot has three vertices (0, 0), (1,1), and (2,2)

Slot.AddVertex 3, 2.0, 0.0

Slot.DeleteVertex 4

Slot.ClosedSlot = True

' Now the slot has (0,0), (1,1), (2,0) in that order

Set Poly = WM.ActiveDocument.NewBody("polygon")

For I = 1 to Slot.VertexCount

Slot.GetVertex I, x, y

Poly.AddVertex 1, x, y

Next

Poly.DeleteVertex 6 ' eliminates the default vertices

Poly.DeleteVertex 5

Poly.DeleteVertex 4

End Sub

See Also WMConstraint (object), WMConstraint.VertexCount (property),WMConstraint.GetVertex (method), WMConstraint.DeleteVertex

Page 543: Working Model 2D - User's Manual

Chapter 3 WMConstraint.AppendPoint (method) 539

(method)

WMConstraint.AppendPoint (method)Syntax WMConstraint.AppendPoint x, y

Description A method to add a new point to a pulley.

Comments AppendPoint is a method which appends a new point (x, y) (Doubleparameters) to a pulley. The point is added after the last point. ThePointCount property will be incremented accordingly.

To access the coordinates of an existing pulley point, use theWMConstraint.Point method.

The current version of WM Basic does not allow you to delete points fromthe pulley. You would need to delete the entire pulley system first.

Applicable only when Kind is Pulley.

Example Sub Main()

' Adds a new node (2.5, 3.5) to the pulley system.

Dim Pulley as WMConstraint

Set Pulley = WM.ActiveDocument.Constraints.Item(1)

if Pulley is not Nothing Then

If Pulley.Kind = "pulley" Then

Pulley.AppendPoint 2.5, 3.5

MsgBox "The Pulley has"+str$(Pulley.PointCount)+"points"

End If

End If

End Sub

See Also WMConstraint (object), WMConstraint.PointCount (property),WMConstraint.Point (method)

WMConstraint.AlwaysActive (property)Syntax WMConstraint.AlwaysActive

Description A Boolean to indicate whether the constraint is always active.

Comments The default value is True, meaning that the constraint is always active. If set True,AlwaysActive overrides the condition set in ActiveWhen, and you cannot modifythe ActiveWhen property.

The AlwaysActive property is applicable to all WMConstraint objects.

Page 544: Working Model 2D - User's Manual

540 Working Model Basic User's Manual

Example (See WMConstraint.ActiveWhen)

See Also WMConstraint (object), WMConstraint.ActiveWhen (property)

WMConstraint.AutoComputeGearRatio (property)Syntax WMConstraint.AutoComputeGearRatio

Description A Boolean object to specify whether the gear ratio is to be automaticallycomputed.

Comments When True, the gear ratio is automatically computed based on the relativeradii of the two bodies specified as gears. If one of the bodies is not acircle and if AutoComputeGearRatio is True, the gear ratio is computedas 1.0.

When True, the value specified in GearRatio is ignored.

The default value is True. Applicable only when Kind is Gear.

Example (See WMConstraint.GearRatio)

See Also WMConstraint (object), WMConstraint.GearRatio (property)

WMConstraint.ClosedSlot (property)Syntax WMConstraint.ClosedSlot

Description A Boolean to indicate whether the curved slot geometry is open or closed.

Comments When ClosedSlot is True, the curved slot geometry is closed; otherwise,the geometry is open. The default value is False.

Applicable only when Kind is CurvedSlot.

Example (See WMConstraint.AddVertex)

See Also WMConstraint (object)

WMConstraint.CurrentLength (property)Syntax WMConstraint.CurrentLength

Description A Double containing the current length of a linear constraint.

Comments The unit is based on the current unit system. The property is read-only.

Only applicable when Kind is Spring, SpringDamper, Rope, Separater,and Rod.

Example (See WMConstraint.Length)

See Also WMConstraint (object)

Page 545: Working Model 2D - User's Manual

Chapter 3 WMConstraint.CurrentRotation (property) 541

WMConstraint.CurrentRotation (property)Syntax WMConstraint.CurrentRotation

Description A Double containing the current rotation of a rotational constraint.

Comments The unit is based on the current unit system. The property is read-only.

Only applicable when Kind is Rspring.

Example (See WMConstraint.Rotation)

See Also WMConstraint (object), WMConstraint.Rotation (property)

WMConstraint.DamperK (property)Syntax WMConstraint.DamperK

Description A WMCell object to specify the multiplicative constant for a dampercomponent of a SpringDamper.

Comments The damper force is defined as -Kv. Only applicable when Kind isSpringDamper. For a Damper constraint, use the propertyWMConstraint.K instead.

Example Sub Main()

' Sets the strut and simulate mass-damper-spring model

Dim D as WMDocument : Set D = WM.Activedocument

Dim strut as WMConstraint

Dim Weight as WMBody

Set Weight = D.NewBody("circle")

Weight.radius.Value = 0.5

Weight.PY.value = -1.5

Set strut = D.NewConstraint("springdamper")

Set strut.Point(2).Body = Weight

strut.DamperK.value = 1.2 ' damping constant

Strut.Length.Value = Strut.CurrentLength

strut.K.Value = 25.0 ' spring constant

D.Run 100

End Sub

See Also WMConstraint (object), WMConstraint.Exponent (property),WMConstraint.K (property)

Page 546: Working Model 2D - User's Manual

542 Working Model Basic User's Manual

WMConstraint.DeleteVertex (method)Syntax WMConstraint.DeleteVertex index

Description A method to delete a control point from a curved slot.

Comments DeleteVertex is a method which, given the index of the curved slotcontrol point (specified in the Integer parameter index), deletes thecontrol point. VertexCount will be updated, and the remaining controlpoints will be shifted accordingly (i.e. their index will be decremented byone).

Applicable only when Kind is CurvedSlot.

Example (See WMConstraint.AddVertex)

See Also WMConstraint (object), WMConstraint.VertexCount (property),WMConstraint.GetVertex (method), WMConstraint.AddVertex (method)

WMConstraint.Elasticity (property)Syntax WMConstraint.Elasticity

Description A WMCell object to specify the elasticity of a linear constraint.

Comments Applicable only when Kind is Rope or Separator.

Example Sub Main()

' Set the elasticity of a separator (assume

' one exists) 1.0.

Dim Doc as WMDocument : Set Doc = WM.ActiveDocument

Dim Separator as WMConstraint

Set Separator = Doc.Constraint("separator")

If Separator is not Nothing then

Separator.Elasticity.Value = 1.0

Else

MsgBox "No constraint with the name 'separator'"

End If

End Sub

See Also WMConstraint (object)

WMConstraint.Exponent (property)Syntax WMConstraint.Exponent

Page 547: Working Model 2D - User's Manual

Chapter 3 WMConstraint.Field (property) 543

Description An Integer to specify the exponent for displacement (for springs) orvelocity (for dampers).

Comments The constraint force is defined by -Kve (for dampers) or Kxe (for springs),where v is relative velocity, x is displacement, and e is the Exponent.

Only applicable when Kind is Spring, Damper, Rdamper, and Rspring.

Example (See WMConstraint.K)

See Also WMConstraint, WMConstraint.K

WMConstraint.Field (property)Syntax WMConstraint.Field

Description A WMCell object to specify the magnitude of the motor or actuator.

Comments Motors and actuators are versatile constraints which can control variousproperties such as length, rotation, velocity, and acceleration. You mustset the MotorType or ActuatorType to specify the controlled quantity,and then specify its magnitude by setting the Field property of theWMConstraint object.

Only applicable when Kind is Motor or Actuator.

Example (See WMConstraint.ActuatorType and WMConstraint.MotorType)

See Also WMConstraint (object), WMConstraint.MotorType (property),WMConstraint.ActuatorType (property)

WMConstraint.FR, FTheta (properties)Syntax WMConstraint.FR, WMConstraint.FTheta

Description WMCell objects to specify the radial (FR) and angular (FTheta)components of a force constraint.

Comments The values are specified in the current force unit with respect to the globalcoordinate system.

Note: To access FR and FTheta properties, the force magnitudespecifications must be set to polar coordinates. When a force is created,the default mode is Cartesian coordinates, in which case FR and FThetaare set to Nothing. You must explicitly specify the polar mode in theProperties window for the force.

Applicable only when Kind is Force.

Example Sub Main()

' If the first constraint in the document is a

Page 548: Working Model 2D - User's Manual

544 Working Model Basic User's Manual

' force, and if the force spec is set to Polar

' coordinates, modify (r, theta) to (10, 45).

Dim Force as WMConstraint

Set Force = WM.ActiveDocument.Constraints.Item(1)

WM.ActiveDocument.UnitSystem = "si degrees"

' Make sure that the object is Force and that the coordinate

' spec mode is Polar (otherwise FR and FTheta returns Nothing).

If (Force is not Nothing) and (Force.Kind = "force") then

If Force.FR is not Nothing then

Force.FTheta.Value = 45' degrees

Force.FR.Value = 10 ' Newton

End If

End If

End Sub

See Also WMConstraint (object), WMConstraint.FX, FY (properties)

WMConstraint.FX, FY (properties)Syntax WMConstraint.FX, WMConstraint.FY

Description WMCell objects to specify the X- and Y-components of a force constraint.

Comments The values are specified in the current force unit with respect to the globalcoordinate system.

Applicable only when Kind is Force.

Example Sub Main()

' Apply force at a corner of a square body.

' Let the direction of the force stay fixed with

' respect to the orientation of the body.

Dim D as WMDocument : Set D = WM.Activedocument

D.Gravity = "none"

Dim Force as WMConstraint

Dim Weight as WMBody

Set Weight = D.NewBody("square")

Weight.width.Value = 1.0

Set Force = D.NewConstraint("Force")

Page 549: Working Model 2D - User's Manual

Chapter 3 WMConstraint.GearRatio (property) 545

Set Force.Point(1).Body = Weight

Force.Point(1).PX.Value = -0.5

Force.Point(1).PY.Value = -0.5

Force.RotateWithBody = True

Force.FX.Value = 10

Force.FY.Value = 0

D.Run 50

End Sub

See Also WMConstraint (object), WMConstraint.FR, FTheta (properties)

WMConstraint.GearRatio (property)Syntax WMConstraint.GearRatio

Description A WMCell object to specify the gear ratio of a gear constraint.

Comments The value is ignored if AutoComputeGearRatio is True. Please note thatthe gear ratio is a unitless quantity.

Applicable only when Kind is Gear.

Example Sub Main()

Dim D as WMDocument : Set D=WM.ActiveDocument

Dim DriveGear as WMBody

Dim DrivenGear as WMBody

Dim GearSys as WMConstraint

Set DriveGear = D.NewBody("circle")

Set DrivenGear = D.NewBody("circle")

DriveGear.Radius.value = 1.5

DrivenGear.Radius.value = 0.5

DrivenGear.PX.Value = 3.0

Set GearSys = D.NewConstraint("gear")

GearSys.Point(1).Body = DriveGear

GearSys.Point(2).Body = DrivenGear

GearSys.AutoComputeGearRatio = False ' required

GearSys.GearRatio.Value = 5.5

' Make the rod active only while t < 2.5

GearSys.RodAlwaysActive = False

Page 550: Working Model 2D - User's Manual

546 Working Model Basic User's Manual

GearSys.RodActive.Formula = "time < 2.5"

' Note: At this point, circles remain unattached to

' the background; you need to attach them with

' pin joint or motor to make the gears work.

End Sub

See Also WMConstraint (object), WMConstraint.AutoComputeGearRatio (property)

WMConstraint.GetVertex (method)Syntax WMConstraint.GetVertex index, x, y

Description A method to obtain the x- and y-coordinates of a specified control point ofa curved slot.

Comments GetVertex is a method which, given the index of a curved slot controlpoint (specified in the Integer parameter index), fills the Doubleparameters x, y as the coordinates of the specified control point.

Applicable only when Kind is CurvedSlot.

Example (See WMConstraint.AddVertex)

See Also WMConstraint (object), WMConstraint.VertexCount (property),WMConstraint.AddVertex (method), WMConstraint.DeleteVertex(method)

WMConstraint.Internal (property)Syntax WMConstraint.Internal

Description A Boolean to specify whether the gear system works as an internal-external gear pair.

Comments When Internal is True, one of the bodies involved in the gear constraint(specified in InternalBody) becomes the internal gear. UseInternalBody to specify which gear is acting as an internal gear.

Default value is False.

Applicable only when Kind is Gear.

Example (See WMConstraint.GearRatio)

See Also WMConstraint (object), WMConstraint.InternalBody (property)

WMConstraint.InternalBody (property)Syntax WMConstraint.InternalBody

Page 551: Working Model 2D - User's Manual

Chapter 3 WMConstraint.K (property) 547

Description An Integer to specify the body acting as the internal gear. Applicableonly when Kind is Gear, and only if Internal is True.

Comments The Integer property returns 1 or 2. The number corresponds to whichbody was selected first when the gear was created.

Example Sub Main()

' Provided that an internal gear constraint exists in doc,

' reports which body is acting as the internal gear.

Dim Doc as WMDocument

Dim Gear as WMConstraint

Set Doc = WM.ActiveDocument

Set Gear = Doc.Constraint("gear")

If Gear is not Nothing then

If Gear.Internal then

MsgBox "Internal gear is "+str$(Gear.InternalBody)

Else

MsgBox "Gear found, but it is not an internal gear"

End If

End If

End Sub

See Also WMConstraint (object), WMConstraint.Internal (property)

WMConstraint.K (property)Syntax WMConstraint.K

Description A WMCell object to specify the multiplicative constant for the constraintforce.

Comments The constraint force is defined by -Kve (for dampers) or -Kxe (for springs),where v is relative velocity, x is displacement, and e is the exponent.

Only applicable when Kind is Spring, Damper, Rdamper, SpringDamperand Rspring.

Example Sub Main()

' Simulate mass-spring model; spring is -kx^2

Dim D as WMDocument : Set D = WM.Activedocument

Dim Spring as WMConstraint

Dim Weight as WMBody

Page 552: Working Model 2D - User's Manual

548 Working Model Basic User's Manual

Set Weight = D.NewBody("circle")

Weight.radius.Value = 0.5

Weight.PY.value = -1.5

Set Spring = D.NewConstraint("spring")

Set Spring.Point(2).Body = Weight

Spring.Exponent = 2

Spring.K.Value = 25.0 ' spring constant

Spring.Length.Value = Spring.CurrentLength

D.Run 100

End Sub

See Also WMConstraint, WMConstraint.Exponent

WMConstraint.Kind (property)Syntax WMConstraint.Kind

Description A String to indicate the type of a constraint.

Comments The Kind property is read-only and automatically defined by WorkingModel when the constraint is created. See the section on WMConstraint(object) for the range of values accepted as this String property.

The Kind property is applicable to all WMConstraint objects.

Example (See WMConstraint.ActuatorType)

See Also WMConstraint (object)

WMConstraint.Length (property)Syntax WMConstraint.Length

Description A WMCell object to specify rest length of a linear constraint.

Comments The unit is based on the current unit system.

Only applicable when Kind is Spring, SpringDamper, Rope, Separator,and Rod.

Example Sub Main()

' Sets a spring-mass model, where the rest length

' of the spring is half of the initial length.

' (i.e. spring is under tension initially)

Dim D as WMDocument : Set D = WM.ActiveDocument

Page 553: Working Model 2D - User's Manual

Chapter 3 WMConstraint.MotorType (property) 549

Dim Spring as WMConstraint

Dim Pendulum as WMBody

Set Pendulum = D.NewBody("circle")

Pendulum.Radius.Value = 0.5

Pendulum.PY.Value = -2.0

Set Spring = D.NewConstraint("spring")

SetSpring.Point(1).Body = Pendulum

Spring.Length.Value = Spring.CurrentLength / 2

D.Run 45

D.Reset

End Sub

See Also WMConstraint (object)

WMConstraint.MotorType (property)Syntax WMConstraint.MotorType

Description A String object to specify the type of a motor constraint.

Comments MotorType can be set to Torque, Acceleration, Velocity, or Rotation.Applicable only when Kind is Motor.

Example Sub Main()

' Sets the motor type to sinusoidal, velocity driver

Dim D as WMDocument : Set D = WM.Activedocument

Dim Motor as WMConstraint

Dim Spinner as WMBody

Set Spinner = D.NewBody("square")

Spinner.Width.Value = 1.0

Set Motor = D.NewConstraint("motor")

Set Motor.Point(2).Body = Spinner

Motor.MotorType = "Velocity"

Motor.Field.Formula = "200*sin(t*8)"

D.Run 100

End Sub

See Also WMConstraint (object)

Page 554: Working Model 2D - User's Manual

550 Working Model Basic User's Manual

WMConstraint.Point (method)Syntax WMConstraint.Point(index)

Description Returns a WMPoint object that represents the point element of a linearconstraint.

Comments The parameter index is an Integer that distinguish one point fromanother. The value of index can be either 1 or 2 for all linear constraintsexcept for a pulley. For a pulley system, index can range from 1 to thenumber of points embedded in the pulley. Refer to theWMConstraint.PointCount property for information.

The Point method returns a WMPoint object. Refer to the section onWMPoint for more information .

Applicable only when Kind is Spring, Damper, SpringDamper, Rod,Separator, Rope, Actuator, Pulley, Pin, SquarePin, Rspring,Rdamper, Motor, Hslot, Vslot, KeyedHslot, KeyedVslot, andCurvedSlot.

To append a point to a pulley system, use the AppendPoint method of theWMConstraint object.

The Point method returns the following depending on the Kind of theWMConstraint object.

Kind Point(1) Point(2)

Spring, Damper,SpringDamper, Rod,Separator, Rope,Actuator

(If the constraint wascreated interactivelywith the mouse) thefirst point created.

(If the constraint wascreated interactivelywith the mouse) thesecond point created.

Pulley The first node created. The second nodecreated.

Pin, SquarePin,Rspring, Rdamper,Motor

Point attached to thebody on the lowerlayer.

Point attached to thebody on the upperlayer.

Hslot, Vlost,KeyedHSlot,KeyedVSlot,CurvedSlot

Point representing theslot element, or theFOR of the slot .

Point attached to thebody moving along theslot.

Note: When you create a pin joint or locked joint by performing JOIN, thebody created earlier belongs to the lower layer.

Example Sub Main()

' Create two links and connect them with a pin joint.

Page 555: Working Model 2D - User's Manual

Chapter 3 WMConstraint.PointCount (property) 551

Dim D as WMDocument : Set D = WM.ActiveDocument

Dim Joint as WMConstraint

Dim Link1 as WMBody

Dim Link2 as WMBody

' Create two bodies

Set Link1 = D.NewBody("rectangle")

Link1.Width.Value = 2.0 : Link1.Height.Value = 0.5

Set Link2 = D.NewBody("rectangle")

Link2.Width.Value = 0.5 : Link2.Height.Value = 2.0

' Create a joint and attach it to the links

Set Joint = D.NewConstraint("pin")

SetJoint.Point(2).Body = Link1

Joint.Point(2).PX.Value = -0.75

Joint.Point(2).PY.Value = 0

Set Joint.Point(1).Body = Link2

Joint.Point(1).PX.Value = 0

Joint.Point(1).PY.Value = 0.75

' Modify the position of the linkage

Link2.PX.Value = 0.0 : Link2.PY.Value = 1.0

End Sub

See Also WMConstraint (object), WMConstraint.PointCount (property),WMConstraint.AppendPoint (method), WMPoint (object)

WMConstraint.PointCount (property)Syntax WMConstraint.PointCount

Description An Integer which shows the number of point elements embedded in aconstraint (endpoints for most constraints, or nodes for pulleys).

Comments Read-only. Most useful when Kind is Pulley. For rotational/linearconstraints and joints, PointCount returns two. For force, torque, and aslot element, PointCount returns 1. To append a point to the pulley, usethe WMConstraint.AppendPoint method.

Example (See WMConstraint.AppendPoint)

See Also WMConstraint (object), WMConstraint.AppendPoint (method),WMConstraint.Point (method)

Page 556: Working Model 2D - User's Manual

552 Working Model Basic User's Manual

WMConstraint.RodActive (property)Syntax WMConstraint.RodActive

Description A WMCell object to specify the condition under which the built-in rodconstraint in the gear becomes an active constraint.

Comments The value specified in RodActive is overridden if RodAlwaysActive isTrue.

Note: Since the property RodAlwaysActive is True by default, you must first set theproperty to False before modifying the RodActive property; otherwise, WorkingModel will not allow modification of the RodActive property.

Applicable only when Kind is Gear.

Example (See WMConstraint.GearRatio)

See Also WMConstraint (object), WMConstraint.RodAlwaysActive (property),WMConstraint.GearRatio (property)

WMConstraint.RodAlwaysActive (property)Syntax WMConstraint.RodAlwaysActive

Description A Boolean to specify whether the build-in rod constraint in the gearshould always be active.

Comments If set True, RodAlwaysActive overrides conditions that may have beengiven in RodActive. The default value is True.

Applicable only when Kind is Gear.

Example (See WMConstraint.GearRatio)

See Also WMConstraint (object), WMConstraint.RodActive (property),WMConstraint.GearRatio (property)

WMConstraint.RotateWithBody (properties)Syntax WMConstraint.RotateWithBody

Description A Boolean object to specify whether the direction of the force is to befixed with respect to the body to which it is attached.

Comments When RotateWithBody is True, the direction of the force is fixed withrespect to the body (i.e., retains the direction specified at the initial frame).The default value is False.

Applicable only when Kind is Force.

Example (See WMConstraint.FX, FY)

Page 557: Working Model 2D - User's Manual

Chapter 3 WMConstraint.Rotation (property) 553

See Also WMConstraint (object), WMConstraint.FX, FY (properties)

WMConstraint.Rotation (property)Syntax WMConstraint.Rotation

Description A WMCell object that specifies the rest rotation of a rotional constraint.

Comments The unit for rotation is based on the current unit system.

Only applicable when Kind is RSpring.

Example Sub Main()

' set up a torsion pendulum

Dim D as WMDocument : Set D = WM.ActiveDocument

D.Gravity = "none"

Dim Spring as WMConstraint

Dim Pendulum as WMBody

Set Pendulum = D.NewBody("rectangle")

Pendulum.Width.Value = 0.5

Pendulum.Height.Value = 2.0

Set Spring = D.NewConstraint("Rspring")

SetSpring.Point(2).Body = Pendulum

Spring.Point(2).PY.Value = 0.75

Pendulum.PR.Value = 45

Spring.Rotation.Value = Spring.CurrentRotation * 2

D.Run 45

D.Reset

End Sub

See Also WMConstraint (object)

WMConstraint.Torque (property)Syntax WMConstraint.Torque

Description A WMCell object to specify the magnitude of Torque.

Comments The magnitude is interpreted in the current torque unit. You can also usethe Field property to specify the torque (see Example below).

Applicable only when Kind is Torque.

Page 558: Working Model 2D - User's Manual

554 Working Model Basic User's Manual

Example Sub Main()

' Creates a body and applies torque to it.

Dim Doc as WMDocument : Set Doc = WM.ActiveDocument

Doc.Gravity = "none"

Dim Body as WMBody : Set Body = Doc.NewBody("square")

Body.Mass.Value = 5

Dim T as WMConstraint

Set T = Doc.NewConstraint("torque")

Set T.Point(1).Body = Body

T.Torque.Value = 10 ' T.Force.Value = 10 would work, too

Doc.Run 50

End Sub

See Also WMConstraint (object), WMConstraint.Field (property)

WMConstraint.VertexCount (property)Syntax WMConstraint.VertexCount

Description An Integer which returns the number of control points embedded in acurved slot joint.

Comments Read-only. Applicable only when Kind is CurvedSlot.

Example (See WMConstraint.AddVertex)

See Also WMConstraint (object), WMConstraint.GetVertex (method),WMConstraint.AddVertex (method), WMConstraint.DeleteVertex(method)

WMDocument (object)Syntax WMDocument

Description An object which provides an interface to Working Model document.

Comments Most of Working Model Basic functionalities operate on a WorkingModel document. You usually declare a WMDocument object beforerunning a simulation or manipulating individual Working Model objects,such as constraints and bodies.

WMDocument has the following properties and methods. Please refer toindividual sections for complete descriptions.

Property/MethodDescription

Page 559: Working Model 2D - User's Manual

Chapter 3 WMDocument (object) 555

AirResistanceType Specifies the type of air resistance.

AirResistanceV2Coeff Specifies the high air resistancecoefficient.

AirResistanceVCeoff Specifies the standard air resistancecoefficient.

AnimationStep Specifies the Animation Step of the simulation.

AssemblyError Specifies the Assembly Error.

AutoAnimationStep Enables or disables the automatic Animation Step determination.

AutoAssemblyError Enables or disables the automatic Assembly Error determination.

AutoEraseTrack Specifies whether the AutoErase Track feature is active.

AutoIntegratorError Enables or disables the automaticIntegrator Error determination.

AutoOverlapError Enables or disables the automatic Overlap Error determination.

AutoSignificantDigits Enables or disables the automaticSignificant Digits determination.

Bodies The collection of all WMBody objects in the document.

Body Returns the specified WMBody object.

ChargeUnit Specifes the charge unit.

Close Closes the document.

CombineTapeScroll Specifies whether the tape controldisplay is combined in line with the horizontal scroll bar.

Constraint Returns the specified WMConstraint object.

Constraints The collection of all WMConstraint objects in the document.

ControlsLocked Lock Control.

Copy Copies selected set of objects to the Clipboard.

CurrentFrame Shows the current frame number of the simulation.

Cut Copies selected set of objects to the Clipboard and deletes the objectsfrom the document.

DecimalDigits Specifies the number of decimal digits displayed in meters and dialogs.

DecimalFormat Specifies the display format for floating point numbers.

Delete Permanently deletes selected set of objects.

DistanceUnit Specifies the distance unit.

ElectricPotentialUnit

Page 560: Working Model 2D - User's Manual

556 Working Model Basic User's Manual

Specifies the electric potential unit.

ElectrostaticConst Specifies the electrostatic constant factor.

ElectrostaticsOn Specifies whether the electrostatic forces are active between bodies.

EnergyUnit Specifies the energy unit.

EraseTrack Erases traced simulation tracks left on the document window.

ExportDXF Exports a DXF file.

ExportMeterData Exports meter data to a file.

ExportStartFrame Specifies the intial frame number when exporting data to a file.

ExportStopFrame Specifies the final frame number when exporting data to a file.

ForceFieldFX, ForceFieldFY, ForceFieldT

Specifies the force field components.

ForceFieldType Specifies the force field type.

ForceUnit Specifies the force unit.

FrequencyUnit Specifies the frequency unit.

Gravity Specifies the type of gravitational force acting in the document.

HistoryFrames Shows the number of frames currently stored in memory.

ImportDXF Imports a DXF file.

Input Returns the specified WMInput object.

Inputs Collection of all WMInput objects in the document.

Integrator Specifies the integration method.

IntegratorError Specifies the Integrator Error.

Join Joins objects.

LinearGravityConst Specifies the linear gravitational constant.

MassUnit Specifies the mass unit.

Name The document name (file name).

NewBody Creates a new WMBody object.

NewConstraint Creates a new WMConstraint object.

NewInput Creates a new WMInput object.

NewOutput Creates a new WMOutput object.

NewPoint Creates a new WMPoint object.

Object Returns the specified WMObject object (regardless of its Kind).

Page 561: Working Model 2D - User's Manual

Chapter 3 WMDocument (object) 557

Objects Collection of all WMObject objects in the document.

Output Returns the specified WMOutput object.

Outputs Collection of all WMOutput objects in the document.

OverlapError Specifies the Overlap Error.

Paste Pastes objects from Clipboard to the Working Model document.

PlanetaryGravityConst Specifies the planetary gravitationalconstant.

PlayerMode Specifies whether the document is in Player mode.

Point Returns the specified WMPoint object.

Points Collection of WMPoint objects in the document.

PowerUnit Specifies the power unit.

Reset Resets the Working Model simulation.

RotationalVelocityUnit

Specifies the rotational velocity unit.

RotationUnit Specifies the rotation unit.

Run Runs the Working Model simulation.

Save Saves the Working Model simulation under the current filename.

SaveAs Saves the Working Model simulation under the specified name.

ScaleFactor Specifes the scale factor of the Working Model document screen.

ScrollTo Scrolls the document screen to a specific location.

Select Selects or de-selects Working Model objects in the document.

SelectAll Selects or de-selects all Working Model objects simultaneously in thedocument.

Selection Contains the objects currently selected in the document.

ShowCoordinates Show or hide the Coordinates bar.

ShowGridLines Show or hide the grid lines.

ShowHelpRibbon Show or hide the Help Ribbon.

ShowRulers Show or hide the rulers.

ShowScrollBars Show or hide the scroll bars.

ShowTapeControl Show or hide the tape control.

ShowToolPalette Show or hide the Toolbar.

Page 562: Working Model 2D - User's Manual

558 Working Model Basic User's Manual

ShowXYAxes Show or hide the x- and y-axes.

SimulationMode Sets the simulation mode (e.g. Fast, Accurate)

SignificantDigits Specifies the number of significant digits.

SkipFrames Specifies the frame skip rate.

Split Splits the selected bodies or constraints.

StartHere Resets the simulation history.

TimeUnit Specifies the time unit.

Tracking Specifies the tracking rate.

UnitSystem Specifies the current unit system.

Update Updates the Working Model document screen to reflect changes inWMCell objects.

VariableIntegrationStep

Sets the integration step to be fixed or variable.

VelocityUnit Specifies the (linear) velocity unit.

ViewWidth Specifies the view width (scaled length of the horizontal ruler).

WarnInconsistent Enables or disables the inconsistent constraint warning.

WarnLargeVorA Enables or disables the large velocity/acceleration warning.

WarnOverlap Enables or disables the initial body overlap warning.

WarnRedundant Enables or disables the redundant constraint warning.

Example Sub Main()

Dim WM1 as WMDocument

Set WM1 = WM.ActiveDocument

MsgBox "The currently active document is " + WM1.Name

End Sub

See Also WM (constant)

WMDocument.AirResistanceType (property)Syntax WMDocument.AirResistanceType

Description A String which controls the type of air resistance acting in the WorkingModel document.

Comments The AirResistanceType property can take one of the following.

Value Unit Description

Page 563: Working Model 2D - User's Manual

Chapter 3 WMDocument.AirResistanceV2Coeff (property) 559

none No air resistance.

standard Standard air resistance, which acts on a body proportional to its crosssectional width and velocity.

high High air resistance, which acts on a body proportional to its crosssectional width and the squared velocity.

The default value for every new document is none.

Use the properties AirResistanceVCoeff and AirResistanceV2Coeffto control standard and high air resistance forces, respectively.

Example Sub Main()

Dim D as WMDocument : Set D = WM.ActiveDocument

D.AirResistanceType = "Standard"

D.AirResistanceVCoeff = 7.0

End Sub

See Also WMDocument (object), WMDocument.AirResistanceVCoeff(property),WMDocument.AirResistanceV2Coeff(property)

WMDocument.AirResistanceV2Coeff (property)Syntax WMDocument.AirResistanceV2Coeff

Description A Double which specifies the high air resistance coefficient in theWorking Model document.

Comments You must turn on the high air resistance first in order for this constant totake effect in the Working Model document (seeWMDocument.AirResistanceType). The propertyAirResistanceV2Coeff pertains to the coefficient k used in computing F= k|v|2A, where F is the force acting on every body (whose cross-sectionalwidth is A (projected to the direction of v) and the velocity is v) in thedocument.

The default value of AirResistanceV2Coeff is 5.0 kg /m sec2 (0.007 lb /in sec2). The numerical value is automatically adjusted to accommodatethe current unit system in order to retain the physical magnitude of theconstant.

See WMDocument.AirResistanceType to specify the high air resistanceconstant.

Example Sub Main()

Dim D as WMDocument : Set D = WM.ActiveDocument

D.AirResistanceType = "High"

Page 564: Working Model 2D - User's Manual

560 Working Model Basic User's Manual

D.AirResistanceV2Coeff = 7.0

End Sub

See Also WMDocument (object), WMDocument.AirResistanceType(property),WMDocument.AirResistanceVCoeff(property)

WMDocument.AirResistanceVCoeff (property)Syntax WMDocument.AirResistanceVCoeff

Description A Double which specifies the standard air resistance coefficient in theWorking Model document.

Comments You must turn on the standard air resistance first in order for this constantto take effect in the Working Model document (seeWMDocument.AirResistanceType). The propertyAirResistanceVCoeff pertains to the coefficient k used in computing F= k|v|A, where F is the force acting on every body (whose cross-sectionalwidth is A (projected to the direction of v) and the velocity is v) in thedocument.

The default value of AirResistanceVCoeff is 5.0 kg /m sec (0.28 lb / insec). The numerical value is automatically adjusted to accommodate thecurrent unit system in order to retain the physical magnitude of theconstant.

See WMDocument. AirResistanceType to specify the standard airresistance constant.

Example (See WMDocument.AirResistanceType)

See Also WMDocument (object), WMDocument.AirResistanceType(property),WMDocument.AirResistanceV2Coeff(property)

WMDocument.AnimationStep (property)Syntax WMDocument.AnimationStep

Description The animation time step of the Working Model document.

Comments AnimationStep is a Double property. The property is exactly equivalentto the Animation Step in the Accuracy dialog of Working Model.

For a new document, the default value of AnimationStep is determinedby Working Model automatically. The value varies according to the sizeand unit system of the model.

In order to specify AnimationStep, you must first setAutoAnimationStep to False.

Example Sub Main()

Page 565: Working Model 2D - User's Manual

Chapter 3 WMDocument.AssemblyError (property) 561

' Uses Fast simulation mode for the active document, and

' set the Animation Step to 0.01

WM.ActiveDocument.SimulationMode = "Fast"

' At this point, AutoAnimationStep is True and AnimationStep

' has the value automatically determined by Working Model.

WM.ActiveDocument.AutoAnimationStep = False

WM.ActiveDocument.AnimationStep = 0.1

End Sub

See Also WMDocument (object), WMDocument.AutoAnimationStep (property)

WMDocument.AssemblyError (property)Syntax WMDocument.AssemblyError

Description Specifies the Assembly Error of the Working Model document.

Comments AssemblyError is a Double property. The property is equivalent to theAssembly Error in the Accuracy dialog of Working Model.

For a new document, the default value of AssemblyError is determinedby Working Model automatically. The value varies according to the sizeand unit system of the model.

In order to specify AssemblyError, you must first setAutoAssemblyError to False.

Example Sub Main()

' Uses Fast simulation mode for the active document, and

' set the Assembly Error to 0.01

WM.ActiveDocument.SimulationMode = "Fast"

' At this point, AutoAssemblyError is True and

' AssemblyError has the value automatically determined by

' Working Model.

WM.ActiveDocument.AutoAssemblyError = False

WM.ActiveDocument.AssemblyError = 0.01

End Sub

See Also WMDocument (object), WMDocument.AutoAssemblyError (property)

WMDocument.AutoAnimationStep (property)Syntax WMDocument.AutoAnimationStep

Page 566: Working Model 2D - User's Manual

562 Working Model Basic User's Manual

Description Specifies whether AnimationStep for WMDocument object is to bedetermined automatically.

Comments AutoAnimationStep is a Boolean property. Setting the property to Trueis equivalent to checking the Automatic radio button under AnimationStep in the Accuracy dialog of Working Model.

When the property is True, Working Model automatically determines anappropriate animation time step.

The default value of AutoAnimationStep is True.

If you set the AutoAnimationStep to be False, the value ofAnimationStep remains unchanged. You need to directly modify thevalue of AnimationStep if necessary.

Example See WMDocument.AnimationStep.

See Also WMDocument (object), WMDocument.AnimationStep (property)

WMDocument.AutoAssemblyError (property)Syntax WMDocument.AutoAssemblyError

Description Specifies whether AssemblyError for WMDocument object is to bedetermined automatically.

Comments AutoAssemblyError is a Boolean property. Setting the property to Trueis equivalent to checking the Automatic radio button under AssemblyError in the Accuracy dialog of Working Model. Please refer to theWorking Model User's Manual for descriptions of Assembly Error.

When the property is True, Working Model will automatically determinean appropriate size of Assembly Error.

The default value of AutoAssemblyError is True.

If you set the AutoAssemblyError to be False, the value ofAssemblyError remains unchanged. You need to modify theAssemblyError property directly if necessary.

Example See WMDocument.AssemblyError.

See Also WMDocument (object), WMDocument.AssemblyError (property)

WMDocument.AutoEraseTrack (property)Syntax WMDocument.AutoEraseTrack

Description A Boolean to specify whether the AutoErase Track feature is active.

Comments When the AutoErase Track feature is active, simulation tracks are erasedautomatically whenever the document is modified. Please refer to the

Page 567: Working Model 2D - User's Manual

Chapter 3 WMDocument.AutoIntegratorError (property) 563

Working Model User's Manual for more information on this feature.

AutoErase Track feature is active when AutoEraseTrack property isTrue.

The default value of AutoEraseTrack is True.

Example (See WMDocument.EraseTrack)

See Also WMDocument.EraseTrack (method)

WMDocument.AutoIntegratorError (property)Syntax WMDocument.AutoIntegratorError

Description Specifies whether IntegratorError for WMDocument object is to bedetermined automatically.

Comments AutoIntegratorError is a Boolean property. Setting the property toTrue is equivalent to checking the Automatic radio button underIntegrator Error in the Accuracy dialog of Working Model. Please refer tothe Working Model User's Manual for descriptions of Integrator Error.

When the property is True, Working Model will automatically determinean appropriate size of Integrator Error.

The default value of AutoIntegratorError is True.

If you set the AutoIntegratorError to be False, the value ofIntegratorError remains unchanged. You need to modify theIntegratorError property directly if necessary.

Example See WMDocument.IntegratorError.

See Also WMDocument (object), WMDocument.IntegratorError (property)

WMDocument.AutoOverlapError (property)Syntax WMDocument.AutoOverlapError

Description Specifies whether OverlapError for WMDocument object is to bedetermined automatically.

Comments AutoOverlapError is a Boolean property. Setting the property to True isequivalent to checking the Automatic radio button under Overlap Error inthe Accuracy dialog of Working Model. Please refer to the WorkingModel User's Manual for descriptions of Overlap Error.

When the property is True, Working Model will automatically determinean appropriate size of Overlap Error.

The default value of AutoOverlapError is True.

If you set the AutoOverlapError to be False, the value of

Page 568: Working Model 2D - User's Manual

564 Working Model Basic User's Manual

OverlapError remains unchanged. You need to modify theOverlapError property directly if necessary.

Example See WMDocument.OverlapError.

See Also WMDocument (object), WMDocument.OverlapError (property)

WMDocument.AutoSignificantDigits (property)Syntax WMDocument.AutoSignificantDigits

Description Specifies whether SignificantDigits for WMDocument object is to bedetermined automatically.

Comments AutoSignificantDigits is a Boolean property. Setting the property toTrue is equivalent to checking the Automatic radio button underSignificant Digits in the Accuracy dialog of Working Model. Please referto the Working Model User's Manual for descriptions of SignificantDigits.

When the property is True, Working Model will automatically determinean appropriate size of Significant Digits.

The default value of AutoSignificantDigits is True.

If you set the AutoSignificantDigits to be False, the value ofSignificantDigits remains unchanged. You need to modify theSignificantDigits property directly if necessary.

Example See WMDocument.SignificantDigits.

See Also WMDocument (object), WMDocument.SignificantDigits (property)

WMDocument.Bodies (property)Syntax WMDocument.Bodies

Description Returns the collection of all WMBody objects present in the document.

Comments The Bodies property is a collection of all WMBody objects present in thedocument. Like any other Collection object, you can use the Item methodto access a specific body within the collection.

The Bodies property is read-only.

If you wish to access a single body in the document instead of acollection, use the Body method of the WMDocument object.

The index parameter given to the Item method is sequential within the setof bodies in the document. For example, if a document Doc has 10 objects(bodies, constraints, etc.) and 3 of the 10 objects are bodies, these bodiesmay be referred to as Doc.Body(3), Doc.Body(6) and Doc.Body(7) withthe Body method. With the Bodies property, these objects are referred to

Page 569: Working Model 2D - User's Manual

Chapter 3 WMDocument.Body (method) 565

as Doc.Bodies.Item(1), Doc.Bodies.Item(2), andDoc.Bodies.Item(3), but not necessarily in that order. The Bodiesproperty is provided as a convenient tool to access all bodies in a loopstatement (see Example), and the indices given to the Item are notpermanently linked to individual WMBody objects.

Example Sub Main()

' change the name of all bodies to "truss member"

Dim D as WMDocument

Dim B as WMBody

Set D = WM.ActiveDocument

For I = 1 to D.Bodies.Count

D.Bodies.Item(I).Name = "truss member"

Next

End Sub

See Also WMDocument (object), WMDocument.Body (method), WMBody (object),Collection (topic)

WMDocument.Body (method)Syntax WMDocument.Body(name | id)

Description Returns the first WMBody object that matches the given name or IDnumber, or the special value Nothing if none is found.

Comments The WMDocument.Body method takes one or the other of the followingparameters:

Parameter Description

name A String containing the name of the WMBody object to be searched. Thestring match will not be case-sensitive.

id An Integer specifying the ID of the WMBody.

Note: The Body method returns a single body, whereas the Bodiesproperty of a WMDocument returns the collection of all bodies within thedocument.

Example Sub Main()

' Outputs the ID number of a body named "Cam Lobe".

Dim D as WMDocument

Dim B as WMBody

Set D = WM.ActiveDocument

Page 570: Working Model 2D - User's Manual

566 Working Model Basic User's Manual

Set B = D.Body("Cam Lobe")

If B is not Nothing then

MsgBox "Cam Lobe ID: "+str$(B.ID)

Else

MsgBox "No object by the name of Cam Lobe found"

End If

End Sub

See Also WMDocument (object), WMDocument.Bodies (property), WMBody (object)

WMDocument.ChargeUnit (property)Syntax WMDocument.ChargeUnit

Description A String which specifies the charge unit in the Working Modeldocument.

Comments The ChargeUnit property can take one of two values as follows.

Value Unit Description

Coulombs Coulombs.

Statcoulombs Statcoulombs.

Both lower- and upper-case letters are accepted. The default value of theChargeUnit property is "Coulombs".

The property may be overwritten when the user explicitly specifies theUnitSystem property of the document, because each unit system has a setof specifications for all measurement units. For example, the SI unitsystem automatically changes distance unit to meters, mass unit tokilograms, and time unit to seconds.

Example (See WMDocument.UnitSystem)

See Also WMDocument.UnitSystem (property), WMDocument.DecimalFormat(property), WMDocument.DecimalDigits (property)

WMDocument.Close (method)Syntax WMDocument.Close

Description Closes the Working Model document.

Comments If the document has been modified without being saved, Working Modelwill display a dialog asking whether the user wishes to save the changes.

Example Sub Main()

Page 571: Working Model 2D - User's Manual

Chapter 3 WMDocument.Collide (method) 567

' Closes the active document

MsgBox "Closing " + WM.ActiveDocument.Name

WM.ActiveDocument.Close

End Sub

See Also WMDocument (object)

WMDocument.Collide (method)Syntax WMDocument.Collide [state]

Description Specifies whether the selected objects could collide.

Comments The WMDocument.Collide method takes the selected set of WMBodyobjects and controls whether the objects could collide or not. You canselect or deselect objects using the Select or SelectAll method of theWMDocument. You can verify the current set of objects by accessingWMDocument.Selection property.

The method takes the following parameter:

Parameter Description

state An optional Boolean specifying whether the objects could collide (ifTrue) or not collide (if False). The parameter is optional, and the defaultvalue is True.

You can use the SelectAll method immediately followed by theCollide method to make all bodies non-collidable. If objects other thanWMBody are included in the selection, they will be ignored.

By default, all WMBody objects could collide with one another. Theexception is made when two bodies are directly connected with joints orgears. For more detail on collision properties, please refer to Chapter 4 ofthe Working Model User's Manual.

Example Sub Main()

' Makes all bodies in the active document not collidable.

Dim D as WMDocument

Set D = WM.ActiveDocument

D.SelectAll ' Selects all objects, including non-WMBody

D.Collide False

End Sub

See Also WMDocument (object), WMDocument.Select (method),WMDocument.Selection (property)

Page 572: Working Model 2D - User's Manual

568 Working Model Basic User's Manual

WMDocument.CombineTapeScroll (property)Syntax WMDocument.CombineTapeScroll

Description A Boolean to show whether the tape control display is combined in linewith the horizontal scroll bar or displayed in parallel with the scroll bar.

Comments CombineTapeScroll is True if the Tape Control is displayed in line withthe horizontal scroll bar. When the property is set to False, the TapeControl is displayed in parallel to the horizontal scroll bar. Changing thecombine status will activate the Save menu item.

Example Sub Main()

' Combines the tape control with horizontal scroll bar.

' Warns the user if it is already so.

Dim D as WMDocument

Set D = WM.ActiveDocument

if D.CombineTapeScroll = True then

MsgBox "Tape Control is already combined"

else

D.CombineTapeScroll = True

end if

End Sub

See Also WMDocument (object)

WMDocument.Constraint (method)Syntax WMDocument.Constraint(name | id)

Description Returns the first WMConstraint object in the document that matches thegiven name or ID number, or the special value Nothing if none is found.

Comments The WMDocument.Constraint method takes one or the other of thefollowing parameters:

Parameter Description

name A String containing the name of the WMConstraint object to besearched. The string match will not be case-sensitive.

id An Integer specifying the ID of the WMConstraint.

Example Sub Main()

Page 573: Working Model 2D - User's Manual

Chapter 3 WMDocument.Constraints (property) 569

' Outputs the name of constraint[3].

Dim D as WMDocument

Dim C as WMConstraint

Set D = WM.ActiveDocument

Set C = D.Constraint(3)

If C is not Nothing Then

MsgBox "Constraint(3) is called "+C.Name

End If

End Sub

See Also WMDocument (object), WMConstraint (object)

WMDocument.Constraints (property)Syntax WMDocument.Constraints

Description Returns the collection of all WMConstraint objects present in thedocument.

Comments The Constraints property is a collection of all WMConstraint objectspresent in the document. Like any other Collection object, you can usethe Item method to access a specific constraint within the collection.

The Constraints property is read-only.

The index parameter given to the Item method is sequential within the setof constraints in the document. For example, if a document Doc has 10objects (bodies, constraints, etc.) and 3 of the 10 objects are constraints,these constraints may be referred to as Doc.Constraint(3),Doc.Constraint(6) and Doc.Constraint(7) with the Constraintmethod. With the Constraints property, these objects are referred to asDoc.Constraints.Item(1), Doc.Constraints.Item(2), andDoc.Constraints.Item(3), but not necessarily in that order. TheConstraints property is provided as a convenient tool to access allconstraints in a loop statement (see Example), and the indices given to theItem are not permanently linked to individual WMConstraint objects.

Example Sub Main()

' hide all the constraints in the document

Dim D as WMDocument

Set D = WM.ActiveDocument

For I = 1 to D.Constraints.Count

D.Constraints.Item(I).Show = False

Page 574: Working Model 2D - User's Manual

570 Working Model Basic User's Manual

Next

End Sub

See Also WMDocument (object), WMConstraint (object), Collection (topic)

WMDocument.ControlsLocked (property)Syntax WMDocument.ControlsLocked

Description A Boolean to show whether the Lock Controls is turned on in theWorking Model document.

Comments ControlsLocked is True if the controls and meters are locked in place;False otherwise. You can set ControlsLocked to True or Falsewhether any Control object (controls and meters) exists in the WorkingModel document. If the flag is set to True, you can create Controls, butyou will not be able to move them until you disable Lock Controlsthrough the menu or by setting ControlsLocked to False.

Example Sub Main()

' Toggles Lock Control on the active document.

Dim D as WMDocument

Set D = WM.ActiveDocument

if D.ControlsLocked = True then

D.ControlsLocked = False

else

D.ControlsLocked = True

end if

End Sub

See Also WMDocument (object)

WMDocument.Copy (method)Syntax WMDocument.Copy

Description Copies selected set of objects in the Working Model document to theClipboard.

Comments The objects to be copied need to be selected first. The Copy method hasno effect if no object is selected.

The method is equivalent of the Copy menu item in the Edit menu. Theselected objects will not be modified.

Example Sub Main()

Page 575: Working Model 2D - User's Manual

Chapter 3 WMDocument.CurrentFrame (property) 571

' Creates a square and duplicates it on the screen.

Dim D as WMDocument

Dim B as WMBody

Set D = WM.ActiveDocument

' Creates a square; by default, located at (0, 0)

Set B = D.NewBody("square")

B.Width.Value = 1.0

D.Select B

D.Copy

' Duplicates a square.

D.Paste

' Now we will select both squares, "cut" them,

' and paste them.

D.SelectAll

D.Cut

D.Paste

End Sub

See Also WMDocument (object), WMDocument.Select (method),WMDocument.SelectAll (method), WMDocument.Cut (method),WMDocument.Paste (method)

WMDocument.CurrentFrame (property)Syntax WMDocument.CurrentFrame

Description An Integer containing the current frame number of the simulation.

Comments The CurrentFrame is an Integer property which contains the currentframe number of the simulation. If no simulation history is stored, orsimulation is reset, CurrentFrame always contains 0.

CurrentFrame is a read-only property.

To obtain the number of frames stored in memory for the currentdocument, use the WMDocument.HistoryFrames property.

Example (See WMDocument.Reset)

See Also WMDocument (object), WMDocument.HistoryFrames (property),WMDocument.Run (method), WMDocument.Reset (method),WMDocument.StartHere (method)

Page 576: Working Model 2D - User's Manual

572 Working Model Basic User's Manual

WMDocument.Cut (method)Syntax WMDocument.Cut

Description Copies a selected set of objects in the Working Model document to theClipboard and deletes the objects from the document.

Comments The objects to be copied need to be selected first.

The method is equivalent of the Cut menu item in the Edit menu. Theselected objects will be deleted from the document.

Example See WMDocument.Copy.

See Also WMDocument (object), WMDocument.Select (method),WMDocument.SelectAll (method), WMDocument.Copy (method),WMDocument.Paste (method)

WMDocument.DecimalDigits (property)Syntax WMDocument.DecimalDigits

Description An Integer which specifies the number of decimal digits displayed inWorking Model's meters and dialogs.

Note: This property is not related to WMDocument.SignificantDigits.

Comments The property has different significance depending on the current setting ofWMDocument.DecimalFormat.

The default value is 3.

Example See WMDocument.DecimalFormat.

See Also WMDocument.DecimalFormat (property), WMDocument.UnitSystem(property)

WMDocument.DecimalFormat (property)Syntax WMDocument.DecimalFormat

Description A String which specifies the display format for floating point numbers inWorking Model's meters and dialogs.

Comments DecimalFormat can take one of the three values as follows. Note that thedisplay format also depends on the setting of the DecimalDigits propertyof the WMDocument object. Please refer to the Working Model User'sManual for more information on Numbers and Units.

Value Description

Auto Working Model automatically adjusts the number display to show easy-to-read numbers. The number of digits after the floating point is exactly the

Page 577: Working Model 2D - User's Manual

Chapter 3 WMDocument.Delete (method) 573

one specified in DecimalDigits. For example, 0.000123 and 333.3333are displayed as 1.2e-4 and 333.3, respectively, provided DecimalDigits= 1.

Floating All numbers are displayed in the form of X.YYYeZ, where X is always onedigit, and the number of sub-decimal digits (i.e., how many Ys to bedisplayed) is given by DecimalDigits. Z, the exponent, is always aninteger. For example, 0.000123 and 333.3333 are displayed as 1.2e-4 and3.3e2, respectively, provided DecimalDigits = 1.

Fixed All numbers are displayed without exponents (no matter how large orsmall it is), with as many sub-decimal digits as specifed inDecimalDigits. For example, 0.000123 and 333.3333 are displayed as0.0 and 333.3, respectively, provided DecimalDigits = 1.

The default value is "Auto".

Example Sub Main()

' Set the number format to fixed with 5 digits.

WM.ActiveDocument.DecimalFormat = "Fixed"

WM.ActiveDocument.DecimalDigits = 5

End Sub

See Also WMDocument.DecimalDigits (property), WMDocument.UnitSystem(property)

WMDocument.Delete (method)Syntax WMDocument.Delete [object]

Description Deletes a selected set of objects in the Working Model document.

Comments The optional parameter, object, can be a WMBody, WMConstraint,WMPoint, WMOutput, or WMInput. If the parameter is provided, the Deletemethod will delete the object.

If no parameter is specified, the Delete method deletes the currentlyselected set of objects. If no object is selected, the Delete method has noeffect.

Example Sub Main()

' Delete all objects in the document

WM.ActiveDocument.SelectAll

WM.ActiveDocument.Delete

End Sub

See Also WMDocument (object), WMDocument.Select (method),WMDocument.SelectAll (method)

Page 578: Working Model 2D - User's Manual

574 Working Model Basic User's Manual

WMDocument.DeletePauseControl (method)Syntax WMDocument.DeletePauseControl index

Description Deletes an existing pause control condition.

Comments The DeletesPauseControl takes the following parameter.

Parameter Description

index An Integer specifying the pause condition. The value of index can bebetween 1 and PauseControlCount inclusive.

Please see the section on WMDocument.NewPauseControl for how pauseconditions are created.

Deleting a pause condition decrements the PauseControlCount propertyby 1 (provided there is at least 1 pause condition before the method iscalled). If a pause condition is deleted, other conditions whose numberwas higher than index will be shifted down and assigned a new number(decremented by 1).

For example, suppose three pause conditions exist. If you invoke:

Doc.DeletePauseControl 2

then the condition 3 will change its number to 2, while the condition 1remains unchanged. No condition 3 exists anymore thereafter. See theExample below.

Example Sub Main()

' Creates three pause conditions and deletes the second.

' Assumes no pause condition exists heretofore.

Dim D as WMDocument

Set D = WM.ActiveDocument

D.NewPauseControl

D.NewPauseControl

D.NewPauseControl

D.PauseControl(1).Formula = "time > 1"

D.PauseControl(2).Formula = "time > 2"

D.PauseControl(3).Formula = "time > 3"

D.DeletePauseControl 2

' At this point, the condition "time > 3" is reassigned

' as Condition 2.

MsgBox "Condition 2 is now:" + D.PauseControl(2).Formula

Page 579: Working Model 2D - User's Manual

Chapter 3 WMDocument.DistanceUnit (property) 575

' The message box displays "time > 3"

End Sub

See Also WMDocument (object), WMDocument.NewPauseControl (method),

WMDocument.PauseControlCount (property),WMDocument.SetPauseControlType (method),WMDocument.GetPauseControlType (method),WMDocument.PauseControl (method)

WMDocument.DistanceUnit (property)Syntax WMDocument.DistanceUnit

Description A String which specifies the distance unit in the Working Modeldocument.

Comments The DistanceUnit property can have one of the following values.

Value Unit Description

Angstroms Angstroms.

Centimeters Centimeters.

Feet Feet.

Inches Inches.

Kilometers Kilometers.

Light Years Light years.

Meters Meters.

Micrometers Micrometers (microns).

Miles Miles.

Millimeters Millimeters.

Mils Mils (one thousandth of an inch).

Nanometers Nanometers.

Parsecs Parsecs.

Yards Yards.

Both lower- and upper-case letters are accepted. The default value of theDistanceUnit property is "Meters".

The property is overwritten when the user explicitly specifies theUnitSystem property of the document, because each unit system has a setof specifications for all measurement units.

Page 580: Working Model 2D - User's Manual

576 Working Model Basic User's Manual

Example See WMDocument.UnitSystem.

See Also WMDocument.UnitSystem (property), WMDocument.DecimalFormat(property), WMDocument.DecimalDigits (property)

WMDocument.ElectricPotentialUnit (property)Syntax WMDocument.ElectricPotentialUnit

Description A String which specifies the electric potential unit in the Working Modeldocument.

Comments The ElectricPotentialUnit property can have one of the followingvalues.

Value Unit Description

Volts Volts.

(null) None. (i.e., ElectricPotentialUnit = "")

The default value of the ElectricPotentialUnit property is "Volts".

The property is overwritten when the user explicitly specifies theUnitSystem property of the document, because each unit system has a setof specifications for all measurement units.

Example See WMDocument.UnitSystem.

See Also WMDocument.UnitSystem (property), WMDocument.DecimalFormat(property), WMDocument.DecimalDigits (property)

WMDocument.ElectrostaticConst (property)Syntax WMDocument.ElectrostaticConst

Description A Double which specifies the electrostatic constant in the Working Modeldocument.

Comments You must turn on the electrostatics first in order for this constant to takeeffect in the Working Model document (seeWMDocument.ElectrostaticsOn). The property ElectrostaticConstpertains to the value of the constant 1/4πε0 used in computing F =

(C1C2/r2)/4πε0, where F is the force acting on every pair of bodies (whose

charge is C1 and C2 and located a distance r apart) in the document.

The default value of ElectrostaticConst is 8.99x109 Nm2/C2. Thenumerical value is automatically adjusted to accommodate the current unitsystem in order to retain the physical magnitude of the constant.

Example (See WMDocument.ElectrostaticsOn)

Page 581: Working Model 2D - User's Manual

Chapter 3 WMDocument.ElectrostaticsOn (property) 577

See Also WMDocument (object), WMDocument.ElectrostaticsOn (property)

WMDocument.ElectrostaticsOn (property)Syntax WMDocument.ElectrostaticsOn

Description A Boolean which specifies whether the electrostatic forces are turned onin the Working Model document.

Comments Electrostatic forces act between each pair of bodies according to theircharge. You can specify the value of ElectrostaticsOn as follows.

Value Unit Description

True Electrostatic force is on.

False Electrostatic force is off.

Use the property WMDocument.ElectrostaticConst to modify the valueof multiplicative constant 1/4πε0.

Example Sub Main()

' Turns on Electrostatics.

Dim D as WMDocument : Set D = WM.ActiveDocument

D.ElectroStaticsOn = True

D.ElectrostaticConst = 8.990e+9

MsgBox D.Electrostaticson

End Sub

See Also WMDocument (object), WMDocument.ElectrostaticConst (property)

WMDocument.EnergyUnit (property)Syntax WMDocument.EnergyUnit

Description A String which specifies the energy unit in the Working Modeldocument.

Comments The EnergyUnit property can have one of the following values

Value Unit Description

Joules Joules (J).

Kilowatt hours Kilowatt hours (kWh).

Kilocalories Kilocalories (Kcal).

B. T. U. British thermal units (BTU).

Electron Volts Electron volts (eV).

Page 582: Working Model 2D - User's Manual

578 Working Model Basic User's Manual

MeV Megaelectron volts (MeV).

Ergs Ergs (Erg).

(null) None. (i.e., EnergyUnit = "")

Both lower- and upper-case letters are accepted. The default value of theDistanceUnit property is "Joules".

The property is overwritten when the user explicitly specifies theUnitSystem property of the document, because each unit system has a setof specifications for all measurement units.

When EnergyUnit is set to "" (null), Working Model displays the energyunit as a composite unit based on the setting in ForceUnit andDistanceUnit. For example, when DistanceUnit is "Meters",ForceUnit is "Newtons", and EnergyUnit is "" (null), then meters andProperties window show the velocity unit as "N m", or Newton-meters.

Example See WMDocument.UnitSystem.

See Also WMDocument.UnitSystem (property), WMDocument.DecimalFormat(property), WMDocument.DecimalDigits (property)

WMDocument.EraseMeterValues (method)Syntax WMDocument.EraseMeterValues

Description Flushes from memory the meter data taken from multiple simulation runs.

Comments When the RetainMeterValues property of the document is True,Working Model stores the meter data from multiple simulations into itsmemory. Use the EraseMeterValues method to flush the memory.

The EraseMeterValues method is only valid when theRetainMeterValues property of the document is True.

Example Sub Main()

' Erase meter values only when the Retain Meter Values

' feature is active

Dim D as WMDocument : Set D = WM.ActiveDocument

If D.RetainMeterValues then

D.EraseMeterValues

End If

End Sub

See Also WMDocument.RetainMeterValues (property)

Page 583: Working Model 2D - User's Manual

Chapter 3 WMDocument.EraseTrack (method) 579

WMDocument.EraseTrack (method)Syntax WMDocument.EraseTrack

Description Erases traced tracks left on the Working Model document window.

Comments Use the EraseTrack method to refresh the simulation tracks.

Example Sub Main()

' Erase tracks only if AutoEraseTrack is off, and

' Tracking is turned on.

Dim D as WMDocument

Set D = WM.ActiveDocument

If (D.AutoEraseTrack = False and D.Tracking <> 0) then

D.EraseTrack

End if

End Sub

See Also WMDocument.AutoEraseTrack (property)

WMDocument.ExportDXF (method)Syntax WMDocument.ExportDXF filename

Description Exports the document to a DXF file.

Comments The method takes the following parameter.

Parameter Description

filename A String which specifies the name of the DXF file.

Please refer to the Working Model User's Manual for details regardinghow DXF files are created from objects in Working Model.

Example Sub Main()

' Opens a file and exports the model to a dxf file.

Dim D as WMDocument

If FileExists("4bar.wm") then

Set D = WM.Open("4bar.wm")

D.ExportDXF "4bar.dxf"

else

MsgBox "Error: File 4bar.wm does not exist."

Page 584: Working Model 2D - User's Manual

580 Working Model Basic User's Manual

end if

End Sub

See Also WMDocument (object), WMDocument.ImportDXF (method)

WMDocument.ExportMeterData (method)Syntax WMDocument.ExportMeterData filename [MeterSelect]

Description Exports the meter data to a text file.

Comments The method takes the following parameters.

Parameter Description

filename A String which specifies the name of the meter data file.

MeterSelect An optional Boolean parameter which specifies whether to export the datafrom selected meters only or from all meters. When set True, WorkingModel will export meter data only from selected meters. UseWMDocument.Select method to select meters and objects. The defaultvalue is False.

By default, frame 0 up to the last frame currently stored in the simulationhistory will be exported to a meter data file. To specify the initial andfinal frames for the meter data export, set ExportStartFrame andExportStopFrame properties of the WMDocument object.

Example Sub Main()

' If time history exists, and meter exists,

' exports meter data from all meters.

Dim D as WMDocument : Set D = WM.ActiveDocument

if D.HistoryFrames > 0 and D.Outputs.Count > 0 then

D.ExportStartFrame = 0

D.ExportStopFrame = D.HistoryFrames

D.ExportMeterData "Datafile.dta"

end if

End Sub

See Also WMDocument (object), WMDocument.ExportStartFrame (property),ExportStopFrame (property)

WMDocument.ExportStartFrame (property)Syntax WMDocument.ExportStartFrame

Page 585: Working Model 2D - User's Manual

Chapter 3 WMDocument.ExportStopFrame (property) 581

Description Specifies the initial frame number when exporting a data file.

Comments The ExportStartFrame is an Integer property which specifies the initialframe number for exporting files. Working Model will export the data file(such as Meter Data), starting from the frame designated byExportStartFrame, finishing the export (and the simulation) with theExportStopFrame.

The default value of ExportStartFrame is 0.

Example (See WMDocument.ExportMeterData)

See Also WMDocument (object), WMDocument.ExportMeterData (method),ExportStopFrame (property)

WMDocument.ExportStopFrame (property)Syntax WMDocument.ExportStopFrame

Description Specifies the final frame number when exporting a data file.

Comments The ExportStopFrame is an Integer property which specifies the finalframe number for exporting files. Working Model will export the data file(such as Meter Data), starting from the frame designated byExportStartFrame, finishing the export (and the simulation) with theExportStopFrame.

The default value of ExportStopFrame is 100 (if no simulation historyexists) or the last frame currently stored in the simulation history.

Example (See WMDocument.ExportMeterData)

See Also WMDocument (object), WMDocument.ExportMeterData (method),ExportStartFrame (property)

WMDocument.ForceFieldFX, ForceFieldFY, ForceFieldT(properties)

Syntax WMDocument.ForceFieldFX, WMDocument.ForceFieldFY,WMDocument.ForceFieldT

Description WMCell properties which specify the X-, Y-, and torque components of theforce field in the Working Model document, respectively

Comments You must activate the force field first in order for these properties to takeeffect in the Working Model document (seeWMDocument.ForceFieldType).

Example (See WMDocument.ForceFieldType)

See Also WMDocument (object), WMDocument.ForceFieldType(property)

Page 586: Working Model 2D - User's Manual

582 Working Model Basic User's Manual

WMDocument.ForceFieldType (property)Syntax WMDocument.ForceFieldType

Description A String which specifies the type of the force field in the WorkingModel document.

Comments The ForceFieldType property can have one of the following values.

Value Unit Description

off Off. No active force field.

pairwise Force field acts between each pair of bodies in the document.

field Force field acts uniformly on the document.

Use WMDocument.ForceFieldFX, ForceFieldFY, and ForceFieldTproperties to specify the individual components of the force field.

The force field acts on bodies in the document in addition to forces set byAirResistanceType, Gravity, and ElectrostaticsOn properties of thedocument.

Example Sub Main()

' Sets up magnetic force field pointing into the

' simulation window.

Dim D as WMDocument : Set D = WM.ActiveDocument

D.ForceFieldType = "field"

D.ForceFieldFX.Formula = "-1e4 * self.charge * self.v.y"

D.ForceFieldFY.Formula = "1e4 * self.charge * self.v.x"

End Sub

See Also WMDocument (object), WMDocument.ForceFieldFX, ForceFieldFY,ForceFieldT (properties)

WMDocument.ForceUnit (property)Syntax WMDocument.ForceUnit

Description A String which specifies the force unit in the Working Model document.

Comments The ForceUnit property can have one of the following values.

Value Unit Description

Dynes Dynes.

Grams (force) Gram forces.

Kilograms (force) Kilogram forces.

Page 587: Working Model 2D - User's Manual

Chapter 3 WMDocument.FrequencyUnit (property) 583

Newtons Newtons.

Poundals Poundals.

Pounds Pounds.

Both lower- and upper-case letters are accepted. The default value of theForceUnit property is "Newtons".

The property is overwritten when the user explicitly specifies theUnitSystem property of the document, because each unit system has a setof specifications for all measurement units.

Example See WMDocument.UnitSystem.

See Also WMDocument.UnitSystem (property), WMDocument.DecimalFormat(property), WMDocument.DecimalDigits (property)

WMDocument.FrequencyUnit (property)Syntax WMDocument.FrequencyUnit

Description A String which specifies the frequency unit in the Working Modeldocument.

Comments The FrequencyUnit property can take one of the following.

Value Unit Description

Hertz Hertz (Hz).

(null) None. (i.e., FrequencyUnit = "")

The default value of the FrequencyUnit property is "" (null).

Both lower- and upper-case letters are accepted. The property isoverwritten when the user explicitly specifies the UnitSystem property ofthe document, because each unit system has a set of specifications for allmeasurement units.

Example See WMDocument.UnitSystem.

See Also WMDocument.UnitSystem (property), WMDocument.DecimalFormat(property), WMDocument.DecimalDigits (property)

WMDocument.GetPauseControlType (method)Syntax WMDocument.GetPauseControlType(index)

Description Returns the String specifying the action to be taken when the pausecondition is satisfied.

Comments The SetPauseControlType method takes the following parameter.

Page 588: Working Model 2D - User's Manual

584 Working Model Basic User's Manual

Parameter Description

index An Integer specifying the pause condition. The value of index can bebetween 1 and PauseControlCount inclusive.

The return value of the GetPauseControlType method can be one of the following:

Value Description

"pause" Pauses the simulation when the condition is satisfied. The user can clickthe Run button to continue the simulation.

"stop" Stops the simulation when the condition is satisfied. After the simulationis stopped with this pause condition, the user must remove or modify thispause condition to continue the simulation further.

"reset" Resets the simulation to frame 0 when the condition is satisfied.

"loop" Loops the simulation when the condition is satisfied. The simulation willbe repeated indefinitely.

To specify the condition, use the SetPauseControlType method.

For more information on pause control, please see the section onWMDocument.NewPauseControl method.

Example Sub Main()

' Checks all the current pause conditions, and switches

' them all to Reset When.

Dim D as WMDocument

Set D = WM.ActiveDocument

for I = 1 to D.PauseControlCount

if D.GetPauseControlType(I) <> "reset" then

D.SetPauseControlType I, "reset"

end if

next

End Sub

See Also WMDocument (object), WMDocument.NewPauseControl (method)WMDocument.PauseControlCount (property), WMDocument.PauseControl(method), WMDocument.SetPauseControlType (method),WMDocument.DeletePauseControl (method)

WMDocument.Gravity (property)Syntax WMDocument.Gravity

Page 589: Working Model 2D - User's Manual

Chapter 3 WMDocument.HistoryFrames(property) 585

Description A String which controls the type of gravitational forces acting in theWorking Model document.

Comments The Gravity property can have one of the following values.

Value Unit Description

none No gravity.

linear Gravity acts uniformly on every body in the document. The force acts inthe negative y-direction. See the propertyWMDocument.LinearGravityConst to modify the gravitational constant.

planetary Gravity acts between each pair of bodies. The magnitude of the gravity isdetermined by Newton's law of gravitation. See the propertyWMDocument.PlanetaryGravityConst to modify the gravitationalconstant.

The default value is linear.

Example Sub Main()

' Sets up the lunar gravitational field.

Dim D as WMDocument : Set D = WM.ActiveDocument

D.Gravity = "linear"

D.LinearGravityConst = 1.67

End Sub

See Also WMDocument (object), WMDocument.LinearGravityConst (property),WMDocument.PlanetaryGravityConst (property)

WMDocument.HistoryFrames(property)Syntax WMDocument.HistoryFrames

Description An Integer containing the number of simulation frames currently storedin memory.

Comments The HistoryFrames is an Integer property which contains the numberof frames currently stored in memory for the given document. If nosimulation history is stored, HistoryFrames always contains 0.

HistoryFrames is a read-only property.

To obtain the current frame number displayed in the document, use theWMDocument.CurrentFrame property.

Example (See WMDocument.ExportMeterData)

See Also WMDocument (object), WMDocument.CurrentFrame (property),WMDocument.Run (method), WMDocument.Reset (method),WMDocument.StartHere (method)

Page 590: Working Model 2D - User's Manual

586 Working Model Basic User's Manual

WMDocument.ImportDXF (method)Syntax WMDocument.ImportDXF filename

Description Imports a DXF file into the document.

Comments The method takes the following parameter.

Parameter Description

filename A String which specifies the name of the DXF file.

Please refer to Working Model User's Manual for details regarding howDXF files are translated to objects in Working Model.

Example Sub Main()

' Imports a DXF file

Dim D as WMDocument : Set D = WM.ActiveDocument

If FileExists("4bar.dxf") then

D.ImportDXF "4bar.dxf"

End if

End Sub

See Also WMDocument (object), WMDocument.ImportDXF (method)

WMDocument.Input (method)Syntax WMDocument.Input(name | id)

Description Returns the first WMInput object that matches the given name or IDnumber, or the special value Nothing if none is found.

Comments The WMDocument.Input method takes one or the other of the followingparameters:

Parameter Description

name A String containing the name of the WMInput object to be searched. Thestring match will not be case-sensitive.

id An Integer specifying the ID of the WMInput.

Example Sub Main()

' Outputs the name of input[2].

Dim D as WMDocument

Dim I as WMInput

Set D = WM.ActiveDocument

Page 591: Working Model 2D - User's Manual

Chapter 3 WMDocument.Inputs (property) 587

Set I = D.Input(2)

If I is not Nothing then

MsgBox I.Name

End If

End Sub

See Also WMDocument (object), WMInput (object)

WMDocument.Inputs (property)Syntax WMDocument.Inputs

Description Returns the collection of all WMInput objects present in the document.

Comments The Inputs property is a collection of all WMInput objects present in thedocument. Like any other Collection objects, you can use the Itemmethod to access a specific input within the collection.

The Inputs property is read-only.

The index parameter given to the Item method is sequential within the setof input objects in the document. For example, if a document Doc has 10objects (bodies, constraints, etc.) and 3 of the 10 objects are inputs, theseinputs may be referred to as Doc.Input(3), Doc.Input(6) andDoc.Input(7) with the Input method. With the Inputs property, theseobjects are referred to as Doc.Inputs.Item(1), Doc.Inputs.Item(2),and Doc.Inputs.Item(3), but not necessarily in that order. The Inputsproperty is provided as a convenient tool to access all input objects in aloop statement (see Example), and the indices given to the Item are notpermanently linked to individual WMInput objects.

Example Sub Main()

' change all the constraints to sliders

Dim D as WMDocument

Set D = WM.ActiveDocument

For I = 1 to D.Inputs.Count

D.Inputs.Item(I).Format = "slider"

Next

End Sub

See Also WMDocument (object), WMInput (object), Collection (topic)

WMDocument.Integrator (property)Syntax WMDocument.Integrator

Page 592: Working Model 2D - User's Manual

588 Working Model Basic User's Manual

Description Specifies the current integrator for the WMDocument object.

Comments Integrator is a String property. It can have one of the followingvalues.

Parameter Description

euler The Euler method.

kutta_merson The Predictor/corrector method.

All documents have kutta_merson as the default simulation mode (whichis set in the Accurate simulation mode).

Example Sub Main()

' Sets the integrator of the active document to

' the Euler method.

Dim D as WMDocument

Set D = WM.ActiveDocument

D.Integrator = "euler"

End Sub

See Also WMDocument (object), WMDocument.SimulationMode (property)

WMDocument.IntegratorError (property)Syntax WMDocument.IntegratorError

Description Specifies the Integrator Error of the Working Model document.

Comments IntegratorError is a Double property. The property is exactlyequivalent to the Integrator Error in the Accuracy dialog of WorkingModel.

For a new document, the default value of IntegratorError is determinedby Working Model automatically. The value varies according to the sizeand unit system of the model.

In order to specify IntegratorError, you must first setAutoIntegratorError to False.

Example Sub Main()

' Uses Fast simulation mode for the active document, and

' set the Integrator Error to 0.01

WM.ActiveDocument.SimulationMode = "Fast"

' At this point, AutoIntegratorError is True and

' IntegratorError has the value automatically determined by

Page 593: Working Model 2D - User's Manual

Chapter 3 WMDocument.Join (method) 589

' Working Model.

WM.ActiveDocument.AutoIntegratorError = False

WM.ActiveDocument.IntegratorError = 0.05

End Sub

See Also WMDocument (object), WMDocument.AutoIntegratorError (property)

WMDocument.Join (method)Syntax WMDocument.Join

Description Join objects that are selected and ready to be joined in the document.

Comments The WMDocument.Join performs the Join operation on objects that areselected and ready to be joined in the document. For example, twoindividual point elements, when selected, can be joined to form a pin joint.Also constraints that are currently split can be rejoined using this method.

Example Sub Main()

' Select point[5] and point[6], and joins them together

' to form a pin joint. Assumes point[5] and point[6] exist.

Dim D as WMDocument

Set D = WM.ActiveDocument

D.SelectAll False ' make sure no others are selected

D.Select D.Point(5)

D.Select D.Point(6)

D.Join

End Sub

See Also WMDocument (object), WMObject (object)

WMDocument.LinearGravityConst (property)Syntax WMDocument.LinearGravityConst

Description A Double which specifies the linear gravity constant in the WorkingModel document.

Comments You must first turn on linear gravity in order for this constant to takeeffect in the Working Model document (see WMDocument.Gravity). Theproperty LinearGravityConst pertains to the gravitational constant gused in computing F = mg, where F is the force acting on every body(whose mass is m) in the document.

Page 594: Working Model 2D - User's Manual

590 Working Model Basic User's Manual

The default value of LinearGravityConst is 9.81 m / sec2 (386 in / sec2).The numerical value is automatically adjusted to accommodate the currentunit system in order to retain the physical magnitude of the constant.

See WMDocument.PlanetaryGravityConst to specify the gravitationalconstant G for planetary gravity.

Example (See WMDocument.Gravity)

See Also WMDocument (object), WMDocument.Gravity (property),WMDocument.PlanetaryGravityConst (property)

WMDocument.MassUnit (property)Syntax WMDocument.MassUnit

Description A String which specifies the mass unit in the Working Model document.

Comments The MassUnit property can have one of the following values.

Value Unit Description

Kilograms Kilograms.

Earth Pounds British pounds.

Slugs Slugs.

Metric Tons Metric tons.

Grams Grams.

Milligrams Milligrams.

Atomic mass units Atomic mass unit.

Both lower- and upper-case letters are accepted. The default value of theMassUnit property is "Kilograms".

The property is overwritten when the user explicitly specifies theUnitSystem property of the document, because each unit system has a setof specifications for all measurement units.

Example See WMDocument.UnitSystem.

See Also WMDocument.UnitSystem (property), WMDocument.DecimalFormat(property), WMDocument.DecimalDigits (property)

WMDocument.Name (property)Syntax WMDocument.Name

Description Returns a String containing the name of the Working Model document.

Comments The Name property is read-only. The property cannot be directly modified

Page 595: Working Model 2D - User's Manual

Chapter 3 WMDocument.NewBody (method) 591

through Working Model Basic. You can save the document under adifferent name using the SaveAs method.

Example Sub Main()

MsgBox "The active document name is " + WM.ActiveDocument.Name

End Sub

See Also WMDocument (object), WMDocument.SaveAs (method).

WMDocument.NewBody (method)Syntax WMDocument.NewBody(type)

Description Creates a new body in the Working Model document, and returns theWMBody object.

Comments The NewBody method takes the following parameter:

Parameter Description

type A String which specifies the type of the body to be created. The value oftype can be circle, square, rectangle, or polygon.

The default dimension of the object is based on the current grid size. Forbrevity, let us denote the grid size as g. The object will have the followingdefault dimensions and positions.

A polygon will have three vertices ((0,0), (g,0), (g,g) in globalcoordinates) by default. Its FOR is set to the geometric center of thepolygon (triangle).

A circle will have a diameter equal to g. The geometric center of thecircle will be placed at (0, 0).

A square and rectangle will have a width and height equal to g. Thegeometric center of the body will be placed at (0, 0).

The current grid size can be viewed by activating the grid lines in theWorking Model document (use WMDocument.ShowGridLines property).

After creating the object, modify the property of the new WMBody object tospecify its initial position and geometry.

Example Sub Main()

' Creates a circle of radius 2 at (x,y)=(3,3)

Dim B1 as WMBody

Dim Doc1 as WMDocument

Doc1 = WM.ActiveDocument

Page 596: Working Model 2D - User's Manual

592 Working Model Basic User's Manual

Set B1 = Doc1.NewBody("Circle")

B1.radius.value = 2

B1.PX.Value = 3 : B1.PY.Value = 3

End Sub

See Also WMDocument (object), WMBody (object), WMDocument.ShowGridLines(property)

WMDocument.NewConstraint (method)Syntax WMDocument.NewConstraint(type)

Description Creates a new constraint in the Working Model document, and returns thecorresponding WMConstraint object.

Comments The NewConstraint method takes the String parameter type, whichspecifies the type of the constraint to be created. The value can be one ofthe following.

Value Description

Pin Pin joint.

SquarePin Locked joint.

Spring Spring.

Damper Damper.

SpringDamper Spring-damper combination.

Rspring Rotational spring.

Rdamper Rotational damper.

Hslot Horizontal slot joint.

Vslot Vertical slot joint.

KeyedHSlot Keyed horizontal slot joint.

KeyedVSlot Keyed vertical slot joint.

CurvedSlot Curved slot joint.

Rod Rod.

Separator Separator.

Rope Rope.

Force Force.

Torque Torque.

Page 597: Working Model 2D - User's Manual

Chapter 3 WMDocument.NewInput (method) 593

Actuator Actuator.

Motor Motor.

Pulley Pulley.

Gear Gear.

When created, constraints default to the following:

Endpoint coordinates are set to (0, 0). Slot points (base points) will beat zero.

A curved slot has three default control points: (0, 0), (1, 1), and (2, 2).

Endpoints are attached to the background.

Magnitude for force and torque is set to 0.

The Kind property of the constraint is set to equal to the String givenin the type parameter. The only exceptions are all linear slot joints(Vslot, Hslot, KeyedHSlot, KeyedVSlot); these constraints haveKind set to "slot".

To specify the constraint properties, directly modify the properties of thenew WMConstraint object after it is created with the NewConstraintmethod.

Example (See WMConstraint)

See Also WMDocument (object), WMConstraint (object)

WMDocument.NewInput (method)Syntax WMDocument.NewInput()

Description Creates a new input object in the Working Model document, and returnsthe corresponding WMInput object.

Comments To specify which object is to be controlled by the WMInput object, youneed to modify the property of the target object itself (see Examplebelow).

The default Format of the input object is Slider.

Example Sub Main()

'Creates a square and sets up a slider bar to control itsinitial x-position

Dim D as WMBody

Dim I as WMInput

Set D = WM.ActiveDocument.NewBody("square")

D.Width.Value = 1.0

Page 598: Working Model 2D - User's Manual

594 Working Model Basic User's Manual

Set I = WM.ActiveDocument.NewInput()

D.PX.Formula = "input[" +str$(I.ID)+ "]"

End Sub

See Also WMDocument (object), WMInput (object)

WMDocument.NewOutput (method)Syntax WMDocument.NewOutput()

Description Creates a new output object in the Working Model document, and returnsthe corresponding WMOutput object.

Comments To specify what quantities are to be displayed on the WMOutput object,you need to modify its properties. See Example below. Also, please referto the section on WMOutput for more information.

The default Format of the WMOutput object is Graph.

Example Sub Main()

'Sets up a square and creates a meter to measure its y-

'position.

Dim B as WMBody

Dim O as WMOutput

Set B = WM.ActiveDocument.NewBody("square")

B.Width.Value = 1.0

Set O = WM.ActiveDocument.NewOutput()

FLD$ = "body["+str$(B.ID)+"].p.y"

O.Column(1).Cell.Formula = FLD

O.Column(1).Label = "Y-Position"

End Sub

See Also WMDocument (object), WMOutput (object)

WMDocument.NewPauseControl (method)Syntax WMDocument.NewPauseControl

Description Creates a new pause control condition.

Comments The NewPauseControl allows for an entry of a new pause controlcondition.

Each WMDocument object maintains a list of pause control conditions. ThePauseControlCount property keeps track of how many pause control

Page 599: Working Model 2D - User's Manual

Chapter 3 WMDocument.NewPauseControl (method) 595

conditions are currently implemented. The PauseControlCount isinitially set to zero, as no pause condition is specified in a blankdocument.

When the NewPauseControl method is invoked, PauseControlCount isincremented by 1 and a new condition is added to the end of the list; hencethe new PauseControlCount is equal to the position of the newcondition. You must use the PauseControl method to specify theformula expression for the pause condition, and use theSetPauseControlType method to specify the action to be taken (e.g.Pause, Stop, or Loop) when the condition is satisfied.

Only three pause control conditions will appear in the Pause Controldialog, but repeated calls to NewPauseControl will continue to add to theend of the list.

To delete a pause control condition, use the DeletePauseControlmethod.

Example Sub Main()

' Creates two pause control conditions; assume no pause

' conditions currently exists. Conditions are:

' 1: pause when frame number exceeds 100

' 2: reset when time exceeds 2.5.

Dim D as WMDocument

Set D = WM.ActiveDocument

' Creates two conditions in a row

D.NewPauseControl

D.NewPauseControl

D.PauseControl(1).Formula = "frame() > 100"

D.PauseControl(2).Formula = "time > 2.5"

D.SetPauseControlType 1, "pause"

D.SetPauseControlType 2, "reset"

End Sub

See Also WMDocument (object), WMDocument.PauseControl (method),

WMDocument.PauseControlCount (property),WMDocument.SetPauseControlType (method),WMDocument.GetPauseControlType (method),WMDocument.DeletePauseControl (method)

Page 600: Working Model 2D - User's Manual

596 Working Model Basic User's Manual

WMDocument.NewPoint (method)Syntax WMDocument.NewPoint(type)

Description Creates a new point element in the Working Model document, and returnsthe corresponding WMPoint object.

Comments The NewPoint method takes the following parameter:

Parameter Description

type A String which specifies what type of point is to be created. The valuecan be either Point (to create a point element), SquarePoint (to create asquare point element), or Anchor (to create an anchor).

Example Sub Main()

' Creates a point at (x,y)=(3,3)

Dim P as WMPoint

Set P = WM.ActiveDocument.NewPoint("SquarePoint")

P.PX.Value = 3.0

P.PY.Value = 3.0

End Sub

See Also WMDocument (object), WMPoint (object)

WMDocument.Object (method)Syntax WMDocument.Object(name | id)

Description Returns the first WMObject object that matches the given name or IDnumber.

Comments Since the Object method returns a WMObject, you must store the returnvalue in another WMObject variable, even if the return value is certain tobe a WMBody object, for example. The method Object is most useful whenyou try to apply a type-independent change to all objects in the entiredocument (see Example).

The WMDocument.Object method takes one or the other of the followingparameters:

Parameter Description

name A String containing the name of the WMObject object to be searched.The string match will be case-sensitive.

id An Integer specifying the ID of the WMObject.

The return value will be Nothing if no WMObject that matches the

Page 601: Working Model 2D - User's Manual

Chapter 3 WMDocument.Objects (property) 597

criterion is found.

Example Sub Main()

' Finds an object named "Body". If it is not a WMBody object,pops up

' warning for bad naming. (You can name any object in any way;this is

' a sample code to clean up naming scheme simply for the sakeof usability)

Dim Doc as WMDocument : Set Doc = WM.ActiveDocument

Dim I as Integer, Obj as WMObject

Set Obj = Doc.Object("body")

If Obj is not Nothing then

If Obj.Kind <> "body" then

MsgBox "Object "+str$(Obj.ID)+" has a name 'body' but itis not!"

End If

End If

End Sub

See Also WMDocument (object), WMObject (object)

WMDocument.Objects (property)Syntax WMDocument.Objects

Description Returns the collection of all WMObject objects (i.e., all Working Modelobjects) present in the document.

Comments The Objects property is a collection of all WMObject objects present inthe document. Like any other Collection objects, you can use the Itemmethod to access a specific object within the collection.

The Objects property is read-only.

Please note the return value of the Item method will be another WMObject.For example, even if you are certain that the returned object is a WMBody,you must use WMObject object to store the return value.

' Assume Doc is a valid WMDocument object.

' Assume body[3] exists.

Dim B as WMBody

Dim Obj as WMObject

B = Doc.Objects.Item(3) ' incorrect usage

Page 602: Working Model 2D - User's Manual

598 Working Model Basic User's Manual

obj = Doc.Objects.Item(3) ' correct usage

Since obj shown above is a WMObject object, you can only access theproperties available in WMObject objects (such as Name, ShowName, etc.).

In order to access body[3] as well as its methods and properties, use theWMDocument.Body method instead.

Example Sub Main()

' show the name of all the objects in the document

Dim Doc as WMDocument : Set Doc = WM.ActiveDocument

For I = 1 to Doc.Objects.Count

Doc.Objects.Item(I).ShowName = True

Next

End Sub

See Also WMDocument (object), WMObject (object), Collection (topic)

WMDocument.Output (method)Syntax WMDocument.Output(name$|id)

Description Returns the first WMOutput object that matches the given name or IDnumber, or the special value Nothing if none is found.

Comments The WMDocument.Output method takes one or the other of the followingparameters:

Parameter Description

name$ A String containing the name of the WMOutput object to be searched.The string match will not be case-sensitive.

id An Integer specifying the ID of the WMOutput.

Example Sub Main()

' Outputs the name of output[2]. Assumes that there exists

' output[2].

Dim D as WMDocument

Dim O as WMOutput

Set D = WM.ActiveDocument

Set O = D.Output(2)

If O is not Nothing then

MsgBox O.Name

Page 603: Working Model 2D - User's Manual

Chapter 3 WMDocument.Outputs (property) 599

End If

End Sub

See Also WMDocument (object), WMOutput (object)

WMDocument.Outputs (property)Syntax WMDocument.Outputs

Description Returns the collection of all WMOutput objects present in the document.

Comments The Outputs property is a collection of all WMOutput objects present inthe document. Like any other Collection objects, you can use the Itemmethod to access a specific output within the collection.

The Outputs property is read-only.

The index parameter given to the Item method is sequential within the setof constraints in the document. For example, if a document Doc has 10objects (bodies, constraints, etc.) and 3 of the 10 objects are outputs, theseconstraints may be referred to as Doc.Output(3), Doc.Output(6) andDoc.Output(7) with the Output method. With the Outputs property,these objects are referred to as Doc.Outputs.Item(1),Doc.Outputs.Item(2), and Doc.Outputs.Item(3), but not necessarilyin that order. The Outputs property is provided as a convenient tool toaccess all outputs in a loop statement (see Example), and the indices givento the Item are not permanently linked to individual WMOutput objects.

Example Sub Main()

' change all the outputs to digital meters

Dim D as WMDocument

Set D = WM.ActiveDocument

For I = 1 to D.Outputs.Count

D.Outputs.Item(I).Format = "digital"

Next

End Sub

See Also WMDocument (object), WMOutput (object), Collection (topic)

WMDocument.OverlapError (property)Syntax WMDocument.OverlapError

Description Specifies the Overlap Error of the Working Model document.

Comments OverlapError is a Double property. The property is equivalent to theOverlap Error in the Accuracy dialog of Working Model.

Page 604: Working Model 2D - User's Manual

600 Working Model Basic User's Manual

For a new document, the default value of OverlapError is determined byWorking Model automatically. The value varies according to the size andunit system of the model.

In order to specify OverlapError, you must first set AutoOverlapErrorto False.

Example Sub Main()

' Uses Fast simulation mode for the active document, and

' set the Overlap Error to 0.01

WM.ActiveDocument.SimulationMode = "Fast"

' At this point, AutoOverlapError is True and

' OverlapError has the value automatically determined by

' Working Model.

WM.ActiveDocument.AutoOverlapError = False

WM.ActiveDocument.OverlapError = 0.1

End Sub

See Also WMDocument (object), WMDocument.AutoOverlapError (property)

WMDocument.Paste (method)Syntax WMDocument.Paste

Description Pastes a selected set of objects from the Clipboard to the Working Modeldocument.

Comments The pasted location is automatically determined by Working Model.

The method is equivalent of the Paste menu item in the Edit menu.

Example (See WMDocument.Copy).

See Also WMDocument (object), WMDocument.Select (method),WMDocument.SelectAll (method), WMDocument.Cut (method),WMDocument.Copy (method)

WMDocument.PauseControl (method)Syntax WMDocument.PauseControl(index)

Description Returns the WMCell object representing the specified pause condition.

Comments The PauseControl method takes the following parameter.

Parameter Description

index An Integer specifying the pause condition. The value of index can be

Page 605: Working Model 2D - User's Manual

Chapter 3 WMDocument.PauseControlCount (property) 601

between 1 and PauseControlCount inclusive.

Each WMDocument object maintains a list of pause control conditions. Youcan use the PauseControl method to specify the formula expressions foreach pause condition. Use SetPauseControlType method to specify theaction to be taken (e.g. Pause, Reset, Loop) when the condition issatisfied.

For more information on pause control, please see the section onWMDocument.NewPauseControl method.

Example Sub Main()

' Creates a new pause control condition. If 3 or moreconditions exist,

' does not allow further additions.

Dim D as WMDocument

Set D = WM.ActiveDocument

if D.PauseControlCount < 3 then

D.NewPauseControl

D.PauseControl(D.PauseControlCount).Formula = "time > 2.5"

D.SetPauseControlType D.PauseControlCount, "reset"

else

MsgBox "Document already has 3 pause conditions!"

end if

End Sub

See Also WMDocument (object), WMDocument.NewPauseControl (method)WMDocument.PauseControlCount (property),WMDocument.SetPauseControlType (method),WMDocument.GetPauseControlType (method),WMDocument.DeletePauseControl (method)

WMDocument.PauseControlCount (property)Syntax WMDocument.PauseControlCount

Description Contains the current number (Integer) of pause control conditions.Read-only.

Comments Each WMDocument maintains a list of pause control conditions. ThePauseControlCount property keeps track of how many pause controlconditions are currently implemented. The PauseControlCount isinitially set to zero, as no pause condition is specified in a blankdocument.

Page 606: Working Model 2D - User's Manual

602 Working Model Basic User's Manual

When the NewPauseControl method is invoked, PauseControlCount isincremented by 1; the new PauseControlCount serves as the index forthe new condition. You must use the PauseControl method to specifythe formula expression for the pause condition, and use theSetPauseControlType method to specify the action to be taken (e.g.Pause, Reset, Stop, or Loop) when the condition is satisfied.

To delete a pause control condition, use the DeletePauseControlmethod. The DeletePauseControl method decrements thePauseControlCount by 1.

Example (See WMDocument.PauseControl)

See Also WMDocument (object), WMDocument.NewPauseControl (method)WMDocument.PauseControl (method),WMDocument.SetPauseControlType (method),WMDocument.GetPauseControlType (method),WMDocument.DeletePauseControl (method)

WMDocument.PlanetaryGravityConst (property)Syntax WMDocument.PlanetaryGravityConst

Description A Double which specifies the planetary gravity constant in the WorkingModel document.

Comments You must turn on the planetary gravity first in order for this constant totake effect in the Working Model document (see WMDocument.Gravity).The property PlanetaryGravityConst pertains to the gravitationalconstant G used in computing F = Gm1m2/r

2, where F is the force actingon every pair of bodies (whose masses are m1 and m2, respectively) in thedocument.

See WMDocument.LinearGravityConst to specify the gravitationalconstant g for linear gravity.

Example Sub Main()

' Sets up the planetary gravitational field.

Dim D as WMDocument : Set D = WM.ActiveDocument

D.Gravity = "planetary"

MsgBox "G = "+str$(D.PlanetaryGravityConst)

End Sub

See Also WMDocument (object), WMDocument.Gravity (property),WMDocument.LinearGravityConst (property)

Page 607: Working Model 2D - User's Manual

Chapter 3 WMDocument.PlayerMode (property) 603

WMDocument.PlayerMode (property)Syntax WMDocument.PlayerMode

Description A Boolean which specifies whether the document is in Player mode.

Comments When the PlayerMode property is True, the document is in Player mode.In Player mode, the toolbar, scroll bars, and most of the menu items aredisabled. The document cannot be modified interactively (withoutchoosing the Edit Mode first); the PlayerMode property must be set toFalse before any interactive modification is to be made.

Using WM Basic, you can modify documents in Player mode.

The default value of the PlayerMode is False.

Example Sub Main()

' Switch a document to player mode

WM.ActiveDocument.PlayerMode = True

End Sub

See Also WMDocument (object)

WMDocument.Point (method)Syntax WMDocument.Point(name | id)

Description Returns the first WMPoint object that matches the given name or IDnumber, or the special value Nothing if none is found.

Comments The WMDocument.Point method takes one or the other of the followingparameters:

Parameter Description

name A String containing the name of the WMPoint object to be searched. Thestring match will not be case-sensitive.

id An Integer specifying the ID of the WMPoint.

Example Sub Main()

' Outputs the name of point[5]. Assumes that point[5] exists.

Dim D as WMDocument

Dim P as WMPoint

Set D = WM.ActiveDocument

Set P = D.Point(5)

Page 608: Working Model 2D - User's Manual

604 Working Model Basic User's Manual

If P is not Nothing then

MsgBox P.Name

End If

End Sub

See Also WMDocument (object), WMPoint (object)

WMDocument.Points (property)Syntax WMDocument.Points

Description Returns the collection of all WMPoint objects present in the document.

Comments The Points property is a collection of all WMPoint objects present in thedocument. Like any other Collection objects, you can use the Itemmethod to access a specific point within the collection.

The Points property is read-only.

The index parameter given to the Item method is sequential within the setof points in the document. For example, if a document Doc has 10 objects(bodies, constraints, etc.) and 3 of the 10 objects are points, these pointsmay be referred to as Doc.Point(3), Doc.Point(6) and Doc.Point(7)with the Point method. With the Points property, these objects arereferred to as Doc.Points.Item(1), Doc.Points.Item(2), andDoc.Points.Item(3), but not necessarily in that order. The Pointsproperty is provided as a convenient tool to access all points in a loopstatement (see Example), and the indices given to the Item are notpermanently linked to individual WMPoint objects.

Example Sub Main()

' change the name of all points to "hinge"

Dim D as WMDocument

Dim B as WMBody

Set D = WM.ActiveDocument

For I = 1 to D.Points.Count

D.Points.Item(I).Name = "hinge"

Next

End Sub

See Also WMDocument (object), WMPoint (object), Collection (topic)

WMDocument.PowerUnit (property)Syntax WMDocument.PowerUnit

Page 609: Working Model 2D - User's Manual

Chapter 3 WMDocument.RetainMeterValues (property) 605

Description A String which specifies the power unit in the Working Modeldocument.

Comments The PowerUnit property can take one of the following.

Value Unit Description

Watts Watts (W).

Horsepower Horsepower (HP).

(null) None. (i.e., PowerUnit = "")

Both lower- and upper-case letters are accepted. The default value of thePowerUnit property is "Watts".

The property is overwritten when the user explicitly specifies theUnitSystem property of the document, because each unit system has a setof specifications for all measurement units.

Example See WMDocument.UnitSystem.

See Also WMDocument.UnitSystem (property), WMDocument.DecimalFormat(property), WMDocument.DecimalDigits (property)

WMDocument.RetainMeterValues (property)Syntax WMDocument.RetainMeterValues

Description A Boolean to specify whether the meter data from multiple simulationsare to be kept in memory.

Comments When RetainMeterValues is True, Working Model keeps the meter datafrom multiple simulations in memory. When the property is False, themeter data is flushed every time new simulation is run. Please refer to theWorking Model User's Manual for more information on the Retain MeterValues feature.

The default value of RetainMeterValues is False.

Use the EraseMeterValues method of the document to flush the memory.

Example (See WMDocument.EraseMeterValues)

See Also WMDocument.EraseMeterValues (method)

WMDocument.Reset (method)Syntax WMDocument.Reset

Description Resets a Working Model simulation.

Comments WMDocument.Reset has no effect if the simulation has not run or is atframe 0.

Page 610: Working Model 2D - User's Manual

606 Working Model Basic User's Manual

Example Sub Main()

' Erase History. Make sure that the current frame is 0.

Dim D as WMDocument : Set D = WM.ActiveDocument

If D.CurrentFrame <> 0 then

if MsgBox("Resetting first; ok?", ebOKCancel) = ebOK then

D.Reset

D.StartHere

end if

else

D.Reset

D.Starthere

end if

End Sub

See Also WMDocument (object), WMDocument.Reset (method)

WMDocument.RotationalVelocityUnit (property)Syntax WMDocument.RotationalVelocityUnit

Description A String which specifies the angular velocity unit in the Working Modeldocument.

Comments The RotationalVelocityUnit property can have one of the followingvalues.

Value Unit Description

Revs/Min Revolutions per minute.

(null) None. (i.e., RotationalVelocityUnit = "")

The default value of the RotationalVelocityUnit property is an emptystring ("", meaning null). When RotationalVelocityUnit is set tonull, Working Model displays the velocity unit as a composite unit basedon the setting in RotationUnit and TimeUnit. For example, whenRotationUnit is "Radians", TimeUnit is "Seconds", andRotationalVelocityUnit is null, then meters and Properties windowshow the velocity unit as "rad/s", or radians per second.

Both lower- and upper-case letters are accepted. The property isoverwritten when the user explicitly specifies the UnitSystem property ofthe document, because each unit system has a set of specifications for allmeasurement units.

Page 611: Working Model 2D - User's Manual

Chapter 3 WMDocument.RotationUnit (property) 607

Example See WMDocument.UnitSystem.

See Also WMDocument.UnitSystem (property), WMDocument.DecimalFormat(property), WMDocument.DecimalDigits (property)

WMDocument.RotationUnit (property)Syntax WMDocument.RotationUnit

Description A String which specifies the rotation unit in the Working Modeldocument.

Comments The RotationUnit property can take one of the following values.

Value Unit Description

Degrees Degrees.

Radians Radians.

Seconds Seconds.

Minutes Minutes.

Revolutions Revolutions.

Both lower- and upper-case letters are accepted. The default value of theRotationUnit property is "Degrees".

The property is overwritten when the user explicitly specifies theUnitSystem property of the document, because each unit system has a setof specifications for all measurement units.

Example See WMDocument.UnitSystem.

See Also WMDocument.UnitSystem (property), WMDocument.DecimalFormat(property), WMDocument.DecimalDigits (property)

WMDocument.Run (method)Syntax WMDocument.Run [frames]

Description Runs a Working Model simulation.

CommentsParameter Description

frames An Integer parameter specifying the number of frames to be run. Thesimulation will stop after computing the frame (frames)-1.

If the parameter frames is omitted, the simulation will run indefinitely. IfPause Control conditions are set, the simulation will stop as soon ascomputing the frame (frames)-1 or at least one of the pause conditions (ifspecified) is satisfied.

Page 612: Working Model 2D - User's Manual

608 Working Model Basic User's Manual

You can use the CurrentFrame property to access the current framenumber when the simulation is paused.

Note: The execution control is given to Working Model until the Runmethod has finished. To avoid running a never-ending script, werecommend providing the parameter frames and/or setting Pause Controlconditions (see WMDocument.NewPauseControl).

Example Sub Main()

' Runs the simulation for 25 frames and saves the result withhistory.

Dim D as WMDocument

Set D = WM.ActiveDocument

D.Run 25 ' Working Model starts the simulation.

' The remainder of the code is not executed until frame 24

' is calculated.

D.Reset

D.SaveAs "model1.wm", True ' saves the history, too.

End Sub

See Also WMDocument (object), WMDocument.Reset (method),WMDocument.CurrentFrame (property), WMDocument.NewPauseControl(method)

WMDocument.Save (method)Syntax WMDocument.Save

Description Saves the Working Model document.

Comments If the document has not been previously saved (i.e., the document is still“untitled”), Working Model will display a dialog prompting the filenameas well as folder/directory location. To avoid the confirmation dialog, usethe SaveAs method.

Example Sub Main()

' Saves the active document if it has a meaningful name

' other than "Untitled".

If InStr(WM.ActiveDocument.Name, "Untitled") then

MsgBox "Use SaveAs first to name the document."

Else

MsgBox "Saving " + WM.ActiveDocument.Name + "."

Page 613: Working Model 2D - User's Manual

Chapter 3 WMDocument.SaveAs (method) 609

WM.ActiveDocument.Save

End If

End Sub

See Also WMDocument (object), WMDocument.SaveAs (method)

WMDocument.SaveAs (method)Syntax WMDocument.SaveAs filename [, isHistorySaved]

Description Saves the Working Model document under the specified filename.

Comments The SaveAs method takes the following parameters.

Parameter Description

filename A String to specify the filename of the document is to be saved.

isHistorySaved (optional) A Boolean to specify whether the simulation history is to besaved. The history will be saved if True. The default value is False.

Example Sub Main()

'Save the current file with time history

Dim WM1 as WMDocument : Set WM1 = WM.ActiveDocument

If Basic.OS = ebMacintosh then

WM1.SaveAs "My Important Model", True

ElseIf Basic.Os = ebWin16 then

WM1.SaveAs "model1.wm", True

End If

End Sub

See Also WMDocument (object), WMDocument.Save (method)

WMDocument.ScaleFactor (property)Syntax WMDocument.ScaleFactor

Description A Double to specify the scale factor of the Working Model documentshown on the screen.

Comments ScaleFactor indicates how large or small the Working Model documentis displayed on the screen.

The ScaleFactor property is inversely proportional to the ViewWidthproperty of the document. Since the document pixel size is not affectedby modifying the ScaleFactor property, ViewWidth will automatically

Page 614: Working Model 2D - User's Manual

610 Working Model Basic User's Manual

double when ScaleFactor is halved, for example.

Please refer to the Working Model User's Manual for more information.

Example Sub Main()

' Sets the view size so that it displays 10 meters wide

' Also, focuses the origin at the center, and reports

' the current scale factor on the window.

Dim D as WMDocument : Set D = WM.ActiveDocument

D.UnitSystem = "si degrees"

D.ViewWidth = 10.0

D.ScrollTo 0, 0

MsgBox "Current Scale Factor: "+str$(D.ScaleFactor)

End Sub

See Also WMDocument.ViewWidth (property)

WMDocument.ScrollTo (method)Syntax WMDocument.ScrollTo x, y

Description Scrolls the document window to focus in a particular area of thedocument.

Comments You can use the ScrollTo method to shift the focus of the documentdisplay to the desired position. The method takes the followingparameters.

Parameter Description

x, y (x, y) global coordinates in the document.

The document will be scrolled so that (x, y) becomes the center of thedocument.

You can also modify ScaleFactor and ViewSize properties to change theoutlook of the document.

Example (See WMDocument.ScaleFactor)

See Also WMDocument.ScaleFactor (property), WMDocument.ViewWidth (property)

WMDocument.Select (method)Syntax WMDocument.Select object [, state]

Description Selects or de-selects the specified object in the document.

Page 615: Working Model 2D - User's Manual

Chapter 3 WMDocument.SelectAll (method) 611

Comments The WMDocument.Select method takes the following parameters:

Parameter Description

object An object of type WMObject (which includes WMBody, WMConstraint,WMInput, WMOutput, and WMPoint).

state An Boolean specifying whether the object is to be selected (if True) ordeselected (if False). The parameter is optional, and tthe default value isTrue.

This method does the equivalent of a “shift-select” in the UI. That is, thespecified object is added/removed from the collection of selected objects.Other selected objects remain selected. If you want only the specifiedobject to be selected, you must first use WMDocument.SelectAll toensure that all other objects are deselected.

Example Sub Main()

' Select point[5]. Assumes that there exists point[5] in

' the active document.

Dim D as WMDocument

Dim P as WMPoint

Set D = WM.ActiveDocument

Set P = D.Point(5)

D.Select P, True '"True" is optional.

End Sub

See Also WMDocument (object), WMObject (object)

WMDocument.SelectAll (method)Syntax WMDocument.SelectAll [state]

Description Selects or de-selects all objects in the document.

Comments The WMDocument.SelectAll method takes the following parameter:

Parameter Description

state An optional Boolean specifying whether all objects are to be selected (ifTrue) or de-selected (if False). The parameter is optional, and the defaultvalue is True.

Example Sub Main()

' De-selects all objects in the document.

Dim D as WMDocument

Page 616: Working Model 2D - User's Manual

612 Working Model Basic User's Manual

Set D = WM.ActiveDocument

D.SelectAll False

End Sub

See Also WMDocument (object)

WMDocument.Selection (property)Syntax WMDocument.Selection

Description An object that represents a collection of WMObject objects selected in thedocument.

Comments WMDocument.Selection itself is a read-only property. The property isautomatically updated when objects are selected or de-selected. Forexample, if you select two objects, Selection represents those two objects.Count will return 2, and Item(1) and Item(2) will return the objectsselected.

The Selection property further has the following properties and methods.

Property Description

Count A read-only Integer that contains the number of objects currentlyselected. The number will increase / decrease as you select more / lessobjects (see WMDocument.Select and WMDocument.SelectAll).

Method Description

Item (n) Returns the nth object in the selection. The returned object may be aWMBody, WMConstraint, WMPoint, WMOutput, or WMInput. This propertycan only be assigned to a variable of type WMObject. This method is onlyof use in looping over all selected objects, regardless of their type andchecking, or modifying, some common property at the WMObject level(like name or id).

Body (n) Returns the nth WMBody object in the selection. If there are fewer than nWMBody objects selected, the return value will be nothing.

Constraint (n) Returns the nth WMConstraint object in the selection. If there are fewerthan n WMConstraint objects selected, the return value will be nothing.

Point (id) Returns the nth WMPoint object in the selection. If there are fewer than nWMPoint objects selected, the return value will be nothing.

Input (n) Returns the nth WMInput object in the selection. If there are fewer than nWMInput objects selected, the return value will be nothing.

Page 617: Working Model 2D - User's Manual

Chapter 3 WMDocument.SetPauseControlType (method) 613

Output (n) Returns the nth WMOutput object in the selection. If there are fewer thann WMOutput objects selected, the return value will be nothing.

Example Sub Main()

' Picks the first object in the document and determines

' its type. If the object is not body, constraint, or point,yields

' a message. (In that case, the object could be an input oroutput.)

Dim B as WMBody

Dim C as WMConstraint

Dim P as WMPoint

Dim D as WMDocument

Set D = WM.ActiveDocument

D.SelectAll

If D.Selection.Item(1) is Nothing Then

' no object exists in the document

Exit Sub

End If

If D.Selection.Item(1).Kind = "body" Then

Set B = D.Selection.Body(1)

ElseIf D.Selection.Item(1).Kind = "constraint" Then

Set C = D.Selection.Constraint(1)

ElseIf D.Selection.Item(1).Kind = "point" Then

Set P = D.Selection.Point(1)

Else

MsgBox "Object 1 is neither body, constraint, nor point!"

End If

End Sub

See Also WMObject (object), WMDocument.Select (method), WMDocument.SelectAll(method)

WMDocument.SetPauseControlType (method)Syntax WMDocument.SetPauseControlType index, condition

Description Specifies the action to be taken when the indexed pause condition is

Page 618: Working Model 2D - User's Manual

614 Working Model Basic User's Manual

satisfied.

Comments The SetPauseControlType method takes the following parameter.

Parameter Description

index An Integer specifying the pause condition. The value of index can bebetween 1 and PauseControlCount inclusive.

condition A String which specifies the action. See below.

The parameter condition takes one of the following values:

Value Description

"pause" Pauses the simulation when the condition is satisfied. The user can clickthe Run button to continue the simulation.

"stop" Stops the simulation when the condition is satisfied. The user cannot clickthe Run button to continue the simulation. After the simulation is stoppedwith this pause condition, the user must remove or modify this pausecondition to continue the simulation further.

"reset" Resets the simulation to frame 0 when the condition is satisfied.

"loop" Loops the simulation when the condition is satisfied. The simulation willbe repeated indefinitely.

To retrieve the condition, use the GetPauseControlType method.

For more information on pause control, please see the section onWMDocument.NewPauseControl method.

Example (See WMDocument.PauseControl)

See Also WMDocument (object), WMDocument.NewPauseControl (method)WMDocument.PauseControlCount (property), WMDocument.PauseControl(method), WMDocument.GetPauseControlType (method),WMDocument.DeletePauseControl (method)

WMDocument.ShowCoordinates (property)Syntax WMDocument.ShowCoordinates

Description A Boolean to show whether the Coordinates bar is turned on in theWorking Model document.

Comments ShowCoordinates is True if the coordinates bar is displayed; Falseotherwise. Changing the Coordinates bar display status will enable theSave menu item.

Example Sub Main()

' Show Coordinates bar. Notifies the user if it is already on.

Page 619: Working Model 2D - User's Manual

Chapter 3 WMDocument.ShowGridLines (property) 615

Dim D as WMDocument

Set D = WM.ActiveDocument

if D.ShowCoordinates = True then

MsgBox "Coordinates bar is already on"

else

D.ShowCoordinates = True

end if

End Sub

See Also WMDocument (object)

WMDocument.ShowGridLines (property)Syntax WMDocument.ShowGridLines

Description A Boolean to show whether the grid lines are displayed in the WorkingModel document.

Comments ShowGridLines is True if the grid lines are displayed; False otherwise.Changing the grid line display status will enable the Save menu item.

Example Sub Main()

' Show grid lines. Warns the user if they are already on.

Dim D as WMDocument

Set D = WM.ActiveDocument

if D.ShowGridLines = True then

MsgBox "Grid lines are already on"

else

D.ShowGridLines = True

end if

End Sub

See Also WMDocument (object)

WMDocument.ShowHelpRibbon (property)Syntax WMDocument.ShowHelpRibbon

Description A Boolean to show whether the Help Ribbon is displayed in the WorkingModel document.

Comments ShowHelpRibbon is True if the Help Ribbon is displayed; Falseotherwise. Changing the Help Ribbon display status will enable the Save

Page 620: Working Model 2D - User's Manual

616 Working Model Basic User's Manual

menu item.

Example Sub Main()

' Hide Help Ribbon. Warns the user if it is already off.

Dim D as WMDocument

Set D = WM.ActiveDocument

if D.ShowHelpRibbon = False then

MsgBox "Help Ribbon is already off"

else

D.ShowHelpRibbon = False

end if

End Sub

See Also WMDocument (object)

WMDocument.ShowRulers (property)Syntax WMDocument.ShowRulers

Description A Boolean to show whether the rulers are displayed in the WorkingModel document.

Comments ShowRulers is True if the rulers are displayed; False otherwise.Changing the ruler display status will activate the Save menu item.

Example Sub Main()

' Show Rulers. Warns the user if it is already on.

Dim D as WMDocument

Set D = WM.ActiveDocument

if D.ShowRulers = True then

MsgBox "Rulers are already on"

else

D.ShowRulers = True

end if

End Sub

See Also WMDocument (object)

WMDocument.ShowScrollBars (property)Syntax WMDocument.ShowScrollBars

Page 621: Working Model 2D - User's Manual

Chapter 3 WMDocument.ShowTapeControl (property) 617

Description A Boolean to show whether the scroll bars are displayed in the WorkingModel document.

Comments ShowScrollBars is True if the rulers are displayed; False otherwise.Changing the scroll bars display status will enable the Save menu item.

Example Sub Main()

' Hide scroll bars. Warns the user if they are already off.

Dim D as WMDocument

Set D = WM.ActiveDocument

if D.ShowScrollBars = False then

MsgBox "Scroll bars are already turned off"

else

D. ShowScrollBars = False

end if

End Sub

See Also WMDocument (object)

WMDocument.ShowTapeControl (property)Syntax WMDocument.ShowTapeControl

Description A Boolean to show whether the tape control is displayed in the WorkingModel document.

Comments ShowTapeControl is True if the Tape Control is displayed; Falseotherwise. Changing the Tape Control display status will enable the Savemenu item.

Example Sub Main()

' Hide Tape Control. Warns the user if it is already off.

Dim D as WMDocument

Set D = WM.ActiveDocument

if D.ShowTapeControl = False then

MsgBox "Tape Control is already off"

else

D. ShowTapeControl = False

end if

End Sub

See Also WMDocument (object)

Page 622: Working Model 2D - User's Manual

618 Working Model Basic User's Manual

WMDocument.ShowToolPalette (property)Syntax WMDocument.ShowToolPalette

Description A Boolean to show whether the Toolbar is displayed in the WorkingModel document.

Comments ShowToolPalette is True if the Toolbar is displayed; False otherwise.Changing the Toolbar display status will enable the Save menu item.

Example Sub Main()

' Hide Tool Palette. Warns the user if it is already off.

Dim D as WMDocument

Set D = WM.ActiveDocument

if D.ShowToolPalette = False then

MsgBox "Tool palette is already off"

else

D. ShowToolPalette = False

end if

End Sub

See Also WMDocument (object)

WMDocument.ShowXYAxes (property)Syntax WMDocument.ShowXYAxes

Description A Boolean to show whether the global x- and y-axes are displayed in theWorking Model document.

Comments ShowXYAxes is True if the axes are displayed; False otherwise. Changingthe axes display status will enable the Save menu item.

Example Sub Main()

' Show XY Axes. Warns the user if it is already on.

Dim D as WMDocument

Set D = WM.ActiveDocument

if D.ShowXYAxes = True then

MsgBox "Axes are already on"

else

D.ShowXYAxes = True

end if

Page 623: Working Model 2D - User's Manual

Chapter 3 WMDocument.SignificantDigits (property) 619

End Sub

See Also WMDocument (object)

WMDocument.SignificantDigits (property)Syntax WMDocument.SignificantDigits

Description Specifies the Significant Digits of the Working Model document.

Comments SignificantDigits is an Integer property. The property is equivalentto the Significant Digits in the Accuracy dialog of Working Model. Thevalue of SignificantDigits can range from 1 to 16. Attempts to assignan out-of-range value are silently ignored while the value ofSignificantDigits remains unchanged.

For a new document, the default value of SignificantDigits isdetermined by Working Model automatically. The value varies accordingto the size and unit system of the model.

In order to specify SignificantDigits, you must first setAutoSignificantDigits to False.

Example Sub Main()

' Uses Fast simulation mode for the active document, and

' set the Significant Digits to 10

WM.ActiveDocument.SimulationMode = "Fast"

' At this point, AutoSignificantDigits is True and

' SignificantDigits has the value automatically determined by

' Working Model.

WM.ActiveDocument.AutoSignificantDigits = False

WM.ActiveDocument.SignificantDigits = 10

End Sub

See Also WMDocument (object), WMDocument.AutoSignificantDigits (property)

WMDocument.SimulationMode (property)Syntax WMDocument.SimulationMode

Description Specifies the current simulation mode for the WMDocument object.

Comments SimluationMode is a String property. Setting the property is exactlyequivalent to choosing the simulation mode in the Accuracy dialog ofWorking Model. All other simulation parameters (such as time step andactive warnings) are automatically determined when the simulation modeis specified to be either Fast or Accuracy. Please refer to the Working

Page 624: Working Model 2D - User's Manual

620 Working Model Basic User's Manual

Model User's Manual for more information.

The property can be one of the following. In particular, the Fast andAccurate modes have predefined parameters for the simulation accuracy.

Parameter Description

fast The Fast mode. Employs the Euler method as the integrator.

accurate The Accurate mode. Employs the Kutta-Merson method as the integrator.

custom No default values.

All documents have Accurate as the default simulation mode.

Example Sub Main()

' Sets the simulation mode of the active document to

' the Fast mode.

Dim D as WMDocument

Set D = WM.ActiveDocument

D.SimulationMode = "Fast"

End Sub

See Also WMDocument (object), WMDocument.Integrator (property)

WMDocument.SkipFrames (property)Syntax WMDocument.SkipFrames

Description An Integer to specify the frame skip rate used in animation.

Comments SkipFrames specifies the rate of frame refresh while animating thesimulation result.

The default value of SkipFrames is 1, indicating that every frame isdisplayed. When set to 2, for example, the animation will skip every otherframe.

Example Sub Main()

' Change the skip frame rate of the active document to 4

WM.ActiveDocument.SkipFrames = 4

End Sub

See Also WMDocument (object)

WMDocument.Split (method)Syntax WMDocument.Split

Page 625: Working Model 2D - User's Manual

Chapter 3 WMDocument.StartHere (method) 621

Description Split objects that are selected and joined in the document.

Comments The WMDocument.Split performs the Split operation on objects that areselected and ready to be split in the document. For example, a pin jointcan be split into two point elements. If a body is selected and it iscurrently attached to something with a joint, then that joint will be splitalso.

Example Sub Main()

' Pins a rectangle the background, splits the pin joint

' (just to show the effect of split), and runs the simulation.

Dim D as WMDocument : Set D = WM.ActiveDocument

Dim Rect as WMBody

Dim Joint as WMConstraint

Set Rect = D.NewBody("rectangle")

Rect.Width.Value = 1.0 : Rect.Height.Value = 2.0

Set Joint = D.NewConstraint("pin")

Set Joint.Point(2).Body = Rect

D.SelectAll False ' Deselect all objects first

D.Select Rect ' Select the rectangle

D.Split

D.Run 25 ' the rectangle will fall

D.Reset

End Sub

See Also WMDocument (object), WMObject (object)

WMDocument.StartHere (method)Syntax WMDocument.StartHere

Description Erases the simulation history stored in memory, and sets the current frameto be the initial frame for the next simulation.

Comments The StartHere method has no effect on the current frame. The methodsimply erases all the simulation history (if any), and sets the current frame(contained in the CurrentFrame property of the document) as the initialframe (frame 0).

As a result of the StartHere method, both HistoryFrames andCurrentFrame properties will be set to 0.

Example (See WMDocument.Reset)

Page 626: Working Model 2D - User's Manual

622 Working Model Basic User's Manual

See Also WMDocument (object), WMDocument.Run (method), WMDocument.Reset(method), WMDocument.CurrentFrame (property),WMDocument.HistoryFrames (property)

WMDocument.TimeUnit (property)Syntax WMDocument.TimeUnit

Description A String which specifies the time unit in the Working Model document.

Comments The TimeUnit property can have one of the following values.

Value Unit Description

Seconds Seconds (with s as unit display for meters).

Seconds (sec) Seconds (with sec as unit display for meters).

Minutes Minutes.

Hours Hours (with h as unit display for meters).

Hours (hr) Hours (with hr as unit display for meters).

Milliseconds Milliseconds.

Years Years.

Microseconds Microseconds.

Days Days.

Both lower- and upper-case letters are accepted. The default value of theTimeUnit property is "Seconds".

The property is overwritten when the user explicitly specifies theUnitSystem property of the document, because each unit system has a setof specifications for all measurement units.

Example See WMDocument.UnitSystem.

See Also WMDocument.UnitSystem (property), WMDocument.DecimalFormat(property), WMDocument.DecimalDigits (property)

WMDocument.Tracking (property)Syntax WMDocument.Tracking

Description An Integer to specify the tracking rate used in animation.

Comments The Tracking property specifies the rate at which a traced track isdisplayed in the Working Model document.

The default value of Tracking is 0, indicating that no traced track isdisplayed. When set to 1, for example, the animation will leave traced

Page 627: Working Model 2D - User's Manual

Chapter 3 WMDocument.UnitSystem (property) 623

track every frame.

Example Sub Main()

' track every 6 frames in the current document

Dim Brick as WMBody

Dim Doc as WMDocument : Set Doc = WM.ActiveDocument

Doc.Gravity = "linear"

Set Brick = Doc.NewBody("square")

Brick.Mass.Value = 1.0

WM.ActiveDocument.Tracking = 6

WM.ActiveDocument.Run 100 ' run for 100 frames and see

End Sub

See Also WMDocument.SkipFrames (property)

WMDocument.UnitSystem (property)Syntax WMDocument.UnitSystem

Description A String which specifies the unit system currently employed in theWorking Model document.

Comments The UnitSystem property can be one of the following.

Value Description

astronomical Astronomical (e.g., light-years for disatance, years for time).

atomic Atomic (e.g., nanometers for distance, atomic mass unit for mass).

cgs The CGS unit system (e.g., centimeters for distance, grams for mass,seconds for time).

si degree The SI unit system (e.g., meters for distance, kilograms for mass, secondsfor time) with degrees as the angular measurement.

si radian The SI unit system (e.g., meters for distance, kilograms for mass, secondsfor time) with radians as the angular measurement.

english (pounds) English system (e.g., inches fordistance, seconds for time) with pounds as the mass measurement (withacceleration on Earth built-in; therefore 0.45 kilogram of mass istranslated to 1 pound).

english (slugs) English system (e.g., inches fordistance, seconds for time) with slugs as the mass measurement.

undefined Any unit system that does not fall into the above descriptions.

Page 628: Working Model 2D - User's Manual

624 Working Model Basic User's Manual

The default value is "si degrees".

Each unit system has a set of specifications for units used in variousmeasurements. Therefore, assigning the UnitSystem property overridesthe setting given in unit properties of the WMDocument object, such asDistanceUnit, MassUnit, and TimeUnit.

For example, if you assign the UnitSystem property to "english(pounds)", then DistanceUnit, MassUnit, and TimeUnit of thedocument will be changed to "inches", "pounds", and "seconds",regardless of the previous setting of these units.

If you change any of the individual measurement units, the UnitSystemproperty will be automatically changed to "undefined", reflecting thefact that the unit system may no longer conform to the one previouslyspecified.

Example Sub Main()

' Starts out with English (pounds) unit system,

' and modifies various unit systems.

Dim D as WMDocument

Set D = WM.ActiveDocument

D.UnitSystem = "english earth pounds"

' At this point, various units are set to default; for example,

' length unit is set to inches, and mass unit is set to pounds.

' For details on each units, see individual sections.

D.DistanceUnit = "feet"

D.TimeUnit = "minutes"

D.MassUnit = "milligrams"

D.ChargeUnit = "Statcoulombs"

D.RotationUnit = "Revolutions"

D.ElectricPotentialUnit = "" ' "" means null string.

D.ForceUnit = "Poundals"

D.EnergyUnit = "Kilocalories"

D.PowerUnit = "Horsepower"

D.FrequencyUnit = "Hertz"

D.VelocityUnit = "Miles per Hour"

D.RotationalVelocityUnit = "Revs/Min"

End Sub

Page 629: Working Model 2D - User's Manual

Chapter 3 WMDocument.Update (method) 625

See Also WMDocument.DecimalDigits (property), WMDocument.DecimalFormat(property)

WMDocument.Update (method)Syntax WMDocument.Update

Description Updates the Working Model document screen to reflect the modificationsmade on any WMCell object.

Comments For performance reasons, when a WMCell object property is modified(e.g., position of a circle, dimension of a rectangle), the document screenwill not be updated until the script is terminated. If you wish to see theresult of a modification immediately, use the Update method tosynchronize the Working Model document window with the currentWMCell object settings.

Note: Any modification on WMCell is immediately recorded in theWorking Model database. Computational results of a simulation isunaffected whether or not the Update method is used. The Updatemethod is only necessary to “refresh” the document screen (i.e., for visualrendering).

You may find the method useful in debugging (to see the effect of a codestep-by-step) and for presentation purposes (to demonstrate animatedresults for audience).

Example Sub Main()

' Moves the circle from 0.0 to 2.0 incrementally by 0.2. Themotion of

' the circle is rendered on the screen as it is repositionedeach time.

' Without the Update, you will only see a circle positioned at(2, 0) at

' the end (i.e., no animation).

Dim Doc as WMDocument, Disk as WMBody

Set Doc = WM.ActiveDocument

Set Disk = Doc.NewBody("circle")

For I = 0.0 to 2.0 Step 0.2

Disk.PX.Value = I

Doc.Update ' comment out this line and see how theresults differ

Next I

End Sub

Page 630: Working Model 2D - User's Manual

626 Working Model Basic User's Manual

See Also WMDocument (object), WMDocument.Reset (method),WMDocument.CurrentFrame (property)

WMDocument.VariableIntegrationStep (property)Syntax WMDocument.VariableIntegrationStep

Description Specifies whether the integration step is to be variable or fixed for theWMDocument object.

Comments VariableIntegrationStep is a Boolean property. Setting the propertyis exactly equivalent to checking the variable time step button in theAccuracy dialog of Working Model.

When the property is True, Working Model will automatically use thevariable time step.

The value of VariableIntegrationStep is set automatically to True orFalse, when you specify the SimulationMode to Accurate or Fast,respectively.

Since the default SimulationMode is Accurate, the default value ofVariableIntegrationStep is True.

Example Sub Main()

' Sets the simulation mode to Accurate mode, then sets the

' integration step to fixed mode.

Dim D as WMDocument

Set D = WM.ActiveDocument

D.SimulationMode = "Accurate"

' at this point VariableIntegrationStep is True, because

' Accurate mode imposes the default setting.

D.VariableIntegrationStep = False

End Sub

See Also WMDocument (object), WMDocument.SimulationMode (property),WMDocument.IntegrationStep (property)

WMDocument.VelocityUnit (property)Syntax WMDocument.VelocityUnit

Description A String which specifies the velocity unit in the Working Modeldocument.

Comments The VelocityUnit property can take one of three values as follows.

Page 631: Working Model 2D - User's Manual

Chapter 3 WMDocument.ViewWidth (property) 627

Value Unit Description

Speed of Light Speed of light (c).

Miles per Hour Miles per hour (mph).

(null) None. (i.e., VelocityUnit = "")

The default value of the VelocityUnit property is null (can be specifiedas a null string, or "").

Both lower and upper case letters are accepted. The property isoverwritten when the user explicitly specifies the UnitSystem property ofthe document, because each unit system has a set of specification for allmeasurement units.

When VelocityUnit is set to null, Working Model displays the velocityunit as a composite unit based on the setting in DistanceUnit andTimeUnit. For example, when DistanceUnit is "m" TimeUnit is "s",and VelocityUnit is "" (null), then meters and Properties window showthe velocity unit as "m/s", or meters per second.

Example See WMDocument.UnitSystem.

See Also WMDocument.UnitSystem (property), WMDocument.DecimalFormat(property), WMDocument.DecimalDigits (property)

WMDocument.ViewWidth (property)Syntax WMDocument.ViewWidth

Description A Double to specify the length represented by the horizontal ruler of theWorking Model document shown on the screen.

Comments ViewWidth indicates the length represented by the width of the WorkingModel document. The number given in ViewWidth is interpreted in thecurrent unit system.

The ViewWidth property is inversely proportional to the ScaleFactorproperty of the document. Since the document pixel size is not affectedby modifying the ViewWidth property, ScaleFactor will automaticallydouble when ViewWidth is halved, for example.

Example (See WMDocument.ScaleFactor)

See Also WMDocument.ScaleFactor (property)

WMDocument.WarnInaccurate (property)Syntax WMDocument.WarnInaccurate

Description Specifies whether the warning dialog for Inaccurate Integration is enabled.

Page 632: Working Model 2D - User's Manual

628 Working Model Basic User's Manual

Comments WarnInaccurate is a Boolean property. Setting the property to True isexactly equivalent to checking the Inaccurate Integration Warning checkbox in the Accuracy dialog of Working Model.

When the property is True, Working Model will bring up a warningdialog box when it detects the presence of a large velocity or accelerationin the simulation, which may cause instability in the system. Please referto the Working Model User's Manual for more information on thiswarning.

The value of WarnInaccurate is set automatically to False or True,when you specify the SimulationMode to Accurate or Fast,respectively.

Since the default SimulationMode is Accurate, the default value ofWarnInaccurate is False.

Example Sub Main()

' Sets the simulation mode to Accurate mode, except

' enable the large-velocity-or-acceleration warning.

Dim D as WMDocument

Set D = WM.ActiveDocument

D.SimulationMode = "Accurate"

' at this point WarnInaccurate is False, because

' Accurate mode imposes the default setting.

D.WarnInaccurate = True

End Sub

See Also WMDocument (object), WMDocument.SimulationMode (property)

WMDocument.WarnInconsistent (property)Syntax WMDocument.WarnInconsistent

Description Specifies whether the warning dialog for inconsistent constraints isenabled.

Comments WarnInconsistent is a Boolean property. Setting the property to True isexactly equivalent to checking the Inconsistent Constraints Warning checkbox in the Accuracy dialog of Working Model.

When the property is True, Working Model will bring up a warningdialog box when it detects an inconsistent constraint during thesimulation. Inconsistent constraints may introduce excessive force in thesimulation and render the system unstable. Please refer to the WorkingModel User's Manual for more information on this warning.

Page 633: Working Model 2D - User's Manual

Chapter 3 WMDocument.WarnOverlap (property) 629

The value of WarnInconsistent is set automatically to True or False,when you specify the SimulationMode to Accurate or Fast,respectively.

Since the default SimulationMode is Accurate, the default value ofWarnInconsistent is True.

Example Sub Main()

' Sets the simulation mode to Fast mode, except

' enable the Inconsistent Constraints Warning.

Dim D as WMDocument

Set D = WM.ActiveDocument

D.SimulationMode = "Fast"

' at this point WarnInconsistent is False, because

' Fast mode imposes the default setting.

D.WarnInconsistent = True

End Sub

See Also WMDocument (object), WMDocument.SimulationMode (property),WMDocument.WarnRedundant (property)

WMDocument.WarnOverlap (property)Syntax WMDocument.WarnOverlap

Description Specifies whether the warning dialog for Initial body Overlap is enabled.

Comments WarnOverlap is a Boolean property. Setting the property to True isexactly equivalent to checking the Initial Body Overlap Warning checkbox in the Accuracy dialog of Working Model.

When the property is True, Working Model will bring up a warningdialog box when it detects two or more bodies are overlapping more thana specified tolerance (set in the PositionalError property) at the firstframe of the simulation. Large overlap between objects may introduceexcessive force in the simulation and render the system unstable. Pleaserefer to the Working Model User's Manual for more information on thiswarning.

The value of WarnOverlap is set automatically to True, when you specifythe SimulationMode to Accurate or Fast.

Since the default SimulationMode is Accurate, the default value ofWarnOverlap is True.

Example Sub Main()

Page 634: Working Model 2D - User's Manual

630 Working Model Basic User's Manual

' In order to prevent unstable simulations,

' checks to make sure the overlap warning is on.

Dim D as WMDocument

Set D = WM.ActiveDocument

If D.WarnOverlap = False then

MsgBox "Overlap warning should be on! Turning it on..."

D.WarnOverlap = True

End If

End Sub

See Also WMDocument (object), WMDocument.SimulationMode (property),WMDocument.PostionalError (property)

WMDocument.WarnRedundant (property)Syntax WMDocument.WarnRedundant

Description Specifies whether the warning dialog for redundant constraints is enabled.

Comments WarnRedundant is a Boolean property. Setting the property to True isexactly equivalent to checking the Redundant Constraints Warning checkbox in the Accuracy dialog of Working Model.

When the property is True, Working Model will bring up a warningdialog box when it detects a redundant constraints during the simulation.Redundant constraints may introduce excessive force in the simulationand render the system unstable. Please refer to the Working Model User'sManual for more information on this warning.

The value of SimulationMode has no bearings to the value of theWarnRedundant property.

The default value of WarnRedundant is False.

Example Sub Main()

' Sets the simulation mode to Fast mode, and

' enable the Redundant Constraints warning.

Dim D as WMDocument

Set D = WM.ActiveDocument

D.SimulationMode = "Fast"

D. WarnRedundant = True

End Sub

See Also WMDocument (object), WMDocument.SimulationMode (property),

Page 635: Working Model 2D - User's Manual

Chapter 3 WMInput (object) 631

WMDocument.WarnInconsistent (property)

WMInput (object)Syntax WMInput

Description An object which provides an interface to input controls used in WorkingModel simulations.

Comments To create a new WMInput object in a Working Model document, use theNewInput method of the WMDocument object.

To specify which object is to be controlled by the WMInput object, youneed to modify the properties of the target object itself (see Examplebelow).

A WMInput object has the following properties.

Property Description

Kind String indicating the type of the object (WMInput). The property is read-only.

Value Double containing the current value of the input.

Format String which indicates the input format. Can be "Slider", "Table","Button" or "TextBox". The format types correspond to the input typespecified in the Properties window.

Min Double to specify the minimum bound of the input. Any Value specifiedbelow Min will be truncated to Min.

Max Double to specify the maximum bound of the input. Any Value specifiedin excess of Max will be truncated to Max.

X, Y Integer to specify the (x, y) coordinates that describe the position of theWMInput object in the document. The values are measured in pixelcoordinates, where the top-left corner of the document window is (0, 0).The x-coordinate increases toward the right edge of the screen, whereasthe y-coordinate increases downward to the bottom of the screen.

Page 636: Working Model 2D - User's Manual

632 Working Model Basic User's Manual

(0, 0)X

Y

Height, Width Integer to specify the height and width of the WMInput object in theWorking Model document. As in X and Y properties, Height and Widthare given in pixel units.

The following properties are applicable only when Format is "Slider".

Property Description

Snaps Integer to determine the number of snaps between given Min and Maxvalues. Working Model divides the range between Min and Max intoequal-sized intervals, so that the slider only snaps at Min, Max, and(Snaps-1) steps in between.

Snaps only affects the mouse-dragging of the slider. Therefore, if a WMBasic script specifies Value to be a quantity that does not fall into any ofthe snapping values, Working Model will accept the number as given (aslong as the value is within the range specified by Min and Max).

ShowText Boolean to indicate whether a text box will be displayed alongside theinput slider. When ShowText is True, the text box will be displayed.

The following property is applicable only when Format is "Button".

Property Description

Momentary Boolean. When Momentary is set to True, the WMInput object (a button,since Format is "Button") becomes active only for the duration in whichthe mouse button is held down. When False, the button acts as a toggleswitch.

The following properties and method are applicable only when Format is"Table".

Property/method Description

DataColumn Integer to specify which column in the file is to be read as a datacolumn. Default value is 1.

TimeColumn Integer to specify which column in the file is to be read as a time

Page 637: Working Model 2D - User's Manual

Chapter 3 WMObject (object) 633

column. Default value is 0, indicating that each row of data correspondsto a single Animation Step.

ReadTable A method to read the data table. Syntax is:

[WMInput].ReadTable filename

where the parameter filename is a String specifying the name of the datafile.

Example Sub Main()

'Creates a square and sets the slider bar to control

'its initial x-position.

Dim D as WMBody

Dim I as WMInput

Dim id as Integer

Set D = WM.ActiveDocument.NewBody("square")

Set I = WM.ActiveDocument.NewInput()

id = I.ID

D.PX.Formula = "input[" + str$(id) + "]"

End Sub

See Also WMOutput (object), WMDocument.NewInput (method)

WMObject (object)Syntax WMObject

Description WMObject provides an interface to attributes common to on-screen objectsin a Working Model document.

Comments WMObject is the parent object of WMBody, WMConstraint, WMPoint,WMInput, and WMOutput, in that these classes inherit properties/methods ofWMObject. An object of any of these five types will also haveproperties/methods of the parent.

A WMObject object has the properties and methods shown below.Accordingly, objects of type WMBody, WMConstraint, WMPoint, WMInput,and WMOutput have all these properties, except X, Y that are only availableto WMInput and WMOutput objects.

The properties X and Y control the screen location of the object and haveno effect on bodies, points and constraints because the screen location isdetermined by scrolling (see WMDocument.ScrollTo).

The properties Width and Height are also available to WMBody objects.However, for a WMBody object, the properties are of type WMCell, and they

Page 638: Working Model 2D - User's Manual

634 Working Model Basic User's Manual

are evaluated in the current distance unit instead of pixels.

Property Description

ID A read-only Integer. Every WMObject object is assigned a uniqueidentification number regardless of its kind. As a general rule, the numberis assigned in the order the object is created.

The ID number is identical to the one used in Working Model's formulalanguage (such as body[5], or constraint[3]).

Kind A read-only String. Every WMObject object “knows” its kind. Forexample, a force object (which is of type WMConstraint) has the Kindstring set to "force" as soon as the object is created. This informationcan be used to identify the object type and define conditional statements.

Every character in the Kind string is in lower-case, and the comparisonneeds to be case-sensitive. For instance, given a force object (Kind ="force"), the comparison:

Force.Kind = "force"

returns True, whereas:Force.Kind = "Force"

returns False.

Name String. Every WMObject object has a default name, depending on itsKind. For example, a body has a default name "rectangle", "polygon","square" or "circle", depending on its geometry. The Name property isfor information only, and the user can freely modify the property.

The Name string always appears on utility windows (Properties, Geometry,and Appearance). You can also display the Name string on the WorkingModel simulation by setting the ShowName property to True (seeShowName below).

Show Boolean to indicate whether the object is visible on the Working Modelsimulation window. You can hide objects by setting the Show to False.The default value for Show is True.

ShowName Boolean to indicate whether the Name property of the object is visible onthe Working Model simulation window. You can display the name(custom-definable; see Name above) of each object when you run thesimulation. The Name is displayed near the frame of reference of theobject. The default value of ShowName is False.

X, Y Integer pixel coordinates to indicate the position of the object on thescreen. These properties are needed for objects of type WMInput andWMOutput, since unlike other objects in Working Model, these objects arenot associated with any other coordinate system besides the pixel map onthe screen.

Page 639: Working Model 2D - User's Manual

Chapter 3 WMObject (object) 635

Height, Width Integer pixel size of the WMInput or WMOutput objects. (Height andWidth are WMCell objects in WMBody objects.)

Method Description

Body() This method casts (converts) the WMObject to WMBody (see Example).

Constraint() This method casts the WMObject to WMConstraint (see Example).

Input() This method casts the WMObject to WMInput (see Example).

Output() This method casts the WMObject to WMOutput (see Example).

Point() This method casts the WMObject to WMPoint (see Example).

In object-oriented programming terms, WMObject may be considered as abase class from which WMBody and others (derived-classes) descend.

Example Sub Main()

'Illustrates the use of type-casts.

' Determines the type of the first object in the document and

' assigns a variable to it.

Dim Doc as WMDocument

Dim obj as WMObject

Dim aBody as WMBody, aPoint as WMPoint, aConstraint asWMConstraint

Dim anInput as WMinput, anOutput as WMOutput

Set Doc = WM.ActiveDocument

Doc.SelectAll

Set obj = Doc.Selection.Item(1)

' Item returns a WMObject

If obj is Nothing Then

Exit Sub

End If

If obj.Kind = "body" Then

Set aBody = obj.Body() : MsgBox "Body found"

ElseIf obj.Kind = "constraint" Then

Set aConstraint = obj.Constraint() : MsgBox "Constraintfound"

ElseIf obj.Kind = "point" Then

Set aPoint = obj.Point() : MsgBox "Point found"

Page 640: Working Model 2D - User's Manual

636 Working Model Basic User's Manual

ElseIf obj.Kind = "output" Then

Set anOutput = obj.Output() : MsgBox "Output found"

ElseIf obj.Kind = "input" Then

Set anInput = obj.Input() : MsgBox "Input found"

End If

End Sub

See Also WMBody (object), WMConstraint (object), WMPoint (object), WMInput(object), WMOutput (object), WMDocument.Selection (property)

WMOutput (object)Syntax WMOutput

Description An object which provides an interface to output meters used in WorkingModel simulations.

Comments A WMOutput object represents meters used in Working Model. Everymeter in Working Model can measure up to four quantities, and so can aWMOutput object.

Each measured quantity is specified using WMOutputColumn objects. AWMOutput object has methods and properties specifying how the valuesare displayed on the meter. Yet a WMOutput object is not much more thana place holder for a WMOutputColumn object. You can access individualcolumns of a WMOutput object using the Column method (see below).

A WMOutput object has the following properties and methods..

Method/PropertyDescription

Column(num) A method which returns the specified WMOutputColumn objectrepresenting the fields of the output meter. The parameter num of typeInteger specifies the column ID.

For num = 0, Column returns the value of the field x (x-axis). For num =n, Column returns the value of the field yn. Please see WMOutputColumnsection for more information.

ConnectPoints A Boolean property to indicate whether the plotted points are to beconnected.

Format A String property to specify the display format of the Output. It can be"digital", "bar", or "graph".

Kind A String property indicating the type of the object ; returns "output".The property is read-only.

ShowAxes A Boolean property to indicate whether x- and y-axes are displayed when

Page 641: Working Model 2D - User's Manual

Chapter 3 WMOutput (object) 637

the Output is in the graph format.

ShowGrid Boolean to indicate whether the grid display is turned on or off.

ShowFrame Boolean to indicate whether the Output has an outlining frame.

ShowLabels Boolean to indicate whether to show the labels on the Output.

ShowUnits Boolean to indicate whether the units are shown on the Output.

X, Y Integer to specify the (x, y) coordinates that describe the position of theWMOutput object in the document. The values are measured in pixelcoordinates, where the top-left corner of the document window is (0, 0).The x-coordinate increases toward the right edge of the screen, whereasthe y-coordinate increases downward to the bottom of the screen.

H, W Integer to specify the height and width of the WMOutput object in theWorking Model document. As in X and Y properties, H and W are given inpixel sizes.

For example, suppose you want to locate the WMOutput object M at (150,50) and change its dimensions to 250 (width) by 120 (height) pixels. Thecode segment would be:

M.X = 150: M.Y = 50

M.W = 250: M.H = 120

(Recall a colon (:) is used to separate two statements in a single line.)

The result would look like the following:

(0, 0)

150

50

250

120

(units in pixels)

(150, 50)

Example Sub Main()

'Creates a meter to plot sin(t). See also

'WMOutputColumn below.

Dim M as WMOutput

Page 642: Working Model 2D - User's Manual

638 Working Model Basic User's Manual

Set M = WM.ActiveDocument.NewOutput()

M.Format = "graph"

M.Column(1).Label = "sine plot"

M.Column(1).Cell.Formula = "sin(t)"

End Sub

See Also WMOutputColumn (object), WMDocument.NewOutput (method)

WMOutputColumn (object)Syntax WMOutputColumn

Description An object which provides an interface to individual formulas of outputs(meters).

Comments A WMOutputColumn object represents one of the output fields of aWMOutput (meter) object. While a WMOutput object contains informationregarding the meter display format, its WMOutputColumn objects holdinformation regarding what quantities are to be displayed in the meter.

Each WMOutputColumn object corresponds to a row in the Propertieswindow for a meter. Just like in Working Model, you can specify thequantity to be measured (using formulas), minimum and maximum valuesfor plotting (or automatic scale), and display the label for each outputcolumn.

The table below shows how the properties of the WMOutputColumn objectcan be specified.

Method/PropertyDescription

AutoScale Boolean to indicate whether the particular output is subject to automaticscaling. AutoScale is True when the automatic scaling is active, andFalse otherwise.

Cell WMCell containing the quantity to be measured. Typically, formulas areused to specify the quantity to be measured (see Example below).

Label String which contains the label for the particular meter column. Label isno more than an informative comment to make the output easy to read.

Min Double to specify the minimum bound of the plotting window when theWMOutput object is in graph format. When AutoScale is True, Minreturns the current minimum bound.

Max Double to specify the maximum bound of the plotting window when theWMOutput object is in graph format. When AutoScale is True, Maxreturns the current maximum bound.

Show Boolean to indicate whether the column is to be displayed on the Output

Page 643: Working Model 2D - User's Manual

Chapter 3 WMPoint (object) 639

object. Show is True when the value is displayed, or False otherwise.

Example Sub Main()

' Creates a digital meter to show t and sin(t)

Dim M as WMOutput

Dim T1 as WMOutputColumn

Set M = WM.ActiveDocument.NewOutput()

M.Format = "digital"

Set T1 = M.Column(2)

T1.Label = "sine of t"

T1.Cell.Formula = "sin(t)"

End Sub

See Also WMOutput (object)

WMPoint (object)Syntax WMPoint

Description An object which provides an interface to points used in Working Modelsimulations.

Comments A WMPoint object has the following properties.

Note: WMPoint object also has properties available in WMObject objects.Please see the section on WMObject for details.

Property Description

Kind (String) indicates the type of the Point (point, squarepoint, oranchor).

PX, PY (WMCell) x- and y-positions of the Point.

PR (WMCell) orientation of the Point.

GlobalPX (Double) global x-position of the Point.

GlobalPY (Double) global y-position of the Point.

GlobalPR (Double) global orientation of the Point.

Body (WMBody) the body to which the Point is attached. If the point is attachedto the background, the Body property returns the background, which hasthe ID of 0 (see Example).

Constraint (WMConstraint) the constraint object which the Point is part of. Read-only. Returns Nothing if the point is not part of any constraint.

Page 644: Working Model 2D - User's Manual

640 Working Model Basic User's Manual

Example Sub Main()

' Creates a square and attaches a point at a corner

' of the square.

Dim D as WMDocument

Dim P as WMPoint

Dim B as WMBody

Set D = WM.ActiveDocument

' Creates a square. By default, it will be located at (0, 0)

Set B = D.NewBody("Square")

B.Width.Value = 1.0 ' Height will also be 1.0

' Creates a point. By default, it will be located at (0, 0)

Set P = D.NewPoint("Point")

If P.Body.ID = 0 then

MsgBox "The point is currently attached to the background."

End If

Set P.Body = B ' attached to the square previously created

MsgBox "Now the point is attached to "+P.Body.Name

' Move the point to the corner of the square. Note Point's

' coordinates are given in terms of the body it is attached.

P.PX.Value = 0.5 ' 0.5 in x from the FOR of the square

P.PY.Value = 0.5 ' 0.5 in y from the FOR of the square

End Sub

See Also WMCell (object), WMBody (object)

Page 645: Working Model 2D - User's Manual

641

C H A P T E R 4

This chapter explains how to use Script Editor, a tool that enables you to edit and debug yourWM Basic scripts. It begins with some general information about working with Script Editorand then discusses editing your scripts, running your scripts to make sure they work properly,debugging them if necessary, and exiting from Script Editor.

ContentsScript Editor BasicsEditing Your ScriptsRunning Your ScriptsDebugging Your ScriptsExiting from Script EditorMenu Reference

Editing and DebuggingScripts

Page 646: Working Model 2D - User's Manual

642 Working Model Basic User's Manual

Script Editor BasicsThis section provides general information that will help you work most effectively withScript Editor. It includes an overview of Script Editor's application window—the interfaceyou'll use to edit, run, and debug your WM Basic scripts—as well as lists of keyboardshortcuts and information on using the Help system.

Script Editor's Application WindowScript Editor's application window contains the following elements:

Toolbar: a collection of tools that you can use to provide instructionsto Script Editor, as discussed in the following subsection.Edit pane: a window containing the WM Basic code for the script youare currently editing.Watch pane: a window that opens to display the watch variable listafter you have added one or more variables to that list.Pane separator: a divider that appears between the edit pane and thewatch pane when the watch pane is open.Status bar: displays the current location of the insertion point withinyour script.

Toolbar

Pane separator

Edit pane

Status bar

Watch pane

ToolbarThe following list briefly explains the purpose of each of the tools on Script Editor's toolbar.These tools are discussed in more detail later in the chapter, in the context of the proceduresin which they are used.

Page 647: Working Model 2D - User's Manual

Chapter 4 Editing and Debugging Scripts 643

Toolbar Tools

ButtonFace

Tool Function

Start Begins execution of a script.

End Stops execution of a script.

ToggleBreakpoint

Adds or removes a breakpoint on aline of WM Basic code.

Add Watch Displays the Add Watch dialog box,in which you can specify the name ofa WM Basic variable. That variable,together with its value (if any), is thendisplayed in the watch pane of ScriptEditor's application window.

Calls Displays the list of procedures calledby the currently executing WM Basicscript. Available only during breakmode.

Single Step Executes the next line of a WM Basicscript and then suspends execution ofthe script. If the script calls anotherWM Basic procedure, execution willcontinue into each line of the calledprocedure.

ProcedureStep

Executes the next line of a WM Basicscript and then suspends execution ofthe script. If the script calls anotherWM Basic procedure, WM Basic willrun the called procedure in itsentirety.

Keyboard ShortcutsThe following lists present various types of keyboard shortcuts, including general shortcuts,navigating shortcuts, editing shortcuts, and debugging shortcuts.

Page 648: Working Model 2D - User's Manual

644 Working Model Basic User's Manual

General Shortcuts

Key(s) Function

F1 (Windowsonly)

Provides context-sensitive help for selectedmenu commands and variables in the watchpane, for WM Basic terms in the edit pane thathave been selected or that contain the insertionpoint, and for displayed dialog boxes.

Shift+F1(Windows only)

Toggles the Help pointer.

Ctrl+F(Windows),Cmd+F(Macintosh)

Displays the Find dialog box, which allows youto specify text for which you want to search.

F3 (Windows),Cmd+G(Macintosh)

Searches for the next occurrence of previouslyspecified text. If you have not previouslyspecified text for which you want to search,displays the Find dialog box.

F4 Invokes the Goto Line dialog box.

Esc (Windows) Deactivates the Help pointer if it is active.Otherwise, compiles your script and returns youto the host application.

Navigating Shortcuts

Key(s) Function

Up arrow Moves the insertion point up one line.

Down arrow Moves the insertion point down one line.

Left arrow Moves the insertion point left by one characterposition.

Right arrow Moves the insertion point right by onecharacter position.

PgUp Moves the insertion point up by one window.

PgDn Moves the insertion point down by onewindow.

Ctrl+PgUp(Windows)

Scrolls the insertion point left by one window.

Ctrl+PgDn(Windows)

Scrolls the insertion point right by onewindow.

Page 649: Working Model 2D - User's Manual

Chapter 4 Editing and Debugging Scripts 645

Ctrl+ Left arrow(Windows),Cmd+Left arrow(Macintosh)

Moves the insertion point to the start of thenext word to the left.

Ctrl+Right arrow(Windows),Cmd+Right arrow(Macintosh)

Moves the insertion point to the start of thenext word to the right.

Home On Windows, places the insertion point beforethe first character in the line. On Macintosh,scrolls back to the beginning of the script(without moving the cursor).

End On Windows, places the insertion point afterthe last character in the line. On Macintosh,scrolls down to the end of the script (withoutmoving the cursor).

Ctrl+Home(Windows)

Places the insertion point before the firstcharacter in the script.

Ctrl+End(Windows)

Places the insertion point after the lastcharacter in the script.

Editing Shortcuts

Key(s) Function

Delete Removes the selected text or removes thecharacter following the insertion point withoutplacing it on the Clipboard.

Backspace Removes the selected text or removes thecharacter preceding the insertion point withoutplacing it on the Clipboard.

Ctrl+Y(Windows)

Deletes the entire line containing the insertionpoint without placing it on the Clipboard.

Tab Inserts a tab character.

Enter Inserts a new line, breaking the current line.

Ctrl+C(Windows),Cmd+C(Macintosh)

Copies the selected text, without removing itfrom the script, and places it on the Clipboard.

Page 650: Working Model 2D - User's Manual

646 Working Model Basic User's Manual

Ctrl+X(Windows),Cmd+X(Macintosh)

Removes the selected text from the script andplaces it on the Clipboard.

Ctrl+V(Windows),Cmd+V(Macintosh)

Inserts the contents of the Clipboard at thelocation of the insertion point.

Shift + anynavigatingshortcut

Selects the text between the initial location ofthe insertion point and the point to which thekeyboard shortcut would normally move theinsertion point. (For example, pressing Shift +Ctrl + Left arrow selects the word to the left ofthe insertion point.

Ctrl+Z(Windows),Cmd+Z(Macintosh)

Reverses the effect of the preceding editingchange(s).

Debugging Shortcuts

Key(s) Function

Shift+F9 Displays the Add Watch dialog box, in whichyou can specify the name of a WM Basicvariable. Script Editor then displays the valueof that variable, if any, in the watch pane of itsapplication window.

Delete Removes the selected watch variable from thewatch pane.

Enter or F2 Displays the Modify Variable dialog box forthe selected watch variable, which enables youto modify the value of that variable.

Cmd+Y(Macintosh)

Performs a syntax check on your script.

Cmd+T(Macintosh), F5

Runs your script.

Cmd+E(Macintosh)

Terminates your script.

F6 If the watch pane is open, switches theinsertion point between the watch pane and theedit pane.

Page 651: Working Model 2D - User's Manual

Chapter 4 Editing and Debugging Scripts 647

Cmd+"="(Macintosh), F8

Activates the Single Step command, whichexecutes the next line of a WM Basic scriptand then suspends execution of the script. Ifthe script calls another WM Basic procedure,execution will continue into each line of thecalled procedure.

Shift+F8 Activates the Procedure Step command, whichexecutes the next line of a WM Basic scriptand then suspends execution of the script. Ifthe script calls another WM Basic procedure,WM Basic will run the called procedure in itsentirety.

Ctrl+Break(Windows) orCmd+period (.)(Macintosh)

Suspends execution of an executing script andplaces the instruction pointer on the next lineto be executed.

F9 Sets or removes a breakpoint on the linecontaining the insertion point.

Using the Help System (Windows Only)Script Editor's Help system provides context-sensitive help both on WM Basic keywords andon how to use various features of Script Editor. The Help system also lets you pinpointinformation on key topics. This subsection describes several ways to get help.Here's how to activate the Help pointer and use it to get help on certain key features of ScriptEditor, including the status bar, toolbar, menu commands, edit pane, watch pane, and paneseparator.

To get context-sensitive help using the Help pointer:1. To activate the Help pointer, press Shift+F1.

When you pass the pointer over an area of Script Editor's applicationwindow on which you can obtain help, a question mark appears besidethe mouse pointer to indicate that the Help pointer is active.

Page 652: Working Model 2D - User's Manual

648 Working Model Basic User's Manual

Help pointer

Note: You can use the Help pointer to obtain help on all toolbar toolsand menu commands, including those that are currently disabled.

2. Place the Help pointer on the item for which you want help and clickthe mouse button.Script Editor's Help system displays information for the item on whichyou clicked.

Here's how to use the keyboard to get context-sensitive help on WM Basic terms, watchvariables, menu commands, and dialog boxes.

To get context-sensitive help using the keyboard:1. Select the WM Basic term on which you want help or place the

insertion point anywhere in the term.-Or-Select the watch variable or menu command on which you want help(including commands that are currently disabled).-Or-Display the dialog box on which you want help.

2. Press F1.Script Editor's Help system displays information on the WM Basicterm, watch variable, menu command, or dialog box.

Here's how to access the Help system and pinpoint specific information within it.

To search for help on a specific topic:1. From the Help menu, choose the Search for Help on command.

The Search dialog box appears.2. Either enter the desired topic in the text box or select it from the

following scrollable list.3. Click the Show Topics button or press Enter.

Page 653: Working Model 2D - User's Manual

Chapter 4 Editing and Debugging Scripts 649

The topic you selected is displayed in the second scrollable list,together with closely related Help topics, if any.

4. Click the Go To button or press Enter.Help is displayed for the topic you selected.

Here's how to display the Help system contents and use it to find information on selectedtopics.

To use the Help system contents:1. From the Help menu, choose Contents.

A list of major topics in Script Editor's Help system appears.2. Select the topic on which you want help.

The Help system either displays information on the selected topic orpresents a list of more specific subtopics from which you can chooseto obtain the desired information.

Editing Your ScriptsThis section explains how to use Script Editor to edit WM Basic code. Although, in somerespects, editing code with Script Editor is like editing regular text with a word-processingprogram, Script Editor also has certain capabilities specifically designed to help you edit WMBasic code.You'll learn how to move around within your script, select and edit text, add comments toyour script, break long WM Basic statements across multiple lines, search for and replaceselected text, and perform a syntax check of your script. The section ends with a briefdiscussion of editing dialog box templates, which is explained in much more detail inChapter 3.

Navigating within a ScriptThe lists of keyboard shortcuts in the preceding section contain a group of navigatingshortcuts, which you can use to move the insertion point around within your script. Whenyou move the insertion point with a keyboard shortcut, Script Editor scrolls the new locationof 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, asexplained below.Script Editor differs from most word-processing programs in that it allows you to place theinsertion point anywhere within your script, including in "empty spaces." (Empty spaces areareas within the script that do not contain text, such as a tab's expanded space or the areabeyond the last character on a line.)Here's how to use the mouse to reposition the insertion point. This approach is especially fastif the area of the screen to which you want to move the insertion point is currently visible.

To move the insertion point with the mouse: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 mouse pointer where you want to position the insertion point.3. Click the left mouse button.

The insertion point is repositioned.

Page 654: Working Model 2D - User's Manual

650 Working Model Basic User's Manual

Note: When you scroll the display with the mouse, the insertion pointremains in its original position until you reposition it with a mouseclick. If you attempt to perform an editing operation when the insertionpoint is not in view, Script Editor automatically scrolls the insertionpoint into view before performing the operation.

Here's how to jump directly to a specified line in your script. This approach is especially fastif the area of the screen to which you want to move the insertion point is not currently visiblebut you know the number of the target line.

To move the insertion point to a specified line in your script:1. Press F4.

Script Editor displays the Goto Line dialog box.

2. Enter the number of the line in your script to which you want to movethe insertion point.

3. Click the OK button or press Enter.The insertion point is positioned at the start of the line you specified. Ifthat line was not already displayed, Script Editor scrolls it into view.Note: The insertion point cannot be moved so far below the end of ascript as to scroll the script entirely off the display. When the last lineof your script becomes the first line on your screen, the script will stopscrolling, and you will be unable to move the insertion point below thebottom of that screen.

Performing Editing Operations with Script EditorThis subsection provides an overview of the editing operations you can perform with ScriptEditor—including inserting, selecting, deleting, cutting, copying, and pasting material—andexplains how to undo, or reverse, the most recent editing operations. You may wish to referto the lists of keyboard shortcuts in the preceding section, which contain a group of editingshortcuts that can be used to perform many of the operations discussed here.

Inserting TextIn Script Editor, inserting text and other characters such as tabs and line breaks works aboutthe same way as it does in a word-processing program: you position the insertion point at thedesired location in the script and start typing.However, as noted in the preceding subsection, Script Editor lets you position the insertionpoint in "empty spaces," which means that you can also insert text into empty spaces—afeature that comes in handy when you want to insert a comment in the space beyond the endof a line in your script. (Adding comments to your script is discussed later in this section.)When you insert characters beyond the end of a line, the space between the insertion pointand the last character on the line is backfilled with tab characters.

Page 655: Working Model 2D - User's Manual

Chapter 4 Editing and Debugging Scripts 651

Another way in which Script Editor differs from word-processing programs is that in ScriptEditor, text does not wrap. If you keep entering text on a given line, eventually you will reacha point at which you can enter no more text on that line. Therefore, you control the linebreaks by pressing Enter when you want to insert a new line in your script. The effect ofpressing Enter depends on where the insertion point is located at the time:

If you press Enter with the insertion point at or beyond the end of aline, a new line is inserted after the current line.If you press Enter with the insertion point at the start of a line, a newline is inserted before the current line.If you press Enter with the insertion point within a line, the current lineis broken into two lines at that location.

If you press Tab, a tab character is inserted at the location of the insertion point, whichcauses text after the tab to be moved to the next tab position. If you insert new text within atab's expanded space, the text that originally appeared on that line is moved to the next tabposition each time the new text that you are entering reaches the start of another tab position.

Selecting TextYou can use either the mouse or the keyboard to select text and other characters in yourscript. Regardless of which method you use, you should be aware that in Script Editor, youcan select either a portion of one line or a series of whole lines, but you cannot select aportion of one line plus one or more whole lines. When you are selecting multiple lines andstart or end your selection partway through a line, Script Editor automatically extends theselection to include the entire starting and ending lines.Here's how to use the mouse to select text in your script.

To select text with the mouse:1. Place the mouse pointer where you want your selection to begin.2. While pressing the left mouse button, drag the mouse until you reach

the end of your selection, and release the mouse button.-Or-While pressing Shift, place the mouse pointer where you want yourselection to end and click the left mouse button.The selected text is highlighted on your display.

Page 656: Working Model 2D - User's Manual

652 Working Model Basic User's Manual

Selected text

Another way to select one or more whole lines with the mouse is to start by placing themouse pointer in the left margin beside the first line you want to select. The pointer becomesa reverse arrow, which points toward the line of text. Click the left mouse button to select asingle line; press the left mouse button and drag up or down to select multiple lines.Here's how to use keyboard shortcuts to select text in your script.

To select text with the keyboard:1. Place the insertion point where you want your selection to begin.2. While pressing Shift, use one of the navigating keyboard shortcuts to

extend the selection to the desired ending point.The selected text is highlighted on your display.

Note: When you intend to select an entire single line of text in your script, it is important toremember 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.Here's how to use the keyboard to select one or more whole lines in your script.

To select an entire line of text with the keyboard:1. Place the insertion point at the beginning of the line you want to select.2. Press Shift + Down arrow.

The entire line, including the end-of-line character, is selected.3. To extend your selection to include additional whole lines of text,

repeat step 2.Once you have selected text within your script, you can perform a variety of other editingoperations on it, including deleting the text, placing it on the Clipboard (either by cutting thetext or copying it), and pasting it.

Deleting TextWhen you delete material, it is removed from your script without being placed on theClipboard.

Page 657: Working Model 2D - User's Manual

Chapter 4 Editing and Debugging Scripts 653

Here's how to remove one or more characters, selected text, or entire lines from your script.

To delete text:To remove a single character to the left of the insertion point, pressBackspace once; to remove a single character to the right of theinsertion point, press Delete once. To remove multiple characters, holddown Backspace or Delete.-Or-To remove text that you have selected, press Backspace or Delete.-Or-(On Windows) To remove an entire line, place the insertion point inthat line and press Ctrl+Y.

Here's how to remove an unwanted line break from your script.

To combine the current line with the following line:1. Place the insertion point after the last character on the current line.2. Press Delete once to delete the hidden end-of-line character.

The current line and the following line are combined.Notes: If any spaces were entered at the end of the current line, youmay have to press Delete one or more additional times to remove thesehidden characters first before you can delete the end-of-line character.Pressing Backspace with the insertion point at the start of a line has noeffect—that is, it will not combine the current line with the precedingline.

Cutting and Copying TextYou can place material from your script on the Clipboard by either cutting it or copying it.Here's how to place on the Clipboard text that you have cut from your script.

To cut a selection:Press Ctrl+X (Windows) or Cmd+X (Macintosh).The selection is removed from your script and placed on theClipboard.

Here's how to place on the Clipboard text that you have copied from your script.

To copy a selection:Press Ctrl+C (Windows) or Cmd+C (Macintosh).The selection remains in your script, and a copy of it is placed on theClipboard.

Pasting TextOnce you have cut or copied material to the Clipboard, here's how to paste it into your scriptat another location.

To paste the contents of the Clipboard into your script:1. Position the insertion point where you want to place the contents of the

Clipboard.

Page 658: Working Model 2D - User's Manual

654 Working Model Basic User's Manual

2. Press Ctrl+V (Windows) or Cmd+V (Macintosh).The contents of the Clipboard appear at the location of the insertionpoint.

If you wish to delete a block of text and insert the contents of the Clipboard in its place, youcan combine the two operations by first selecting the text you want to remove and thenpressing Ctrl+V (Windows) or Cmd+V (Macintosh) to replace it with the contents of theClipboard.

Undoing Editing OperationsYou can undo editing operations that produce a change in your script, including:

The insertion of a series of charactersThe insertion of a block of text from the ClipboardThe deletion of a series of charactersThe deletion or cutting of a block of text

You cannot undo operations that don't produce any change in your script, such as moving theinsertion point, selecting text, and copying material to the Clipboard.Here's how to reverse the effect of the preceding editing operation.

To undo an editing operation:Press Ctrl+Z (Windows) or Cmd+Z (Macintosh).Your script is restored to the way it looked before you performed theediting operation.

Adding Comments to Your ScriptYou can add comments to your script to remind yourself or others of how your code works.Comments are ignored when your script is executed.In WM Basic, the apostrophe symbol ( ' ) is used to indicate that the text from the apostropheto the end of the line is a comment.Here's how to designate an entire line as a comment.

To add a full-line comment:1. Type an apostrophe ( ' ) at the start of the line.2. Type your comment following the apostrophe.

When your script is run, the presence of the apostrophe at the start ofthe line will cause the entire line to be ignored.

Here's how to designate the last part of a line as a comment.

To add a comment at the end of a line of code:1. Position the insertion point in the empty space beyond the end of the

line of code.2. Type an apostrophe ( ' ).3. Type your comment following the apostrophe.

When your script is run, the code on the first portion of the line will beexecuted, but the presence of the apostrophe at the start of thecomment will cause the remainder of the line to be ignored.

Although you can place a comment at the end of a line containing executable code, youcannot place executable code at the end of a line containing a comment because the presence

Page 659: Working Model 2D - User's Manual

Chapter 4 Editing and Debugging Scripts 655

of the apostrophe at the start of the comment will cause the balance of the line (including thecode) to be ignored.

Breaking a WM Basic Statement across Multiple LinesBy default, in Script Editor, a single WM Basic statement can extend only as far as the rightmargin, and each line break represents a new statement. However, you can override thisdefault if you want to break a long statement across two or more lines.Here's how to indicate that two or more lines of WM Basic code should be treated as a singlestatement when your script is run.

To break a WM Basic statement across multiple lines:1. Type the WM Basic 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.3. Press the spacebar once to insert a single space.4. Type an underscore ( _ ).

Note: The underscore is the line-continuation character, whichindicates that the WM Basic statement continues on the following line.

5. Repeat steps 2–4 to place a line-continuation character at the end ofeach line in the series except the last.When you run your script, the code on this series of lines will beexecuted as a single WM Basic statement, just as if you had typed theentire statement on the same line.

Searching and ReplacingScript Editor makes it easy to search for specified text in your script and automaticallyreplace instances of specified text.

Finding Text in Your ScriptHere's how to locate instances of specified text quickly anywhere within your script.

To find specified text:1. Move the insertion point to where you want to start your search. (To

start at the beginning of your script, press Ctrl+Home (Windows) orHome (Macintosh).)

2. Press Ctrl+F (Windows) or Cmd+F (Macintosh).Script Editor displays the Find dialog box:

3. In the Find What field, specify the text you want to find.

Page 660: Working Model 2D - User's Manual

656 Working Model Basic User's Manual

4. Select the Match Case check box if you want the search to be case-sensitive. Otherwise, the search will be case-insensitive.

5. Click the Find Next button or press Enter.The Find dialog box remains displayed, and Script Editor eitherhighlights the first instance of the specified text or indicates that itcannot be found.

6. If the specified text has been found, repeat step 5 to search for the nextinstance of it.Note: If the Find dialog box blocks your view of an instance of thespecified text, you can move the dialog box out of your way andcontinue with your search. You can also click the Cancel button,which removes the Find dialog box while maintaining the establishedsearch criteria, and then press F3 to find successive occurrences of thespecified text. (If you press F3 when you have not previously specifiedtext for which you want to search, Script Editor displays the Finddialog box so you can specify the desired text.)

Replacing Text in Your ScriptHere's how you can automatically replace either all instances or selected instances ofspecified text.

To replace specified text:1. Move the insertion point to where you want to start the replacement

operation. (To start at the beginning of your script, press Ctrl+Homeon Windows or Home on Macintosh.)

2. Choose the Replace command from the Search menu.Script Editor displays the Replace dialog box:

3. In the Find What field, specify the text you want to replace.4. In the Replace With field, specify the replacement text.5. Select the Match Case check box if you want the replacement

operation to be case-sensitive. Otherwise, it will be case-insensitive.6. To replace all instances of the specified text, click the Replace All

button.

Page 661: Working Model 2D - User's Manual

Chapter 4 Editing and Debugging Scripts 657

Script Editor either replaces the specified text throughout your scriptand indicates the number of occurrences it has changed, or it indicatesthat the specified text cannot be found.

7. To replace selected instances of the specified text, click the Find Nextbutton.Script Editor either highlights the first instance of the specified text orindicates that it cannot be found.

8. If the specified text has been found, either click the Replace button toreplace that instance of it or click the Find Next button to highlight thenext instance (if any).Each time you click the Replace button, Script Editor replaces thatinstance of the specified text and automatically highlights the nextinstance.

Checking the Syntax of a ScriptWhen you try to run or debug a script whose syntax hasn't been checked, Script Editor firstperforms a syntax check automatically.Here's how to perform a syntax check manually when you are editing your script, withouthaving to run it.

To perform a syntax check:1. From the Run menu, choose the Syntax Check command.

Script Editor either indicates that no errors have been found ordisplays an error message that specifies the first line in your scriptwhere an error has been found and briefly describes the nature of thaterror.

2. Click the OK button or press Enter.If Script Editor has found a syntax error, the line containing the error ishighlighted on your display.

3. Correct the syntax error.4. Repeat steps 1–3 until you have found and corrected all syntax errors.

Editing Dialog Box Templates (Windows Only)If you are running the WM Basic on Windows, the Insert New Dialog and Edit Dialogcommands will appear in the Edit menu. These commands allow you to use the features ofDialog Editor to create a new dialog box template and insert it into your script or edit anexisting dialog box template contained in your script.Here's how to invoke Dialog Editor and use it to create a new dialog box template for use inyour script.

To insert a new dialog box template into your script:1. Place the insertion point where you want the new dialog box template

to appear in your script.2. From the Edit menu, choose the Insert New Dialog command.

Script Editor's application window is temporarily disabled, and DialogEditor appears, displaying a new dialog box in its application window.

3. Use Dialog Editor to create your dialog box.

Page 662: Working Model 2D - User's Manual

658 Working Model Basic User's Manual

4. Exit from Dialog Editor and return to Script Editor.Script Editor automatically places the new dialog box templategenerated by Dialog Editor in your script at the location of theinsertion point.

Here's how to invoke Dialog Editor and use it to modify a dialog box template contained inyour script.

To edit an existing dialog box template in your script:1. Select the WM Basic code for the entire dialog box template.2. From the Edit menu, choose the Edit Dialog command.

Script Editor's application window is temporarily disabled, and DialogEditor appears, displaying in its application window a dialog boxcreated from the code you selected.

3. Use Dialog Editor to modify your dialog box.4. Exit from Dialog Editor and return to Script Editor.

Script Editor automatically replaces the dialog box template youoriginally selected with the revised template generated by DialogEditor.

Refer to Chapter 4 for a detailed discussion of how to use Dialog Editor to create and editdialog box templates.

Running Your ScriptsOnce you have finished editing your script, you will want to run it to make sure it performsthe way you intended. You can also pause or stop an executing script.Here's how to compile your script, if necessary, and then execute it.

To run your script:Click the Start tool on the toolbar.-Or-Press F5.The script is compiled (if it has not already been compiled), the focusis switched to the Working Model window, and the script is executed.Note: During script execution, Script Editor's application window isavailable only in a limited manner. Some of the menu commands maybe disabled, and the toolbar tools may be inoperative.

Here's how to suspend the execution of a script that you are running.

To pause an executing script:Press Ctrl+Break (Windows) or Cmd+"." (period) (Macintosh).Execution of the script is suspended, and the instruction pointer (a grayhighlight) appears on the line of code where the script stoppedexecuting.Note: The instruction pointer designates the line of code that will beexecuted next if you resume running your script.

Here's how to stop the execution of a script that you are running.

Page 663: Working Model 2D - User's Manual

Chapter 4 Editing and Debugging Scripts 659

To stop an executing script:Click the End tool on the toolbar.Note: Many of the functions of Script Editor's application windowmay be unavailable while you are running a script. If you want to stopyour script but find that the toolbar is currently inoperative, pressCtrl+C (Windows) or Cmd+"." (period) (Macintosh) to pause yourscript, then click the End tool.

Debugging Your ScriptsThis section presents some general information that will help you work most effectively withScript Editor's debugging capabilities and then explains how to trace the execution of yourscript, how to set and remove breakpoints, and how to add watch variables and modify theirvalue.

Using the WM Basic DebuggerWhile debugging, you are actually executing the code in your script line by line. Therefore,to prevent any modifications to your script while it is being run, the edit pane is read-onlyduring 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 removewatch variables, but you cannot make any changes to the script until you stop running it.To let you follow and control the debugging process, Script Editor displays an instructionpointer on the line of code that is about to be executed—that is, the line that will be executednext if you either proceed with the debugging process or run your script at full speed. Whenthe instruction pointer is on a line of code, the text on that line appears in black on a graybackground that spans the width of the entire line. The following illustration shows thedifference between the instruction pointer and the selection highlight (discussed in thepreceding section), in which the text appears in white on a black background that spans onlythe width of the selected text.

Selectionhighlight

Instructionpointer

Page 664: Working Model 2D - User's Manual

660 Working Model Basic User's Manual

Tracing Script ExecutionScript Editor gives you two ways to trace script execution—single step and procedure step—both of which involve stepping through your script code line by line. The distinction betweenthe two is that the single step process traces into calls to user-defined functions andsubroutines, whereas the procedure step process does not trace into these calls (although itdoes execute them).Here's how to trace the execution of your script with either the single step or procedure stepmethod.

To step through your script:1. Click the Single Step or Procedure Step tool on the toolbar.

-Or-Press F8 (Single Step) or Shift+F8 (Procedure Step).Script Editor places the instruction pointer on the sub main line ofyour script.Note: When you initiate execution of your script with any of thesemethods, the script will first be compiled, if necessary. Therefore,there may be a slight pause before execution actually begins. If yourscript contains any compile errors, it will not be executed. To debugyour script, first correct any compile errors, then initiate executionagain.

2. To continue tracing the execution of your script line by line, repeatstep 1.Each time you repeat step 1, Script Editor executes the line containingthe instruction pointer and moves the instruction pointer to the nextline to be executed.

3. When you finish tracing the execution of your script, either click theStart tool on the toolbar (or press F5) to run the balance of the script atfull speed or click the End tool to halt execution of the script.

When you are stepping through a subroutine, you may need to determine the procedure callsby which you arrived at that point in your script. Here's how to use the Calls dialog box toobtain this information.

To display the Calls dialog box:1. Click the Calls tool on the toolbar.

Script Editor displays the Calls dialog box, which lists the procedurecalls made by your script in the course of arriving at the presentsubroutine.

Page 665: Working Model 2D - User's Manual

Chapter 4 Editing and Debugging Scripts 661

2. From the Calls dialog box, select the name of the procedure you wishto view.

3. Click the Show button.Script Editor highlights the currently executing line in the procedureyou selected, scrolling that line into view if necessary. (During thisprocess, the instruction pointer remains in its original location in thesubroutine.)

When you are stepping through a subroutine, you may want to repeat or skip execution of asection of code. Here's how to use the Set Next Statement command to move the instructionpointer to another line within that subroutine.

To move the instruction pointer to another line within a subroutine:1. Place the insertion point in the line where you want to resume stepping

through the script.2. From the Debug menu, choose the Set Next Statement command.

The instruction pointer moves to the line you selected, and you canresume stepping through your script from there.Note: You can only use the Set Next Statement command to move theinstruction pointer within the same subroutine. If you place theinsertion point on a line that is not in the same subroutine, the Set NextStatement command will be disabled in the Debug menu.

Setting and Removing BreakpointsIf you want to start the debugging process at the first line of your script and then step throughyour code line by line until you reach the end of the code that you need to debug, the methoddescribed in the preceding subsection works fine. But if you only need to debug one or moreportions of a long script, that method can be pretty cumbersome.An alternate strategy is to set one or more breakpoints at selected lines in your script. ScriptEditor suspends execution of your script just before it reaches a line containing a breakpoint,thereby allowing you to begin or resume stepping through the script from that point.

Setting BreakpointsYou can set breakpoints to begin the debugging process partway through your script, tocontinue debugging at a line outside the current subroutine, and to debug only selectedportions of your script.Valid breakpoints can only be set on lines in your script that contain code, including lines infunctions and subroutines. Although you can set a breakpoint anywhere within a script priorto execution, when you compile and run the script, invalid breakpoints (that is, breakpoints

Page 666: Working Model 2D - User's Manual

662 Working Model Basic User's Manual

on lines that don't contain code) are automatically removed. While you are debugging yourscript, Script Editor will beep if you try to set a breakpoint on a line that does not containcode.Here's how to begin the debugging process at a selected point in your script.

To start debugging partway through a script:1. Place the insertion point in the line where you want to start debugging.2. To set a breakpoint on that line, click the Toggle Breakpoint tool on

the toolbar.-Or-Press F9.The line on which you set the breakpoint now appears in contrastingtype.

3. Click the Start tool on the toolbar.-Or-Press F5.Script Editor runs your script at full speed from the beginning and thenpauses prior to executing the line containing the breakpoint. It placesthe instruction pointer on that line to designate it as the line that will beexecuted next when you either proceed with debugging or resumerunning the script.

If you want to continue debugging at another line in your script, you can use the Set NextStatement command in the Debug menu to move the instruction pointer to the desired line—provided the line is within the same subroutine.If you want to continue debugging at a line that isn't within the same subroutine, here's howto move the instruction pointer to that line.

To continue debugging at a line outside the current subroutine:1. Place the insertion point in the line where you want to continue

debugging.2. To set a breakpoint on that line, press F9.3. To run your script, click the Start tool on the toolbar or press F5.

The script executes at full speed until it reaches the line containing thebreakpoint and then pauses with the instruction pointer on that line.You can now resume stepping through your script from that point.

If you only need to debug parts of your script, here's how to facilitate the task by usingbreakpoints.

To debug selected portions of your script:1. Place a breakpoint at the start of each portion of your script that you

want to debug.Note: Up to 255 lines in your script can contain breakpoints.

2. To run the script, click the Start tool on the toolbar or press F5.The script executes at full speed until it reaches the line containing thefirst breakpoint and then pauses with the instruction pointer on thatline.

3. Step through as much of the code as you need to.

Page 667: Working Model 2D - User's Manual

Chapter 4 Editing and Debugging Scripts 663

4. To resume running your script, click the Start tool on the toolbar orpress F5.The script executes at full speed until it reaches the line containing thesecond breakpoint and then pauses with the instruction pointer on thatline.

5. Repeat steps 3 and 4 until you have finished debugging the selectedportions of your script.

Removing BreakpointsBreakpoints can be removed either manually or automatically.Here's how to delete breakpoints manually one at a time.

To remove a single breakpoint manually:1. Place the insertion point on the line containing the breakpoint that you

want to remove.2. Click the Toggle Breakpoint tool on the toolbar.

-Or-Press F9.The breakpoint is removed, and the line no longer appears incontrasting type.

Here's how to delete all breakpoints manually in a single operation.

To remove all breakpoints manually:Select the Clear All Breakpoints command from the Debug menu.Script Editor removes all breakpoints from your script.

Breakpoints are removed automatically under the following circumstances: (1) As mentionedearlier, when your script is compiled and executed, breakpoints are removed from lines thatdon't contain code. (2) When you exit from Script Editor, all breakpoints are cleared.

Adding a Watch VariableAs you debug your script, you can use Script Editor's watch pane to monitor selectedvariables. For each of the variables on this watch variable list, Script Editor displays thename of the variable, where it is defined, its value (if the variable is not in scope, its value isshown as <not in context>), and other key information such as its type and length (if it is astring). The values of the variables on the watch list are updated each time you enter breakmode.Here's how to add a variable to Script Editor's watch variable list.

To add a watch variable:1. Click the Add Watch tool on the toolbar.

-Or-Press Shift+F9.Script Editor displays the Add Watch dialog box.

Page 668: Working Model 2D - User's Manual

664 Working Model Basic User's Manual

2. Use the controls in the Context box to specify where the variable isdefined (locally, publicly, or privately) and, if it is defined locally, inwhich routine it is defined.

3. In the Variable Name field, enter the name of the variable you want toadd to the watch variable list.You can only watch variables of fundamental data types, such asInteger, Long, Variant, and so on; you cannot watch complexvariables such as structures, arrays, or Working Model objects. Youcan, however, watch individual elements of arrays or structuremembers using the following syntax:

[variable [(index,...)] [.member [(index,...)]]...]

Where variable is the name of the structure or array variable, index is aliteral number, and member is the name of a structure member.For example, the following are valid watch expressions:Watch Variable Description

a(1) Element 1 of array a

person.age Member age of structure person

company(10,23).person.age Member age of structure person that isat element 10,23 within the array ofstructures called company

Note: If you are executing the script, you can display the names of allthe variables that are "in scope," or defined within the current functionor subroutine, on the drop-down Variable Name list and select thevariable you want from that list.

4. Click the OK button or press Enter.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 watchpane was already open, it expands far enough to display the variableyou just added.Note: Although you can add as many watch variables to the list as youwant, the watch pane only expands until it fills half of Script Editor'sapplication window. If your list of watch variables becomes longer

Page 669: Working Model 2D - User's Manual

Chapter 4 Editing and Debugging Scripts 665

than that, you can use the watch pane's scroll bars to bring hiddenportions of the list into view.

The list of watch variables is maintained between script executions. Depending on theimplementation, it may also be maintained between invocations of Script Editor.In order to delete a variable from Script Editor's watch variable list or modify the value of avariable on the list, you must first select the desired variable. Here's how to select a variableon the list.

To select a watch variable:Place the mouse pointer on the variable you want to select and clickthe left mouse button.-Or-If one of the variables on the watch list is already selected, use thearrow keys to move the selection highlight to the desired variable.-Or-If the insertion point is in the edit pane, press F6 to highlight the mostrecently selected variable on the watch list and then use the arrow keysto move the selection highlight to the desired variable.Note: Pressing F6 again returns the insertion point to its previousposition in the edit pane.

Here's how to delete a selected variable from Script Editor's watch variable list.

To delete a watch variable:1. Select the variable on the watch list.2. Press Delete.

The selected variable is removed from the watch list.

Modifying the Value of a VariableWhen the debugger has control, you can modify the value of any of the variables on ScriptEditor's watch variable list. Here's how to change the value of a selected watch variable.

To modify the value of a variable on the watch variable list:1. Place the mouse pointer on the name of the variable whose value you

want to modify and double-click the left mouse button.-Or-Select the name of the variable whose value you want to modify andpress Enter or F2.Script Editor displays the Modify Variable dialog box.

Page 670: Working Model 2D - User's Manual

666 Working Model Basic User's Manual

Notes: The name of the variable you selected on the watch variable listappears in the Name field. If you want to change another variable, youcan either enter a different variable in the Name field or select adifferent variable from the Variables list box, which shows the namesof the variables that are defined within the current function orsubroutine.When you use the Modify Variable dialog box to change the value of avariable, you don't have to specify the context. Script Editor firstsearches locally for the definition of that variable, then privately, thenpublicly.

2. Enter the new value for your variable in the Value field.3. Click the OK button.

The new value of your variable appears on the watch variable list.When changing the value of a variable, Script Editor converts the new value to be of thesame type as the variable being changed. For example, if you change the value of an Integervariable to 1.7, a conversion between a floating-point number and an Integer is performed,assigning the value 2 to the Integer variable.When modifying a Variant variable, Script Editor needs to determine both the type andvalue of the data. Script Editor uses the following logic in performing this assignment (in thisorder):

If the new value is Then

Null The Variant variable is assigned Null (VarType1)

Empty The Variant variable is assigned Empty(VarType 0).

True The Variant variable is assigned True (VarType11).

False The Variant variable is assigned False(VarType 11).

Page 671: Working Model 2D - User's Manual

Chapter 4 Editing and Debugging Scripts 667

number The Variant variable is assigned the value ofnumber. The type of the variant is the smallestdata type that fully represents that number.

You can force the data type of the variable using atype-declarator letter following number, such as%, #, &, !, or @.

date The Variant variable is assigned the value of thenew date (VarType 7)

Anything else The Variant variable is assigned a String(VarType 8).

Script Editor will not assign a new value if it cannot be converted to the same type as thespecified variable.

Exiting from Script EditorHere's how to get out of Script Editor. What happens when you exit depends on (1) whetheryou have made changes to your script and (2) whether your script contains errors.

To exit from Script Editor:Choose the Exit and Return command from the File menu.If you have made changes to your script, Script Editor displays adialog box asking whether you want to save the script. If you eitherclick the No button or click the Yes button and your script contains noerrors, you exit from Script Editor immediately. If you click the Yesbutton and your script contains errors, Script Editor highlights the linecontaining the first error and displays a dialog box asking whether youwant to exit anyway. If you click the Yes button, Script Editor savesyour script, errors and all, and then you exit from Script Editor.If you haven't made any changes to your script, you exit from ScriptEditor immediately, regardless of whether the script contains errorsfrom a previous editing session.

Menu ReferenceFile Menu

CommandKeyboardShortcut Function

N ew (Windows)New Script(Macintosh)

Ctrl+N(Windows)Cmd+N(Macintosh)

Creates a new scriptdocument.

Page 672: Working Model 2D - User's Manual

668 Working Model Basic User's Manual

O pen (Windows)

Open Script(Macintosh)

Ctrl+O(Windows)Cmd+O(Macintosh)

Opens an existing scriptdocument.

Close(MacintoshOnly)

Cmd+W Closes the Script Editorwindow and returns you toWorking Model.

S ave Cmd+S(Macintosh)

Saves the current scriptdocument under its filename.

Save A s Saves the current scriptdocument under a newfilename.

New WorkingModelDocument(Macintosh)

Creates a new WorkingModel document.

Open WorkingModelDocument(Macintosh)

Open an existing WorkingModel document.

Quit WorkingModel(Macintosh)

Cmd+Q Closes Script Editor and quitsWorking Model.

E x it (Windows) Alt+F4 orCtrl+W

Closes the current scriptdocument and returns you toWorking Model.

Edit Menu

Command

KeyboardShortcut Function

U ndo Ctrl+Z(Windows),Cmd+Z(Mantic)

Reverses the effect of the precedingediting change(s).

Cu t Ctrl+X(Windows),Cmd+X(Macintosh)

Removes the selected text from thescript and places it on the Clipboard.

Page 673: Working Model 2D - User's Manual

Chapter 4 Editing and Debugging Scripts 669

C opy Ctrl+C(Windows),Cmd+C(Macintosh)

Copies the selected text, withoutremoving it from the script, and placesit on the Clipboard.

P aste Ctrl+V(Windows),Cmd+V(Macintosh)

Inserts the contents of the Clipboard atthe current position of the insertionpoint.

D elete Delete orBackspace

Removes the selected text from thescript without placing it on theClipboard.

I nsert NewDialog...(Windows)

(Windows Only) Invokes the DialogEditor, which you can use to create anew dialog box for insertion into yourscript.

E ditDialog...(Windows)

(Windows Only) Invokes the DialogEditor, which you can use to edit theselected dialog box template. (Thiscommand is only enabled if a dialogbox template is currently selected.)

F ind... Ctrl+F(Windows),Cmd+F(Macintosh)

Displays the Find dialog box, whichallows you to specify text for which youwant to search.

Find N ext F3(Windows),Cmd+G(Macintosh)

Searches for the next occurrence ofpreviously specified text. If you havenot previously specified text for whichyou want to search, displays the Finddialog box.

R eplace... Cmd+R(Macintosh)

Displays the Replace dialog box, whichallows you to substitute replacementtext for instances of specified text.

G otoLine...

F4 Presents the Goto Line dialog box,which allows you to move the insertionpoint to the start of a specified linenumber in your script.

Note: The Insert New Dialog and Edit Dialog commands only appear in the Edit menu if youare running the WM Basic 2.1 on a platform that supports Dialog Editor.

Page 674: Working Model 2D - User's Manual

670 Working Model Basic User's Manual

Run Menu

CommandKeyboardShortcut Function

S tart Cmd+T(Macintosh), F5

Begins execution of a script.

E nd Cmd+E(Macintosh)

Stops execution of an executingscript.

S y ntaxCheck

Cmd+Y(Macintosh)

Verifies the syntax of thestatements in your script bycompiling it.

Debug Menu

CommandKeyboardShortcut Function

A ddWatch...

Shift+F9 Displays the Add Watch dialogbox, in which you can specifythe name of a WM Basicvariable. That variable,together with its value (if any),is then displayed in the watchpane of Script Editor'sapplication window.

D eleteWatch

Delete Deletes a selected variablefrom the watch variable list.

M odify... Enter or F2 Displays the Modify Variabledialog box for a selectedvariable, which enables you tomodify the value of thatvariable.

S ingle Step Cmd+"="(Macintosh), F8

Steps through the script codeline by line, tracing into calledprocedures.

P rocedureStep

Shift+F8 Steps through the script codeline by line without tracing intocalled procedures.

T oggleBreakpoint

Cmd+B(Macintosh), F9

Toggles a breakpoint on theline containing the insertionpoint.

Page 675: Working Model 2D - User's Manual

Editing and Debugging Scripts 671

C lear AllBreakpoints

Removes all breakpointspreviously set with the ToggleBreakpoint command.

Set N extStatement

Enables you to place theinstruction pointer on anotherline within the currentprocedure and resume scriptexecution from that point.

Help Menu (Windows Only)

Command

KeyboardShortcut Function

C ontents Displays a list of major topics on whichyou can obtain help.

S earch forHelp on...

Displays the Search dialog box, whichallows you to search for Help topicscontaining specific keywords.

Page 676: Working Model 2D - User's Manual
Page 677: Working Model 2D - User's Manual

673

C H A P T E R 5

Dialog Editor is a tool that enables you to create and modify custom dialog boxes for use inyour WM Basic scripts. Although the WM Basic statements used to display a dialog box andrespond to the choices made by a user of the dialog box may seem complicated, DialogEditor makes it easy to generate the WM Basic statements needed for your custom dialogboxes.Note: Currently, Dialog Editor is available only on Working Model for Windows. However,Working Model for Macintosh is perfectly capable of running scripts that include dialogs.For sample code, see entries in Chapter 2 that are related to Dialog Manipulation, PredefinedDialogs, and User Dialogs (the list of such entries can be found in section “LanguageElements by Category” of the Introduction).

ContentsOverviewUsing the Dialog EditorCreating a Custom Dialog BoxEditing a Custom Dialog BoxEditing an Existing Dialog BoxTesting an Edited Dialog BoxIncorporating a Dialog Box Template into Your ScriptExiting from Dialog EditorMenu Reference

Editing Custom Dialog Boxes(Windows Only)

Page 678: Working Model 2D - User's Manual

674 Working Model Basic User's Manual

OverviewSometimes your script will need to obtain information from the user. In many cases, you canobtain this information by using one of WM Basic's predefined dialog boxes in your script.When you must go beyond the information-gathering capabilities provided by predefineddialog boxes, you can use Dialog Editor to create a custom dialog box for use in your script.Dialog Editor is a tool that allows you to generate a dialog box template in WM Basic simplyby editing an on-screen dialog box layout. You can then incorporate the template that DialogEditor generates into your script.The balance of this section provides general information that you'll need in order to workwith Dialog Editor, including:

Features that Dialog Editor supportsAn introduction to Dialog Editor's application windowA list of keyboard shortcutsHow to use the Help system

Then, in the following sections, you'll learn how to use Dialog Editor to create and editcustom dialog boxes and to edit dialog boxes captured from other applications. You'll alsolearn how to test an edited dialog box and incorporate the dialog box template generated byDialog Editor into your script. And finally, you'll learn how to exit from Dialog Editor.

Features of the Dialog EditorDialog Editor supports the following features:

Visual editing of a dialog box template in WM BasicThe creation of dynamic dialog boxes

Using the Dialog EditorThis section presents general information that will help you work most effectively withDialog Editor. It includes an overview of Dialog Editor's application window—the interfaceyou'll use to create and edit dialog box templates in WM Basic—as well as a list of keyboardshortcuts and information on using the Help system.

Dialog Editor's Application WindowBefore you begin creating a new custom dialog box, Dialog Editor's application windowlooks like this:

Page 679: Working Model 2D - User's Manual

Chapter 5 Editing Custom Dialog Boxes (Windows Only) 675

Toolbar

Dialog box

Status bar

The application window contains the following elements:Toolbar: a collection of tools that you can use to provide instructionsto Dialog Editor, as discussed in the following subsectionDialog box: the visual layout of the dialog box that you are currentlycreating or editingStatus bar: provides key information about the operation you arecurrently performing, including the name of the currently selectedcontrol or dialog box, together with its position on the display and itsdimensions; the name of a control you are about to add to the dialogbox with the mouse pointer, together with the pointer's position on thedisplay; the function of the currently selected menu command; and theactivation of Dialog Editor's testing or capturing functions

Note: Dialog boxes created with Dialog Editor normally appear in an 8 point Helvetica font,both in Dialog Editor's application window and when the corresponding WM Basic code isrun.

Dialog Editor's ToolbarThe following list briefly explains the purpose of each of the tools on Dialog Editor's toolbar,which you can use to add controls to your dialog box, make various changes to the dialogbox and its controls, and test the dialog box's functioning.

Icon Tool Function

Run Runs the dialog box for testingpurposes.

Information Displays the Information dialog box forthe selected dialog box or control.

Page 680: Working Model 2D - User's Manual

676 Working Model Basic User's Manual

Pick Lets you select, move, and resize itemsand control the insertion point.

OK Button Adds an OK button to your dialog box.

Cancel Button Adds a Cancel button to your dialogbox.

Push Button Adds a push button to your dialog box.

Option Button Adds an option button to your dialogbox.

Check Box Adds a check box to your dialog box.

Group Box Adds a group box to your dialog box.

Text Adds a text control to your dialog box.

Text Box Adds a text box to your dialog box.

List Box Adds a list box to your dialog box.

Combo Box Adds a combo box to your dialog box.

Drop List Box Adds a drop list box to your dialog box.

Picture Adds a picture to your dialog box.

Picture Button Adds a picture button to your dialogbox.

The types of dialog box controls that you can add with the control tools are fully described inthe next section of the chapter.

Keyboard Shortcuts for Dialog EditorThe following keyboard shortcuts can be used for some of the operations you will performmost frequently in Dialog Editor.

Key(s) Function

Alt+F4 Closes Dialog Editor's application window.

Ctrl+C Copies the selected dialog box or control, withoutremoving it from Dialog Editor's applicationwindow, and places it on the Clipboard.

Ctrl+D Creates a duplicate copy of the selected control.

Page 681: Working Model 2D - User's Manual

Chapter 5 Editing Custom Dialog Boxes (Windows Only) 677

Ctrl+G Displays the Grid dialog box.

Ctrl+I Displays the Information dialog box for the selecteddialog box or control.

Ctrl+V Inserts the contents of the Clipboard into DialogEditor. If the Clipboard contains WM Basicstatements describing one or more controls, thenDialog Editor adds those controls to the currentdialog box. If the Clipboard contains the WM Basictemplate for an entire dialog box, then Dialog Editorcreates a new dialog box from the statements in thetemplate.

Ctrl+X Removes the selected dialog box or control fromDialog Editor's application window and places it onthe Clipboard.

Ctrl+Z Undoes the preceding operation.

Del Removes the selected dialog box or control fromDialog Editor's application window without placingit on the Clipboard.

F1 Displays Help for the currently active window.

F2 Runs the dialog box for testing purposes.

F3 Sizes certain controls to fit the text they contain.

Shift+F1 Toggles the Help pointer.

Using the Help SystemDialog Editor provides several ways to obtain on-line help.Here's how to display Help for the window or dialog box that is currently active.

To display Help for the currently active window:Press F1.If Dialog Editor's application window was active, the Help systemcontents appear. If a dialog box was active, Help for that dialog boxappears.

Here's how to access the Help system and search for a specific topic within it.

To pinpoint a specific topic in the Help system:1. From the Help menu, choose the Search for Help on command.

A scrollable list of Help topics appears.2. Select the desired topic from the list.

The topic you selected is displayed in a second scrollable list, togetherwith closely related Help topics, if any.

3. If the desired topic is not already highlighted on the second list, selectit and press Enter.

Page 682: Working Model 2D - User's Manual

678 Working Model Basic User's Manual

Help is displayed for the topic you selected.

Creating a Custom Dialog BoxThis section describes the types of controls that Dialog Editor supports. It also explains howto create controls and initially position them within your dialog box, and offers some pointerson creating controls efficiently.In the next section, "Editing a Custom Dialog Box," you'll learn how to make various typesof changes to the controls that you've created—moving and resizing them, assigning labelsand accelerator keys, and so forth.

Types of Controls

Dialog Editor supports the following types of standard Windows controls:Push button: a command button. The default OK and Cancel buttonsare special types of push buttons.Option button: one of a group of two or more linked buttons that letusers select only one from a group of mutually exclusive choices. Agroup of option buttons works the same way as the buttons on a carradio: because the buttons operate together as a group, clicking anunselected button in the group selects that button and automaticallydeselects the previously selected button in that group.Check box: a box that users can check or clear to indicate theirpreference regarding the alternative specified on the check box label.

Page 683: Working Model 2D - User's Manual

Chapter 5 Editing Custom Dialog Boxes (Windows Only) 679

Group box: a rectangular design element used to enclose a group ofrelated controls. You can use the optional group box label to display atitle for the controls in the box.Text: a field containing text that you want to display for the users'information. The text in this field wraps, and the field can contain amaximum of 255 characters. Text controls can either display stand-alone text or be used as labels for text boxes, list boxes, combo boxes,drop list boxes, pictures, and picture buttons. You can choose the fontin which the text appears.Text box: a field into which users can enter text (potentially, as muchas 32K). By default, this field holds a single line of nonwrapping text.If you choose the Multiline setting in the Text Box Information dialogbox, this field will hold multiple lines of wrapping text.List box: a displayed, scrollable list from which users can select oneitem. The currently selected item is highlighted on the list.Combo box: a text field with a displayed, scrollable list beneath it.Users can either select an item from the list or enter the name of thedesired item in the text field. The currently selected item is displayedin the text field. If the item was selected from the scrolling list, it ishighlighted there as well.Drop list box: a field that displays the currently selected item,followed by a downward-pointing arrow, which users can click totemporarily display a scrolling list of items. Once they select an itemfrom the list, the list disappears and the newly selected item isdisplayed in the field.Picture: a field used to display a Windows bitmap or metafile.Picture button: a special type of push, or command, button on whicha Windows bitmap or metafile appears.

Notes: 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 actupon these controls, and when they tab through the dialog box, the focus skips over thesecontrols.You can obtain a Windows bitmap or metafile from a file or from a specified library.

Adding Controls to a Dialog BoxIn this subsection, you'll learn how to create controls and determine approximately wherethey first appear within your dialog box. In the following subsection, you'll learn how todetermine the positioning of controls more precisely.Here's how to add one or more controls to your dialog box using simple mouse and keyboardmethods.

To add a control:1. From the toolbar, choose the tool corresponding to the type of control

you want to add.When you pass the mouse pointer over an area of the display where acontrol can be placed, the pointer becomes an image of the selected

Page 684: Working Model 2D - User's Manual

680 Working Model Basic User's Manual

control with crosshairs (for positioning purposes) to its upper left. Thename and position of the selected control appear on the status bar.When you pass the pointer over an area of the display where a controlcannot be placed, the pointer changes into a circle with a slash throughit (the "prohibited" symbol).Note: You can only insert a control within the borders of the dialogbox you are creating. You cannot insert a control on the dialog box'stitle bar or outside its borders.

2. Place the pointer where you want the control to be positioned and clickthe mouse button.The control you just created appears at the specified location. (To bemore specific, the upper left corner of the control will correspond tothe position of the pointer's crosshairs at the moment you clicked themouse button.) The control is surrounded by a thick frame, whichmeans that it is selected, and it may also have a default label.After the new control has appeared, the mouse pointer becomes anarrow, to indicate that the Pick tool is active and you can once againselect any of the controls in your dialog box.

3. To add another control of the same type as the one you just added,press Ctrl+D.A duplicate copy of the control appears.To add a different type of control, repeat steps 1 and 2.

4. To reactivate the Pick tool, click the arrow-shaped tool on the toolbar.-Or-Place the mouse pointer on the title bar of the dialog box or outside theborders of the dialog box (that is, on any area where the mouse pointerturns into the "prohibited" symbol) and click the mouse button.

As you plan your dialog box, keep in mind that a single dialog box can contain no more than255 controls and that a dialog box will not operate properly unless it contains either an OKbutton, a Cancel button, a push button, or a picture button. (When you create a new customdialog box, an OK button and a Cancel button are provided for you by default.)Later in the chapter, you'll learn more about selecting controls, and you'll learn how to assignlabels.

Using the Grid to Help You Position Controls within aDialog BoxThe preceding subsection explained how to determine approximately where a newly createdcontrol will materialize in your dialog box. Here, you'll learn how to use Dialog Editor's gridto help you fine-tune the initial placement of controls.The area of your dialog box in which controls can be placed (that is, the portion of the dialogbox below the title bar) can be thought of as a grid, with the X (horizontal) axis and the Y(vertical) axis intersecting in the upper left corner (the 0, 0 coordinates). The position ofcontrols can be expressed in terms of X units with respect to the left border of this area and interms of Y units with respect to the top border. (In fact, the position of controls is expressedin this manner within the dialog box template that you produce by working with DialogEditor.)

Page 685: Working Model 2D - User's Manual

Chapter 5 Editing Custom Dialog Boxes (Windows Only) 681

Here's how to display the grid and adjust its X and Y settings, which can help you positioncontrols more precisely within your dialog box.

To display and adjust the grid:1. Press Ctrl+G.

Dialog Editor displays the following dialog box:

2. To display the grid in your dialog box, select the Show grid check box.3. To change the current X and Y settings, enter new values in the X and

Y fields.Note: The values of X and Y in the Grid dialog box determine thegrid's spacing. Assigning smaller X and Y values produces a moreclosely spaced grid, which enables you to move the mouse pointer insmaller horizontal and vertical increments as you position controls.Assigning larger X and Y values produces the opposite effect on boththe grid's spacing and the movement of the mouse pointer. The X andY settings entered in the Grid dialog box remain in effect regardless ofwhether you choose to display the grid.

4. Click the OK button or press Enter.Dialog Editor displays the grid with the settings you specified. Withthe grid displayed, you can line up the crosshairs on the mouse pointerwith the dots on the grid to position controls precisely and align themwith respect to other controls.

Grid

Page 686: Working Model 2D - User's Manual

682 Working Model Basic User's Manual

As you move the mouse pointer over the dialog box after you have chosen a control toolfrom the toolbar, the status bar displays the name of the type of control you have selected andcontinually updates the position of the mouse pointer in X and Y units. (This informationdisappears if you move the mouse pointer over an area of the screen where a control cannotbe placed.) After you click the mouse button to add a control, that control remains selected,and the status bar displays the control's width and height in dialog units as well as its nameand position, as shown in the preceding illustration, in which the push button is selected.

Note: Dialog units represent increments of the font in which Dialog Editor creates dialogboxes (namely, 8 point Helvetica). Each X unit represents an increment equal to 1/4 of thatfont, and each Y unit represents an increment equal to 1/8 of that font.

Creating Controls EfficientlyCreating dialog box controls in random order might seem like the fastest approach. However,the order in which you create controls has some important implications, so a little advanceplanning can save you a lot of work in the long run.Here are several points about creating controls that you should keep in mind:

Tabbing order: Users can select dialog box controls by tabbing, asexplained in the next subsection. The order in which you create thecontrols is what determines the tabbing order. That is, as users tabthrough the dialog box, the focus is changed from one control to thenext in the order in which you created the controls (regardless of theorder in which you position the controls in the dialog box). The closeryou can come to creating controls in the order in which you want themto receive the tabbing focus, the fewer tabbing-order adjustmentsyou'll have to make later on.Option button grouping: If you want a series of option buttons towork together as a mutually exclusive group, you must create all thebuttons in that group one right after the other, in an unbrokensequence. If you get sidetracked and create a different type of controlbefore you have finished creating all the option buttons in your group,you'll split the buttons into two (or more) separate groups. (Let's sayyou want to create an option button group with five buttons. Youcreate three of the buttons and then create a list box, after which youfinish creating the last two buttons. When you test your dialog box,you'll find that all five of these option buttons don't work together as amutually exclusive group. Instead, the first three buttons will form onemutually exclusive group, and the last two buttons will form anothermutually exclusive group.)Accelerator keys: As explained later in the chapter, you can provideeasy access to a text box, list box, combo box, or drop list box byassigning an accelerator key to an associated text control, and you canprovide easy access to the controls in a group box by assigning anaccelerator key to the group box label. To do this, you must create thetext control or group box first, followed immediately by the controlsthat you want to associate with it. If the controls are not created in the

Page 687: Working Model 2D - User's Manual

Chapter 5 Editing Custom Dialog Boxes (Windows Only) 683

correct order, they will not be associated in your dialog box template,and any accelerator key you assign to the text control or group boxlabel will not work properly.

If you don't create controls in the most efficient order, the resulting problems with tabbingorder, option button grouping, and accelerator keys usually won't become apparent until youtest your dialog box. Although you can still fix these problems at that point, as explainedlater in the chapter, it will definitely be more cumbersome. In short, it's easier to prevent (orat least minimize) problems of this sort than to fix them after the fact.

Editing a Custom Dialog BoxIn the preceding section, you learned how to create controls and determine where theyinitially appear within your dialog box. In this section, you'll learn how to make various typesof changes to both the dialog box and the controls in it. The following topics are included:

Selecting items so that you can work with themUsing the Information dialog box to check and/or change variousattributes of itemsChanging the position and size of itemsChanging titles and labelsAssigning accelerator keysSpecifying picturesCreating or modifying picture libraries under WindowsDuplicating and deleting controlsUndoing editing operations

Selecting ItemsIn order to edit a dialog box or a control, you must first select it. When you select an item, itbecomes surrounded by a thick frame, as you saw in the preceding section.Here's how to select a control using either mouse or keyboard methods.

To select a control:With the Pick tool active, place the mouse pointer on the desiredcontrol and click the mouse button.-Or-With the Pick tool active, press the Tab key repeatedly until the focusmoves to the desired control.The control is now surrounded by a thick frame to indicate that it isselected and you can edit it.

Here's how to select the entire dialog box using either mouse or keyboard methods.

To select the dialog box:With the Pick tool active, place the mouse pointer on the title bar ofthe dialog box or on an empty area within the borders of the dialog box(that is, on an area where there are no controls) and click the mousebutton.-Or-

Page 688: Working Model 2D - User's Manual

684 Working Model Basic User's Manual

With the Pick tool active, press the Tab key repeatedly until the focusmoves to the dialog box.The dialog box is now surrounded by a thick frame to indicate that it isselected and you can edit it.

Using the Information Dialog BoxThe Information dialog box enables you to check and adjust various attributes of controls anddialog boxes. This subsection explains how to display the Information dialog box andprovides an overview of the attributes with which it lets you work. In the followingsubsections, you'll learn more about how to use the Information dialog box to make changesto your dialog box and its controls.Here's how to use the Dialog Box Information dialog box to check and adjust attributes thatpertain to the dialog box as a whole.

To display the Information dialog box for a dialog box:With the Pick tool active, place the mouse pointer on an area of thedialog box where there are no controls and double-click the mousebutton.-Or-With the Pick tool active, select the dialog box and either click theInformation tool on the toolbar, press Enter, or press Ctrl+I.Dialog Editor displays the Dialog Box Information dialog box:

Here's how to use the Information dialog box for a control to check and adjust attributes thatpertain to that particular control.

To display the Information dialog box for a control:With the Pick tool active, place the mouse pointer on the desiredcontrol and double-click the mouse button.-Or-

Page 689: Working Model 2D - User's Manual

Chapter 5 Editing Custom Dialog Boxes (Windows Only) 685

With the Pick tool active, select the control and either click theInformation tool on the toolbar, press Enter, or press Ctrl+I.Dialog Editor displays an Information dialog box corresponding to thecontrol you selected. Here is an example:

The following lists show the attributes that you can change with the Dialog Box Informationdialog box and the Information dialog boxes for the various controls. In some cases(specified below), it's mandatory to fill in the fields in which the attributes are specified—that is, you must either leave the default information in these fields or replace it with moremeaningful information, but you can't leave the fields empty. In other cases, filling in thesefields is optional—that is, you can either leave the default information in the fields, replace itwith more meaningful information, or leave the fields entirely empty.Note: A quick way to determine whether it's mandatory to fill in a particular Informationdialog box field is to see whether the OK button becomes grayed out when you delete theinformation in that field. If it does, then you must fill in that field.In many cases, you could simply leave the generic-sounding default information in theInformation dialog box fields and worry about replacing it with more meaningful informationafter you paste the dialog box template into your script. However, if you take a few momentsto replace the default information with something specific when you first create your dialogbox, not only will you save yourself some work later on but you may also find that yourchanges make the WM Basic code produced by Dialog Editor more readily comprehensibleand hence easier to work with.

Attributes That You Can Adjust with the Dialog BoxInformation Dialog Box

The Dialog Box Information dialog box can be used to check and adjust the followingattributes, which pertain to the dialog box as a whole.

Mandatory/Optional Attribute

Optional Position: X and Y coordinates on the display, indialog units

Mandatory Size: width and height of the dialog box, in dialogunits

Page 690: Working Model 2D - User's Manual

686 Working Model Basic User's Manual

Optional Style: options that allow you to determine whetherthe close box and title bar are displayed

Optional Text$: text displayed on the title bar of the dialogbox

Mandatory Name: name by which you refer to this dialog boxtemplate in your WM Basic code

Optional .Function: name of a WM Basic function in yourdialog box

Optional Picture Library: picture library from which oneor more pictures in the dialog box are obtained

Attributes That You Can Adjust with the Information DialogBox for a Control

The Information dialog box for a control can be used to check and adjust the followingattributes. The second column of the list indicates the control(s) to which each attributepertains.

Mandatory/Optional Control(s) Affected Attribute

Mandatory All controls Position: X and Ycoordinates within thedialog box, in dialog units

Mandatory All controls Size: width and height ofthe control, in dialog units

Optional Push button, optionbutton, check box,group box, and text

Text$: text displayed on acontrol

Optional Text Font: font in which text isdisplayed

Optional Text box Multiline: option thatallows you to determinewhether users can enter asingle line of text ormultiple lines

Optional OK button, Cancelbutton, push button,option button, groupbox, text, picture,and picture button

.Identifier: name by whichyou refer to a control inyour WM Basic code

Page 691: Working Model 2D - User's Manual

Chapter 5 Editing Custom Dialog Boxes (Windows Only) 687

Mandatory Check box, text box,list box, combo box,and drop list box

.Identifier: name by whichyou refer to a control inyour WM Basic code; alsocontains the result of thecontrol after the dialog boxhas been processed

Optional Picture, picturebutton

.Identifier: name of the filecontaining a picture thatyou want to display or thename of a picture that youwant to display from aspecified picture library

Optional Picture Frame: option that allowsyou to display a 3-D frame

Mandatory List box, combobox, and drop listbox

Array$: name of an arrayvariable in your WM Basiccode

Mandatory Option button .Option Group: name bywhich you refer to a groupof option buttons in yourWM Basic code

Changing Position and SizeThis subsection explains how Dialog Editor helps you keep track of the location anddimensions of dialog boxes and controls, and presents several ways to move and resize theseitems.

Keeping Track of Position and SizeDialog Editor's display can be thought of as a grid, in which the X (horizontal) axis and the Y(vertical) axis intersect in the upper left corner of the display (the 0, 0 coordinates). Theposition of the dialog box you are creating can be expressed in terms of X units with respectto the left border of the parent window and in terms of Y units with respect to the top border.As explained in the preceding section, the portion of your dialog box below the title bar canalso be thought of as a grid, with the X and Y axes intersecting in the upper left corner of thisarea. The position of controls within the dialog box can be expressed in terms of X units withrespect to the left border of this area and in terms of Y units with respect to the top border.When you select a dialog box or control, the status bar displays its position in X and Y unitsas well as its width and height in dialog units. Each time you move or resize an item, thecorresponding information on the status bar is updated. You can use this information toposition and size items more precisely.

Changing the Position of an ItemDialog Editor provides several ways to reposition dialog boxes and controls.Here's how to move a dialog box or control by dragging it with the mouse.

Page 692: Working Model 2D - User's Manual

688 Working Model Basic User's Manual

To reposition an item with the mouse:1. With the Pick tool active, place the mouse pointer on an empty area of

the dialog box or on a control.2. Depress the mouse button and drag the dialog box or control to the

desired location.Note: The increments by which you can move a control with themouse are governed by the grid setting. For example, if the grid's Xsetting is 4 and its Y setting is 6, you'll be able to move the controlhorizontally only in increments of 4 X units and vertically only inincrements of 6 Y units. This feature is handy if you're trying to aligncontrols in your dialog box. If you want to move controls in smaller orlarger increments, press Ctrl+G to display the Grid dialog box andadjust the X and Y settings.

Here's how to move a selected dialog box or control by pressing the arrow keys.

To reposition an item with the arrow keys:1. Select the dialog box or control that you want to move.2. Press an arrow key once to move the item by 1 X or Y unit in the

desired direction.-Or-Depress an arrow key to "nudge" the item steadily along in the desireddirection.Note: When you reposition an item with the arrow keys, a faint, partialafterimage of the item may remain visible in the item's originalposition. These afterimages are rare and will disappear once you testyour dialog box.

Here's how to move a selected dialog box by changing its coordinates in the Dialog BoxInformation dialog box.

To reposition a dialog box with the Dialog Box Information dialog box:1. Display the Dialog Box Information dialog box.2. Change the X and Y coordinates in the Position group box.

-Or-Leave the X and/or Y coordinates blank.

3. Click the OK button or press Enter.If you specified X and Y coordinates, the dialog box moves to thatposition. If you left the X coordinate blank, the dialog box will becentered horizontally relative to the parent window of the dialog boxwhen the dialog box is run. If you left the Y coordinate blank, thedialog box will be centered vertically relative to the parent window ofthe dialog box when the dialog box is run.

Here's how to move a selected control by changing its coordinates in the Information dialogbox for that control.

Page 693: Working Model 2D - User's Manual

Chapter 5 Editing Custom Dialog Boxes (Windows Only) 689

To reposition a control with the Information dialog box:1. Display the Information dialog box for the control that you want to

move.2. Change the X and Y coordinates in the Position group box.3. Click the OK button or press Enter.

The control moves to the specified position.Notes: When you move a dialog box or control with the arrow keys or with the Informationdialog box, the item's movement is not restricted to the increments specified in the gridsetting.When you attempt to test a dialog box containing hidden controls (i.e., controls positionedentirely outside the current borders of your dialog box), Dialog Editor displays a messageadvising you that there are controls outside the dialog box's borders and asks whether youwish to proceed with the test. If you proceed, the hidden controls will be disabled for testingpurposes. (Testing dialog boxes is discussed later in the chapter.)

Changing the Size of an ItemDialog boxes and controls can be resized either by directly manipulating them with themouse or by using the Information dialog box. Certain controls can also be resizedautomatically to fit the text displayed on them.Here's how to change the size of a selected dialog box or control by dragging its borders orcorners with the mouse.

To resize an item with the mouse:1. With the Pick tool active, select the dialog box or control that you

want to resize.2. Place the mouse pointer over a border or corner of the item.3. Depress the mouse button and drag the border or corner until the item

reaches the desired size.Here's how to change the size of a selected dialog box or control by changing its Widthand/or Height settings in the Information dialog box.

To resize an item with the Information dialog box:1. Display the Information dialog box for the dialog box or control that

you want to resize.2. Change the Width and Height settings in the Size group box.3. Click the OK button or press Enter.

The dialog box or control is resized to the dimensions you specified.Here's how to adjust the borders of certain controls automatically to fit the text displayed onthem.

To resize selected controls automatically:1. With the Pick tool active, select the option button, text control, push

button, check box, or text box that you want to resize.2. Press F2.

The borders of the control will expand or contract to fit the textdisplayed on it.

Page 694: Working Model 2D - User's Manual

690 Working Model Basic User's Manual

Note: Windows metafiles always expand or contract proportionally to fit within the picturecontrol or picture button control containing them. In contrast, windows bitmaps are of a fixedsize. If you place a bitmap in a control that is smaller than the bitmap, the bitmap is clippedoff on the right and bottom. If you place a bitmap in a control that is larger than the bitmap,the bitmap is centered within the borders of the control. Picture controls and picture buttoncontrols must be resized manually.

Changing Titles and LabelsBy default, when you begin creating a dialog box, its title reads "Untitled," and when youfirst create group boxes, option buttons, push buttons, text controls, and check boxes, theyhave generic-sounding default labels, such as "Group Box" and "Option Button."Here's how to change the title of your dialog box as well as the labels of group boxes, optionbuttons, push buttons, text controls, and check boxes.

To change a dialog box title or a control label:1. Display the Information dialog box for the dialog box whose title you

want to change or for the control whose label you want to change.2. Enter the new title or label in the Text$ field.

Note: Dialog box titles and control labels are optional. Therefore, youcan leave the Text$ field blank.

3. If the information in the Text$ field should be interpreted as a variablename rather than a literal string, select the Variable Name check box.

4. Click the OK button or press Enter.The new title or label is now displayed on the title bar or on thecontrol.

Although OK and Cancel buttons also have labels, you cannot change them. The remainingcontrols (text boxes, list boxes, combo boxes, drop list boxes, pictures, and picture buttons)don't have their own labels, but you can position a text control above or beside these controlsto serve as a de facto label for them.

Assigning Accelerator KeysAccelerator keys enable users to access dialog box controls simply by pressing Alt + aspecified letter. Users can employ accelerator keys to choose a push button or an optionbutton; toggle a check box on or off; and move the insertion point into a text box or groupbox or to the currently selected item in a list box, combo box, or drop list box.An accelerator key is essentially a single letter that you designate for this purpose from acontrol's label. You can assign an accelerator key directly to controls that have their ownlabel (option buttons, push buttons, check boxes, and group boxes). (You can't assign anaccelerator key to OK and Cancel buttons because, as noted above, their labels can't beedited.) You can create a de facto accelerator key for certain controls that don't have theirown labels (text boxes, list boxes, combo boxes, and drop list boxes) by assigning anaccelerator key to an associated text control.Here's how to designate a letter from a control's label to serve as the accelerator key for thatcontrol.

Page 695: Working Model 2D - User's Manual

Chapter 5 Editing Custom Dialog Boxes (Windows Only) 691

To assign an accelerator key:1. Display the Information dialog box for the control to which you want

to assign an accelerator key.2. In the Text$ field, type an ampersand (&) before the letter you want to

designate as the accelerator key.3. Click the OK button or press Enter.

The letter you designated is now underlined on the control's label, andusers will be able to access the control by pressing Alt + theunderlined letter.

Note: Accelerator key assignments must be unique within a particular dialog box. If youattempt to assign the same accelerator key to more than one control, Dialog Editor displays areminder that that letter has already been assigned.

If, for example, you have a push button whose label reads Apply, you can designate A as theaccelerator key by displaying the Push Button Information dialog box and typing &Apply inthe Text$ field. When you press Enter, the button label looks like the following illustration,and users will be able to choose the button by typing Alt+A.

As another example, let's say you have a list box that is immediately preceded in the dialogbox template by a text control whose label reads 1994 Project Files. By using the methoddescribed above, you can designate F as the accelerator key. When you click OK or pressEnter, the text control label looks like the following illustration, and users will be able tomove the insertion point to the currently selected item in the list box by typing Alt+F.

Note: In order for such a de facto accelerator key to work properly, the text control or groupbox label to which you assign the accelerator key must be associated with the control(s) towhich you want to provide user access—that is, in the dialog box template, the description ofthe text control or group box must immediately precede the description of the control(s) thatyou want associated with it. The simplest way to establish such an association is to create thetext control or group box first, followed immediately by the associated control(s).

Specifying PicturesIn the preceding section, you learned how to add picture controls and picture button controlsto your dialog box. But these controls are nothing more than empty outlines until you specifythe pictures that you want them to display.

Page 696: Working Model 2D - User's Manual

692 Working Model Basic User's Manual

A picture control or picture button control can display a Windows bitmap or metafile, whichyou can obtain from a file or from a specified library. (Refer to the following subsection forinformation on creating or modifying picture libraries under Windows.)Here's how to display a Windows bitmap or metafile from a file on a picture control orpicture button control by using the control's Information dialog box to indicate the file inwhich the picture is contained.

To specify a picture from a file:1. Display the Information dialog box for the picture control or picture

button control whose picture you want to specify.2. In the Picture source option button group, select File.3. In the Name$ field, enter the name of the file containing the picture

you want to display in the picture control or picture button control.Note: By clicking the Browse button, you can display the Select aPicture File dialog box and use it to find the file.

4. Click the OK button or press Enter.The picture control or picture button control now displays the pictureyou specified.

Here's how to display a Windows bitmap or metafile from a library on a picture control orpicture button control by first using the Dialog Box Information dialog box to specify thelibrary and then using the control's Information dialog box to indicate the name of thepicture.

To specify a picture from a picture library:1. Display the Dialog Box Information dialog box.2. In the Picture Library field, specify the name of the picture library that

contains the picture(s) you want to display in your dialog box.Notes: By clicking the Browse button, you can display the Select aPicture Library dialog box and use it to find the library.If you specify a picture library in the Dialog Box Information dialogbox, all the pictures in your dialog box must come from this library.

3. Click the OK button or press Enter.4. Display the Information dialog box for the picture control or picture

button control whose picture you want to specify.5. In the Picture source option button group, select Library.6. In the Name$ field, enter the name of the picture you want to display

on the picture control or picture button control. (This picture must befrom the library that you specified in step 2.)

7. Click the OK button or press Enter.The picture control or picture button control now displays the pictureyou specified.

Creating or Modifying Picture Libraries under WindowsThe Picture statement in WM Basic allows images to be specified as individual picturefiles or as members of a picture library, which is a DLL that contains a collection of pictures.

Page 697: Working Model 2D - User's Manual

Chapter 5 Editing Custom Dialog Boxes (Windows Only) 693

Currently, both Windows bitmaps and metafiles are supported. You can obtain a picturelibrary either by creating a new one or by modifying an existing one, as described below.Each image is placed into the DLL as a resource identified by its unique resource identifier.This identifier is the name used in the Picture statement to specify the image.The following resource types are supported in picture libraries:

Resource Type Description

2 Bitmap. This is defined in windows.h as RT_BITMAP.

256 Metafile. Since there is no resource type formetafiles, 256 is used.

Here's how to create a new picture library to contain the Windows bitmaps or metafiles thatyou want to display on picture controls or picture button controls in your dialog box.

To create a picture library under Windows:1. Create a C file containing the minimal code required to establish a

DLL. The following code can be used:#include <windows.h>int CALLBACK LibMain(

HINSTANCE hInstance,WORD wDataSeg,WORD wHeapSz,LPSTR lpCmdLine) {UnlockData(0);return 1;

}2. Use the following code to create a DEF file for your picture library:

LIBRARYDESCRIPTION "My Picture Library"EXETYPE WINDOWSCODE LOADONCALL MOVABLE DISCARDABLEDATA PRELOAD MOVABLE SINGLEHEAPSIZE 1024

3. Create a resource file containing your images. The following exampleshows a resource file using a bitmap called sample.bmp and ametafile called usa.wmf.#define METAFILE 256USA METAFILE "usa.wmf"MySample BITMAP "sample.bmp"

4. Create a make file that compiles your C module, creates the resourcefile, and links everything together.

Here's how to modify an existing picture library to contain the Windows bitmaps or metafilesthat you want to display on picture controls or picture button controls in your dialog box.

To modify an existing picture library:1. Make a copy of the picture library you want to modify.2. Modify the copy by adding images using a resource editor such as

Borland's Resource Workshop or Microsoft's App Studio.Note: When you use a resource editor, you need to create a newresource type for metafiles (with the value 256).

Page 698: Working Model 2D - User's Manual

694 Working Model Basic User's Manual

Duplicating and Deleting ControlsHere's how to use Dialog Editor's duplicating feature, which saves you the work of creatingadditional controls individually if you need one or more copies of a particular control.

To duplicate a control:1. Select the control that you want to duplicate.2. Press Ctrl+D.

A duplicate copy of the selected control appears in your dialog box.3. Repeat step 2 as many times as necessary to create the desired number

of duplicate controls.Duplicating is a particularly efficient approach if you need to create a group of controls, suchas a series of option buttons or check boxes. Simply create the first control in the group andthen, while the newly created control remains selected, repeatedly press Ctrl+D until youhave created the necessary number of copies.Dialog Editor also enables you to delete single controls or even clear the entire dialog box.If you want to remove controls from your dialog box selectively, here's how to delete themone at a time.

To delete a single control:1. Select the control you want to delete.2. Press Del.

The selected control is removed from your dialog box.If you want to "wipe the slate clean" and start all over again with your dialog box, here's howto remove all its controls in a single operation.

To delete all the controls in a dialog box:1. Select the dialog box.2. Press Del.3. If the dialog box contains more than one control, Dialog Editor

prompts you to confirm that you want to delete all controls. Click theYes button or press Enter.All the controls disappear, but the dialog box's title bar and close box(if displayed) remain unchanged.

Undoing Editing OperationsYou can undo editing operations that produce a change in your dialog box, including:

The addition of a controlThe insertion of one or more controls from the ClipboardThe deletion of a controlChanges made to a control or dialog box, either with the mouse or withthe Information dialog box

You cannot undo operations that don't produce any change in your dialog box, such asselecting controls or dialog boxes and copying material to the Clipboard.Here's how to reverse the effect of the preceding editing operation.

To undo an editing operation:Press Ctrl+Z.

Page 699: Working Model 2D - User's Manual

Chapter 5 Editing Custom Dialog Boxes (Windows Only) 695

Your dialog box is restored to the way it was before you performed theediting operation.

Editing an Existing Dialog BoxThere are three ways to edit an existing dialog box: (1) You can copy the WM Basic templateof the dialog box you want to edit from a script to the Clipboard and paste it into DialogEditor. (2) You can use the capture feature to "grab" an existing dialog box from anotherapplication and insert a copy of it into Dialog Editor. (3) You can open a dialog box templatefile that has been saved on a disk. Once you have the dialog box displayed in Dialog Editor'sapplication window, you can edit it using the methods described earlier in the chapter.

Pasting an Existing Dialog Box into Dialog EditorYou can use Dialog Editor to modify the WM Basic statements in your script that correspondto an entire dialog box or to one or more dialog box controls.If you want to modify a WM Basic dialog box template contained in your script, here's howto select the template and paste it into Dialog Editor for editing.

To edit an existing dialog box directly:

1. Select the entire WM Basic dialog box template (from the BeginDialog instruction to the End Dialog instruction) in your script.

2. Choose Edit Dialog in the Edit menu of the Script Editor.Dialog Editor creates a new dialog box corresponding to the templateselected in the Script Editor.

To paste an existing dialog box into Dialog Editor:

1. Copy the entire WM Basic dialog box template (from the BeginDialog instruction to the End Dialog instruction) from your scriptto the Clipboard.

2. Open Dialog Editor.3. Press Ctrl+V.4. When Dialog Editor asks whether you want to replace the existing

dialog box, click the Yes button.Dialog Editor creates a new dialog box corresponding to the templatecontained on the Clipboard.

If you want to modify the WM Basic statements in your script that correspond to one or moredialog box controls, here's how to select the statements and paste them into Dialog Editor forediting.

To paste one or more controls from an existing dialog box into DialogEditor:1. Copy the WM Basic description of the control(s) from your script to

the Clipboard.2. Open Dialog Editor.3. Press Ctrl+V.

Dialog Editor adds to your current dialog box one or more controlscorresponding to the description contained on the Clipboard.

Page 700: Working Model 2D - User's Manual

696 Working Model Basic User's Manual

Notes: When you paste a dialog box template into Dialog Editor, the tabbing order of thecontrols is determined by the order in which the controls are described in the template. Whenyou 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 WM Basic statements that describe the dialog box or controls,the Dialog Translation Errors dialog box will appear when you attempt to paste thesestatements into Dialog Editor. This dialog box shows the lines of code containing the errorsand provides a brief description of the nature of each error.

Capturing a Dialog Box from Another ApplicationHere's how to capture the standard Windows controls from any standard Windows dialog boxin another application and insert those controls into Dialog Editor for editing.

To capture an existing standard Windows dialog box:1. Display the dialog box you want to capture.2. Open Dialog Editor.3. Choose the Capture Dialog command from the File menu.

Dialog Editor's application window moves behind all other openapplication windows, and the dialog box you displayed in step 1reappears. The mouse pointer, previously an arrow, now looks like abutterfly net.

4. Place the mouse pointer over the dialog box that you want to capture.If the mouse pointer is over a standard Windows dialog box thatcontains some standard Windows controls, a tiny dialog box appears infront of the mouse pointer's butterfly net to indicate that the pointerhas found controls that can be captured. If the mouse pointer is notover a standard Windows dialog box that contains standard Windowscontrols, the butterfly net remains unchanged to indicate that themouse pointer has not found controls that can be captured.

Mouse pointer positioned over an area of the screen that doesnot contain standard Windows controls

Mouse pointer positioned over a standard Windows dialogbox that contains some standard Windows controls

5. Click the mouse button.Dialog Editor's application window moves in front of all other openapplication windows and now displays the standard Windows controlsfrom the target dialog box.Note: Dialog Editor only supports standard Windows controls andstandard Windows dialog boxes. Therefore, if the target dialog boxcontains both standard Windows controls and custom controls, onlythe standard Windows controls will appear in Dialog Editor'sapplication window. If the target dialog box is not a standard Windowsdialog box, you will be unable to capture the dialog box or any of itscontrols.

Page 701: Working Model 2D - User's Manual

Chapter 5 Editing Custom Dialog Boxes (Windows Only) 697

Opening a Dialog Box Template FileHere's how to open any dialog box template file that has been saved on a disk so you can editthe template in Dialog Editor.

To open a dialog box template file:1. Choose Open from the File menu.

The Open Dialog File dialog box appears.2. Select the file containing the dialog box template that you want to edit

and click the OK button.Dialog Editor creates a dialog box from the statements in the templateand displays it in the application window.

Note: If there are any errors in the WM Basic statements that describe the dialog box, theDialog Translation Errors dialog box will appear when you attempt to load the file intoDialog Editor. This dialog box shows the lines of code containing the errors and provides abrief description of the nature of each error.

Testing an Edited Dialog BoxDialog Editor lets you run your edited dialog box for testing purposes. When you click theTest tool, your dialog box comes alive, which gives you an opportunity to make sure itfunctions properly and fix any problems before you incorporate the dialog box template intoyour script.Before you run your dialog box, take a moment to look it over for basic problems such as thefollowing:

Does the dialog box contain a command button—that is, a default OKor Cancel button, a push button, or a picture button?Does the dialog box contain all the necessary push buttons?Does the dialog box contain a Help button if one is needed?Are the controls aligned and sized properly?If there is a text control, is its font set properly?Are the close box and title bar displayed (or hidden) as you intended?Are the control labels and dialog box title spelled and capitalizedcorrectly?Do all the controls fit within the borders of the dialog box?Could you improve the design of the dialog box by adding one or moregroup boxes to set off groups of related controls?Could you clarify the purpose of any unlabeled control (such as a textbox, list box, combo box, drop list box, picture, or picture button) byadding a text control to serve as a de facto label for it?Have you made all the necessary accelerator key assignments?

After you've fixed any elementary problems, you're ready to run your dialog box so you cancheck for problems that don't become apparent until a dialog box is activated.Testing your dialog box is an iterative process that involves running the dialog box to seehow well it works, identifying problems, stopping the test and fixing those problems, thenrunning the dialog box again to make sure the problems are fixed and to identify any

Page 702: Working Model 2D - User's Manual

698 Working Model Basic User's Manual

additional problems, and so forth—until the dialog box functions the way you intend. Here'show to test your dialog box and fine-tune its performance.

To test your dialog box:1. Click the Run tool on the toolbar.

-Or-Press F5.The dialog box becomes operational, and you can check how itfunctions.

2. To stop the test, click the Run tool, press F5, or double-click the dialogbox's close box (if it has one).

3. Make any necessary adjustments to the dialog box.4. Repeat steps 1–3 as many times as you need in order to get the dialog

box working properly.When testing a dialog box, you can check for operational problems such as the following:

Tabbing order: When you press the Tab key, does the focus movethrough the controls in a logical order? (Remember, the focus skipsover items that users cannot act upon, including group boxes, textcontrols, and pictures.)When you paste controls into your dialog box, Dialog Editor placestheir descriptions at the end of your dialog box template, in the orderin which you paste them in. Therefore, you can use a simple cut-and-paste technique to adjust the tabbing order. First, click the Run tool toend the test and then, proceeding in the order in which you want thecontrols to receive the focus, select each control, cut it from the dialogbox (by pressing Ctrl+X), and immediately paste it back in again (bypressing Ctrl+V). The controls will now appear in the desired order inyour template and will receive the tabbing focus in that order.Option button grouping: Are the option buttons grouped correctly?Does selecting an unselected button in a group automatically deselectthe previously selected button in that group?To merge two groups of option buttons into a single group, click theRun tool to end the test and then use the Option Button Informationdialog box to assign the same .Option Group name for all the buttonsthat you want included in that group.Text box functioning: Can you enter only a single line ofnonwrapping text, or can you enter multiple lines of wrapping text?If the text box doesn't behave the way you intended, click the Run toolto end the test; then display the Text Box Information dialog box andselect or clear the Multiline check box.Accelerator keys: If you have assigned an accelerator key to a textcontrol or group box in order to provide user access to a text box, listbox, combo box, drop list box, or group box, do the accelerator keyswork properly? That is, if you press Alt + the designated acceleratorkey, does the insertion point move into the text box or group box or tothe currently selected item in the list box, combo box, or drop list box?

Page 703: Working Model 2D - User's Manual

Chapter 5 Editing Custom Dialog Boxes (Windows Only) 699

If the accelerator key doesn't work properly, it means that the text box,list box, combo box, drop list box, or group box is not associated withthe text control or group box to which you assigned the acceleratorkey—that is, in your dialog box template, the description of the textcontrol or group box does not immediately precede the description ofthe control(s) that should be associated with it. As with tabbing-orderproblems (discussed above), you can fix this problem by using asimple cut-and-paste technique to adjust the order of the controldescriptions in your template. First, click the Run tool to end the test;then cut the text control or group box from the dialog box andimmediately paste it back in again; and finally, do the same with eachof the controls that should be associated with the text control or groupbox. The controls will now appear in the desired order in yourtemplate, and the accelerator keys will work properly.

Incorporating a Dialog Box Template into YourScriptDialog boxes and dialog box controls are communicated between Dialog Editor and yourscript via the Clipboard, where they are represented as WM Basic statements. Here's how tocopy a dialog box or control and paste it into your script.

To incorporate a dialog box or control into your script:1. Select the dialog box or control that you want to incorporate into your

script.2. Press Ctrl+C.3. Open your script and paste in the contents of the Clipboard at the

desired point.The dialog box template or control is now described in WM Basicstatements in your script, as shown in the following example.

Page 704: Working Model 2D - User's Manual

700 Working Model Basic User's Manual

Exiting from Dialog EditorHere's how to get out of Dialog Editor. When you exit, you can save your dialog boxtemplate (that is, the WM Basic description of the dialog box) as a text file.

To exit from Dialog Editor:1. Press Alt+F4.

If you have made changes to your dialog box template, Dialog Editorasks whether you want to save those changes.

2. If you want to save your changes to a text file, click the Yes button.Dialog Editor displays the Save Dialog File dialog box, which you canuse to specify the file to which you want to save your template.

Menu/Tools ReferenceFile Menu

MenuCommand

ToolbarTool

KeyboardShortcut

Function

N ew Creates a new dialog box. DialogEditor prompts you beforediscarding any changes you havemade to your current dialog box.

Page 705: Working Model 2D - User's Manual

Chapter 5 Editing Custom Dialog Boxes (Windows Only) 701

O pen... Displays the Open Dialog Filedialog box, which you can use toopen an existing dialog boxtemplate. Dialog Editor promptsyou before discarding anychanges you have made to yourcurrent dialog box.

S ave If you have already created a filefor the current dialog boxtemplate, saves the template tothat file.

If you have not yet created a filefor the current dialog boxtemplate, displays the SaveDialog File dialog box, which youcan use to specify the file towhich you want to save thecurrent template.

Save A s...

Displays the Save Dialog Filedialog box, which you can use tosave the current dialog boxtemplate in a file under a newname.

T estDialog

F5 Toggles between the run mode (inwhich the dialog box "comesalive" for testing purposes) andthe edit mode (in which you canmake changes to the dialog box).

C aptureDialog

Captures the standard Windowscontrols from a standardWindows dialog box in anotherWindows application.

E x it Alt+F4 Closes Dialog Editor. DialogEditor prompts you beforediscarding any changes you havemade to your current dialog box.

Exit &Return

Alt+F4 Closes Dialog Editor and returnsyou to the host application.Dialog Editor prompts you beforediscarding any changes you havemade to your current dialog box.

Page 706: Working Model 2D - User's Manual

702 Working Model Basic User's Manual

Edit Menu

MenuCommand

ToolbarTool

KeyboardShortcut

Function

U ndo Ctrl+Z Allows you to undo up to 10preceding operations. The Undocommand continually indicatesthe next operation you can undoby selecting it and grays out whenthere are no more operations thatcan be undone.

Cu t Ctrl+X Removes the selected dialog boxor control from Dialog Editor'sapplication window and places iton the Clipboard.

C opy Ctrl+C Copies the selected dialog box orcontrol, without removing it fromDialog Editor's applicationwindow, and places it on theClipboard.

P aste Ctrl+V Inserts the contents of theClipboard into Dialog Editor.

If the Clipboard contains WMBasic statements describing oneor more controls, then thosecontrols are added to the currentdialog box. If the Clipboardcontains the WM Basic templatefor an entire dialog box, thenDialog Editor creates a newdialog box from the statements inthe template.

If the WM Basic statementscontain errors, Dialog Editordisplays the Dialog TranslationErrors dialog box, which helpsyou pinpoint the location andnature of the errors.

Page 707: Working Model 2D - User's Manual

Chapter 5 Editing Custom Dialog Boxes (Windows Only) 703

D elete Del Removes the selected dialog boxor control from Dialog Editor'sapplication window withoutplacing it on the Clipboard. If youhave selected the dialog box andit contains more than one control,Dialog Editor prompts you beforeremoving all the controls from it.

Duplic a te Ctrl+D Creates a duplicate copy of theselected control.

Si z e toText

F3 Adjusts the borders of certaincontrols to fit the text displayedon them.

I nfo... Ctrl+I Displays the Information dialogbox for the selected dialog box orcontrol. You can use this dialogbox to check and adjust variousattributes of controls and dialogboxes.

G rid... Ctrl+G Displays the Grid dialog box,which you can use to display orturn off the grid and adjust thegrid's spacing.

Controls Menu

MenuCommand

ToolbarTool Function

O K button

Adds a default OK button to your dialog box.An OK button is a special type of push, orcommand, button.

C a ncelbutton

Adds a default Cancel button to your dialogbox. A Cancel button is a special type ofpush, or command, button.

P ushbutton

Adds a push, or command, button to yourdialog box.

O ptionbutton

Adds an option button to your dialog box. Anoption button is one of a group of two or morelinked buttons that let users select only onefrom a group of mutually exclusive choices.

Page 708: Working Model 2D - User's Manual

704 Working Model Basic User's Manual

C heckbox

Adds a check box to your dialog box. Userscan check or clear a check box to indicatetheir preference regarding the alternativespecified on the check box label.

G roupbox

Adds a group box to your dialog box. A groupbox is a rectangular design element used toenclose a group of related controls. You canuse the optional group box label to display atitle for the controls in the box.

T ext Adds a text control to your dialog box. A textcontrol is a field containing text that you wantto display for the users' information. The textin this field wraps, and the field can contain amaximum of 255 characters. Text controlscan either display stand-alone text or be usedas labels for text boxes, list boxes, comboboxes, drop list boxes, pictures, and picturebuttons. You can choose the font in which thetext appears.

T e xt box Adds a text box to your dialog box. A textbox is a field into which users can enter text(potentially, as much as 32K). By default, thisfield holds a single line of nonwrapping text.If you choose the Multiline setting in the TextBox Information dialog box, this field willhold multiple lines of wrapping text.

L ist box Adds a list box to your dialog box. A list boxis a displayed, scrollable list from which userscan select one item. The currently selecteditem is highlighted on the list.

Com b obox

Adds a combo box to your dialog box. Acombo box consists of a text field with adisplayed, scrollable list beneath it. Users caneither select an item from the list or enter thename of the desired item in the text field. Thecurrently selected item is displayed in the textfield. If the item was selected from thescrolling list, it is highlighted there as well.

Page 709: Working Model 2D - User's Manual

Chapter 5 Editing Custom Dialog Boxes (Windows Only) 705

D rop listbox

Adds a drop list box to your dialog box. Adrop list box consists of a field that displaysthe currently selected item, followed by adownward-pointing arrow, which users canclick to temporarily display a scrolling list ofitems. Once they select an item from the list,the list disappears and the newly selected itemis displayed in the field.

P i cture Adds a picture to your dialog box. A pictureis a field used to display a Windows bitmap ormetafile.

Picturebutton

Adds a picture button to your dialog box. Apicture button is a special type of push, orcommand, button on which a Windowsbitmap or metafile appears.

Help Menu

MenuCommand

KeyboardShortcut

Function

C ontents F1 Presents a list of major topics in the Helpsystem. By clicking a topic on the list, youcan display the available Help informationabout that topic.

S earchfor HelpOn...

Displays a dialog box that allows users tosearch for Help topics containing specifickeywords.

A boutDialogEditor...

Displays the About Dialog Editor dialog box,which indicates application name, versionnumber, copyright statement, and icon, aswell as additional information such as amountof available memory and disk space.

Pick Tool

ToolbarTool Function

Pick

Lets you select, move, and resize items and control theinsertion point.

Page 710: Working Model 2D - User's Manual

706 Working Model Basic User's Manual

Using a Custom DialogYou can use a custom dialog box to display information to a user while providing anopportunity to respond. After using Dialog Editor to insert a dialog box template into yourscript, you’ll need to make the following modifications to your script.

1. Create a dialog record by using a Dim statement.2. Put information into the custom dialog box by assigning values to

dialog box controls.3. Display the custom dialog box by using either the Dialog( ) function or

the Dialog statement.4. Retrieve values from the custom dialog box after the user closes it.

Creating a Dialog RecordTo store the values retrieved from a customer dialog box, you create a dialog record with aDim statement, using the following syntax:

Dim DialogRecord As DialogVariableHere are some examples of how to create dialog records:

Dim b As UserDialog ' Define a dialog record "b"Dim PlayCD As CDDialog ' Define a dialog record "PlayCD"

Here is a sample script named DIALOG1.WBS that illustrates how to create a dialog recordnamed b within a dialog box template named UserDialog. Notice that the dialog boxtemplate precedes the statement that creates the dialog record and that the Dialog statementfollows both of them in the script.

Sub Main()Dim Listbox1$() 'Initialize listbox array'Define the dialog box templateBegin Dialog UserDialog ,,163,94,"Grocery Order"

Text 13,6,32,8,"&Quantity:",.Text1TextBox 48,4,28,12,.TextBox1ListBox 12,28,68,32,ListBox1$,.ListBox1OKButton 112,8,40,14CancelButton 112,28,40,14

End DialogDim b as UserDialog 'Create the dialog recordDialog b 'Display the dialog

End Sub

Put information into the custom dialog boxIf you open and run the sample script shown in the previous section, you'll see a dialog boxthat resembles the following (the dialog box you see may be slightly different):

Page 711: Working Model 2D - User's Manual

Chapter 5 Editing Custom Dialog Boxes (Windows Only) 707

As you can see, this isn't a very useful dialog box. For one thing, the user doesn't see anyitems in the list box along the left side of this dialog box. To put information into this customdialog box, you assign values to dialog box controls by modifying the statements in yourscript that are responsible for displaying those controls to the user. The following table liststhe dialog box controls to which you can assign variables and the types of information youcan control:

Control(s) Types of information:

List box, drop-down list box, orcombo box

Items

Text box Default text

Check box Values

In the following sections, you’ll learn how to define and fill an array, set the default text in atext box, and set the initial focus and tab order for the controls in your custom dialog.

Defining and filling an arrayYou can store items in the list box shown in the example above by creating an array and thenassigning values to the elements of the array. For example, you could include the followinglines to initialize an array with three elements and assign the names of three common fruits tothese elements of your array:

Dim Listbox1$(3) 'Initialize listbox arrayListbox1$(0) = "Apples" Listbox1$(1) = "Oranges"

Listbox1$(2) = "Pears"

Setting default text in a text boxYou can set the default value of the text box in your script to 12 with the followingstatement, which must follow the statement that defines the dialog record but precede thestatement or function that displays the custom dialog box:

b.TextBox1 = "12"

Setting the initial focus and controlling the tab order

You can control which control has the focus when your custom dialog box is first displayedas well as the tabbing order between controls by understanding two rules that WM Basic

Page 712: Working Model 2D - User's Manual

708 Working Model Basic User's Manual

follows. First, the focus in a custom dialog box is always set initially to the first control toappear in the dialog box template. Second, the order in which subsequent controls appearwithin the dialog box template determines the tabbing order. That is, pressing the TAB keywill change the focus from the first control to the second one, pressing the TAB key againwill change the focus to the third control, and so on.

Displaying the Dialog BoxTo display a custom dialog box, you can use either a Dialog() function or a Dialogstatement.

Using the Dialog( ) functionYou 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 on an OKbutton, Cancel button, or takes another action.

response% = Dialog(b)The Dialog() function returns any of the following values:

Value returned: If:

-1 The OK button was clicked.

0 The Cancel button was clicked.

>0 A push button was clicked. The returned numberrepresents which button was clicked based on its orderin the dialog box template (1 is the first push button, 2is the second push button, and so on).

Using the Dialog statementYou can use the Dialog statement when you don’t need to determine how the user closedyour 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. The following statement is anexample of the correct use of the Dialog statement.

Dialog b

Retrieving values from the Dialog BoxAfter displaying a custom dialog box for your user, your script must retrieve the values of thedialog controls. You retrieve these values by referencing the appropriate identifiers in thedialog record.You’ll find an example of how to retrieve values from a custom dialog box in the followingsample script.

SampleIn the following script, named DIALOG2.WBS, shows several of the techniques describedearlier 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 usedto store information about how the dialog box was closed. An identifier named ListBox1 isused to determine whether the user chose "Apples", "Oranges", or "Pears" in the list box

Page 713: Working Model 2D - User's Manual

Chapter 5 Editing Custom Dialog Boxes (Windows Only) 709

named ListBox$. Finally, a Select Case…End Select statement is used to display amessage box appropriate to the manner in which the user dismissed the custom dialog box.

Sub Main()Dim Listbox1$(2)Dim response%Listbox1$(0) = "Apples" Listbox1$(1) = "Oranges"

Listbox1$(2) = "Pears"Begin Dialog UserDialog ,,163,94,"Grocery Order"

Text 13,6,32,8,"&Quantity:",.Text1TextBox 48,4,28,12,.TextBox1ListBox 12,28,68,32,ListBox1$,.ListBox1OKButton 112,8,40,14CancelButton 112,28,40,14

End DialogDim b as UserDialog b.TextBox1 = "12"response = Dialog(b)Select Case response%

Case -1Fruit$ = ListBox1$(b.listbox1)MsgBox "Thank you for ordering " + b.TextBox1 + " " +

Fruit$Case 0

MsgBox "Your order has been cancelled."End Select

End Sub

Using a Dynamic Dialog BoxIn the previous section, you learned how to use custom dialog boxes. As you learned, youcan retrieve the values from dialog box controls after the user dismisses the dialog box byreferencing the identifiers in the dialog record.You can also retrieve values from the dialog box while the dialog box is displayed, using afeature of WM Basic called dynamic dialog boxes.The following script, named DIALOG3.WBS, illustrates the most important concepts you’llneed to understand in order to create a dynamic dialog box in your script:

Dim Fruits(2) as StringDim Vegetables(2) as StringFunction DialogControl(ctrl$, action%, suppvalue%) As Integer

Select Case action%Case 1

DlgListBoxArray "listbox1", fruitsDlgValue "listbox1", 0

Case 2If ctrl$ = "OptionButton1" Then

DlgListBoxArray "listbox1", fruitsDlgValue "listbox1", 0

ElseIf ctrl$ = "OptionButton2" ThenDlgListBoxArray "listbox1", vegetablesDlgValue "listbox1", 0

End IfEnd Select

End Function

Page 714: Working Model 2D - User's Manual

710 Working Model Basic User's ManualSub Main()

Dim ListBox1$()Dim Produce$Fruits(0) = "Apples" Fruits(1) = "Oranges"

Fruits(2) = "Pears"Vegetables(0) = "Carrots"

Vegetables(1) = "Peas" Vegetables(2) = "Lettuce"Begin Dialog UserDialog ,,163,94,"Grocery

Order",.DialogControlText 13,6,32,8,"&Quantity:",.Text1TextBox 48,4,28,12,.TextBox1ListBox 12,28,68,32,ListBox1$,.ListBox1OptionGroup .OptionGroup1

OptionButton 12,68,48,8,"&Fruit",.OptionButton1OptionButton 12,80,48,8,"&Vegetables",.OptionButton2

OKButton 112,8,40,14CancelButton 112,28,40,14

End DialogDim b as UserDialog b.TextBox1 = "12"response% = Dialog(b)Select Case response%

Case -1If b.optiongroup1 = 0 Then

produce$ = fruits(b.listbox1)Else

produce$ = vegetables(b.listbox1)End IfMsgBox "Thank you for ordering " & b.TextBox1 & " " &

produce$Case 0

MsgBox "Your order has been cancelled."End Select

End Sub

In the remainder of this section, you’ll learn how to make a dialog box dynamic byexamining the workings of this sample script.

Making a Dialog Box DynamicThe first thing to notice about this script, which a more complex variation of theDIALOG2.WBS script described earlier in this chapter, is that an identifier named.DialogControl has been added to the Begin Dialog statement. As you will learn in thefollowing section, this parameter to the Begin Dialog statement tells WM Basic to passcontrol to a function procedure named DialogControl.

Using a Dialog FunctionBefore WM Basic displays a custom dialog by executing a Dialog statement or Dialog()function, it must first initialize the dialog box. During this initialization process, WM Basicchecks to see if you’ve defined a dialog function as part of your dialog box template. If so,

Page 715: Working Model 2D - User's Manual

Editing Custom Dialog Boxes (Windows Only) 711

WM Basic will give control to your dialog function, allowing your script to carry out certainactions, such as hiding or disabling dialog box controls.After completing its initialization process, WM Basic displays your custom dialog box.When the user selects an item in a list box, clears a check box, or carries out certain otheractions within the dialog box, WM Basic will again call your dialog function.In fact, WM Basic also calls your dialog function repeatedly even while the user is notinteracting with the dialog box.

Responding to User ActionsA WM Basic dialog function can respond to six types of user actions:Action Description

1 This action is sent immediately before the dialog box is shown for thefirst time.

2 This action is sent when:

A button is clicked, such as OK, Cancel, or a pushbutton.

A check box's state has been modified.

An option button is selected. In this case,ControlName$ contains the name of the optionbutton that was clicked, and SuppValue containsthe index of the option button within the optionbutton group (0-based).

The current selection is changed in a list box, droplist box, or combo box. In this case, ControlName$contains the name of the list box, combo box, ordrop list box, and SuppValue contains the index ofthe 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 beenchanged. This action is only sent when the control loses focus.

4 This action is sent when a control gains the focus.

5 This action is sent continuously when the dialog box is idle.

6 This action is sent when the dialog box is moved.

You’ll find a more complete explanation of these action codes in Chapter 2, A-Z Reference inthe Working Model Basic User’s Manual in the reference for DlgProc function.

Page 716: Working Model 2D - User's Manual
Page 717: Working Model 2D - User's Manual

713

C H A P T E R 6

You can use another application to control Working Model through DDE (on Windows) orApple events (on Macintosh). You can write a script or a macro using the externalapplication, that sends instructions to Working Model in WM Basic language.This chapter provides instructions to establish the communication between applications.

ContentsSending WM Basic Program via DDESending WM Basic Program via Apple events

Controlling Working Modelfrom Another Application

Page 718: Working Model 2D - User's Manual

714 Working Model Basic User's Manual

Sending a WM Basic Program via DDEWorking Model is a DDE server and supports the topic WMBasic. Via DDE, any applicationcan send WM Basic commands to Working Model. Shown below are a few examples ofhow you can send instructions to Working Model from another application.Note: The method for establishing a DDE conversation varies significantly from oneapplication to another. Please refer to the documentation for the application for reference.

Using Microsoft Excel 5.0You can write a Visual Basic macro in Excel that directly sends a series of instructions inWM Basic to Working Model. Please refer to the User’s Manual for Excel to find out moredetails.

Sending a Single Line of WM Basic CodeShown below is a Visual Basic script written as an Excel macro.

Sub Macro1()' Assume Working Model is runningchannelID = Application.DDEInitiate("WM", "WMBasic")Application.DDEExecute channelID, "MsgBox ""Hello"""Application.DDETerminate channelID

End SubThe first line, DDEInitiate, establishes the link with WM (WorkingModel, which runs as WM.EXE) under the topic WMBasic. WorkingModel must be running for DDEInitiate to work. The functionDDEInitiate returns the channelID (an integer describing thechannel number) which will be used in subsequent DDEconversations.DDEExecute statement takes the first parameter channelID, and theprogram written in WM Basic as the second parameter. Note that thedouble-quotation marks (") need to be repeated when sent throughDDEExecute.To finish the DDE conversation, add DDETerminate statement in yourmacro.

When Working Model receives the above statements, Sub Main() and End Sub areautomatically inserted to create a complete program as follows:

Sub Main()MsgBox "Hello"

End Sub

Sending a WM Basic ProgramIf you want to send more than one line of WM Basic code,

the code needs to be a complete program (includes Sub Main() andEnd Sub), andyou need to bracket the beginning and the end of the program byspecial symbols $wmstart$ and $wmend$. Otherwise, Working Modelwould add Sub Main() and End Sub to every line, and your programwould not function properly.

For example:

Page 719: Working Model 2D - User's Manual

Chapter 6 Controlling Working Model from Another Application 715Sub Macro1()

channelID = Application.DDEInitiate("WM", "WMBasic")Application.DDEExecute channelID, "$wmstart$"Application.DDEExecute channelID, "Sub Main()"Application.DDEExecute channelID, "Dim Box as WMBody"Application.DDEExecute channelID, "Set Box =

WM.ActiveDocument.NewBody("square")"Application.DDEExecute channelID, "Box.Width.Value = 0.2"Application.DDEExecute channelID, "End Sub"Application.DDEExecute channelID, "$wmend$"Application.DDETerminate channelID

End SubWorking Model will start processing the target program upon receiving $wmend$. The abovecode is interpreted as the following WM Basic program:

Sub Main()Dim Box as WMBodySet Box = WM.ActiveDocument.NewBody("square")Box.Width.Value = 0.2

End Sub

Using Visual BasicYou can write a standalone Visual Basic program that sends a series of instructions toWorking Model. This scheme may seem a bit strange at first, since WM Basic closelymimics Visual Basic. After all, what is wrong with writing your entire application in WMBasic?Nothing, really. But under following circumstances, you may find it appropriate to takeadvantage of the facility.

You already have a large application written in Visual Basic, and youwish to modify a part of the program so that it interacts with WorkingModel.You wish to write a Visual Basic application, but most of itsfunctionality does not require Working Model. For instance, you wishto distribute your application to other people who may or may not ownWorking Model, and the interactions with Working Model are not acritical part of your application.

Sending a Single Line of WM Basic CodeShown below is an example of how you may send a command from Visual Basic program.Assume the variable myControl is a valid Visual Basic control.

myControl.LinkTopic = "WM|WMBasic" ' specifies app and topicmyControl.LinkMode = 2myControl.LinkExecute "MsgBox ""Hello"""

(Note that the two repeating quotations marks ("") are necessary to indicate a singlequotation symbol within the parameter of LinkExecute.)The second line (myControl.LinkMode = 2) sets the link mode to 2 (Manual Mode).Working Model only supports the manual mode link. For more information, please refer tothe documentation on Visual Basic.When Working Model receives the above statements, Sub Main() and End Sub areautomatically inserted to create a complete program as follows:

Sub Main()

Page 720: Working Model 2D - User's Manual

716 Working Model Basic User's ManualMsgBox "Hello"

End Sub

Sending a WM Basic ProgramIf you wish send multiple lines of WM Basic code, you need to call the LinkExecute methodrepeatedly. Furthermore:

the code needs to be a complete program (includes Sub Main() andEnd Sub), andyou need to bracket the beginning and the end of the program byspecial symbols $wmstart$ and $wmend$. Otherwise, Working Modelwould add Sub Main() and End Sub to every line, and your programwould not function properly.

For example:myControl.LinkTopic = "WM|WMBasic" ' specifies app and topicmyControl.LinkItem = ""myControl.LinkMode = 2myControl.LinkExecute "$wmstart$"myControl.LinkExecute "Sub Main()"myControl.LinkExecute "Dim B as WMbody"myControl.LinkExecute "Set B =WM.ActiveDocument.NewBody(""square"")"myControl.LinkExecute "B.Width.Value = 0.2"myControl.LinkExecute "End Sub"myControl.LinkExecute "$wmend$"

Working Model will start processing the code upon receiving $wmend$.

Sending a WMBasic Program via Apple EventsWorking Model supports the Required suite of Apple events. It also supports the DoScriptevent (part of Miscellaneous suite). Shown below is an example of how you can sendinstructions to Working Model from AppleScript Editor. Other applications (although notdiscussed here) supporting Apple events include Claris FileMaker.Note: The method for establishing an Apple events communication varies significantly fromone application to another. Please refer to the documentation for the application forreference.

Using AppleScript EditorAppleScript Editor is an editing tool used to create scripts that automate various Macintoshoperations. AppleScript Editor is included in Macintosh System 7.5.You can send a WM Basic program through AppleScript using a DoScript statement.

Sending a Single Line of WM Basic CodeShown below is an example of an AppleScript code which executes WM Basic code:

tell application "Working Model"DoScript "MsgBox \"Hello\""

end tellNote that the backslash (\) must be added in front of a double-quotation mark (") to beproperly interpreted by the DoScript command.When Working Model receives the above statements, Sub Main() and End Sub areautomatically inserted to create a complete program as follows:

Page 721: Working Model 2D - User's Manual

Controlling Working Model from Another Application 717Sub Main()

MsgBox "Hello"End Sub

Sending a WM Basic ProgramIf you wish send multiple lines of WM Basic code, you need to call the DoScript commandrepeatedly. Furthermore:

the code needs to be a complete program (includes Sub Main() andEnd Sub), andyou need to bracket the beginning and the end of the program byspecial symbols $wmstart$ and $wmend$. Otherwise, Working Modelwould add Sub Main() and End Sub to every line, and your programwould not function properly

For example:tell application "Working Model"

DoScript "$wmstart$"DoScript "Sub Main()"DoScript "Dim B as WMBody"DoScript "Set B = WM.ActiveDocument.NewBody(\"square\")"DoScript "B.Width.Value = 0.2"DoScript "End Sub"DoScript "$wmend$"

end tell

Working Model will start processing the code upon receiving $wmend$.

Page 722: Working Model 2D - User's Manual
Page 723: Working Model 2D - User's Manual

719

A P P E N D I X A

This section contains listings of all the runtime errors. It is divided into three subsections, thefirst describing errors messages compatible with "standard" Basic as implemented byMicrosoft Visual Basic, the second describing error messages specific to WM Basic, and thethird describing error messages that only pertain to Working Model operations.A few error messages contain placeholders which get replaced by the runtime when formingthe completed runtime error message. These placeholders appear in the following list as theitalicized word placeholder.For details on how you can trap and handle errors please see the section on Error Handling(topic) in the Chapter 2 of this manual.

Visual Basic Compatible Error MessagesErrorNumber

Error Message

3 Return without GoSub

5 Illegal procedure call

6 Overflow

7 Out of memory

9 Subscript out of range

10 This array is fixed or temporarily locked

11 Division by zero

13 Type mismatch

14 Out of string space

19 No Resume

20 Resume without error

26 Dialog needs End Dialog or push button

Runtime Error Messages

Page 724: Working Model 2D - User's Manual

720 Working Model Basic User's Manual

ErrorNumber

Error Message

28 Out of stack space

35 Sub or Function not defined

48 Error in loading DLL

49 Bad DLL calling convention

51 Internal error

52 Bad file name or number

53 File not found

54 Bad file mode

55 File already open

57 Device I/O error

58 File already exists

59 Bad record length

61 Disk full

62 Input past end of file

63 Bad record number

64 Bad file name

67 Too many files

68 Device unavailable

70 Permission denied

71 Disk not ready

74 Can't rename with different drive

75 Path/File access error

76 Path not found

91 Object variable or With block variable not set

93 Invalid pattern string

94 Invalid use of Null

139 Only one user dialog may be up at any time

140 Dialog control identifier does not match any currentcontrol

Page 725: Working Model 2D - User's Manual

Appendix A Runtime Error Messages 721

ErrorNumber

Error Message

141 The placeholder statement is not available on this dialogcontrol type

143 The dialog control with the focus may not be hidden ordisabled

144 Focus may not be set to a hidden or disabled control

150 Dialog control identifier is already defined

163 This statement can only be used when a user dialog isactive

260 No timer available

281 No more DDE channels

282 No foreign application responded to a DDE initiate

283 Multiple applications responded to a DDE initiate

285 Foreign application won't perform DDE method oroperation

286 Timeout while waiting for DDE response

287 User pressed Escape key during DDE operation

288 Destination is busy

289 Data not provided in DDE operation

290 Data in wrong format

291 Foreign application quit

292 DDE conversation closed or changed

295 Message queue filled; DDE message lost

298 DDE requires ddeml.dll

429 OLE Automation server can't create object

430 Class doesn't support OLE Automation

431 OLE Automation server cannot load file

432 File name or class name not found during OLEAutomation operation

433 OLE Automation object does not exist

434 Access to OLE Automation object denied

435 OLE initialization error

Page 726: Working Model 2D - User's Manual

722 Working Model Basic User's Manual

ErrorNumber

Error Message

436 OLE Automation method returned unsupported type

437 OLE Automation method did not return a value

438 Object doesn't support this property or methodplaceholder

439 OLE Automation argument type mismatch placeholder

440 OLE Automation error placeholder

443 OLE Automation Object does not have a default value

452 Invalid ordinal

460 Invalid Clipboard format

520 Can't empty clipboard

521 Can't open clipboard

600 Set value not allowed on collections

601 Get value not allowed on collections

603 ODBC - SQLAllocEnv failure

604 ODBC - SQLAllocConnect failure

608 ODBC - SQLFreeConnect error

610 ODBC - SQLAllocStmt failure

3129 Invalid SQL statement; expected 'DELETE', 'INSERT','PROCEDURE', 'SELECT', or 'UPDATE'

3146 ODBC - call failed

3148 ODBC - connection failed

3276 Invalid database ID

WM Basic-Specific Error MessagesErrorNumber

Error Message

800 Incorrect Windows version

801 Too many dimensions

802 Can't find window

803 Can't find menu item

Page 727: Working Model 2D - User's Manual

Appendix A Runtime Error Messages 723

ErrorNumber

Error Message

804 Another queue is being flushed

805 Can't find control

806 Bad channel number

807 Requested data not available

808 Can't create pop-up menu

809 Message box canceled

810 Command failed

811 Network error

812 Network function not supported

813 Bad password

814 Network access denied

815 Network function busy

816 Queue overflow

817 Too many dialog controls

818 Can't find list box/combo box item

819 Control is disabled

820 Window is disabled

821 Can't write to ini file

822 Can't read from ini file

823 Can't copy file onto itself

824 OLE Automation unknown object name

825 Can't redimension a fixed array

826 Can't load and initialize extension

827 Can't find extension

828 Unsupported function or statement

829 Can't find ODBC libraries

830 OLE Automation Lbound or Ubound on non-Array value

831 Incorrect definition for dialog procedure

Page 728: Working Model 2D - User's Manual

724 Working Model Basic User's Manual

Error Messages in Working Model OperationsErrorNumber

Error Message

900 Failure during Working Model API call

901 A Working Model API call failed because the object itreferenced no longer exists

902 Attempted to set a property which the referenced objectdoes not have

903 Attempted to get a property which the referenced objectdoes not have

904 Unrecognized string parameter in subroutine call

905 Bad parameter in subroutine call

906 Could not load the specified library. Check its locationand confirm that it compiles.

907 Could not run the specified script. Check its location andconfirm that it compiles.

999 Invalid object variable

Page 729: Working Model 2D - User's Manual

725

A P P E N D I X B

The following table contains a list of all the errors generated by the WM Basic compiler.With some errors, the compiler changes placeholders within the error to text from the scriptbeing compiled. These placeholders are represented in this table by the word placeholder.

1 Variable Required - Can't assign to this expression

2 Letter range must be in ascending order

3 Redefinition of default type

4 Out of memory, too many variables defined

5 Type-character doesn't match defined type

6 Expression too complex

7 Cannot assign whole array

8 Assignment variable and expression are different types

10 Array type mismatch in parameter

11 Array type expected for parameter

12 Array type unexpected for parameter

13 Integer expression expected for an array index

14 Integer expression expected

15 String expression expected

18 Left of "." must be an object, structure, or dialog

19 Invalid string operator

20 Can't apply operator to array type

21 Operator type mismatch

22 "placeholder" is not a variable

23 "placeholder" is not a array variable or a function

Compiler Error Messages

Page 730: Working Model 2D - User's Manual

726 Working Model Basic User's Manual

24 Unknown placeholder "placeholder"

25 Out of memory

26 placeholder: Too many parameters encountered

27 placeholder: Missing parameter(s)

28 placeholder: Type mismatch in parameter placeholder

29 Missing label "placeholder"

30 Too many nested statements

31 Encountered new-line in string

32 Overflow in decimal value

33 Overflow in hex value

34 Overflow in octal value

35 Expression is not constant

37 No type-characters allowed on parameters with explicit type

39 Can't pass an array by value

40 "placeholder" is already declared as a parameter

41 Variable name used as label name

42 Duplicate label

43 Not inside a function

44 Not inside a sub

46 Can't assign to function

47 Identifier is already a variable

48 Unknown type

49 Variable is not an array type

50 Can't redimension an array to a different type

51 Identifier is not a string array variable

52 0 expected

55 Integer expression expected for file number

56 placeholder is not a method of the object

57 placeholder is not a property of the object

Page 731: Working Model 2D - User's Manual

Appendix B Compiler Error Messages 727

58 Expecting 0 or 1

59 Boolean expression expected

60 Numeric expression expected

61 Numeric type FOR variable expected

62 For...Next variable mismatch

63 Out of string storage space

64 Out of identifier storage space

65 Internal error 1

66 Maximum line length exceeded

67 Internal error 3

68 Division by zero

69 Overflow in expression

70 Floating-point expression expected

72 Invalid floating-point operator

74 Single character expected

75 Subroutine identifier can't have a type-declaration character

76 Script is too large to be compiled

77 Variable type expected

78 Can't evaluate expression

79 Can't assign to user or dialog type variable

80 Maximum string length exceeded

81 Identifier name already in use as another type

84 Operator cannot be used on an object

85 placeholder is not a property or method of the object

86 Type-character not allowed on label

87 Type-character mismatch on routine placeholder

88 Destination name is already a constant

89 Can't assign to constant

90 Error in format of compiler extensions

91 Identifier too long

Page 732: Working Model 2D - User's Manual

728 Working Model Basic User's Manual

92 Expecting string or structure expression

93 Can't assign to expression

94 Dialog and Object types are not supported in this context

95 Array expression not supported as parameter

96 Dialogs, objects, and structures expressions are not supported as aparameter

97 Invalid numeric operator

98 Invalid structure element name following "."

99 Access value can't be used with specified mode

101 Invalid operator for object

102 Can't LSet a type with a variable-length string

103 Syntax error

104 placeholder is not a method of the object

105 No members defined

106 Duplicate type member

107 Set is for object assignments

108 Type-character mismatch on variable

109 Bad octal number

110 Bad number

111 End-of-script encountered in comment

112 Misplaced line continuation

113 Invalid escape sequence

114 Missing End Inline

115 Statement expected

116 ByRef argument mismatch

117 Integer overflow

118 Long overflow

119 Single overflow

120 Double overflow

121 Currency overflow

122 Optional argument must be Variant

Page 733: Working Model 2D - User's Manual

Compiler Error Messages 729

123 Parameter must be optional

124 Parameter is not optional

125 Expected: Lib

126 Illegal external function return type

127 Illegal function return type

128 Variable not defined

129 No default property for the object

130 The object does not have an assignable default property

131 Parameters cannot be fixed length strings

132 Invalid length for a fixed length string

133 Return type is different from a prior declaration

134 Private variable too large. Storage space exceeded

135 Public variables too large. Storage space exceeded

Page 734: Working Model 2D - User's Manual
Page 735: Working Model 2D - User's Manual

731

A P P E N D I X C

The following table lists all WM Basic language elements and on which platforms theselanguage elements are supported. A solid square ( ) indicates that the element is supported.The blank square ( ) indicates that the element is not supported.

Language Element Windows

Macintosh

&

'

()

*

+

-

/

<

<=

<>

= (assignment)

= (operator)

>

>=

\

^

_

Abs

ActivateControl

Language Elements byPlatform

Page 736: Working Model 2D - User's Manual

732 Working Model Basic User's Manual

Language Element Windows

Macintosh

And

AnswerBox

AppActivate

AppClose

AppFileName$

AppFind

AppGetActive$

AppGetPosition

AppGetState

AppHide

AppList

AppMaximize

AppMinimize

AppMove

AppRestore

AppSetState

AppShow

AppSize

AppType

ArrayDims

ArraySort

Asc

AskBox$

AskPassword$

Atn

Basic.Capability

Basic.Eoln$

Basic.FreeMemory

Basic.HomeDir$

Basic.OS

Basic.PathSeparator$

Page 737: Working Model 2D - User's Manual

Appendix C Language Elements by Platform 733

Language Element Windows

Macintosh

Basic.Version$

Beep

Begin Dialog

Boolean

ButtonEnabled

ButtonExists

Call

CancelButton

CBool

CCur

CDate

CDbl

ChDir

ChDrive

CheckBox

CheckBoxEnabled

CheckBoxExists

Choose

Chr, Chr$

CInt

Clipboard$ (function)

Clipboard$ (statement)

Clipboard.Clear

Clipboard.GetFormat

Clipboard.GetText

Clipboard.SetText

CLng

Close

ComboBox

ComboBoxEnabled

ComboBoxExists

Page 738: Working Model 2D - User's Manual

734 Working Model Basic User's Manual

Language Element Windows

Macintosh

Command, Command$

Const

Cos

CreateObject

CSng

CStr

CurDir, CurDir$

Currency

CVar

CVDate

CVErr

Date

Date, Date$ (functions)

Date, Date$ (statements)

DateAdd

DateDiff

DatePart

DateSerial

DateValue

Day

DDB

DDEExecute

DDEInitiate

DDEPoke

DDERequest, DDERequest$

DDESend

DDETerminate

DDETerminateAll

DDETimeOut

Declare

DefBool

Page 739: Working Model 2D - User's Manual

Appendix C Language Elements by Platform 735

Language Element Windows

Macintosh

DefCur

DefDate

DefDbl

DefInt

DefLng

DefObj

DefSng

DefStr

DefVar

Desktop.ArrangeIcons

Desktop.Cascade

Desktop.SetColors

Desktop.SetWallpaper

Desktop.Snapshot

Desktop.Tile

Dialog (function)

Dialog (statement)

Dim

Dir, Dir$

DiskDrives

DiskFree

DlgControlId

DlgEnable (function)

DlgEnable (statement)

DlgFocus (function)

DlgFocus (statement)

DlgListBoxArray (function)

DlgListBoxArray (statement)

DlgSetPicture

DlgText (statement)

DlgText$ (function)

Page 740: Working Model 2D - User's Manual

736 Working Model Basic User's Manual

Language Element Windows

Macintosh

DlgValue (function)

DlgValue (statement)

DlgVisible (function)

DlgVisible (statement)

Do...Loop

DoEvents (function)

DoEvents (statement)

DoKeys

Double

DropListBox

EditEnabled

EditExists

End

Environm Environ$

Eof

Eqv

Erase

Erl

Err (function)

Err (statement)

Error

Error, Error$

Exit Do

Exit For

Exit Function

Exit Sub

Exp

FileAttr

FileCopy

FileDateTime

FileDirs

Page 741: Working Model 2D - User's Manual

Appendix C Language Elements by Platform 737

Language Element Windows

Macintosh

FileExists

FileLen

FileList

FileParse$

FileType

Fix

For...Next

Format, Format$

FreeFile

Function...End

Fv

Get

GetAttr

GetCheckBox

GetComboBoxItem$

GetComboBoxItemCount

GetEditText$

GetListBoxItem$

GetListBoxItemCount

GetObject

GetOption

Global

GoSub

Goto

GroupBox

Hex, Hex$

HLine

Hour

HPage

HScroll

HWND

Page 742: Working Model 2D - User's Manual

738 Working Model Basic User's Manual

Language Element Windows

Macintosh

HWND.Value

If...Then...Else

IIf

Imp

Inline

Input#

Input, Input$

InputBox, InputBox$

InStr

Int

Integer

IPmt

IRR

Is

IsDate

IsEmpty

IsError

IsMissing

IsNull

IsNumeric

IsObject

Item$

ItemCount

Kill

LBound

LCase, LCase$

Left, Left$

Len

Let

Like

Line Input #

Page 743: Working Model 2D - User's Manual

Appendix C Language Elements by Platform 739

Language Element Windows

Macintosh

Line$

LineCount

ListBox

ListBoxEnabled

ListBoxExists

Loc

Lock

Lof

Log

Long

LSet

LTrim, LTrim$

MacID

MacScript

Main

Mci

Menu

MenuItemChecked

MenuItemEnabled

MenuItemExists

Mid, Mid$

Mid, Mid$

Minute

MIRR

MkDir

Mod

Month

MsgBox (function)

MsgBox (statement)

MsgClose

MsgOpen

Page 744: Working Model 2D - User's Manual

740 Working Model Basic User's Manual

Language Element Windows

Macintosh

MsgSetText

MsgSetThermometer

Name

Net.AddCon$

Net.Browse$

Net.CancelCon

Net.Dialog

Net.GetCaps

Net.GetCon$

Net.User$

Not

Nothing

Now

NPer

Npv

Object

Oct. Oct$

OKButton

On Error

Open

OpenFilename$

Option Base

Option Compare

Option CStrings

OptionButton

OptionEnabled

OptionExists

OptionGroup

Or

Picture

PictureButton

Page 745: Working Model 2D - User's Manual

Appendix C Language Elements by Platform 741

Language Element Windows

Macintosh

Pmt

PopupMenu

PPmt

Print

Print #

PrinterGetOrientation

PrinterSetOrientation

PrintFile

Private

Public

PushButton

Put

Pv

QueEmpty

QueFlush

QueKeyDn

QueKeys

QueKeyUp

QueMouseClick

QueMouseDblClk

QueMouseDblDn

QueMouseDn

QueMouseMove

QueMouseMoveBatch

QueMouseUp

QueSetRelativeWindow

Random

Randomize

Rate

ReadINI$

ReadINISection

Page 746: Working Model 2D - User's Manual

742 Working Model Basic User's Manual

Language Element Windows

Macintosh

ReDim

REM

Reset

Resume

Return

Right, Right$

RmDir

Rnd

RSet

RTrim, RTrim$

SaveFileName$

Screen.DlgBaseUnitsX

Screen.DlgBaseUnitsY

Screen.Height

Screen.TwipsPerPixelX

Screen.TwipsPerPixelY

Screen.Width

Second

Seek

Seek

Select...Case

SelectBox

SelectButton

SelectComboboxItem

SelectListboxItem

SendKeys

Set

SetAttr

SetCheckbox

SetEditText

SetOption

Page 747: Working Model 2D - User's Manual

Appendix C Language Elements by Platform 743

Language Element Windows

Macintosh

Sgn

Shell

Sin

Single

Sleep

Sln

Space, Space$

Spc

SQLBind

SQLClose

SQLError

SQLExecQuery

SQLGetSchema

SQLOpen

SQLRequest

SQLRetrieve

SQLRetrieveToFile

Sqr

Stop

Str, Str$

StrComp

String

String, String$

Sub...End

Switch

SYD

System.Exit

System.FreeMemory

System.FreeResources

System.MouseTrails

System.Restart

Page 748: Working Model 2D - User's Manual

744 Working Model Basic User's Manual

Language Element Windows

Macintosh

System.TotalMemory

System.WindowsDirectory$

System.WindowsVersion$

Tab

Tan

Text

TextBox

Time, Time$ (functions)

Time, Time$ (statements)

Timer

TimeSerial

TimeValue

Trim, Trim$

Type

UBound

UCase, UCase$

UnLock

Val

Variant

VarType

ViewportClear

ViewportClose

ViewportOpen

VLine

VPage

VScroll

Weekday

While...Wend

Width#

WinActivate

WinClose

Page 749: Working Model 2D - User's Manual

Language Elements by Platform 745

Language Element Windows

Macintosh

WinFind

WinList

WinMaximize

WinMinimize

WinMove

WinRestore

WinSize

Word$

WordCount

Write #

WriteINI

Xor

Year

Page 750: Working Model 2D - User's Manual
Page 751: Working Model 2D - User's Manual

747

A P P E N D I X D

The following list contains important WM Basic limitations:Line numbers are not supported. Labels can be used in place of linenumbers are targets for the Goto statement.Strings are limited in length to 32,764 characters. This includes local,public, and private strings, as well as strings within structures andarrays.The Visual Basic declaration modifiers Static and Shared are notsupported.The default string space is 8K, which expands automatically up to amaximum of 1 MB. This space contains all strings and arraysregardless of their scope.The default stack size for the runtime is 2,048 bytes. This spacecontains all local variables (except arrays and variable-length strings)and passed parameters.The stack is also used by the runtime for storage of intermediatevalues, so the actual available stack space will be slightly less.Calls made to subroutines or functions in other scripts use the stack ofthe caller.The data area that holds private variables is limitated to 16K. This dataspace contains all private variables except strings and arrays, whichare stored in the string space.The data area that holds public variables is limited to 16K. This dataspace contains all public variables except strings and arrays, which arestored in the string space.The size of a source script is limited to 65534 characters. Thislimitation can be avoided by breaking up large scripts into smallerones.A compiled script consists of p-code, constant data, and symbolicinformation, each of which is limited to 64K. These limitations can beavoided by breaking up large scripts into smaller ones, which is rarelynecessary.Arrays can have up to 60 dimensions.Variable names are limited to 80 characters.

WM Basic Limitations

Page 752: Working Model 2D - User's Manual

748 Working Model Basic User's Manual

Labels are limited to 80 characters.Each executing script contains a table of structures that track callsmade to external routines. Each structure is approximately 88 byteswith an overal size limited to 64K.The number of open DDE channels is not fixed; rather, it is limitedonly by available memory and system resources.The number of open files is limited to 255 or the operating systemlimit, whichever is less.The number of characters within a string literal (a string enclosedwithin quotation marks) is limited to 1024 characters. (Strings can beconcatenated using the concatenation [&] operator with the normalstring limit of 32,764 characters.)The number of nesting levels (i.e., loops within loops) is limited bycompiler memory.Queue playback buffer size is limited to 64K. With 10 bytes per event,this allows for 6,553 events.Each GoSub requires 2 bytes of the WM Basic runtime stack.Arrays and user-defined types cannot be passed to a method of an OLEautomation object.Arrays and user-defined types cannot be set as the value of a propertyof an OLE automation object.Arrays and user-defined types cannot be returned from a method orproperty of an OLE automation object.Array indexes must be in the following range:-32768 <= array-index <=32767The size of an array cannot exceed 32K. For example, an array ofintegers, each of which requires 2 bytes of storage, is limited to thefollowing maximum number of elements:max_num_elements = (32767 - overhead) / 2

where overhead is currently approximately 16 bytes.A maximum of 128 fonts can be used within a single user dialog,although the practical limitation imposed by the operating system maybe less.

Page 753: Working Model 2D - User's Manual

749

A P P E N D I X E

The following section describes differences between Visual Basic and WM Basic. In theproceeding discussion, "VB" is used to refer to Visual Basic 3.0, and VBA is used to refer toVisual Basic for Applications 1.0.The following sections are covered:

ArraysConstantsData TypesDeclarationsDeclare StatementFloating Point NumbersLanguage Element DifferencesNatural Language SupportObjectsOLE AutomationParameter PassingStringsVariantsStack SizeExpression EvaluationFile Searching

WM Basic/Visual BasicDifferences

Page 754: Working Model 2D - User's Manual

750 Working Model Basic User's Manual

ArraysVB and VBA support huge arrays, WM Basic does not.

ConstantsVBA supports shared constants (using the Public keyword). In WM Basic, constants mustbe repeated within each script in which they are used.VB and VBA do not allow the concatenation of constant elements. For example, thefollowing script compiles in WM Basic but not in VB or VBA:

Const t$ = "Hello" & Chr$(9) & "there."Sub Main()

Msgbox t$End Sub

VBA allows a user to redefine global constants at the subroutine/function level withoutaffecting their global values; WM Basic does not. For example, the following script willcompile and execute in VBA but not in WM Basic:

Const t = "Hello"Sub Main()

Const t$ = "Good Bye"MsgBox t$ 'Displays Good Bye

End Sub

Data TypesWM Basic and VBA support the Boolean and Date data types, VB does not.

DeclarationsIn VB and VBA, if a variable is initially declared with a type declaration character, then thatcharacter must appear with every use of that variable. WM Basic relaxes this by not requiringthe type declaration character with every use of that variable.Both VB and VBA support the Static keyword as a modifier for the Sub and Functionstatements. WM Basic supports use of this keyword with these statements with no effect.A variable used in a comparison expression that hasn't been declared will be implicitlydeclared in VB and VBA. In WM Basic, this will be seen as an unresolved function:

Sub Mainif a$ = "hello" then beep

End SubIn WM Basic, the above script will compile, but gives a Sub or function not definederror when executed. In VB and VBA, this will automatically declare a variable called a$ asa String.WM Basic allows the @ type declaration character to be specified with currency constants;VB and VBA do not.

Declare StatementVBA supports shared Declare statements (using the Public keyword). In WM Basic, thesemust be declared in every script in which they are used.WM Basic supports a superset of that functionality available in VB—namely, the additionalcalling conventions.

Page 755: Working Model 2D - User's Manual

Appendix E WM Basic/Visual Basic Differences 751

WM Basic and VB pass values to external routines in the same manner with the followingexceptions:

WM Basic passes True or False as Boolean values (signed short inC). VB passes these as Boolean variants.Variants are passed as internal variant structures in both WM Basicand VB. For all numeric values, the types are the same. Strings,however, in WM Basic are passes as a 16-bit internal value, whereas inVB they are passed as a 32-bit pointer to a null-terminated string.The variant structure in both systems is a 4-byte type (a 32-bitinteger—the same value as returned by the VarType function),followed by 4 bytes of slop, followed by the value of the variable, asshown below:Bytes 0-3 Bytes 4-7 Bytes 8-15

VarType Alignmentslop

Value

Strings within variants are passed within an internal variant structurein both WM Basic and VB.

Floating Point NumbersIn VB and VBA, floating point numbers are interpreted as doubles unless they are explicitlyaccompanied by a type-declaration character. Thus, the following line assigns a Double inVB and VBA, whereas in WM Basic, it assigns a Single:

a = 0.00001In WM Basic, additional checking is performed to determine if a floating point number canbe accurately represented as a Single. If so, then the number is stored as a Single, requiring4 bytes rather than 8.The implications of this difference can be seen in the following code:

Dim a As Variant,b As Varianta = 1000b = .00001a = a + bMsgBox a

In VB and VBA, since the variables a and b are assigned Double values, the addition isperformed between two doubles, resulting in the value 1000.00001. In WM Basic, on theother hand, a and b are assigned Single values, resulting in an addition between two singles.When these two singles are added, there is a loss of precision resulting in the value 1000.In situations such as this, you should explicitly force the types using type-declarationcharacters. The above code can be re-written as follows:

Dim a As Variant,b As Varianta = 1000#b = .00001#a = a + bMsgBox a 'WM Basic displays 1000.00001

Currency NumbersIn VB , Double numbers do not convert to Currency numbers the same way. In VB, forexample, the following script will fail:

Page 756: Working Model 2D - User's Manual

752 Working Model Basic User's ManualSub Main

result = CCur("-1.401298E-45")End Sub

The above fails in VB because the number being converted is known to be a Double. In WMBasic, any number between the valid range supported by Currency is convertable toCurrency, even if the number is expressed in scientific notation or is extremely small(approaching zero).

Language Element DifferencesThe following language elements allow specification of additional parameters for displayinghelp in VBA:

MsgBox (statement)MsgBox (function)InputBox/InputBox$ (functions)

WM Basic and VB do not support these parameters.VBA and WM Basic uses a slightly different syntax for the following SQL functions (due toWM Basic's lack of support for variant arrays):

SQLErrorSQLGetSchemaSQLRetrieveSQLRequest

The above functions are supported only by VBA, not by VBWM Basic does not support any of the following VBA language elements:

Language Element TypeArray FunctionebHiragana ConstantebKatakana ConstantebLowerCase ConstantebNarrow ConstantebProperCase ConstantebUpperCase ConstantebWide ConstantExit Property StatementFor Each...Next StatementIsArray FunctionLenB FunctionLoadPicture FunctionOn...Gosub StatementOn...Goto StatementOption Explicit StatementOption Private StatementProperty Get...End Property StatementProperty Let...End Property StatementProperty Set...End Property Statement

Page 757: Working Model 2D - User's Manual

Appendix E WM Basic/Visual Basic Differences 753

Language Element TypeSavePicture StatementScreen.MousePointer PropertyStatic StatementStrConv FunctionTypeName FunctionTypeOf FunctionWith...End With Statement

The syntax for MsgBox and InputBox does not support the context and HelpFile parameters.

Natural Language SupportVBA supports multi-byte characters (sometimes referred to as natural language support);WM Basic and VB do not.

ObjectsWM Basic does not support any of VB's objects (except clipboard, screen, and a few others).

OLE AutomationWM Basic does not support named parameters. Visual Basic does not support named-parameters either; this is a feature of VBA.WM Basic does not support the VBA bracket syntax used with OLE automation objects. Forexample, the following two expressions are equivalent in VBA:

Application.Workbooks(1).Worksheets(“Sheet1”).Range(“A1”)[A1]

WM Basic does not support the VBA bracket syntax used to resolve the scope of a method orproperty:

Dim a As ObjectSet a = CreateObject("Word.Basic")a.[MsgBox] "Hello, world." '<-- Won't work in WM Basic

Parameter PassingVB and WM Basic do not support optional parameters. This is supported by VBA.

StringsIn WM Basic, variable-length strings within structures require 2 bytes of storage. In VB andVBA, variable-length strings within structures require 4 bytes of storage.The implications of this difference can be seen in the following code:

Type SampleLastName As String

End TypeSub Main

Dim a As SampleMsgBox Len(a)

End SubIn the above code, Visual Basic displays 4, while WM Basic displays 2.

Page 758: Working Model 2D - User's Manual

754 Working Model Basic User's Manual

In WM Basic, variable-length strings are limited to 32K in length. In VB, variable-lengthstrings are limited to 64K. In VBA, variable-length strings have no limits on their lengths.This limitation has implications on the string functions. For example, the Left functionreturns a specified number of characters from the left side of a string. The second parameterrepresents the number of characters to return—in VBA, this parameter is a Long whereas, inWM Basic, this parameter is an Integer. To demonstrate, the following statement willoverflow in WM Basic, but not in VBA:

s$ = Left(s$,300000)VB and VBA do not accept strings in some functions expecting numbers such as Int andFix. WM Basic allows strings as long as they are convertible to numbers.

Dim A As VariantABS(19) 'OKA = "10"ABS(A) 'OKABS("10") 'Works in WM Basic, not in VB/VBA

In WM Basic, these functions will accept any data type convertible to a number. If the datatype is a string, WM Basic converts it to a Double.Fixed-length strings within structures are size-adjusted upwards to an even size. Thus,structures in WM Basic are always even sized. VB and VBA allow fixed-length stringswithin structures to maintain an odd size.

VariantsPassing variants either by value or by reference to external routines (using the Declarestatement) passes either the entire variant structure (ByVal) or a pointer to a variant structure(ByRef) used internally by WM Basic. This means that passing variants to externallydeclared routines can only be done if that routine is aware of the internal variant structureused by WM Basic. This applies specifically to strings and OLE automation objects storedwithin the variant.In VB and VBA, on the other hand, strings and OLE automation objects within variants arestored in their native format (i.e., 32-bit pointer to a null-terminated string or an LPDISPATCHvalue).VBA supports variant arrays; WM Basic and VB do not. This includes use of the Array andIsArray functions.WM Basic and VBA support error variants; VB does not.

Passing Variants by ReferenceIn VBA, variants cannot be passed by reference to user-defined routines accepting non-variant parameters. For example, the following will not work in VBA:

Sub Test(ByRef a As Integer)End SubSub Main

Dim v As Variantv = 5Test v '<-- VBA gives error here

End SubIn WM Basic, the above example works as expected. WM Basic actually performs aconversion of the Variant v to a temporary Integer value and passes this temporary valueby reference. Upon return from the call to Test, WM Basic convers the temporary Integerback to a Variant.

Page 759: Working Model 2D - User's Manual

Appendix E WM Basic/Visual Basic Differences 755

Passing Optional Variants to Forward Declared RoutinesWM Basic does not catch the following error:

Declare Sub Test(Optional v As Variant) '<-- LINE 1Sub Main

TestEnd SubSub Test(v As Variant) '<-- LINE 5End Sub

In the above script, the Declare statement on line 1 defines a prototype for the Test functionthat is incompatible with the actual declaration on line 5.

Stack SizeWM Basic uses a default stack of 2K, expandable to 8K. VB and VBA uses a much largerstack size. For example, VBA allocates approximately 14K for the stack.Since the stack for WM Basic is smaller, you may have to be more attentive when using localvariables, especially fixed-length strings and structures, since storage for all local variablescomes from the stack.Note: Variable-length strings only require 2 bytes of storage on the stack. Wherever possible,use variable length strings in place of fixed-length strings.

Expression EvaluationWith Boolean expressions (i.e., expression involving And, Or, Xor, Eqv, and Imp), if oneoperand is Null and the other argument is numeric, then Null is returned regardless of thevalue of the other operand. For example, the following expression returns Null:

Null And 300000Despite the fact that the expression returns Null, VBA evaluates the numeric operandanyway, converting it to a Long. If an overflow occurs during conversion, a trappableruntime error is generated. In WM Basic, the expression returns Null regardless of the valueof the numeric operand. For example, the following expression will overflow in VBA, butnot in WM Basic:

Null And 5E200

File SearchingThe filename matching algorithm used by WM Basic is different than that used by VB. Thisaffects commands that perform directory searching, such as Dir, Kill, and FileList. Thefollowing differences exist:

In VB, an asterisk within the filename matches any characters up tothe end of the filename or to the period, whichever comes first.In VB, the period is a separator for the filename and the extension. InWM Basic, the period is treated as a normal filename character.

The following table describes the meaning of some common file specifications.Specification

Meaning in VB Meaning in WM Basic

* All files. All files.

*.* All files. All files that have an

Page 760: Working Model 2D - User's Manual

756 Working Model Basic User's Manual

extension.

s*e All files that begin with"s".

All files that begin with "s"and end with "e".

s*.* All files that begin with"s".

All files that begin "s" andhave an extension.

test. The file "test" with noextension.

The file called "test.". WMBasic will never find thisfile under Windows orDOS.

test.* All files having the rootname "test" with anyextension, such as "test","test.txt", and so on.

All files having the rootname "test" with anextension. The file "test"with no extension will notbe found.

This filename matching algorithm is the same across all platforms that support WM Basic.

Page 761: Working Model 2D - User's Manual

757

– (minus sign), subtraction operator, 52–53! (exclamation point)

activating parts of files, 260used for Single type-declaration character. See type-

declaration charactersused within user-defined formats, 242

" (quote), embedding within strings, 305# (number sign)

as delimiter for date literals, 305delimiter for date literals, 129delimiter for parsing input, 274–76used for Double type-declaration character. See type-

declaration charactersused to specify ordinal values, 152used within user-defined formats, 241wildcard used with Like (operator), 297

#ERROR code#reading from sequential files, 275writing to sequential files, 492

#FALSE#reading from sequential files, 275writing to sequential files, 492

#NULL#reading from sequential files, 275writing to sequential files, 492

#TRUE#reading from sequential files, 275writing to sequential files, 492

$ (dollar sign), used for String type-declarationcharacter. See type-declaration characters

$wmend$, 695, 696, 698$wmstart$, 695, 696, 698% (percent)

used for Integer type-declaration character. See type-declaration characters

used within user-defined formats, 241& (ampersand)

concatenation operator, 48octal/hexadecimal formats, 305used for Long type-declaration character. See type-

declaration charactersused within user-defined formats, 242

& (operator), vs. addition, 51' (apostrophe), used with comments, 48–50( ) (parentheses)

used in expressions, 49–50() (parentheses)

used to pass parameters by value, 49* (asterisk)

multiplication operator, 50used within user-defined formats, 242wildcard. See wildcardswildcard used with Like (operator), 297

+ (plus sign), addition operator, 50–52, (comma)

used with Print, 371used within user-defined formats, 241

. (period)used to separate object from property, 53–54used with structures, 53–54used within filenames, 124used within user-defined formats, 241

/ (slash)division operator, 54–55used within filenames, 123used within user-defined formats, 241

: (colon)used with labels, 264used within filenames, 123, 124used within user-defined formats, 241

; (semicolon), used with Print, 371, 373< (less than)

comparison operator, 3–4used within user-defined formats, 242

Index

Page 762: Working Model 2D - User's Manual

758 Working Model Basic User's Manual

<= (less than or equal), comparison operator, 3–4<> (not equal), comparison operator, 3–4= (equal sign)

assignment statement, 55–56comparison operator, 3–4

> (greater than)comparison operator, 3–4used within user-defined formats, 242

>= (greater than or equal), comparison operator, 3–4? (question mark)

wildcard. See wildcardswildcard used with Like (operator), 297

@ (at sign)used for Currency type-declaration character. See

type-declaration charactersused within user-defined formats, 242

\ (backslash)integer division operator, 56used with escape characters, 358used within filenames, 123used within user-defined formats, 242

^ (caret), exponentiation operator, 57_ (underscore), line-continuation character, 57–58__stdcall calling convention, 1450 (digit), used within user-defined formats, 240Abs (function), 58–59absolute value, 58–59accelerator keys, in Dialog Editor, 661

assigning to dialog controls, 669–71testing, 679

actions, dialog, 172, 691ActivateControl (statement), 59–60activating

applications, 64–65windows, 482–83

aliasesused with external subroutines and functions, 146

alignment, considerations for cross-platform scripting,122

And (operator), 60–61annuities

future values of, 250interest rates of, 396–97number of periods for, 340–41payments for, 367–68present value of, 341–42, 384–85principal payments for, 369–71

AnswerBox (function), 61–63antilogarithm function (Exp), 224Any (data type), 63–64, 147AppActivate (statement), 64–65

AppClose (statement), 65–66Append (keyword), 350–53AppFilename$ (function), 66AppFind$ (function), 66–67AppGetActive$ (function), 67AppGetPosition (statement), 67–68AppGetState (function), 68–69AppHide (statement), 69–70AppleScript, executing, 312applications

activating, 64–65changing size of, 75–76closing, 65–66finding, 66–67finding active, 67getting position of, 67–68getting state of, 68–69getting type of, 76–77hiding, 69–70listing, 70–71maximizing, 71minimizing, 71–72moving, 72–73restoring, 73–74retrieving filenames of, 66running, 426–27selecting menu commands from, 315–16setting state of, 74showing, 75

AppList (statement), 70–71AppMaximize (statement), 71AppMinimize (statement), 71–72AppMove (statement), 72–73AppRestore (statement), 73–74AppSetState (statement), 74AppShow (statement), 75AppSize (statement), 75–76AppType (function), 76–77arctangent function (Atn), 84arguments

parentheses use, 49–50passed to functions, 248passed to subroutines, 450to external routines, 93, 147, 151

arithmetic operators. See operatorsarranging

icons, 155windows

cascading, 155–56tiling, 158–59

ArrayDims (function), 77–78

Page 763: Working Model 2D - User's Manual

Index 759

arrays, 3ArrayDims (function), 77–78declaring, 79

as local, 161–63as private, 376–77as public, 377–80

Dim (statement), 161–63dimensions

getting bounds of, 80getting lower bound, 292–93getting number of, 77–78, 80getting upper bound, 466–67LBound (function), 292–93maximum number of, 161reestablishing, 398–99UBound (function), 466–67

dynamic, 80, 161, 376, 378, 398–99erasing, 215–16filling combo boxes from, 170filling drop list boxes from, 170filling list boxes from, 170filling with application names, 70–71filling with disk names, 166filling with query results, 441filling with window objects, 485fixed-sized, declaring, 79list of language elements, 3operations on, 80passing, 80Private (statement), 376–77Public (statement), 377–80selecting items of, 414–15setting default lower bound of, 356size, changing while running, 398–99sorting, 81total size of, 161, 376, 378

ArraySort (statement), 81As Any (keyword), 147Asc (function), 81–82AskBox$ (function), 82–83AskPassword$ (function), 83–84assigning, objects, 420–21assignment

= (statement), 55–56Let (statement), 296–97LSet (statement), 310–11overflow during, 55, 297rounding during, 226RSet (statement), 404

Atn (function), 84used to calculate Pi, 363

attributes. See files, attributes ofautomation. See OLE automationBasic.Capability (method), 84–85, 120Basic.Eoln$ (property), 85–86Basic.FreeMemory (property), 86Basic.HomeDir$ (property), 86Basic.OS (property), 87, 120Basic.PathSeparator$ (property), 87Basic.Version$ (property), 87–88BasicScript

free memory of, 86functions to get information from, 12home directory of, 86version of, 87–88

Beep (statement), 88Begin Dialog (statement), 88–90Binary (keyword), 350–53binary data

reading, 251–53writing, 381–84

binary filesopening, 350–53reading from, 251–53writing to, 381–84

binary operatorsAnd (operator), 60–61Eqv (operator), 214–15Imp (operator), 272–73list of, 12–13Not (operator), 338–39Or (operator), 362–63Xor (operator), 494–95

bitmaps, used in dialog boxes, 364, 366Body (method)

of WMDocument, 544Body (property)

of WMPoint, 616Boolean (data type), 91

converting to, 96range of values, 91storage requirements, 91

Boolean constantsFalse (constant), 227True (constant), 464

breakpoints, in Script Editor, 640removing, 642setting, 640–41

bugs (error trapping), 219–20, 348–50built-in dialogs. See dialogs, built-inButtonEnabled (function), 91–92ButtonExists (function), 92

Page 764: Working Model 2D - User's Manual

760 Working Model Basic User's Manual

buttons. See also push buttonson toolbar

in Dialog Editor, 653–54in Script Editor, 620–21

by value, forcing parameters, 248, 450ByRef (keyword), 92–93, 146, 148, 247, 248, 449, 450byte ordering, with files, 121byte ordering, with structures, 121ByVal (keyword), 49, 93–94, 146, 147, 246, 248, 449,

450Call (statement), 94–95calling

external routines, 144–53other routines, 94–95

calling conventions__stdcall, 145CDecl, 145for external routines, under Macintosh, 148for external routines, under Win32, 148for external routines, under Windows, 148Pascal, 145System, 145

Cancel buttonsadding to dialog template, 95getting label of, 177in Dialog Editor, 657setting label of, 176

capabilitiesof network, 334–36of platform, 84–85

capturingactive application, 157–58active window, 157–58entire screen, 157–58

capturing dialog boxes from another application, inDialog Editor, 676–77

cascading desktop windows, 155–56Case Else (statement), 413case sensitivity, when comparing strings, 356–57case statement, 412–13CBool (function), 96CCur (function), 96–97cd audio, Mci (function), 313–15CDate, CVDate (functions), 97CDbl (function), 98CDecl (keyword), 144–53CDecl calling convention, 145character

codes, 81–82converting to number, 81–82

ChDir (statement), 98–99

ChDrive (statement), 99check boxes

adding to dialog template, 99–101checking for existence of, 101–2checking if enabled, 101getting state of, 178, 255in Dialog Editor, 657setting state of, 179, 422–23

CheckBox (statement), 99–101CheckBoxEnabled (function), 101CheckBoxExists (function), 101–2Choose (function), 102–3Chr, Chr$ (functions), 103chunking. See parsingCInt (function), 103–4Clipboard

erasing, 105–6getting contents of, 104–5, 106–7getting type of data in, 106list of language elements, 3placing snapshots into, 157–58setting contents of, 105, 107

Clipboard$ (function), 104–5Clipboard$ (statement), 105Clipboard.Clear (method), 105–6Clipboard.GetFormat (method), 106Clipboard.GetText (method), 106–7Clipboard.SetText (method), 107CLng (function), 107–8Close (statement), 108–9closing

all files, 400applications, 65–66files, 108–9windows, 483–84

code resourcessearch rules for, 152specifying, on the Macintosh, 153

Collection (topic), 497collections

defined, 346elements, identifying, 346indexing, 346methods of, 346properties of, 346

colors, changing desktop, 156combo boxes

adding to dialog template, 109–10checking for existence of, 111–12checking if enabled, 110–11getting edit field of, 177

Page 765: Working Model 2D - User's Manual

Index 761

getting number of items in, 256–57getting selection of, 255–56in Dialog Editor, 657selecting item from, 416setting edit field of, 176setting items in, 170

ComboBox (statement), 109–10ComboBoxEnabled (function), 110–11ComboBoxExists (function), 111–12command line, retrieving, 112Command, Command$ (functions), 112comments, 113

' (apostrophe), 48–50adding to scripts, in Script Editor, 632list of language elements, 3Rem (statement), 400

common dialogsfile open, 353–55file save, 406–7

comparing strings, 445–46comparison operators, 3–4

list of, 3–4table of, 113used with mixed types, 114used with numbers, 114used with strings, 114used with variants, 115

compatibility mode, opening files in, 352compiler errors, 705–9concatenation operator (&), 48conditionals

Choose (function), 102–3If...Then...Else (statement), 270–71IIf (function), 271–72Switch (function), 451–52

conjunction operator (And), 60–61Const (statement), 115–17constants. See also literals

declaring, 115–17ebAbort (constant), 189ebBold (constant), 190ebBoldItalic (constant), 191ebBoolean (constant), 191ebCurrency (constant), 192ebDate (constant), 193ebDirectory (constant), 194–95ebDOS16 (constant), 87ebDouble (constant), 195ebEmpty (constant), 195ebExclamation (constant), 195–96ebHidden (constant), 196

ebIgnore (constant), 196–97ebInformation (constant), 197ebInteger (constant), 197–98ebItalic (constant), 198ebLandscape (constant), 198ebLeftButton (constant), 198–99ebLong (constant), 199ebMacintosh (constant), 87, Error! Not a valid

bookmark in entry on page 199ebMaximized (constant), 199ebMinimized (constant), 200ebNo (constant), 200ebNone (constant), 200–201ebNormal (constant), 201ebNull (constant), 202ebObject (constant), 202ebOK (constant), 202ebOKCancel (constant), 202–3ebOKOnly (constant), 203ebOS2 (constant), 87ebPortrait (constant), 203ebQuestion (constant), 203–4ebReadOnly (constant), 204ebRegular (constant), 204–5ebRestored (constant), 205ebRetry (constant), 205ebRetryCancel (constant), 206ebRightButton (constant), 206ebSingle (constant), 206–7ebSolaris (constant), 87ebString (constant), 207ebSystem (constant), 207–8ebSystemModal (constant), 208ebVariant (constant), 208ebVolume (constant), 208–9ebWin16 (constant), 87, 195ebWin32 (constant), 87ebWindows (constant), 209–10ebYes (constant), 210ebYesNo (constant), 210ebYesNoCancel (constant), 210–11Empty (constant), 212False (constant), 227folding, 306giving explicit type to, 116list of, 118list of language elements, 17naming conventions of, 116Nothing (constant), 339Null (constant), 342–43Pi (constant), 363

Page 766: Working Model 2D - User's Manual

762 Working Model Basic User's Manual

scoping of, 117True (constant), 464

control IDs, retrieving, 167control structures, 213

Do...Loop (statement), 182–83Exit Do (statement), 221–22Exit For (statement), 222–23Exit Function (statement), 223Exit Sub (statement), 224For...Next (statement), 237–38Function...End Function (statement), 245–49GoSub (statement), 262–63, 401–2Goto (statement), 263–64If...Then...Else (statement), 270–71list of, 5–6Select...Case (statement), 412–13Sub...End Sub (statement), 448–51While...Wend (statement), 481–82

control.ini file, 156controlling applications

list of language elements, 4–5Menu (statement), 315–16QueEmpty (statement), 385–86QueFlush (statement), 386QueKeyDn (statement), 386–87QueKeys (statement), 387–88QueKeyUp (statement), 388QueMouseClick (statement), 388–89QueMouseDblClk (statement), 389–90QueMouseDblDn (statement), 390–91QueMouseDn (statement), 391–92QueMouseMove (statement), 392QueMouseMoveBatch (statement), 393–94QueMouseUp (statement), 394QueSetRelativeWindow (statement), 394–95

controlling program flow. See control structurescontrols. See dialog controlsconversations. See DDEconversion. See data conversioncoordinate systems

dialog base units, 407–8pixels, 408–9–10twips per pixel, 409

copyingdata

using = (statement), 55–56using Let (statement), 296–97using LSet (statement), 310–11using RSet (statement), 404

files, 228–29text. See Clipboard

in Script Editor, 631user-defined types, 310

Cos (function), 118cosine, 118counters, used with For...Next (statement), 238counting

items in combo box, 256–57items in list box, 259–60items in string, 289–90lines in string, 300–301words, 491–92

CreateObject (function), 118–20creating dialog boxes, in Dialog Editor, 656–61creating new objects, 162, 337–38cross-platform scripting, 120–24

alignment, 122byte ordering with files, 121byte ordering with structures, 121determining capabilities of platform, 120determining platform, 84–85, 120end-of-line character, 122getting end-of-line character, 85–86getting path separator, 87getting platform, 87path separators, 123portability of compiled code, 122portability of drive letters, 124relative paths, 124unsupported language elements, 123

CSng (function), 124–25CStr (function), 125CurDir, CurDir$ (functions), 125–26Currency (data type), 126

converting to, 96–97range of values, 126storage requirements, 126

currency format, 239custom controls, activating, 59–60custom dialogs. See user dialogscutting text, in Script Editor, 631CVar (function), 126–27CVDate (function), 97CVErr (function), 127–28data conversion

character to number, 81–82during expression evaluation, 225list of language elements, 7number to character, 103number to hex string, 266number to octal string, 347string to number, 471–72

Page 767: Working Model 2D - User's Manual

Index 763

testing for numbers, 287–88to Boolean, 96to Currency, 96–97to Date, 97, 136, 284–85, 463–64to Double, 98to error, 127–28to Integer, 103–4to Long, 107–8to Single, 124–25to String, 125, 445to Variant, 126–27

data conversion functionsAsc (function), 81–82CBool (function), 96CCur (function), 96–97CDate, CVDate (functions), 97CDbl (function), 98Chr, Chr$ (functions), 103CInt (function), 103–4CLng (function), 107–8CSng (function), 124–25CStr (function), 125CVar (function), 126–27CVErr (function), 127–28Hex, Hex$ (functions), 266Oct, Oct$ (functions), 347Str, Str$ (functions), 445Val (function), 471–72

data objects. See objectsdata sources

retrieving DBMS of, 436retrieving list of, 435retrieving name of, 436retrieving owner qualifier of, 436retrieving server of, 436

data typesAny (data type), 63–64, 147arguments. See argumentsarrays. See arraysBoolean (data type), 91changing default, 153–55converting. See data conversionconverting between. See data conversionCurrency (data type), 126Date (data type), 129Dim (statement), 161–63Double (data type), 185–86Integer (data type), 280list of, 7–8Long (data type), 309–10Object (data type), 343–44

Private (statement), 376–77Public (statement), 377–80returned from external functions, 146Single (data type), 427–28String (data type), 446–48user-defined, 470–71Variant (data type), 472–76

data, sharing. See DDEdatabase

list of language elements, 8database functions

SQLBind (function), 430SQLClose (function), 431SQLError (function), 432SQLExecQuery (function), 433SQLGetSchema (function), 435SQLOpen (function), 438SQLRequest (function), 439SQLRetrieve (function), 441SQLRetrieveToFile (function), 442

databasesclosing, 431opening, 438placing data, 430querying, 433, 439, 441, 442retrieving errors from, 432retrieving information about, 435retrieving list of, 435retrieving list of owners of, 435retrieving name of, 436retrieving qualifier of, 436tables

retrieving list of, 436Date (data type), 129

converting to, 97, 136, 463–64range of values, 129specifying date constants, 129storage requirements, 129

Date, Date$ (functions), 130Date, Date$ (statements), 130–31date/time functions

Date, Date$ (functions), 130Date, Date$ (statements), 130–31DateAdd (function), 131–33DateDiff (function), 133–34DatePart (function), 134–35DateSerial (function), 136Day (function), 136–37FileDateTime (function), 229Hour (function), 267IsDate (function), 284–85

Page 768: Working Model 2D - User's Manual

764 Working Model Basic User's Manual

list of language elements, 8–9Minute (function), 319–20Month (function), 322–23Now (function), 339–40Second (function), 410Time, Time$ (functions), 461Time, Time$ (statements), 461–62Timer (function), 462TimeSerial (function), 463Weekday (function), 480–81Year (function), 495

DateAdd (function), 131–33DateDiff (function), 133–34DatePart (function), 134–35dates

adding, 131–33converting to, 136, 284–85current, 130, 339–40Date (data type), 129day of month, 136–37day of week, 480–81file creation, 229file modification, 229month of year, 322–23parts of, 134–35reading from sequential files, 275setting, 130–31subtracting, 133–34year, 495

DateSerial (function), 136DateValue (function), 136Day (function), 136–37DDB (function), 137–38DDE

AppActivate (statement), 64–65changing timeout, 144DoEvents (function), 184DoEvents (statement), 184ending conversation, 142–43executing remote command, 138–39getting text, 140–41getting value from another application, 140–41initiating conversation, 139list of language elements, 9sending text, 140setting data in another application, 141–42setting value in another application, 140Shell (function), 426–27starting conversation, 139terminating conversation, 142–43–44

DDEExecute (statement), 138–39

DDEInitiate (function), 139DDEPoke (statement), 140DDERequest, DDERequest$ (functions), 140–41DDESend (statement), 141–42DDETerminate (statement), 142–43DDETerminateAll (statement), 143–44DDETimeout (statement), 144debugger, invoking, 444debugging scripts, in Script Editor, 638. See also Script

Editorbreakpoints, 640

removing, 642setting, 640–41

instruction pointer, 638moving to another line in subroutine, 639

procedure calls, tracing, 639script execution, tracing, 638–39watch variables, 642

adding, 642–44deleting, 644modifying value of, 644–45selecting, 644

decision making. See also control structuresChoose (function), 102–3If...Then...Else (statement), 270–71IIf (function), 271–72Select...Case (statement), 412–13Switch (function), 451–52

Declare (statement), 63, 144–53declaring

implicit variables, 161object variables, 162, 337–38, 343, 345with Dim (statement), 161–63with Private (statement), 376–77with Public (statement), 377–80

default data type, changing, 153–55default properties, 226DefType (statement), 153–55degrees, converting to radians, 84DELETE (SQL statement), 434, 440deleting controls, in Dialog Editor, 674deleting text, in Script Editor, 630–31delimited files, reading, 274–76depreciation

calculated using double-declining balance method,137–38

straight-line depreciation, 429sum of years' digits depreciation, 452–53

Desktop.ArrangeIcons (method), 155Desktop.Cascade (method), 155–56Desktop.SetColors (method), 156

Page 769: Working Model 2D - User's Manual

Index 765

Desktop.SetWallpaper (method), 156–57Desktop.Snapshot (method), 157–58Desktop.Tile (method), 158–59Dialog (function), 159–60Dialog (statement), 160–61dialog actions, 172, 691dialog boxes, in Dialog Editor. See also dialog controls;

dialog controls, in Dialog Editor; Dialog Editor; userdialogsattributes of, adjusting with Information dialog box,

664–65capturing from another application, 676–77creating, 656–61editing, 651, 661–74incorporating dialog boxes or dialog controls into

script, 679Information dialog box for, displaying, 662–63moving

with arrow keys, 667with Information dialog box, 667with mouse, 666–67

opening dialog box template files in Dialog Editor,677

pasting dialog box controls into Dialog Editor, 675–76pasting dialog boxes into Dialog Editor, 675, 676resizing, 668

with Information dialog box, 668with mouse, 668

selecting, 662testing, 678

for basic problems, 677–78for operational problems, 678–79when there are hidden controls, 668

titles of, changing, 669dialog callback. See dialog proceduresdialog controls. See also dialog controls, in Dialog Editor

activating, 59–60adding, in Dialog Editor, 658–59Cancel buttons

adding to dialog template, 95getting label of, 177in Dialog Editor, 657setting label of, 176

changing focus of, 169–70changing text of, 176–77check boxes

adding to dialog template, 99–101checking existence of, 101–2checking if enabled, 101getting state of, 178, 255in Dialog Editor, 657

setting state of, 179, 422–23combo boxes

adding to dialog template, 109–10checking for existence of, 111–12checking if enabled, 110–11getting edit field of, 177getting number of items in, 256–57getting selection of, 255–56in Dialog Editor, 657selecting item from, 416setting edit field of, 176setting items in, 170

deleting, in Dialog Editor, 674disabling, 168–69drop list boxes

adding to dialog template, 186–88getting selection index of, 178getting selection of, 177in Dialog Editor, 657setting items in, 170setting selection of, 176, 179

duplicating, in Dialog Editor, 673enabling, 168–69getting enabled state of, 167–68getting focus of, 169getting text of, 177–78getting value of, 178getting visibility of, 179–80group boxes

adding to dialog template, 265–66getting label of, 177in Dialog Editor, 657setting label of, 176

list boxesadding to dialog template, 301–3checking for existence of, 303–4checking if enabled, 303getting number of items in, 259–60getting selection index of, 178getting selection of, 177, 258–59in Dialog Editor, 657selecting item from, 416–17setting items in, 170setting selection of, 176, 179

list of language elements, 9–10moving, in Dialog Editor, 666–67–68OK buttons

adding to dialog template, 347–48getting label of, 177in Dialog Editor, 657setting label of, 176

Page 770: Working Model 2D - User's Manual

766 Working Model Basic User's Manual

option buttonsadding to dialog template, 358–59checking existence of, 360–61checking if enabled, 359–60getting label of, 177getting selection index of, 178getting state of, 261–62grouping within dialog template, 361–62in Dialog Editor, 657selecting, 179setting label of, 176setting state of, 424–25

picture button controlsadding to dialog template, 365–67

picture buttonsin Dialog Editor, 657

picture controlsadding to dialog template, 363–65in Dialog Editor, 657setting image of, 174–76

positioning with grid, in Dialog Editor, 659–60push buttons

adding to dialog template, 380–81checking for existence of, 92checking if enabled, 91–92getting label of, 177in Dialog Editor, 657selecting, 415setting label of, 176

resizing, in Dialog Editor, 668–69retrieving ID of, 167selecting, in Dialog Editor, 662setting value of, 178–79setting visibility of, 180–82text boxes

adding to dialog template, 459–61getting content of, 177, 257–58in Dialog Editor, 657, 679setting content of, 176, 423–24

text controlsadding to dialog template, 458–59getting label of, 177in Dialog Editor, 657setting label of, 176

dialog controls, in Dialog Editor. See also dialog boxes,in Dialog Editor; dialog controls; Dialog Editor; userdialogsaccelerator keys

assigning to, 669–71testing, 679

adding to dialog box, 658–59

attributes of, adjusting with Information dialog box,664, 665–66

Cancel buttons, 657check boxes, 657combo boxes, 657creating efficiently, 660–61deleting

all controls, 674one control, 674

drop list boxes, 657duplicating, 673group boxes, 657hidden, 668Information dialog box for, displaying, 663–64labels of, changing, 669list boxes, 657moving

with arrow keys, 667with Information dialog box, 667–68with mouse, 666–67

OK buttons, 657option buttons, 657

grouping, 661, 679pasting controls into Dialog Editor, 675–76picture buttons, 657. See also dialog controls, in

Dialog Editor, specifying picturespicture controls, 657. See also dialog controls, in

Dialog Editor, specifying picturespositioning with grid, 659–60push buttons, 657resizing, 668

automatically, 668–69with Information dialog box, 668with mouse, 668

selecting, 662specifying pictures, 671

from file, 671from picture library, 671–72

tabbing order of, 660, 676, 678text boxes, 657, 679text controls, 657types of, 656–57

Dialog Editor, 651, 652. See also dialog boxes, in DialogEditor; dialog controls; dialog controls, in DialogEditor; user dialogsapplication window, 652–53Controls menu, 683–84controls supported by, 656–57Dialog Translation Errors dialog box, 676, 677Edit menu, 682–83exiting from, 680

Page 771: Working Model 2D - User's Manual

Index 767

features of, 652File menu, 680–81grid, displaying and adjusting, 659–60help

for current window, 655on selected topics, 655–56

Help menu, 684–85Information dialog box, 662–66

adjusting control attributes with, 664, 665–66adjusting dialog box attributes with, 664–65displaying

for controls, 663–64for dialog boxes, 662–63

keyboard shortcuts, 654–55Pick tool, 685picture libraries, 672–73

creating for use in, 672–73modifying for use in, 673

toolbar of, 653–54undoing editing operations, 674

dialog procedures, 171–74actions sent to, 172, 691

dialog templates. See user dialogsdialog units, calculating, 407–8dialogs, built-in. See also user dialogs

AnswerBox (function), 61–63AskBox$ (function), 82–83AskPassword$ (function), 83–84InputBox, InputBox$ (functions), 277–78listing of, 14–15MsgBox (function), 323–26MsgBox (statement), 327MsgClose (statement), 327MsgOpen (statement), 327–29MsgSetText (statement), 329MsgSetThermometer (statement), 329–30PopupMenu (function), 368–69SaveFilename$ (function), 406–7SelectBox (function), 414–15user-defined, 88–90

Dim (statement), 161–63dimensions. See arrays, dimensionsDir, Dir$ (functions), 163–65directories

changing, 98–99containing BasicScript, 86containing Windows, 455creating, 321–22getting list of, 230getting path separator, 87parsing names of, 234–35

removing, 403retrieving, 125–26retrieving filenames from, 163–65, 231–34

disabling, dialog controls, 168–69disjunction operator (Or), 362–63disk drives

changing, 99getting free space of, 166–67platform support, 124retrieving current directory of, 125–26retrieving list of, 166

DiskDrives (statement), 166DiskFree (function), 166–67displaying messages, 323–26, 327

breaking text across lines, 325DlgControlId (function), 167DlgEnable (function), 167–68DlgEnable (statement), 168–69DlgFocus (function), 169DlgFocus (statement), 169–70DlgListBoxArray (function), 170DlgProc (function), 171–74DlgSetPicture (statement), 174–76DlgText (statement), 176–77DlgText$ (function), 177–78DlgValue (function), 178DlgValue (statement), 178–79DlgVisible (function), 179–80DlgVisible (statement), 180–82DLLs. See also external routines

calling, 144–53Declare (statement), 144–53search rules for, under Windows, 152

Do...Loop (statement), 182–83exiting Do loop, 221–22

documentation. See commentsDoEvents (function), 184DoEvents (statement), 184Double (data type), 185–86

converting to, 98internal format, 186range of values, 186storage requirements, 185–86

double-declining balance method, used to calculatedepreciation, 137–38

drives. See disk drivesdrop list boxes

adding to dialog template, 186–88getting selection index of, 178getting selection of, 177in Dialog Editor, 657

Page 772: Working Model 2D - User's Manual

768 Working Model Basic User's Manual

setting items in, 170setting selection of, 176, 179

DropListBox (statement), 186–88duplicating controls, in Dialog Editor, 673dynamic arrays, 80dynamic data exchange. See DDEdynamic dialogs. See user dialogsdynamic link libraries. See DLLse. See logarithmsebAbort (constant), 189ebBold (constant), 190ebBoldItalic (constant), 191ebBoolean (constant), 191ebCurrency (constant), 192ebDate (constant), 193ebDirectory (constant), 194–95ebDOS (constant), 87ebDouble (constant), 195ebEmpty (constant), 195ebExclamation (constant), 195–96ebHidden (constant), 196ebIgnore (constant), 196–97ebInformation (constant), 197ebInteger (constant), 197–98ebItalic (constant), 198ebLandscape (constant), 198ebLeftButton (constant), 198–99ebLong (constant), 199ebMacintosh (constant), 87, Error! Not a valid

bookmark in entry on page 199ebMaximized (constant), 199ebMinimized (constant), 200ebNo (constant), 200ebNone (constant), 200–201ebNormal (constant), 201ebNull (constant), 202ebObject (constant), 202ebOK (constant), 202ebOKCancel (constant), 202–3ebOKOnly (constant), 203ebOS2 (constant), 87ebPortrait (constant), 203ebQuestion (constant), 203–4ebReadOnly (constant), 204ebRegular (constant), 204–5ebRestored (constant), 205ebRetry (constant), 205ebRetryCancel (constant), 206ebRightButton (constant), 206ebSingle (constant), 206–7ebSolaris (constant), 87

ebString (constant), 207ebSystem (constant), 207–8ebSystemModal (constant), 208ebVariant (constant), 208ebVolume (constant), 208–9ebWin16 (constant), 87, 195ebWin32 (constant), 87ebWindows (constant), 209–10ebYes (constant), 210ebYesNo (constant), 210ebYesNoCancel (constant), 210–11edit controls. See text boxesEditEnabled (function), 211EditExists (function), 211–12editing custom dialog boxes, 651, 661–74Else (keyword), 270–71ElseIf (keyword), 270–71embedded objects. See OLE automationembedded quotation marks, 305Empty (constant), 212Empty, testing for, 285enabling, dialog controls, 168–69End (statement), 213end of file

checking, 213–14checking for, 213–14

end-of-line, in sequential files, 276entry points, Main (statement), 313Environ, Environ$ (functions), 213environment variables, getting, 213environment, controlling

list of language elements, 6–7EOF (function), 213–14equivalence operator (Eqv), 214–15Eqv (operator), 214–15Erase (statement), 215–16Erl (function), 216–17Err (function), 217Err (statement), 218Error (statement), 218–19error handlers

cascading, 220nesting, 219, 349removing, 349resetting, 218, 349resuming, 349, 400–401

error messagesBasicScript-specific, 702, 703compatible with Visual Basic, 699compiler, 705–9runtime, 699–702

Page 773: Working Model 2D - User's Manual

Index 769

error trapping, 219–20, 348–50Error, Error$ (functions), 220–21errors

BasicScript-specific, 220cascading, 220Erl (function), 216–17Err (function), 217Err (statement), 218Error (statement), 218–19Error, Error$ (functions), 220–21generating, 218–19getting error number of, 217getting line number of, 216–17getting text of, 220–21handling, 219–20list of language elements, 10On Error (statement), 348–50range of values for, 218resetting state of, 218Resume (statement), 400–401resuming control after, 220setting, 218SQL, 432Stop (statement), 444trapping, 348–50user-defined, 220

converting to, 127–28printing, 371printing to sequential files, 373reading from binary/random files, 252reading from sequential files, 275testing for, 285–86writing to random/binary files, 383writing to sequential files, 492

Visual Basic compatibility with, 220escape characters, table of, 358exclusive or operator (Xor), 494–95executing scripts, in Script Editor

pausing execution of, 637starting execution of, 637stopping execution of, 637tracing execution of, 638–39

Exit Do (statement), 182, 221–22Exit For (statement), 222–23, 238Exit Function (statement), 223Exit Sub (statement), 224exiting

from Dialog Editor, 680from Script Editor, 646

exiting from Dialog Editor, 680exiting operating environment, 453

Exp (function), 224exponentiation operator (^), 57expressions

evaluation of, 225–26promotion of operands within, 225propagation of Null through, 342

external routinescalling, 144–53calling conventions of, 148passing parameters, 147

data formats, 149null pointers, 149strings, 148using ByVal (keyword), 93, 151

specified with ordinal numbers, 152under Macintosh, 152under Windows, 152

False (constant), 227file I/O

Close (statement), 108–9EOF (function), 213–14Get (statement), 251–53Input# (statement), 274–76Line Input# (statement), 298–99Loc (function), 306–7Lock (statement), 307–8Lof (function), 308–9Open (statement), 350–53Print# (statement), 371–72Put (statement), 381–84Reset (statement), 400Seek (function), 410–11Seek (statement), 411–12Spc (function), 430Tab (function), 457Unlock (statement), 467–69Width# (statement), 482Write# (statement), 492–93

file numbers, finding available, 245file open dialog box, 353–55file save dialog box, 406–7file system

list of language elements, 11–12FileAttr (function), 227–28FileCopy (statement), 228–29FileDateTime (function), 229FileDirs (statement), 230FileExists (function), 230–31FileLen (function), 231FileList (statement), 231–34FileParse$ (function), 234–35

Page 774: Working Model 2D - User's Manual

770 Working Model Basic User's Manual

filesattributes of

ebArchive (constant), 190ebDirectory (constant), 194–95ebHidden (constant), 196ebNone (constant), 200–201ebNormal (constant), 201ebReadOnly (constant), 204ebSystem (constant), 207–8ebVolume (constant), 208–9getting, 253–55setting, 421–22used with Dir, Dir$ (functions), 165used with FileList (statement), 233used with GetAttr (function), 254

attributes, used with SetAttr (statement), 422checking existence of, 230–31checking for end of, 213–14closing, 108–9closing all, 400copying, 228–29deleting, 291–92end-of-line character, 122getting date and time of, 229getting length of, 231getting list of, 163–65, 231–34getting mode of, 227–28getting next available file number, 245getting position within, 306–7, 410–11getting size of, 308–9list of language elements, 10–11locking regions in, 307–8opening, 350–53

access capabilities, 352modes, 351setting another process's access rights, 352setting record length, 352truncating to zero length, 351

printing, 375–76reading, 274–76reading binary data from, 251–53reading lines from, 298–99renaming, 330–31requesting name of, 406–7setting read/write position in, 411–12sharing, 352splitting names of, 234–35types of

ebWindows (constant), 209–10FileType (function), 236getting, 236

unlocking regions in, 467–69writing binary data to, 381–84writing query results to, 442writing to, 371–72, 492–93

FileType (function), 236financial functions

DDB (function), 137–38Fv (function), 250IPmt (function), 280–82IRR (function), 282–83list of, 12MIRR (function), 320–21NPer (function), 340–41Npv (function), 341–42Pmt (function), 367–68PPmt (function), 369–71Pv (function), 384–85Rate (function), 396–97Sln (function), 429SYD (function), 452–53

findingapplications, 66–67files, 163–65strings, 278–79windows, 484–85

Fix (function), 236–37. See also Int (function)fixed arrays, 79fixed numeric format, 239fixed-length strings

conversion between variable-length, 447declaring, 161, 376, 378passing to external routines, 148, 150within structures, 465

floating-point valuesDouble (data type), 185–86Single (data type), 427–28

focus, of dialog controlsgetting, 169setting, 169–70

fonts, within user-dialogs, 90For...Next (statement), 237–38

exiting For loop, 222–23formatting data

built-in, 239built-in formats

date/time, 240numeric, 239

in filesSpc (function), 430Tab (function), 457Width# (statement), 482

Page 775: Working Model 2D - User's Manual

Index 771

user-defined formats, 240date/time, 243numeric, 240string, 242

forward referencing, with Declare (statement), 63, 144–53

FreeFile (function), 245Function...End Function (statement), 245–49Function...End Sub (statement), exiting function, 223Functions, 24

defining, 245–49exiting function, 223naming conventions of, 246returning values from, 247

future value of annuity, calculating, 250fuzzy string comparisons, 297–98Fv (function), 250general date format, 240general number format, 239generating random numbers, 395Get (statement), 251–53GetAttr (function), 253–55GetCheckBox (function), 255GetComboBoxItem$ (function), 255–56GetComboBoxItemCount (function), 256–57GetEditText$ (function), 257–58GetListBoxItem$ (function), 258–59GetListBoxItemCount (function), 259–60GetOption (function), 261–62global (public) variables, 377–80Global (statement) (Public [statement]), 377–80GoSub (statement), 262–63

returning from, 401–2Goto (statement), 263–64grep (Like [operator]), 297–98grid, in Dialog Editor, 659–60group boxes

adding to dialog template, 265–66getting label of, 177in Dialog Editor, 657setting label of, 176

GroupBox (statement), 265–66grouping option buttons, 361–62handles, getting operating system file handles, 227–28height, of screen, 408–9help

in Dialog Editor, 655–56, 684–85in Script Editor, 624–26, 649

Hex, Hex$ (functions), 266hexadecimal characters, in strings, 358hexadecimal strings

converting to, 266converting to numbers, 471–72

hidingapplications, 69–70dialog controls, 180–82

HLine (statement), 266–67home directory, 86Hour (function), 267HPage (statement), 267–68HScroll (statement), 268HWND (object), 268–69HWND (object), getting value of, 269–70icons, arranging on desktop, 155idle loops

DoEvents (function), 184DoEvents (statement), 184

If...Then...Else (statement), 270–71If...Then...End If (statement), shorthand for (IIf), 271–

72IIf (function), 271–72Imp (operator), 272–73implication operator (Imp), 272–73implicit variable declaration, with DefType (statement),

153–55indexing collections, 346infinite loops, breaking out of, 183, 238, 482Information dialog box, in Dialog Editor, 662–66ini files. See also win.ini file; control.ini file

list of language elements, 12reading items from, 397reading section names from, 397–98writing items to, 493–94

Inline (statement), 273–74Input (keyword), 350–53Input# (statement), 274–76InputBox, InputBox$ (functions), 277–78INSERT (SQL statement), 434, 440inserting text, in Script Editor, 628insertion point, moving, in Script Editor, 626–27

to specified line, 627–28with keyboard, 622–23with mouse, 627

instantiation of OLE objects, 118–20InStr (function), 278–79Int (function), 279–80. See also Fix (function)Integer (data type), 280

converting to, 103–4range of values for, 280storage requirements of, 280

integer division operator (\), 56Interactive Operation, 20

Page 776: Working Model 2D - User's Manual

772 Working Model Basic User's Manual

intercepting (trapping) errors, 219–20, 348–50interest payments, calculating, 280–82internal rate of return, calculating, 282–83, 320–21IPmt (function), 280–82IRR (function), 282–83Is (operator), 283–84IsDate (function), 284–85IsEmpty (function), 285IsError (function), 285–86IsMissing (function), 249, 286–87, 451IsNull (function), 287IsNumeric (function), 287–88IsObject (function), 288–89Item$ (function), 289ItemCount (function), 289–90iterating through collections, 346jumps

GoSub (statement), 262–63Goto (statement), 263–64Return (statement), 401–2

keyboard shortcutsin Dialog Editor, 654–55in Script Editor, 621–24

keystrokes, sendingDoEvents (function), 184DoEvents (statement), 184QueKeyDn (statement), 386–87restrictions, 388special characters, 419to applications, 185, 386–87–88

keywordslist of, 291restrictions for, 291

Kill (statement), 291–92labels

in place of line numbers, 299naming conventions of, 264used with GoSub (statement), 262used with Goto (statement), 264

LBound (function), 292–93used with OLE arrays, 293

LCase, LCase$ (functions), 293–94least precise operand, 356Left, Left$ (functions), 294Len (function), 294–96Len (keyword), specifying record length, 350–53Let (statement), 296–97Lib (keyword), 144–53Like (operator), 297–98line breaks, in MsgBox (statement), 325line continuation, 57–58

in Script Editor, 633Line Input# (statement), 298–99line numbers, 299Line$ (function), 299–300LineCount (function), 300–301linking. See DDE; OLE automationlist boxes

adding to dialog template, 301–3checking for existence of, 303–4checking if enabled, 303getting number of items in, 259–60getting selection index of, 178getting selection of, 177, 258–59in Dialog Editor, 657selecting item from, 416–17setting items in, 170setting selection of, 176, 179

ListBox (statement), 301–3ListBoxEnabled (function), 303ListBoxExists (function), 303–4literals, 305–6Loc (function), 306–7local variables. See also variables

declaring, 161–63Lock (statement), 307–8locking file regions, 307–8Lof (function), 308–9Log (function), 309logarithm function (Log), 309logarithms

Exp (function), 224Log (function), 309

logical constantsFalse (constant), 227True (constant), 464

logical negation, 338–39logical operators

And (operator), 60–61Eqv (operator), 214–15Imp (operator), 272–73list of, 12–13Not (operator), 338–39Or (operator), 362–63Xor (operator), 494–95

Long (data type), 309–10converting to, 107–8range of values, 310storage requirements for, 310

long date format, 240long time format, 240looping

Page 777: Working Model 2D - User's Manual

Index 773

Do...Loop (statement), 182–83exiting Do loop, 221–22exiting For loop, 222–23For...Next (statement), 237–38

lowercasing strings, 293–94LSet (statement), 310–11LTrim, LTrim$ (functions), 311MacID (function), 65, 165, 292, 311–12, 427Macintosh, MacID (function), 311–12MacScript (statement), 312Main (statement), 313matching strings, 297–98math functions

Abs (function), 58–59Atn (function), 84Cos (function), 118Exp (function), 224Fix (function), 236–37Int (function), 279–80list of, 13Log (function), 309Randomize (statement), 395–96Rnd (function), 403–4Sgn (function), 425–26Sin (function), 427Sqr (function), 444Tan (function), 457–58

math operators. See operatorsmaximizing

applications, 71windows, 485–86

Mci (function), 313–15medium date format, 240medium time format, 240memory

available, 453–54available resources, 454available within BasicScript, 86total, 455total size for arrays, 161

Menu (statement), 315–16MenuItemChecked (function), 316MenuItemEnabled (function), 317MenuItemExists (function), 317menus

determining existence of, 317determining if checked, 316determining if enabled, 317pop-up, 368–69selecting, 315–16

menus, reference for

in Dialog Editor, 680–85in Script Editor, 646–49

message dialogchanging text of, 329closing, 327creating, 327–29setting thermometer, 329–30

messages, error. See error messagesmessages, runtime error, 699–702metafiles

used in dialog boxes, 364, 366used with picture controls, 175, 365, 367

Methods, 24defined, 344invoking, 345with OLE automation, 343

Mid, Mid$ (functions), 317–18Mid, Mid$ (statements), 318–19minimizing

applications, 71–72windows, 486–87

Minute (function), 319–20MIRR (function), 320–21MkDir (statement), 321–22Mod (operator), 322modeless message dialog, 328modes, for open files, 227–28Month (function), 322–23most precise operand, 356mouse

clicking button, 388–89double-clicking button, 389–90double-pressing button, 390–91moving, 392moving in batch, 393–94pressing button, 391–92releasing button, 394setting coordinates relative to window, 394–95trails, setting, 454

movingapplications, 72–73controls, in Dialog Editor, 666–67–68dialog boxes, in Dialog Editor, 666–67windows, 487–88

MsgBox (function), 323–26MsgBox (statement), 327

constants used withebAbort (constant), 189ebArchive (constant), 190ebCancel (constant), 191–92ebCritical (constant), 192

Page 778: Working Model 2D - User's Manual

774 Working Model Basic User's Manual

ebDataObject (constant), 192–93ebDefaultButton1 (constant), 194ebDefaultButton2 (constant), 194ebDefaultButton3 (constant), 194ebExclamation (constant), 195–96ebIgnore (constant), 196–97ebInformation (constant), 197ebNo (constant), 200ebOK (constant), 202ebOKCancel (constant), 202–3ebOKOnly (constant), 203ebQuestion (constant), 203–4ebRetry (constant), 205ebRetryCancel (constant), 206ebSystemModal (constant), 208ebYes (constant), 210ebYesNo (constant), 210ebYesNoCancel (constant), 210–11

MsgClose (statement), 327MsgOpen (statement), 327–29MsgSetText (statement), 329MsgSetThermometer (statement), 329–30multidimensional arrays. See arraysName (statement), 330–31naming conventions

of constants, 116of functions, 246of labels, 264of subroutines, 449of variables, 163

negationlogical, 338–39unary minus operator, 52–53

nesting, For...Next (statement), 238net present value, calculating, 341–42Net.AddCon (method), 331–32Net.Browse$ (method), 332–33Net.CancelCon (method), 333Net.Dialog (method), 333–34Net.GetCaps (method), 334–36Net.GetCon$ (method), 337Net.User$ (property), 337networks

canceling connection, 333capabilities of, 334–36getting name of connection, 337getting user name, 337invoking browse dialog box, 332–33invoking network dialog, 333–34list of language elements, 13–14redirecting local device, 331–32

New (keyword), 162, 337–38, 420–21Next (keyword), 237–38Not (operator), 338–39Nothing (constant), 339

used with Is (operator), 283Now (function), 339–40NPer (function), 340–41Npv (function), 341–42Null

checking for, 287propagation of, 342vs. Empty, 342–43

Null (constant), 342–43nulls, embedded within strings, 447numbers

adding, 51converting from strings, 471–72converting to strings, 445floating-point, 185–86, 427–28getting sign of, 425–26hexadecimal representation, 305IsNumeric (function), 287–88octal representation, 305printing, 371–72reading from binary/random files, 251–53reading from sequential files, 274–76testing for, 287–88truncating, 236–37, 279–80writing to binary/random files, 381–84writing to sequential files, 371–72, 492–93

numeric operators– (operator), 52–53\ (operator), 56* (operator), 50+ (operator), 50–52/ (operator), 54–55^ (operator), 57list of, 14

Object (data type), 343–44storage requirements for, 343

object collections. See collectionsobjects, 22, 344–47. See also OLE automation

accessing methods of, 345accessing properties of, 343, 345assigning, 420–21assigning values to, 345automatic destruction, 344collections of, 346comparing, 283–84, 346creating, 420–21creating new, 162, 337–38

Page 779: Working Model 2D - User's Manual

Index 775

declaring, 161–63, 343, 345, 376–77declaring as public, 377–80defined, 344instantiating, 343invoking methods of, 343list of language elements, 14OLE, creating, 118–20predefined, table of, 347testing for, 288–89testing if uninitialized, 283using dot separator, 343

Oct, Oct$ (functions), 347octal characters, in strings, 358octal strings

converting to, 347converting to numbers, 471–72

OK buttonsadding to dialog template, 347–48getting label of, 177in Dialog Editor, 657setting label of, 176

OKButton (statement), 347–48OLE automation. See also DDE

automatic destruction, 344CreateObject (function), 118–20creating objects, 118–20default properties of, 226Object (data type), 343–44Set (statement), 420–21

On Error (statement), 219, 348–50on/off format, 240Open (statement), 350–53operating environment

exiting, 453free memory of, 453–54free resources of, 454restarting, 454–55total memory in, 455

operators– (operator), 52–53& (operator), 48\ (operator), 56* (operator), 50+ (operator), 50–52/ (operator), 54–55< (operator), 3–4<= (operator), 3–4<> (operator), 3–4= (operator), 3–4> (operator), 3–4>= (operator), 3–4

^ (operator), 57And (operator), 60–61Eqv (operator), 214–15Imp (operator), 272–73Is (operator), 283–84Like (operator), 297–98Mod (operator), 322Not (operator), 338–39Or (operator), 362–63precedence of, 355precision of, 356Xor (operator), 494–95

Option Base (statement), 161, 356, 376, 378option buttons

adding to dialog template, 358–59checking existence of, 360–61checking if enabled, 359–60getting label of, 177getting selection index of, 178getting state of, 261–62grouping within dialog template, 361–62in Dialog Editor, 657, 661, 679selecting, 179setting label of, 176setting state of, 424–25

Option Compare (statement), 356–57effect on InStr (function), 279effect on Like (operator), 297effect on string comparisons, 114, 446

Option CStrings (statement), 358Optional (keyword), 146, 246, 449optional parameters

checking for, 286–87passed to functions, 248passed to subroutines, 450passing to external routines, 146passing to functions, 246passing to subroutines, 449

OptionButton (statement), 358–59OptionEnabled (function), 359–60OptionExists (function), 360–61OptionGroup (statement), 361–62Or (operator), 362–63ordinal values, 152Output (keyword), 350–53overflow, in assignment, 55, 297pane, in Script Editor

edit, 620separator, 620watch, 620

Parameters, 25

Page 780: Working Model 2D - User's Manual

776 Working Model Basic User's Manual

passing by reference, 92–93passing by value, 49–50, 93–94to external routines, 93, 147, 151

parentheses, used in expressions, 49–50parsing

filenames, 234–35list of language elements, 14strings

by item, 289by line, 299–300by words, 490–91counting items within, 289–90counting lines within, 300–301counting words within, 491–92

Pascal calling convention, 145password, requesting from user, 83–84pasting text. See also Clipboard

in Script Edtior, 631path separator

getting, 87on different platforms, 123

pathsextracting from filenames, 234–35specifying relative, 124

pausing script execution, 428percent format, 239period (.), used to separate object from property, 53–54period (.), used with structures, 53–54Pi (constant), 363PICT files, on the Macintosh, 176, 365, 367Picture (statement), 363–65picture button controls

adding to dialog template, 365–67picture buttons

in Dialog Editor, 657picture controls

adding to dialog template, 363–65automatic loading of images into, 180caching, 180deleting image of, 175in Dialog Editor, 657setting image of, 174–76

picture libraries, creating or modifying, 672–73PictureButton (statement), 365–67pictures, specifying, in Dialog Editor, 671–72platform constants, 87

ebDOS (constant), 87ebMacintosh (constant), 87ebOS2 (constant), 87ebSolaris (constant), 87ebWin16 (constant), 87

ebWin32 (constant), 87Pmt (function), 367–68Point (method)

of WMConstraint, 529of WMDocument, 581

PopupMenu (function), 368–69portability of compiled code, 122PPmt (function), 369–71precedence of operators, 355precision

loss of, 55of operators, 356

predefined dialogs. See dialogs, built-inpredefined objects, table of, 347present value, calculating, 384–85Preserve (keyword), 398–99preserving elements while redimensioning arrays, 398–

99Print (statement), 371–72print zones, 371, 373Print# (statement), 371–72printer orientation

constants used withebLandscape (constant), 198ebPortrait (constant), 203

getting, 374–75setting, 375

PrinterGetOrientation (function), 374–75PrinterSetOrientation (statement), 375PrintFile (function), 375–76printing

files, 375–76list of language elements, 14–15to stdout, 371–72to viewports, 371–72

Private (keyword), 246, 449Private (statement), 376–77private variables, declaring, 376–77procedures. See subroutines; functions

list of language elements, 15tracing calls of, in Script Editor, 639

program flow. See control structurespromotion

automatic, 356of operands in expressions, 225

prompting for input. See dialogs, built-inProperties, 23

accessing, 345defined, 344with OLE automation, 343

Public (keyword), 246, 449

Page 781: Working Model 2D - User's Manual

Index 777

Public (statement), 377–80public variables, declaring, 377–80push buttons

adding to dialog template, 380–81checking for existence of, 92checking if enabled, 91–92getting label of, 177in Dialog Editor, 657selecting, 415setting label of, 176

PushButton (statement), 380–81Put (statement), 381–84Pv (function), 384–85qualifiers

of database owners, 436of databases, 436of tables, 436

QueEmpty (statement), 385–86QueFlush (statement), 386QueKeyDn (statement), 386–87QueMouseClick (statement), 388–89QueMouseDblClk (statement), 389–90QueMouseDblDn (statement), 390–91QueMouseDn (statement), 391–92QueMouseMove (statement), 392QueMouseMoveBatch (statement), 393–94QueMouseUp (statement), 394QueSetRelativeWindow (statement), 394–95queues

constants used withebLeftButton (constant), 198–99ebRightButton (constant), 206

emptying, 385–86playing back, 386waiting for playback of, 184

radians, converting to degrees, 84Random (function), 395Random (keyword), 350–53random files

opening, 350–53reading, 251–53setting record length, 352writing to, 381–84

random numbersgenerating

between 0 and 1, 403–4within range, 395

initializing random number generator, 395–96Randomize (statement), 395–96Rate (function), 396–97Read (keyword), 350–53

ReadIni$ (function), 397ReadIniSection (statement), 397–98records. See user-defined typesrecursion, 247, 450Redim (statement), 398–99redimensioning arrays, 398–99reference counting, 344regular expressions, with Like (operator), 297–98relaxed type checking, 63–64Rem (statement), 400remainder, calculating, 322remote execution, with DDEExecute (statement), 138–

39renaming files, 330–31repeating statements. See loopingreplacing text, in Script Editor, 634–35requesting user input. See dialogs, built-inreserved words, 291Reset (statement), 400resetting error handler, 349resizing

applications, 75–76controls, in Dialog Editor, 668–69dialog boxes, in Dialog Editor, 668windows, 489–90

resolution, of screen, 408–9–10resources, of operating environment, 454restoring

applications, 73–74windows, 488–89

restricted words, 291Resume (statement), 220, 348–50, 400–401Return (statement), 401–2Right, Right$ (functions), 402RmDir (statement), 403Rnd (function), 403–4rounding, 226RSet (statement), 404RTrim, RTrim$ (functions), 405running other programs, 426–27runtime errors, 699–702SaveFilename$ (function), 406–7scientific format, 239scoping

of constants, 117of object variables, 421

Screen.DlgBaseUnitsX (property), 407–8Screen.DlgBaseUnitsY (property), 408Screen.Height (property), 408–9Screen.TwipsPerPixelX (property), 409Screen.TwipsPerPixelY (property), 409

Page 782: Working Model 2D - User's Manual

778 Working Model Basic User's Manual

Screen.Width (property), 409–10Script Editor, 619. See also debugging scripts, in Script

Editorapplication window, 620comments, adding to script, 632Debug menu, 649dialog box templates, editing for use in, 636Edit menu, 647–48edit pane, 620exiting from, 646File menu, 646–47Help menu, 649Help system, 624

getting context-sensitive help, 624–25searching for help on specific topics, 625–26using contents, 626

insertion point, moving, 626–27to specified line, 627–28with keyboard, 622–23with mouse, 627

instruction pointer, 638moving to another line in subroutine, 639

keyboard shortcutsdebugging, 623–24editing, 623general, 621–22navigating, 622–23

pane separator, 620Run menu, 648scripts

checking syntax of, 635–36navigating within, 622–23, 626–28pausing execution of, 637running, 637stopping execution of, 637tracing execution of, 638–39

selection highlight, 629statements, continuing on multiple lines, 633status bar, 620text

copying, 631cutting, 631deleting, 630–31inserting, 628pasting, 631replacing, 634–35searching for, 633–34selecting, 629–30

toolbar, 620–21undoing editing operations, 631–32watch pane, 620

Scripting Operation, 21scripts, debugging, in Script Editor. See debugging

scripts, in Script Editorscrolling

HLine (statement), 266–67HPage (statement), 267–68HScroll (statement), 268VLine (statement), 479VPage (statement), 479–80VScroll (statement), 480

searching for text, in Script Editor, 633–34Second (function), 410seed, for random number generator, 395–96Seek (function), 410–11Seek (statement), 411–12SELECT (SQL statement), 434, 440Select...Case (statement), 412–13SelectBox (function), 414–15SelectButton (statement), 415SelectComboBoxItem (statement), 416selecting

controls, in Dialog Editor, 662dialog boxes, in Dialog Editor, 662

selecting text, in Script Editor, 629–30SelectListBoxItem (statement), 416–17sending keystrokes, 386–87SendKeys (statement), 184separator lines, in dialog boxes, 265sequential files

opening, 350–53reading, 274–76reading lines from, 298–99writing to, 371–72, 492–93

Set (statement), 420–21SetAttr (statement), 421–22SetCheckBox (statement), 422–23SetEditText (statement), 423–24SetOption (statement), 424–25Sgn (function), 425–26Shared (keyword), 350–53sharing

data. See DDEfiles, 352

sharing variables, 379Shell (function), 64, 426–27short date format, 240short time format, 240showing

applications, 75dialog controls, 180–82

sign, of numbers, 425–26

Page 783: Working Model 2D - User's Manual

Index 779

simulating events. See controlling applicationsSin (function), 427sine function (Sin), 427Single (data type), 427–28

conversion to, 124–25range of values, 428storage requirements, 428

Sleep (statement), 428Sln (function), 429sounds

Beep (statement), 88Mci (function), 313–15

Space, Space$ (functions), 429–30Spc (function), 371, 373, 430special characters, 103, 419

escape characters, 358SQLBind (function), 430SQLClose (function), 431SQLError (function), 432SQLExecQuery (function), 433SQLGetSchema (function), 435SQLOpen (function), 438SQLRequest (function), 439SQLRetrieve (function), 441SQLRetrieveToFile (function), 442Sqr (function), 444square root function (Sqr), 444standard numeric format, 239Statements, 24, 34Static (keyword), 246, 449status bar

in Dialog Editor, 653in Script Editor, 620

stdout, printing to, 371–72Step (keyword), 237–38Stop (statement), 444stopping script execution, 213, 444storage

for fixed-length strings, 447Str, Str$ (functions), 445straight-line depreciation, 429StrComp (function), 445–46String (data type), 446–48string functions

Item$ (function), 289LCase, LCase$ (functions), 293–94Left, Left$ (functions), 294Len (function), 294–96Line$ (function), 299–300LTrim, LTrim$ (functions), 311Mid, Mid$ (functions), 317–18

Option Compare (statement), 356–57Right, Right$ (functions), 402RTrim, RTrim$ (functions), 405Space, Space$ (functions), 429–30StrComp (function), 445–46String, String$ (functions), 448Trim, Trim$ (functions), 464UCase, UCase$ (functions), 467Word$ (function), 490–91

string operators& (operator), 48+ (operator), 50–52Like (operator), 297–98list of, 15

String, String$ (functions), 448strings

comparing, 114, 297–98, 356–57, 445–46concatenation, 48, 50–52

vs. addition, 48, 51converting from numbers, 445converting to, 125converting to lowercase, 293–94converting to numbers, 471–72converting to uppercase, 467copying, 310–11, 404counting items within, 289–90counting lines within, 300–301counting words within, 491–92escape characters in, 358finding one within another, 278–79fixed-length vs. variable-length, 447fixed-length, declaring, 161, 376, 378getting leftmost characters from, 294getting length of, 294–96getting rightmost characters from, 402getting substrings from, 317–18list of language elements, 15–16of same characters, 448of spaces, 429–30parsing by item, 289printing, 371–72reading from sequential files, 274–76–77, 298–99requesting from user, 82–83, 277–78retrieving items from, 289retrieving lines from, 299–300retrieving words from, 490–91setting substrings in, 318–19String (data type), 446–48trimming leading and trailing spaces from, 464trimming leading spaces from, 311trimming trailing spaces from, 405

Page 784: Working Model 2D - User's Manual

780 Working Model Basic User's Manual

writing to sequential files, 371–72, 492–93stripping spaces. See trimmingstructures. See user-defined typesSub...End Sub (statement), 448–51

exiting subroutine, 224subroutines

defining, 448–51exiting subroutine, 224naming conventions of, 449

substringsfinding, 278–79getting, 317–18getting leftmost characters from, 294getting rightmost characters from, 402setting, 318–19

sum of years' digits depreciation, 452–53Switch (function), 451–52SYD (function), 452–53syntax, checking, in Script Editor, 635–36System 7.0, 312System calling convention, 145system date. See datessystem time. See timeSystem.Exit (method), 453System.FreeMemory (property), 453–54System.FreeResources (property), 454System.MouseTrails (method), 454System.Restart (method), 454–55System.TotalMemory (property), 455System.WindowsDirectory$ (property), 455System.WindowsVersion$ (property), 455–56Tab (function), 371, 373, 457tables

retrieving column data types, 436retrieving column names of, 436retrieving list of, 436retrieving qualifier of, 436

Tan (function), 457–58tangent function (Tan), 457–58task list, filling array with, 70–71templates. See user dialogstesting dialog boxes, in Dialog Editor, 668, 677–79Text (statement), 458–59text boxes

adding to dialog template, 459–61checking existence of, 211–12checking if enabled, 211getting content of, 177, 257–58in Dialog Editor, 657, 679setting content of, 176, 423–24

text controls

adding to dialog template, 458–59getting label of, 177in Dialog Editor, 657setting label of, 176

TextBox (statement), 459–61thermometers, in message dialogs, 329–30tiling desktop windows, 158–59time

forming from components, 463getting current time, 339–40, 461getting specific time, 463hours, 267minutes, 319–20seconds, 410seconds since midnight, 462setting current time, 461–62

Time, Time$ (functions), 461Time, Time$ (statements), 461–62time/date functions. See date/time functionsTimer (function), 462TimeSerial (function), 463TimeValue (function), 463–64toolbar

in Dialog Editor, 653–54in Script Editor, 620–21

trigonometric functionsAtn (function), 84Cos (function), 118Sin (function), 427Tan (function), 457–58

Trim, Trim$ (functions), 464trimming

leading and trailing spaces from strings, 464leading spaces from strings, 311trailing spaces from strings, 405

True (constant), 464true/false format, 240truncating numbers, 236–37, 279–80twips per pixel, calculating, 409Type (statement), 465–66type checking, relaxed, with Declare (statement), 63–64type coercion, 225type-declaration characters

effect on interpretation when reading numbers fromsequential files, 274

for Currency, 126for Double, 186for Integer, 280for Long, 310for Single , 428for String, 447

Page 785: Working Model 2D - User's Manual

Index 781

used when converting to number, 288used when declaring literals, 305–6used with Dim (statement), 161used with external subroutines and functions, 145

UBound (function), 466–67used with OLE arrays, 466

UCase, UCase$ (functions), 467unary minus operator, 52–53underflow, 55undo

in Dialog Editor, 674in Script Editor, 631–32

uninitialized objects, 343, 345Nothing (constant), 339testing for with Is (operator), 283

universal date formatreading, 275used with literals, 129, 305writing, 492

Unlock (statement), 467–69unlocking file regions, 467–69unsupported language elements, 123UPDATE (SQL statement), 434, 440uppercasing strings, 467user dialogs

automatic timeout for, 160available controls in, 88Begin Dialog (statement), 88–90CheckBox (statement), 99–101ComboBox (statement), 109–10control outside bounds of, 172creating, 88–90default button for, 159Dialog (function), 159–60Dialog (statement), 160–61dialog procedures of, 171–74DlgControlId (function), 159–60DlgEnable (function), 167–68DlgEnable (statement), 168–69DlgFocus (function), 169DlgFocus (statement), 169–70DlgListBoxArray (function), 170DlgListBoxArray (statement), 170–71DlgProc (function), 171–74DlgSetPicture (statement), 174–76DlgText (statement), 176–77DlgText$ (function), 177–78DlgValue (function), 178DlgValue (statement), 178–79DlgVisible (function), 179–80DlgVisible (statement), 180–82

DropListBox (statement), 186–88expression evaluation within, 90GroupBox (statement), 265–66idle processing for, 173, 691invoking, 159–60–61list of language elements, 16–17ListBox (statement), 301–3nesting capabilities of, 174OKButton (statement), 347–48OptionButton (statement), 358–59OptionGroup (statement), 361–62Picture (statement), 363–65PictureButton (statement), 365–67pressing Enter within, 348pressing Esc within, 95PushButton (statement), 380–81required statements within, 89showing, 172Text (statement), 458–59TextBox (statement), 459–61

user-defined errorsconverting to, 127–28generating, 218–19printing, 371printing to sequential files, 373reading from binary/random files, 252reading from sequential files, 275testing for, 285–86writing to random/binary files, 383writing to sequential files, 492

user-defined functions. See functionsuser-defined types, 470–71

copying, 470declaring, 470defining, 465–66getting size of, 294–96, 471passing, 471

Val (function), 471–72Value (property), 269–70variables

assigning objects, 420–21declaring

as local, 161–63as private, 376–77as public, 377–80with Dim, 161–63with Private (statement), 376–77with Public (statement), 377–80

getting storage size of, 294–96implicit declaration of, 161initial values of, 162, 377, 379

Page 786: Working Model 2D - User's Manual

782 Working Model Basic User's Manual

list of language elements, 17naming conventions of, 163watch, in Script Editor, 642–45

Variant (data type), 472–76variants

#FALSE#, 275#NULL#, 275#TRUE#, 275adding, 51, 474assigning, 473automatic promotion of, 356containing no data, 342–43, 474converting to, 126–27disadvantages, 475Empty (constant), 212getting length of, 294–96getting types of, 473, 476–77list of language elements, 17–18Null (constant), 342–43operations on, 474passing nonvariant data to routines taking variants,

475passing to routines taking nonvariants, 476printing, 371–72reading from sequential files, 274–76storage requirements of, 475testing for Empty, 285testing for Error, 285–86testing for Null, 287testing for objects, 288–89types of, 472, 476

ebBoolean (constant), 191ebCurrency (constant), 192ebDate (constant), 193ebDouble (constant), 195ebEmpty (constant), 195ebError (constant), 193ebInteger (constant), 197–98ebLong (constant), 199ebNull (constant), 202ebObject (constant), 202ebSingle (constant), 206–7ebString (constant), 207ebVariant (constant), 208

Variant (data type), 472–76writing to sequential files, 371–72, 492–93

VarType (function), 476–77version

of BasicScript, 87–88of Windows, 455–56

ViewportClear (statement), 477

ViewportClose (statement), 477–78ViewportOpen (statement), 478–79viewports

clearing, 477closing, 477–78keys used in, 478opening, 478–79printing to, 371–72

Visual Basic, error messages, 699VisualBasic, 20VLine (statement), 479VPage (statement), 479–80VScroll (statement), 480wallpaper, changing desktop, 156–57watch variables, in Script Editor, 642

adding, 642–44deleting, 644modifying value of, 644–45selecting, 644

waveform audio, Mci (function), 313–15Weekday (function), 480–81While...Wend (statement), 481–82Width# (statement), 482width, of screen, 409–10wildcards. See also MacID (function)

used with Dir, Dir$ (functions), 164win.ini file, 136, 157, 245, 375, 397, 398, 464, 494WinActivate (statement), 482–83WinClose (statement), 483–84windows

activating, 482–83capturing, 157–58closing, 483–84constants used with

ebMaximized (constant), 199ebMinimized (constant), 200ebRestored (constant), 205

directory of, 455finding, 484–85getting list of, 485getting value of, 269–70maximizing, 485–86minimizing, 486–87moving, 487–88resizing, 489–90restoring, 488–89scrolling, 266–67–68, 479–80version of, 455–56

WinFind (function), 484–85WinList (statement), 485WinMaximize (statement), 485–86

Page 787: Working Model 2D - User's Manual

Index 783

WinMinimize (statement), 486–87WinMove (statement), 487–88WinRestore (statement), 488–89WinSize (statement), 489–90WM (constant), 33, 498WM Basic, 33WM.ActiveDocument (property), 499WM.DeleteMenuItem (method), 499WM.Documents (property), 500WM.EnableMenuItem (method), 501WM.GetMenuItem (method), 502WM.InsertMenuItem (method), 503WM.LoadWMBLibrary (method), 504WM.NewDocument (method), 505WM.Open (method), 506WM.RunScript (method), 506WM.ShowAppearanceWindow (property), 508WM.ShowGeometryWindow (property), 508WM.ShowPropertiesWindow (property), 509WM.UnloadWMBLibrary (method), 507WM.Version (property), 509WMBody (object), 36, 509WMCell (object), 512WMConstraint (object), 39, 514WMConstraint.ActiveWhen (property), 516WMConstraint.ActuatorType (property), 517WMConstraint.AddVertex (method), 517WMConstraint.AlwaysActive (property), 519WMConstraint.AppendPoint (method), 518WMConstraint.AutoComputeGearRatio (property),

520WMConstraint.ClosedSlot (property), 520WMConstraint.CurrentLength (property), 520WMConstraint.CurrentRotation (property), 520WMConstraint.DamperK (property), 521WMConstraint.DeleteVertex (method), 521WMConstraint.Elasticity (property), 522WMConstraint.Exponent (property), 522WMConstraint.Field (property), 523WMConstraint.FR, FTheta (properties), 523WMConstraint.FX, FY (properties), 524WMConstraint.GearRatio (property), 525WMConstraint.GetVertex (method), 526WMConstraint.Internal (property), 526WMConstraint.InternalBody (property), 526WMConstraint.K (property), 527WMConstraint.Kind (property), 528WMConstraint.Length (property), 528WMConstraint.MotorType (property), 529WMConstraint.Point (method), 529WMConstraint.PointCount (property), 531

WMConstraint.RodActive (property), 531WMConstraint.RodAlwaysActive (property), 532WMConstraint.RotateWithBody (properties), 532WMConstraint.Rotation (property), 532WMConstraint.Torque (property), 533WMConstraint.VertexCount (property), 534WMDocument (object), 34, 534WMDocument.AirResistanceType (property), 538WMDocument.AirResistanceV2Coeff (property), 539WMDocument.AirResistanceVCoeff (property), 539WMDocument.AnimationStep (property), 540WMDocument.AssemblyError (property), 540WMDocument.AutoAnimationStep (property), 541WMDocument.AutoAssemblyError (property), 541WMDocument.AutoEraseTrack (property), 542WMDocument.AutoIntegratorError (property), 542WMDocument.AutoOverlapError (property), 543WMDocument.AutoSignificantDigits (property), 543WMDocument.Bodies (property), 544WMDocument.Body (method), 544WMDocument.ChargeUnit (property), 545WMDocument.Close (method), 546WMDocument.Collide (method), 546WMDocument.CombineTapeScroll (property), 547WMDocument.Constraint (method), 547WMDocument.Constraints (property), 548WMDocument.ControlsLocked (property), 549WMDocument.Copy (method), 549WMDocument.CurrentFrame (property), 550WMDocument.Cut (method), 551WMDocument.DecimalDigits (property), 551WMDocument.DecimalFormat (property), 551WMDocument.Delete (method), 552WMDocument.DeletePauseControl (method), 553WMDocument.DistanceUnit (property), 554WMDocument.ElectricPotentialUnit (property), 555WMDocument.ElectrostaticConst (property), 555WMDocument.ElectroStaticsOn (property), 556WMDocument.EnergyUnit (property), 556WMDocument.EraseMeterValues (method), 557WMDocument.EraseTrack (method), 558WMDocument.ExportDXF (method), 558WMDocument.ExportMeterData (method), 559WMDocument.ExportStartFrame (property), 559WMDocument.ExportStopFrame (property), 560WMDocument.ForceFieldFX, ForceFieldFY,

ForceFieldT (property), 560WMDocument.ForceFieldType (property), 560WMDocument.ForceUnit (property), 561WMDocument.FrequencyUnit (property), 562WMDocument.GetPauseControlType (method), 562

Page 788: Working Model 2D - User's Manual

784 Working Model Basic User's Manual

WMDocument.Gravity (property), 563WMDocument.HistoryFrames (property), 564WMDocument.ImportDXF (method), 564WMDocument.Input (method), 565WMDocument.Inputs (property), 566WMDocument.Integrator (property), 566WMDocument.IntegratorError (property), 567WMDocument.Join (method), 568WMDocument.LinearGravityConst (property), 568WMDocument.MassUnit (property), 569WMDocument.Name (property), 569WMDocument.NewBody (method), 570WMDocument.NewConstraint (method), 570WMDocument.NewInput (method), 572WMDocument.NewOutput (method), 572WMDocument.NewPauseControl (method), 573WMDocument.NewPoint (method), 574WMDocument.Object (method), 575WMDocument.Objects (property), 575WMDocument.Output (method), 576WMDocument.Outputs (property), 577WMDocument.OverlapError (property), 578WMDocument.Paste (method), 578WMDocument.PauseControl (method), 579WMDocument.PauseControlCount (property), 580WMDocument.PlanetaryGravityConst (property), 580WMDocument.PlayerMode (property), 581WMDocument.Point (method), 581WMDocument.Points (property), 582WMDocument.PowerUnit (property), 583WMDocument.Reset (method), 584WMDocument.RetainMeterValues (property), 583WMDocument.RotationalVelocityUnit (property), 584WMDocument.RotationUnit (property), 585WMDocument.Run (method), 585WMDocument.Save (method), 586WMDocument.SaveAs (method), 587WMDocument.ScaleFactor (property), 587WMDocument.ScrollTo (method), 588WMDocument.Select (method), 588WMDocument.SelectAll (method), 589

WMDocument.Selection (property), 590WMDocument.SetPauseControlType (method), 591WMDocument.ShowCoordinates (property), 592WMDocument.ShowGridLines (property), 593, 605WMDocument.ShowHelpRibbon (property), 593WMDocument.ShowRulers (property), 594WMDocument.ShowScrollBars (property), 594WMDocument.ShowTapeControl (property), 595WMDocument.ShowToolPalette (property), 596WMDocument.ShowXYAxes (property), 596WMDocument.SignificantDigits (property), 597WMDocument.SimulationMode (property), 597WMDocument.SkipFrames (property), 598WMDocument.Split (method), 598WMDocument.StartHere (method), 599WMDocument.TimeUnit (property), 600WMDocument.Tracking (property), 600WMDocument.UnitSystem (property), 601WMDocument.Update (method), 602WMDocument.VariableIntegrationStep (property),

603WMDocument.VelocityUnit (property), 604WMDocument.WarnInaccurate (property), 605WMDocument.WarnInconsistent (property), 606WMDocument.WarnOverlap (property), 607WMDocument.WarnRedundant (property), 607WMInput (object), 608WMObject (object), 610WMOutput (object), 613WMOutputColumn (object), 615WMPoint (object), 37, 616Word$ (function), 490–91WordCount (function), 491–92word-wrapping, in MsgBox (statement), 325Write (keyword), 350–53Write# (statement), 492–93WriteIni (statement), 493–94Xor (operator), 494–95Year (function), 495yes/no format, 239yielding, 184, 428

Page 789: Working Model 2D - User's Manual

Changes to Working Model Basic™

This section describes changes in the WM Basic™ Script language that willaffect scripts written for Working Model 3.0.3.

Page 790: Working Model 2D - User's Manual

Title: Language differences between BasicScript 2.1, 2.2, and 2.25Category: BasicScript LanguageDocument Number: 0000223ACirculation: Public - Everyone Applies To: All versions of BasicScript

This document describes the changes in the BasicScript language that affect scripts written for BasicScript 2.1or BasicScript 2.0. The goal of this document is to describe what causes older scripts to break when runningthem in BasicScript 2.2.

Other related documents:

"Upgrading to BasicScript 2.25" describes programmatic changes in the BasicScript APIs that arerelevant when upgrading from BasicScript 2.1 to 2.2 and 2.25. This document is distributed with theBasicScript Programmer's Guide and is available for download from the Partners Web site."BasicScript 2.1 to 2.2 Changes in Language Reference" described the changes in the LanguageReference that occurred between versions 2.1 and 2.2. This document is available for download fromthe Partners Web site."Modifying compilation for backward compatibility" is a knowledge base article describing specialundocumented flags for compiling old scripts. The knowledge base is available forbrowsing/searching on the Partners Web site.

SendKeys

The default value for the second parameter to Shell was changed from True to False. Script that containstatement such as:SendKeys "Hello"

Will need to be changed to:SendKeys "Hello",True

Type Declaration Characters

In version 2.1, the following was allowed:Dim a$ As String

This now produces an error. The following are correct syntaxes:Dim a$Dim a As String

(Note: The embedder can disable this new behavior by setting the CF_RESERVED2 flag in the wFlagsmember of the ebCOMPILESTRUCT structure.)

Using Keywords as Identifiers

In BasicScript 2.1, the following was allowed:MsgBox% = 10

In BasicScript 2.2, this is not allowed, as MsgBox is a built-in keyword. You can get around this by renamingthe variable to a different unreserved name or by declaring the variable with the Dim,Private, or Public statement:

Page 791: Working Model 2D - User's Manual

Dim MsgBox As IntegerMsgBox = 10

Once redeclared in this manner, the MsgBox command/function can no longer be called to display a dialogbox.

The re-use of language elements in this manner only applies to built-in keywords defined either by BasicScriptor by any of your application's extensions. Additional restrictions apply to reserved words (a subcategory ofkeywords as described below).

(Note: The embedder can disable this new behavior by setting the CF_RESERVED1 flag in the wFlagsmember of the ebCOMPILESTRUCT structure.)

Using Reserved Words as Identifiers

BasicScript 2.1 allowed reserved words to be used as variable names when accompanied by a type declarationcharacter as shown below:For$ = "Hello"

This is a very bad practice that should be discouraged. These variables should renamed in the script.

A complete list of reserved words is contained in the User's Guide in the alphabetical entry entitled "Keywords(topic)".

(Note: The embedder can allow reserved words to be redefined in this manner by setting the CF_RESERVED1flag in the wFlags member of the ebCOMPILESTRUCT structure.)

Default Data Type

In version 2.0 of BasicScript, the default data type was Integer. BasicScript 2.1 and 2.2 now use Variant asthe default data type.

This introduces many problems if a script contains many implicit variables and function. In such cases, thefollowing statement can be placed at the top of such scripts to change the default data typeback to Integer:Option Default Integer

A better solution would be to add an Option Explicit statement at the top of the script to expose all the implicitdeclarations, then explicitly define each variable and function as the appropriate type. Implicit declarationsoccasionally cause inadvertant bugs in the script.

Using Predefined Objects as Identifiers

As is the case in all versions of BasicScript, you cannot use the names of predefined objects as identifiers inscripts. For example, if your application introduces an object called "Form" and a predefined object of that typecalled "Form1", then the user is prevented from using "Form1" as the name of a variable in the script as shownbelow:Dim Form1 As Integer '<-- This will produce an error

There are many predefined objects built-in to BasicScript, some of which are new, resulting in potentialproblems in scripts which use these names for variables, subroutines, or functions. For example, since Msg isa new built-in object, the following code will no longer compile:Dim Msg As StringMsg = "Hello"

Page 792: Working Model 2D - User's Manual

The following lists all the objects predefined by BasicScript:

Object Name EB20 EB21 EB22

HWND Yes Yes Yes

Viewport No No Yes

Msg No No Yes

Clipboard Yes Yes Yes

Desktop Yes Yes Yes

System Yes Yes Yes

Net Yes Yes Yes

Screen Yes Yes Yes

Basic Yes Yes Yes

MacID Yes Yes Yes

Err No No Yes

Obsolete Syntax

Although some language elements that have been replaced with more modern syntax, the older style syntax isstill supported. The following table shows these replacements in the case that the user wants to use the moremodern language element:

Language Element Replace With

Err (function) Err[.Number] (default property)

Err (statement) Err[.Number] (default property)

MsgClose (statement) Msg.Close (method)

MsgOpen (statement) Msg.Open (method)

MsgSetText (statement) Msg.Text (property)

MsgSetThermometer (statement) Msg.Thermometer (property)

ViewportClear (statement) Viewport.Clear (method)

ViewportClose (statement) Viewport.Close (method)

ViewportOpen (statement) Viewport.Open (method)

New Constants

As is the case in all versions of BasicScript, you cannot use the names of constants as identifiers in scripts. Forexample, each of the following statements is illegal:Dim ebYes As Integer '<-- Illegal (cannot redefine constant)ebYes = 10 '<-- Illegal (cannot assign to constant)

BasicScript 2.2 introduces a number of constants not present in earlier version. Each of these constants ispreceeded by the two letters "eb" and are described in the following table:ebAlias ebArray ebBackebCFBitmap ebCFDIB ebCFMetafileebCFPalette ebCFText ebCFUnicodeTextebCr ebCrLf ebFirstFourDaysebFirstFullWeek ebFirstJan1 ebFormFeed

Page 793: Working Model 2D - User's Manual

ebFriday ebFromUnicode ebHideebHiragana ebIMEAlphaDbl ebIMEAlphaSngebIMEDisabled ebIMEHiragana ebIMEKatakanaDblebIMEKatakanaSng ebIMENoOp ebIMEOffebIMEOn ebKatakana ebLfebLINUX ebLowerCase ebMaximizedFocusebMinimizedFocus ebMinimizedNoFocus ebMondayebNarrow ebNormalFocus ebNormalNoFocusebNullChar ebNullString ebProperCaseebSaturday ebSunday ebTabebThursday ebTuesday ebUnicodeebUpperCase ebUseSystem ebVerticalTabebWednesday ebWide

Despite the fact that these constants are made unique by their two-letter prefix, there is still a possibility that aduplicate identifier exists in older scripts. In this case, the only alternative is to rename the identifier.

Null Keyword

In BasicScript 2.0, the Null keyword was implemented as a function that returned a zero-length string. InBasicScript 2.1 and above, "Null" is a reserved compiler keyword representing a special state of Variants.Code that uses the Null function must be replaced with an empty string literal as shown below:

The statement:s$ = Null()

Should be replaced with:s$ = ""

Passing Uninitialized Strings to External Routines

In BasicScript 2.1 and earlier, uninitialized strings were passed to the external routines (i.e., those declaredwith the Declare statement) as zero-length strings. BasicScript 2.2 and above pass unititialized strings asNULL.

Resetting the Error State

In BasicScript 2.1 and earlier, the error state was reset when Err was set to -1. In BasicScript 2.2 and later, theerror state is reset under the following conditions:

When a Resume statement is executed.When Err is set to -1.When an On Error statement is executed.When Err.Clear is executed.When Exit Sub, Exit Function, End Sub, or End Function is executed.

Instr

In BasicScript 2.1 and earlier, the InStr function was able to determine its behavior from the type of data pasedas the first parameter. For example, the following was legal:

pos = Instr("Hello, world.","world",0)

In BasicScript 2.2 and later, the first parameter must be specified in order for the last parameter to be specified.In other words, given the following syntax, InStr uses the rules described below:

Page 794: Working Model 2D - User's Manual

Instr([start,] search,find, [,compare])

If there are this many parameters Then Instr assumes the following were specified

2 search,find

3 start,search,find

4 start,search,find,compare

Double Precision in Loop Counters

Consider the following loop:Dim d As DoubleFor d = 3.7 To 4.1 Step 0.1MsgBox dNext d

In the above script, the following are printed in the dialogs:3.73.83.94

In BasicScript 2.2 and later, the dialog containing "4.1" is not displayed, whereas in version 2.1, the number"4.1" was displayed.

This difference is due to the imprecise internal representation of 0.1 in IEEE format. In the last iterationthrough the loop, this error has accumulated such that the loop counter is slightly greater than 4.1, preventingthe final iteration of the loop. In BasicScript 2.1, the addition was handled differently.

The behavior of BasicScript 2.2 is consistent with that if Visual Basic.

(c) Copyright 1991-1996 Summit Software Company. All rights reserved.