close

Enter

Log in using OpenID

WIL Reference Manual - WinBatch Tech Database

embedDownload
WIL Reference Manual
Manual Revision ~ Jun 2014
Copyright 2014 В© by Wilson WindowWare Inc.
All rights reserved.
No part of this manual may be reproduced or transmitted in any form or by any means, electronic or
mechanical, including photocopying and recording, for any purpose without the express written
permission of Wilson WindowWare, Inc. Information in this document is subject to change without notice
and does not represent a commitment by Wilson WindowWare, Inc.
The software described herein is furnished under a license agreement. It is against the law to copy this
software under any circumstances except as provided by the license agreement.
U.S. Government Restricted Rights
Use, duplication, or disclosure by the Government is subject to restrictions as set forth in subdivision
(b)(3)(ii) of the Rights in Technical Data and Computer Software clause at 252.227-7013.
Contractor/manufacturer is Wilson WindowWare, Inc. / 5421 California Ave. SW / Seattle, WA 98136 /
Orders: 800-762-8383 / Support: 206-937-9335 / Fax: 206-935-7129.
Trademarks
Microsoft and MS-DOS are registered trademarks of Microsoft Corporation.
Windows, Explorer, Word for Windows, NotePad, Visual Basic, ClearType and Excel are trademarks of
Microsoft Corporation. WordPerfect, WordPro are trademarks of IBM. Power Builder is a trademark of
PowerSoft Corporation.
WinBatchпѓ’, and WebBatchпѓ’ are registered trademarks of Wilson WindowWare, Inc.
WinMacro, and WinBatch Studio are trademarks of Wilson WindowWare, Inc.
CONTENTS
CONTENTS
iВ WIL Reference Manual
CONTENTS
iiiВ INTRODUCTION
What is WIL?
What is WIL good for?
Products that use WIL
Notational Conventions
Acknowledgments
15В 15В 15В 16В 17В 17В WIL TUTORIAL
Creating WIL Scripts Files
Running WIL Utilities
Command Line Parameters
What is a WIL Program?
Our First WIL Program
Functions and Parameters
Displaying Text
User Input
Using Variables
Making Decisions
Control of Program Flow
Exploring WIL
Running Programs
Display and Input
Manipulating Windows
Files and Directories
Handling Errors
Debugging WIL Scripts
Selection Methods
Nicer File Selection
Nicer Messages
Running DOS Programs
Sending Keystrokes to Programs
Our Completed WIL File
19В 19В 19В 20В 21В 22В 22В 25В 26В 28В 29В 32В 37В 38В 39В 42В 46В 47В 50В 50В 54В 55В 56В 57В 58В THINGS TO KNOW
Recovering from Cancel
Extenders: Networking, TCP/IP, Microsoft
Terminating WIL processing
Carriage Return Line Feed
Extension Associations and the Run Functions
Debug
Internal Control Functions
Partial Window Names
61В 61В 62В 64В 64В 64В 64В 65В 65В iii
CONTENTS
System.ini and its device= lines
Dividing Floating Point Numbers
File Delimiters
OLE / COM
dotNet
66В 66В 67В 68В 74В WIL LANGUAGE
Language Components
Constants
Identifiers
Variables
Variable Substitution
Lists Explained
Keywords
Operators
Precedence and Evaluation Order
Comments
Assignment Statements
Control Statements
Function Parameters
User Defined Functions
Arrays
Error Handling
Using ErrorMode
Using IntControl 73
79В 79В 79В 80В 81В 81В 82В 83В 84В 85В 86В 86В 86В 86В 87В 90В 92В 92В 92В WIL FUNCTION REFERENCE
Introduction
About
Abs
Acos
AddExtender
AppExist
AppWaitClose
ArrayFileGet
ArrayFileGetCsv
ArrayFilePut
ArrayFilePutCsv
ArrayFromStr
ArrayInsert
ArrayItemize
Arrayize
ArrayLocate
ArrayRedim
ArrayRemove
ArrayReverse
ArraySearch
ArraySort
ArraySwapElements
ArrayToStr
ArrDimension
ArrInfo
iv
93В 93В 94В 94В 95В 95В 97В 98В 99В 100В 101В 102В 103В 104В 105В 105В 106В 107В 108В 110В 111В 112В 113В 114В 115В 116В CONTENTS
117В 118В 119В 120В 121В 123В 126В 127В 129В 131В 133В 134В 135В 136В 136В 136В 137В 138В 139В 141В 142В 142В 143В 145В 146В 147В 148В 149В 150В 150В 151В 153В 153В 154В 155В 157В 158В 160В 162В 162В 163В 164В 165В 165В 166В 167В 168В 168В 170В 170В 172В 173В ArrInitialize
ArrRemove
Asin
AskColor
AskDirectory
AskFileName
AskFileText
AskFont
AskItemList
AskLine
AskPassword
AskTextBox
AskYesNo
Atan
Average
Beep
Binary Operations
BinaryAlloc
BinaryAllocArray
BinaryAnd
BinaryBufInfo
BinaryCheckSum
BinaryClipGet
BinaryClipPut
BinaryCompare
BinaryConvert
BinaryCopy
BinaryEodGet
BinaryEodSet
BinaryFree
BinaryHashRec
BinaryIncr
BinaryIndex
BinaryIndexBin
BinaryIndexEx
BinaryIndexNc
BinaryOleType
BinaryOr
BinaryPeek
BinaryPeekHex
BinaryPeekStr
BinaryPeekStrW
BinaryPoke
BinaryPokeHex
BinaryPokeStr
BinaryPokeStrW
BinaryRead
BinaryReadEx
BinaryReplace
BinarySort
BinaryStrCnt
BinaryTagExtr
v
CONTENTS
BinaryTagFind
BinaryTagIndex
BinaryTagInit
BinaryTagLen
BinaryTagRepl
BinaryWrite
BinaryWriteEx
BinaryXlate
BinaryXor
Break
ButtonNames
Call
Ceiling
Char2Num
ChrGetCodePage
ChrHexToString
ChrHexToUnicode
ChrSetCodePage
ChrStringToHex
ChrStringToUnicode
ChrUnicodeToHex
ChrUnicodeToString
ClipAppend
ClipGet
ClipGetEx
ClipHasFormat
ClipPut
ComputerNameGet
ComputerNameSet
Continue
Cos
Cosh
CreateObject
CurrentFile {*M}
CurrentPath {*M}
CurrFilePath {*M}
DataCast
DDEExecute
DDEInitiate
DDEPoke
DDERequest
DDETerminate
DDETimeout
Debug
DebugData
DebugTrace
Decimals
Dialog
User-Defined-Callback Function or Subroutine
Using Internet Explorer Controls in WIL Dialogs
DialogControlGet
DialogControlSet
vi
174В 176В 177В 179В 181В 183В 183В 185В 186В 187В 188В 189В 191В 191В 192В 192В 193В 193В 194В 194В 195В 195В 196В 196В 197В 198В 199В 199В 200В 201В 202В 203В 203В 203В 204В 205В 206В 206В 207В 208В 209В 210В 211В 212В 214В 215В 219В 220В 240В 250В 259В 264В CONTENTS
271В 276В 279В 286В 287В 289В 290В 293В 293В 294В 295В 295В 297В 297В 298В 298В 299В 299В 301В 301В 302В 303В 303В 304В 305В 306В 307В 310В 311В 312В 313В 316В 316В 317В 318В 318В 319В 321В 321В 322В 323В 324В 325В 326В 326В 327В 328В 329В 330В 331В 332В 333В DialogControlState
DialogObject
DialogProcOptions
DirAttrGet
DirAttrGetEx
DirAttrSet
DirAttrSetEx
DirChange
DirExist
DirGet
DirHome
DirInfoToArray
DirItemize
DirMake
DirRemove
DirRename
DirScript
DirSize
DirWindows
DiskExist
DiskFree
DiskInfo
DiskScan
DiskSize
DiskVolInfo
Display
DllCall
DllCallbackCreate
DllCallbackDestroy
DllCall Additional Information
DllCallCdecl
DllFree
DllHinst
DllHwnd
DllLastError
DllLoad
DllStructAlloc
DllStructFree
DllStructPeek
DllStructPoke
DOSVersion
Drop
DropWild
EndSession
Environment
EnvironSet
EnvItemize
ErrorEvent
ErrorMode
Exclusive
Execute
ExeTypeInfo
vii
CONTENTS
Exit
Exp
Fabs
FileAppend
FileAttrGet
FileAttrGetEx
FileAttrSet
FileAttrSetEx
FileBaseName
FileClose
FileCompare
FileCopy
FileCopyAttr
FileCreateTemp
FileDelete
FileDigest
FileExist
FileExtension
FileFullName
FileGet
FileGetW
FileInfoToArray
FileItemize
FileItemPath
FileLocate
FileMapName
FileMove
FileMoveAttr
FileNameLong
FileNameShort
FileOpen
FilePath
FilePut
FilePutW
FileRead
FileRename
FileRoot
FileSize
FileSizeEx
FileTimeCode
FileTimeGet
FileTimeGetEx
FileTimeSet
FileTimeSetEx
FileTimeTouch
FileVerInfo
FileWrite
FileYmdHms
FindWindow
Floor
For
ForEach
viii
334В 334В 335В 335В 336В 337В 339В 340В 342В 342В 343В 344В 346В 347В 348В 348В 349В 350В 351В 351В 352В 352В 354В 355В 356В 356В 358В 359В 360В 360В 361В 363В 363В 364В 364В 365В 366В 366В 367В 368В 369В 370В 370В 371В 372В 373В 375В 376В 377В 377В 378В 379В CONTENTS
381В 381В 381В 382В 383В 383В 384В 385В 387В 389В 390В 391В 391В 392В 393В 393В 394В 395В 396В 397В 398В 432В 433В 434В 434В 435В 435В 436В 436В 438В 439В 440В 441В 442В 442В 443В 444В 444В 445В 445В 446В 447В 447В 448В 448В 449В 449В 450В 451В 452В 452В 454В GetExactTime
GetObject
GetTickCount
GoSub
Goto
IconExtract
IconInfo
IconReplace
If … Endif
IgnoreInput
IniDelete
IniDeletePvt
IniItemize
IniItemizePvt
IniRead
IniReadPvt
IniWrite
IniWritePvt
InstallFile
Int
IntControl
IsDefined
IsFloat
IsInt
IsKeyDown
IsLicensed
IsNumber
ItemCount
ItemCountCsv
ItemExtract
ItemExtractCsv
ItemInsert
ItemLocate
ItemLocateWild
ItemRemove
ItemReplace
ItemSort
KeyToggleGet
KeyToggleSet
LastError
Log10
LogDisk
LogE
Max
Message
Min
Mod
MouseClick
MouseClickBtn
MouseCoords
MouseInfo
MouseMove
ix
CONTENTS
MousePlay
MsgTextGet
Net101
NetInfo
Num2Char
ObjectClose
ObjectClrNew
ObjectClrOption
ObjectClrType
ObjectConstToArray
ObjectCreate
ObjectEventAdd
ObjectEventRemove
ObjectGet
ObjectOpen
ObjectType
ObjectTypeGet
ParseData
Pause
PipeClientClose
PipeClientOpen
PipeClientSendRecvData
PipeInfo
PipeServerClose
PipeServerCreate
PipeServerRead
PipeServerWrite
PlayMedia
PlayMidi
PlayWaveForm
Print
PtrGlobal
PtrGlobalDefine
PtrGlobalTest
PtrPersistent
Random
Registration Database Operations
RegApp
RegCloseKey
RegConnect
RegCreateKey
RegDeleteKey
RegDelValue
RegEntryType
RegExistKey
RegExistValue
RegLoadHive
RegOpenFlags
RegOpenKey
RegOpenKeyEx
RegQueryBin
RegQueryDword
x
455В 457В 458В 458В 459В 459В 460В 462В 464В 467В 468В 471В 473В 475В 477В 477В 480В 484В 484В 485В 485В 487В 487В 488В 488В 489В 489В 490В 491В 492В 493В 493В 494В 495В 496В 497В 497В 498В 499В 500В 501В 502В 502В 503В 507В 508В 508В 509В 510В 511В 512В 513В CONTENTS
514В 515В 516В 517В 517В 518В 518В 519В 520В 521В 522В 523В 524В 525В 526В 527В 527В 528В 529В 529В 530В 531В 532В 533В 534В 535В 535В 536В 537В 538В 543В 543В 544В 545В 549В 550В 551В 552В 552В 553В 554В 557В 559В 560В 562В 563В 563В 564В 565В 566В 566В 567В RegQueryEx
RegQueryExpSz
RegQueryItem
RegQueryKey
RegQueryKeyLastWriteTime
RegQueryKeys
RegQueryMulSz
RegQueryQword
RegQueryStr
RegQueryValue
RegSetBin
RegSetDword
RegSetEx
RegSetExpSz
RegSetMulSz
RegSetQword
RegSetValue
RegUnloadHive
Reload {*M}
Return
RtStatus
Run
RunEnviron
RunHide
RunHideWait
RunIcon
RunIconWait
RunShell
RunWait
RunWithLogon
RunZoom
RunZoomWait
Select
SendKey
SendKeysChild
SendKeysTo
SendMenusTo
SendMessageA
SendMessageW
ShellExecute
ShortcutDir
ShortcutEdit
ShortcutExtra
ShortcutInfo
ShortcutMake
Sin
Sinh
SnapShot
Sounds
SoundVolume
Sqrt
StrByteCount
xi
CONTENTS
StrCat
StrCharCount
StrClean
StrCmp
StrCnt
StrFill
StrFix
StrFixBytes
StrFixBytesL
StrFixChars
StrFixCharsL
StrFixLeft
StriCmp
StrIndex
StrIndexNc
StrIndexWild
StrInsert
StrLen
StrLenWild
StrLower
StrOverlay
StrReplace
StrScan
StrSub
StrSubWild
StrTrim
StrTypeInfo
StrUpper
Switch
SysParamInfo
Tan
Tanh
Terminate
TerminateApp
TimeFunctions
TimeAdd
TimeDate
TimeDayofWeek
TimeDelay
TimeDiff
TimeDiffDays
TimeDiffSecs
TimeJulianDay
TimeJulToYmd
TimeSubtract
TimeWait
TimeYmdHms
UacElevationLevel
UacExePromptTest
UacManifestSettings
VarType
Version
xii
567В 568В 569В 570В 570В 571В 572В 573В 574В 574В 575В 575В 576В 577В 578В 579В 579В 580В 581В 581В 582В 583В 583В 584В 585В 586В 586В 588В 589В 590В 591В 591В 592В 593В 594В 594В 595В 596В 596В 597В 598В 598В 599В 600В 600В 601В 601В 602В 603В 603В 604В 605В CONTENTS
606В 606В 608В 609В 610В 611В 611В 612В 612В 613В 614В 615В 615В 616В 616В 618В 619В 620В 620В 621В 622В 622В 624В 624В 626В 628В 628В 629В 631В 632В 632В 633В 634В 635В 636В 636В 637В 638В 641В 641В 642В 643В 643В 644В 645В VersionDLL
WaitForKey
WaitForKeyEx
WallPaper
While
WinActivate
WinActiveChild
WinArrange
WinClose
WindowOnTop
WinExeName
WinExist
WinExistChild
WinGetActive
WinHelp
WinHide
WinIconize
WinIdGet
WinIsDOS
WinItemChild
WinItemize
WinItemizeEx
WinItemNameId
WinItemProcId
WinMetrics
WinName
WinPlace
WinPlaceChild
WinPlaceGet
WinPlaceSet
WinPosition
WinPositionChild
WinResources
WinShow
WinState
WinSysInfo
WinTitle
WinVersion
WinWaitChild
WinWaitClose
WinWaitExist
WinWaitReady
WinZoom
Yield
Yields
647В 647В 647В 647В 651В 652В MENU FILES
About Menu Files
How Menu Files are used
Menu File Structure
Modifying Menus
Menu Hotkeys
xiii
CONTENTS
Menu Items
653В APPENDIX Constants
Predefined Constants
String Constants
Floating Point Constants
655В 655В 656В 656В INDEX
659В xiv
INTRODUCTION
INTRODUCTION
What is WIL?
The Windows Interface Language (WIL) is an easy-to-use yet very powerful
general-purpose programming language with over 500 functions for file
management, sending keystrokes, disk drive management, directory management,
binary file access, multimedia support, COM/OLE support, clipboard handling,
system control, program management, string handling, displaying information, user
prompting, window management, floating point & integer arithmetic, execution
control and more. Many operations that require pages of code in other programming
languages can be accomplished with a single WIL function call.
What is WIL good for?
Using WIL, you can make small batch files to use as system management utilities.
Connecting to network servers, printing batch jobs out at odd hours, upgrading
software, and metering application use, are just a few of the chores handled by the
system utilities made with WIL.
You can also write major business applications. Experience with small utilities
encourages the leap to major projects. WIL is the common glue that can bind any
off-the-shelf or custom Windows and DOS programs together. Software from any
vendor can be combined to make a solution. Automated business solutions save time,
save money, and make money for the companies using them to leverage their
investment in hardware, software and people.
With the WebBatch implementation of WIL, your Windows NT-based web server
can process orders, dynamically respond to visitor choices, manage group discussion
lists, and publish tech support pages; nearly anything you've seen done on the
Internet using Perl or C can often be done much easier and faster using WIL.
WIL gives you some very powerful features:
п‚·
Traditional batch-language file management capabilities such as copying
files, changing the directory, or launching applications
п‚·
Structured programming, including GOSUB, SWITCH CASE,
FOR...NEXT, WHILE...ENDWHILE, IF...ELSE...ENDIF
п‚·
Complete support for user interaction, including standard Windows dialog
boxes, check boxes, radio buttons, and file list selectors
15
INTRODUCTION
п‚·
Time and date functions for scheduling operations
п‚·
Send keystrokes and menu commands directly to applications
п‚·
Network support: extenders included for Novell and Win32 Networks
п‚·
Link to Windows Dlls, third party MAPI and TAPI Dlls, or your own C or
C++ Dlls
п‚·
Extensive string manipulation, integer and floating point arithmetic,
including trig and log functions
п‚·
System control -- read and change system values like the current wallpaper,
keyboard repeat rate, etc.
п‚·
Manipulate windows (change their size or location)
п‚·
Control multimedia hardware (sound cards, CD-ROM drives, etc.)
п‚·
Launch a script by clicking an icon in the Explorer or Start Menu
п‚·
Complete binary access to any file
Your implementation of WIL may include all of these features and more; see your
program's help file for complete details.
Products that use WIL
WIL is supported by several Wilson WindowWare products, including WinBatch,
WinBatch+Compiler, and WebBatch.
WIL scripts are written in a plain ASCII text file, which can be created by WinBatch
Studio, Notepad or most word processors.
These text files can take one of two forms, depending on your particular
implementation of WIL: batch files or menu files.
Batch Files
A batch file is simply a list of WIL commands and function calls, executed in
order (just like the old DOS batch language).
Menu Files
A menu file is similar to a batch file, except that multiple chunks of WIL code
are organized into menu and sub-menus, and each routine is launched by
pressing the appropriate keystroke or selecting an item from the menu. (The
name and location of the menus vary depending on the particular
implementation of WIL menu files.)
Because WIL can be implemented in many different ways, with several different
applications, this manual must at times be somewhat general. Therefore, you will
need to refer to your application's User's Guide for information on any additional
16
INTRODUCTION
functions which may be available, as well as functions which may be unavailable or
which may operate differently than presented here. In all cases, your product-specific
documentation and help files supersedes the information provided in this Reference
Manual.
Batch file
implementations of WIL
WinBatch
WinBatch+Compiler
WebBatch
Menu file
implementations of WIL
WinBatch Studio
PopMenu (a utility included with WinBatch)
FileMenu (a utility included with WinBatch)
Some features aren't appropriate for a particular implementation; for example,
WebBatch doesn't include any window-management functions, but it has many
functions that are only appropriate in a web server environment.
Notational Conventions
Throughout this manual, we use the following conventions to distinguish elements of
text:
Boldface
Used for important points, programs, function names, and parts of syntax that must
appear as shown.
System
Used for items in menus and dialogs, as they appear to the user.
Small fixed-width
Used for WIL sample code.
Italics
Used for emphasis, and to liven up the documentation just a bit.
Acknowledgments
WIL software developed by Morrie Wilson, Richard Merit and Tony Deets.
Documentation written by Richard Merit, Morrie Wilson, Jim Stiles, Liv Browning,
Laura Plaut and Deana Falk.
17
WIL TUTORIAL
WIL TUTORIAL
Creating WIL Scripts Files
WIL is a script file interpreter. Before you can do anything
useful with the WIL interpreter, you must have at least one WIL
script file to interpret.
Your program installation puts several sample scripts into a
"samples" directory. Sample scripts are located in a "samples"
subdirectory in the WinBatch directory.
WIL script files must be formatted as plain ASCII text files.
You can create them with WinBatch Studio, the Windows
Notepad or another text editor. Word processors like
WordPerfect, WordPro, and Microsoft Word can also save
scripts in plain text files.
The .WBT (WinBatch) extension is used in this manual for
batch file extensions, but, you can use others just as well. If you
want to click on a batch file and have Windows run it, be sure
that you associate it in Windows with your executable program
file. When you installed your program, an association was
automatically established between the interpreter
(WinBatch.exe) and .WBT files.
Each line in a script file contains a statement written in WIL,
Wilson WindowWare's Windows Interface Language.
A statement can be a maximum of 2048 characters long (refer to
WIL Function Reference, pg. 93, for information on the
commands). Indentation does not matter. A statement can
contain functions, commands, and comments. You can give
each script file a name which has an extension of WBT (e.g.
TEST.WBT). We'll use the terms WinBatch script files and
WBT files interchangeably.
Running WIL Utilities
WIL system utilities are very versatile. They can be run from:
п‚·
icons in the Windows Explorer.
п‚·
from macros in word processors and spreadsheets.
19
WIIL TUTO
ORIAL
п‚·
from a command lin
ne entry, such as
a the Window
ws logo
m
option in
n Windows.
key +R Taskbar menu
п‚·
by double clicking.
п‚·
from menu
m
items viaa the FileMenu
u and PopMenuu
utilitiees.
п‚·
from other WIL scriipts to serve ass single or multtiple
nts", event hand
dlers, or schedu
ulers.
"agen
п‚·
from any Windows application or application maacro
language that can ex
xecute another Windows proggram.
Softw
ware suite macrro languages an
nd application
buildeers like Visual Basic and Pow
werBuilder are
examp
ples of these.
Com
mmand Liine Param
meters
WIL
W utilities ru
un like any oth
her Windows program. They can be
run
r from a com
mmand line, a shortcut
s
or an icon
i
in a shell
program
p
like th
he Windows Explorer, or a Start menu selecction.
WIL
W utilities are
a usually run as files with th
he extension .W
WBT.
When
W
some WIL
W utilities aree used, they neeed informationn
passed
p
to them
m when they run
n. This is easily
y done by passsing
command
c
line parameters to them.
This
T capability
y can be used from
fr
the comm
mand line in thee
Start|Run
S
menu
u.
Parameters
P
can
n be also be passed through th
he command liine
entry
e
included in the item pro
operties of any
y shortcut icon.
Finally,
F
an app
plication can seend parameterss to a WIL utiliity it
launches
l
from a command lin
ne or from a fu
unction in a maacro
language.
l
A command lik
ke this runs a WinBatch
W
systeem utility from
ma
command
c
line or a shortcut iccon.
Command
C
linee:
winbatch.ex
xe filename.w
wbt p1 p2... p[n]
This
T command
d line can be en
ntered into a Co
ommand Line text
entry
e
box like this one:
20
WIL TUTORIAL
"filename.wbt" is any valid WBT file, and is a required
parameter.
"p1 p2 ... p[n]" are optional parameters to be passed to the WBT
file on startup. Each is delimited from the next by one space
character.
Parameters passed to a WBT file will be automatically inserted
into variables named param1, param2, etc. The WinBatch
utility will be able to use these. An additional variable, param0,
gives you the total number of command-line parameters.
What is a WIL Program?
A WIL program, like a DOS batch file, is simply a list of
commands for the computer to process. Any task which will be
run more than once, or which requires entering multiple
commands or even a single complex command, is a good
candidate for automation as a WIL program. For example,
suppose you regularly enter the following commands to start
Windows:
First:
cd \windows
then:
win
and then:
cd \
Here, you are changing to the Windows directory, running
Windows, and then returning to the root directory. Instead of
having to type these three commands every time you run
Windows, you can create a DOS batch file, called WI.BAT,
21
WIL TUTORIAL
which contains those exact same commands:
cd \windows
win
cd \
Now, to start Windows, you merely need to type the single
command WI, which runs the WI.BAT batch file, which
executes your three commands.
WIL programs work basically the same way.
Our First WIL Program
Tutor Example
1. Open an editor,
such as WinBatch
Studio.
2. Type the line.
3. Save the
program with a
proper extension.
(in WinBatch, this
extension will be
.WBT.) Name it
'tutor.wbt'.
4. Run tutor.wbt by
double-clicking on
the filename.
Our first WIL program will simply run our favorite Windows
application: Solitaire. If you are using a menu script-based
implementation of the WIL Interpreter, refer to the section on
Menu Files (pg. 647) for instructions on how to create and
edit WIL menu items. If you are using a batch file-based
implementation of the WIL Interpreter, you will be creating
your batch files using an editor, such as WinBatch Studio,
that is capable of saving text in pure ASCII format. In either
case, let's create a WIL program containing the following
line of text. The following code should all be on a single line:
Run("C:\Program Files\Microsoft
Games\Solitaire\Solitaire.exe", "")
Note: various Windows platforms may have a different file
path to Solitaire.
Save the program, as tutor.wbt, and run it (refer to your
product documentation, the User's Guide, for information on
how to execute a WIL program). Presto! It's Solitaire.
Functions and Parameters
Now, let's look more closely at the line we entered:
Run("C:\Program Files\Microsoft
Games\Solitaire\Solitaire.exe", "")
The first part, Run, is a WIL function. As you might have
guessed, its purpose is to run a Windows program. There are a
22
WIL TUTORIAL
large number of functions and commands in WIL, and each
has a certain syntax which must be used. The correct syntax
for all WIL functions may be found in the WIL Function
Reference (pg. 93). The entry for Run starts off as follows:
Syntax:
Run(program-name,params)
Parameters:
(s) program-name
(s) params
the name of the desired .EXE, .COM,
.PIF, .BAT file, or a data file.
optional parameters as required by the
application.
Like all WIL functions, Run is followed by a number of
parameters, enclosed in parentheses. Parameters are simply
additional pieces of information which are provided when a
particular function is used; they may be either required or
optional. Optional parameters are indicated by being enclosed in
square brackets. In this case, Run has two required parameters:
the name of the program to run, and the arguments to be passed
to the program.
WIL functions use several types of parameters. Multiple
parameters are separated by commas. In the example
Run("C:\Program Files\Microsoft
Games\Solitaire\Solitaire.exe", "")
Notes:
1. Strings are
delimited by
quotes, ("", "")
2. '(s)' denotes
the parameter
requires a string.
"C:\Program Files\Microsoft Games\Solitaire\Solitaire.exe"
and "" are both string constants. String constants can be
identified by the quote marks which delimit (surround) them.
You may use either double ("), single forward (') or single back
(`) quote marks as string delimiters; the examples in this
manual will use double quotes.
In our shorthand method for indicating syntax the (s) in front of
a parameter indicates that it is a string parameter.
You may have noticed how we said earlier that the two
parameters for the Run function are required, and yet the entry
for Run in the WIL Function Reference describes the second
parameter -"parameters" - as being optional.
Which is correct? Well, from a WIL language standpoint, the
second parameter is required. That is, if you omit it, you will get
a syntax error, and your WIL program will halt. However, the
program that you are running may not need parameters.
23
WIL TUTORIAL
Solitaire, for example, does not take parameters. The way we
handle this in our programs is to specify a null string - two
quote marks with nothing in between - as the second parameter,
as we have done in our example above.
To illustrate this further, let's create a WIL program containing
the following line:
Run("notepad.exe", "")
Example 2
1. Open Notepad.
2. Type in the
line.
3. Save the file as
notetest.wbt.
4. Close Notepad
This is just like our previous file, with only the file name of the
program having been changed. Save the file, and run it.
Is Notepad running? If it is - good. If not, check your script.
WinBatch will look for Notepad.exe on the computer's search
path. If it isn't there, you may need to locate it with the
Windows Explorer. Add a complete pathname to the run
statement and the script should work.
Now, edit the WIL program as follows:
Run("notepad.exe", "c:\autoexec.bat")
5. Run the wbt by
double-clicking
on the filename.
Save the program and run the WIL program again. You should
now be in Notepad, with AUTOEXEC.BAT loaded. As we've
just demonstrated, Notepad is an example of a program which
can be run with or without a file name parameter passed to it by
WIL.
It can often be helpful to add descriptive text to your WIL
programs:
; This is an example of the Run function in WIL
Run("notepad.exe", "c:\autoexec.bat")
Note:
semi-colons
denote comments.
The semi-colon at the beginning of the first line signifies a
comment, and causes that line to be ignored. You can place
comment lines, and/or blank lines anywhere in your WIL
programs. In addition, you can place a comment on the same
line as a WIL statement by preceding the comment with a semicolon. For example:
Run("notepad.exe", "") ; a very useful function
Everything to the right of a semi-colon is ignored. However, if a
semi-colon appears in a string delimited by quotes, it is treated
as part of the string.
24
WIL
W TUT
TORIAL
D
Displaying
g Text
Now, let's modify our orriginal WIL pro
ogram as follow
ws:
; tutor
r.wbt
Display
y(5,"Good Luc
ck!","Remembe
er … it's onl
ly a game")
Run("C:
:\Program Fil
les\Microsoft
t
Games\S
Solitaire\Sol
litaire.exe",
, "")
T
Tutor Examplee
ccontinued...
11. Exit Solitaire.
And run itt. Notice the litttle dialog box which pops upp on the
screen witth words of enccouragement:
22. Activate or
oopen your editor.
33. Load tutor.wbt.
44. Add the new
liines.
55. Save the file.
66. Run the wbt byy
ddouble-clicking
oon the filename.
That's don
ne by the Displlay function in the second linne above.
Here's the reference for Display:
D
Syntax:
Display (seconds, title,, text)
Parameteers:
(i) secon
nds
(s) title
(s) text
seconds to dissplay the messaage (max
3600).
title of the win
ndow to be dispplayed.
text of the win
ndow to be dispplayed.
The Display function haas three parameeters. The first parameter is
the numbeer of seconds which
w
the displaay box will rem
main on the
screen (yo
ou can make the box disappeaar before then bby pressing
any key orr mouse button
n). This is a numeric constan
nt, andunlike string constants-itt does not need
d to be enclosedd in quotes
(although it can be, if yo
ou wish, as WIL
L will automattically try to
convert strring variables to
t numeric varriables when neecessary, and
vice versaa). In our examp
ple above, we are displaying the box for
5 seconds.. The second parameter is thee title of the meessage box,
and the thiird parameter is
i the actual tex
xt displayed inn the box.
Note: In our
o shorthand method
m
for ind
dicating syntax the (s) in
front of a parameter
p
indiicates that it is a string. An (i)) indicates
that it is an
n integer, (f) in
ndicates a floatting point numbber
parameter, (a) indicates an array, (r) in
ndicates a COM
M/.NET
object refeerence , (t) indiicates special type
t
informatioon described
in the funcction’s text and
d (v) indicates a variant.
25
WIL TUTORIAL
Now, exit Solitaire (if you haven't done so already), and edit the
WIL program by placing a semi-colon at the beginning of the line
with the Run function. This is a handy way to disable, or
"comment out," lines in your WIL programs when you want to
modify and test only certain segments. Your WIL program should
look like this:
Tutor Example
continued...
1. Exit Solitaire.
2. Edit tutor.wbt Comment out the
Run statement.
3. Save the file.
4. Run the wbt by
double-clicking
on the filename.
; tutor.wbt
Display(5,"Good Luck","Remember … it's only a game")
; Run("C:\Program Files\Microsoft
Games\Solitaire\Solitaire.exe", "")
Feel free to experiment with modifying the parameters in the
Display function. Try adjusting the value of the first parameter. If
you look up Display in the WIL reference section, you will see
that the acceptable values for this parameter are 1-3600. If you
use a value outside this range, WIL will adjust it to "make it fit";
that is, it will treat numbers less than 1 as if they were 1, and
numbers greater than 3600 as 3600.
Also, try using a non-integer value, such as 2.9, and see what
happens (it will be converted to an integer). Play around with the
text in the two string parameters; try making one, or both, null
strings ("").
User Input
Now, let's look at ways of getting input from a user and making
decisions based on that input. The most basic form of input is a
simple Yes/No response, and, indeed, there is a WIL function
called AskYesNo:
Syntax:
AskYesNo(title,question)
Parameters
(s) title
(s) question
Returns:
(i)
title of the question box.
question to be put to the user.
@YES or @NO, depending on the
button pressed.
You should be familiar with the standard syntax format by now;
it shows us that AskYesNo has two required parameters. The
Parameters section tells us that these parameters both take
strings, and tells us what each of the parameters means.
26
WIL TUTORIAL
You will notice that there is also a new section here, called
Returns. This section shows you the possible values that may
be returned by this function. All functions return values. We
weren't concerned with the values returned by the Run and
Display functions. But with AskYesNo, the returned value is
very important, because we will need that information to decide
how to proceed. We see that AskYesNo returns an integer
value.
The integer value returned by AskYesNo is either 1 or 0. The
equivalent predefined constants are @YES or @NO, @TRUE
or @FALSE. You can test for any of these. They are
equivalent.
Therefore an integer is a whole (non-fractional) number, such as
0, 1, or 2 (the number 1.5 is not an integer, it is a floating point
number). We also see that the integer value returned by
AskYesNo is either @YES or @NO. @YES and @NO are
predefined constants in WIL. All predefined constants begin
with an @ symbol. You will find a list of all predefined
constants in the Appendix (pg.655). Even though the words Yes
and No are strings, it is important to remember that the
predefined constants @YES and @NO are not string variables.
(Actually, @YES is equal to 1, and @NO is equal to 0. Don't
worry if this is confusing; you really don't need to remember or
even understand it.)
Now, let's modify our WIL program as follows:
AskYesNo("Really?", "Play Solitaire now?")
Run("C:\Program Files\Microsoft
Games\Solitaire\Solitaire.exe", "")
Tutor Example
continued...
and run it. You should have gotten a nice dialog box which asked
if you wanted to play Solitaire:
1. Delete the
Display
statement. Add
AskYesNo
statement.
Delete semi-colon
from the Run.
2. Save the file.
3. Run the wbt by
double-clicking
on the filename.
27
WIL TUTORIAL
but no matter what you answered, it started Solitaire anyway.
This is not very useful. We need a way to use the Yes/No
response to determine further processing. First, we need to
explore the concept and use of variables.
Using Variables
A variable is simply a placeholder for a value. The value that
the variable stands for can be either a text string (string
variable) or a number (numeric variable).
Tutor Example
continued...
You may remember from Algebra 101 that if X=3, then X+X=6.
X is simply a numeric variable, which stands here for the
number 3. If we change the value of X to 4 (X=4), then the
expression X+X is now equal to 8.
1. Exit Solitaire.
2. Edit tutor.wbt Add variable
name.
3. Save the file.
4. Run the wbt by
double-clicking
on the filename.
Okay. We know that the AskYesNo function returns a value of
either @YES or @NO. What we need to do is create a variable
to store the value that AskYesNo returns, so that we can use it
later on in our WIL program.
First, we need to give this variable a name. In WIL, variable
names must begin with a letter, may contain any combination of
letters or numbers, and may be from 1 to 30 characters long. So,
let's use a variable called response.
(We will distinguish variable names in this text by printing them
in all lowercase letters; we will print function and command
names starting with a capital letter. However, in WIL, the case
is not significant, so you can use all lowercase, or all uppercase,
or whatever combination you prefer.)
We assign the value returned by AskYesNo to the variable
response, as follows:
response=AskYesNo("Really?", "Play Solitaire now?")
Notice the syntax. The way that WIL processes this line is to
first evaluate the result of the AskYesNo function. The function
returns a value of either @YES or @NO. Then, WIL assigns
this returned value to response. Therefore, response is now
equal to either @YES or @NO, depending on what the user
enters.
Now, we need a way to make a decision based upon this
variable.
28
WIL TUTORIAL
Making Decisions
WIL provides a way to conditionally execute a statement, and
that is by using the If ... Endif command.
Actually, there are several forms of the If statement -- the
structured form and the single statement form.
Structured Forms
If expression
series of statements
Endif
If expression
series of statements
Else
series of statements
Endif
Single Statement Forms
If expression
Then statement.
If expression
Then statement
Else statement
(We refer to If ... Endif as a command, rather than a function,
because functions are followed by parameters in parentheses,
while commands are not. Commands tend to be used to control
the flow of execution within the WIL Interpreter.)
Tutor Example
continued...
1. Exit Solitaire.
2. Edit tutor.wbt Add If/Endif
command to
check return of
the variable.
3. Save the file.
4. Run the wbt by
double-clicking
on the filename.
The use of If ... Endif can easily be illustrated by going back to
our WIL program and making these modifications:
response=AskYesNo("Really?", "Play Solitaire now?")
If response == @YES
Run("C:\Program Files\Microsoft
Games\Solitaire\Solitaire.exe", "")
Endif
However, as this example is a single statement, rather than a
series of statements, the single statement structure is more
appropriate. There are generally many different ways to perform
any task in WIL. With experience you will be able to decide the
best way to do any task.
response=AskYesNo("Really?", "Play Solitaire now?")
If response == @YES Then Run("C:\Program
Files\Microsoft Games\Solitaire\Solitaire.exe", "")
29
WIL TUTORIAL
Experiment with
additional If
structures.
In this example, we are using If ... Then to test whether the
value of the variable response is @YES. If it is @YES, we start
Solitaire. If it isn't @YES, we don't. The rule is: if the condition
following the If keyword is true or works out to a non-zero
value, then the statement(s) following are performed. If the
condition following the If keyword is false or works out to a
zero value, then the statement(s) following are ignored.
There is something extremely important that you should note
about the syntax of these If ... Endif commands: the double
equal signs (==). In WIL, a single equal sign (=) is an
assignment operator-it assigns the value on the right of the
equal sign to the variable on the left of the equal sign.
response=AskYesNo("Really?", "Play Solitaire now?")
This is saying, in English: "Assign the value returned by the
AskYesNo function to the variable named response." But in the
statement:
If response == @YES Then Run("C:\Program
Files\Microsoft Games\Solitaire\Solitaire.exe", "")
we do not want to assign a new value to response, we merely
want to test whether it is equal to @YES. Therefore, we use the
double equal signs (==), which is the equality operator in WIL.
The statement above is saying, in English: "If the value of the
variable named response is equal to @YES, then run the
program SOLITAIRE.EXE." If you used a single equal sign (=)
here by mistake, you would get an error message:
30
WIL TUTORIAL
Note:
(=) this IS that
(==) this
EQUALS that
Which is WIL's way of telling you to re-check your syntax.
If you've become confused, just remember that a single equal
sign (=) is an assignment operator, used to assign a value to a
variable. Double equal signs (==) are an equality operator, used
to test whether the values on both sides of the operator are the
same.
If you have a problem with one of your WIL programs, make
sure to check whether you've used one of these symbols
incorrectly. It's a very common mistake, which is why we
emphasize it so strongly!
We've seen what happens when the statement(s) following the If
condition are true. But what happens when the condition is
false? Remember we said that when the If condition is false, the
following statement(s) are ignored. There will be times,
however when we want to perform an alternate action in this
circumstance. For example, suppose we want to display a
message if the user decides that he or she doesn't want to play
Solitaire. We could write:
response=AskYesNo("Really?","Play Solitaire now?")
If response == @YES
Run("C:\Program Files\Microsoft
Games\Solitaire\Solitaire.exe", "")
Else
Display(5, "", "Game canceled")
Endif
Using the single statement If...Then...Else structure the same
code would look like:
response=AskYesNo("Really?", "Play Solitaire now?")
If response == @YES Then Run("C:\Program
Files\Microsoft Games\Solitaire\Solitaire.exe", "")
Else Display(5, "", "Game canceled")
When you have only single statements to execute when
conditions are true or false, the single statement form may be
preferred. However, what would happen if you had several
functions you wanted to perform if the user answered Yes? You
would end up with something unwieldy:
response=AskYesNo("Really?", "Play Solitaire now?")
If [email protected] Then Display(5,"","On your mark")
If [email protected] Then Display(5,"", "Get set ...")
If [email protected] Then Display(5, "", "Go!")
If [email protected] Then Run("C:\Program
Files\Microsoft Games\Solitaire\Solitaire.exe", "")
31
WIL TUTORIAL
If [email protected] Then Display(5,"","Game canceled")
Clearly, the best way of handling this is to Use the If... Else...
Endif structured form.
response=AskYesNo("Really?", "Play Solitaire now?")
If response == @YES
Display(5, "", "On your mark ...")
Display(5, "", "Get set ...")
Display(5, "", "Go!")
Run("C:\Program Files\Microsoft
Games\Solitaire\Solitaire.exe", "")
Else
Display(5, "", "Game canceled")
Endif
Control of Program Flow
The linear flow of statements (executing one statement after
another) is not always preferred or possible. WIL provides the
standard set of flow control commands: For, While, Switch and
GoSub. These commands give you the ability to redirect the
flow of control in your programs.
The For command controls the looping of a block of code based
on an incrementing index. The While command conditionally
and/or repeatedly executes a series of statements. The Switch
statement allows selection among multiple blocks of statements.
GoSub transfers control to another point in the WIL program
and saves the location for a Return statement.
Let’s explore the use of these commands further. Perhaps you
need to break your Solitaire habit by limiting your time of play
(it has, by now, become obvious to your boss and co-workers
that, ever since you got this program, all you do is play
Solitaire).
First you need to ask yourself how long you would like to play
by adding The following line to the top of your script.
mins=AskLine("Solitaire","How many mins do you want to play?","", 0)
This will display a message box which prompts you for the
number of minutes you would like to play.
Once you enter the desired number of minutes, you could
display an additional message as a response to the specific
32
WIL
W TUT
TORIAL
T
Tutor Examplee
ccontinued...
11. Exit Solitaire.
(I
(If it is running.)
22. Edit tutor.wbt A
Add AskLine to
thhe top of the
sscript.Save the
fi
file.
33. Run the wbt byy
ddouble-clicking
oon the filename.
amount off time entered.
Switch, ass you remembeer, allows selecction from amoong
multiple blocks
b
of statem
ments. Each blo
ock of statemennts is called
a case.
In the follo
owing sample, there are seveeral case statem
ment blocks.
Selection of
o one of the cases is determiined by the num
mber of
minutes sttored in the varriable mins.
If the num
mber is 3, then case
c
3 will be executed.
e
All nnumbers not
accounted
d for will be exeecuted by the default
d
case, m
mins.
Type the following
f
codee into tutor.wb
bt. Test the Swiitch
statement by entering a number
n
into the AskLine diaalog box. Try
running it several times using
u
various numbers.
n
11. Exit Solitaire.
22. Edit tutor.wbt
too add the Switch
h
sstatement.
Your code should lo
ook like the folllowing. Remoove extra
statements.
m
mins = AskLin
ne("Solitaire
e","How many mins do you want to play
y?","",0)
m
mins = Int(mi
ins)
S
Switch mins
case 0
ay(5, "", "Game canceled
d")
Displa
exit
break
case 1
ge("Only a minute?", "Wow! You've go
ot willpower. ")
Messag
break
case 2
ge("2 Minutes?", "This isn't much of
f a break.")
Messag
break
case 3
Messag
ge("3 Minutes?", "You've barely got time to shuf
ffle")
break
case 4
ge("HA,HA,HA",
Messag
break
"I dare you to try to
t beat me.")
33
WIL TUTORIAL
case mins
;default case - must be last in the switch
Message("THAT LONG!!!", "Where did you get all that time?")
break
EndSwitch
Run("C:\Program Files\Microsoft Games\Solitaire\Solitaire.exe", "")
In our example, each case statement block is composed of three
parts; a case statement followed by a number, a series of one or
more statements and the break command. If the number behind
the case statement matches the number behind the switch
statement, then the case block is executed. Once the correct
message has been displayed, break terminates the case block
and transfers control to the EndSwitch statement.
Now we need to create a timer to track the time elapsed and
compare it to the time entered. The While command, which
repeats execution of a series of statements by telling WIL, "Do
the following while a condition is present," does this job nicely.
First let’s set up a couple of variables.
goal = mins * 60
timer = 0
Tutor Example
continued...
1. Exit Solitaire.
2. Edit tutor.wbt
Set up variables.
Add the timing
code below the
Run statement.
3. Save the file.
4. Run the wbt by
double-clicking
on the filename.
Now for the While statement. The first line sets the condition,
"While the timer is less than the goal execute this series of
statements."
While timer < goal
remain = goal - timer
WinTitle("Solitaire","Solitaire (%remain% seconds
left)")
TimeDelay(10)
timer = timer + 10
EndWhile
The rest of our series of statements include: a computation of
the time remaining (remain) to be displayed, a line to display
the time remaining in the Solitaire window title bar, a
TimeDelay statement to allow time to pass, and a statement to
calculate the time elapsed. EndWhile marks the end of
statements. WIL marches through the While loop until the
variable timer exceeds the value of the variable goal.
So what happens if suddenly your time is up and you’re four
moves away from winning? Can’t have that happening.
34
WIL TUTORIAL
We can give ourselves the opportunity To add more time by
adding another Askline statement.
mins=AskLine("More Time?","Enter additional
minutes.", 0, 0)
Tutor Example
continued...
1. Exit Solitaire.
2. Edit tutor.wbt
Add new line to
bottom of script.
3. Save the file.
4. Run the wbt by
double-clicking
on the filename.
If a time is entered the timer will need to be used again. Of
course, it would be easy to copy that portion of the script and
insert it after the new line. However, the same script can be
utilized with the assistance of GoSub.
GoSub causes the flow of control to go to another point in the
WIL program while remembering its point of origin. The name
GoSub is an abbreviation of "Go To Subroutine". You must
specify where you want the flow of control to be transferred -the subroutine name, and you must mark this point with a label.
A label is simply a destination address, or marker. The form of
the GoSub command is:
GoSub label
where label is an identifier that you specify. (the first character
must be a letter, the label name may consist of any combination
of letters and numbers, and the label name may be up to 249
characters long). In addition, the label is preceded by a colon (:)
at the point where it is being used as a destination address.
"WaterHazard"
Tutor Example
continued...
1. Exit Solitaire.
2. Edit tutor.wbt
Add :dumdedum
label to bottom.
Move timing loop
below label.
Add Return after
loop. After Run
statement add
GoSub
dumdedum.
3. Save the file.
4. Run the wbt by
In our sample script, we move the timing loop to the bottom of
the script, add a label marked :dumdedum above the timing
script as the destination address. After EndWhile, add the
statement, Return to allow the flow of control to return from
the bottom of the GoSub.
We’ll add a GoSub statement in after the Run statement. The
GoSub statement is saying, in English "go to the line marked
:dumdedum, and continue processing from there, but remember
where you came from." When Return is reached, control will
be transferred back to the statement after the original GoSub.
Notice that the label dumdedum is preceded by a colon as the
address, but not on the line where it follows the GoSub
keyword. This is important. Although you can have multiple
lines in your WIL program which say GoSub dumdedum, you
can have only one line marked :dumdedum (just like you can
have several people going to your house, but can have only one
house with a particular address). Of course, you can use many
different labels in a WIL program, just as you can use many
different variables, as long as each has a unique name.
35
WIL TUTORIAL
double-clicking
on the filename.
Tutor Example
continued...
1. Exit Solitaire.
2. Edit tutor.wbt
-Add check for
return of
AskLine.
Add WinClose
and Exit.
(See code below)
3. Save the file.
4. Run the wbt by
double-clicking
on the filename.
In addition to changing the message displayed in the
"mins=AskLine" statement, a default time has been added. The
value returned will need to be checked. In the example below,
"!=" signifies "not equal to". Therefore the line reads, "If mins is
not equal to zero then GoSub dumdedum."
If mins!=0 then GoSub dumdedum
If a time is returned, GoSub will send execution to the
:dumdedum label and the waiting process will begin again.
After the time has elapsed, control will be returned to the
statement following the GoSub.
The last thing we want to do is end the program with the
WinClose function and display a final message.
The Exit command is used to keep the processing from "falling
through" to the subroutine at the end of the program. In this
case, the dumdedum subroutine sits at the end. Exit causes a
WIL program to end immediately and not fall into the
dumdedum loop.
Script Stop Our altered script has the following appearance from the Run
statement to the bottom.
Run("C:\Program Files\Microsoft Games\Solitaire\Solitaire.exe", "")
GoSub dumdedum
mins=AskLine("More Time?", "Enter additional minutes", 0, 0)
If mins!=0 then GoSub dumdedum
WinClose("Solitaire")
Message("Time's Up", "Get Back to Work!")
Exit
:dumdedum
goal = mins * 60
timer = 0
While timer < goal
remain = goal - timer
WinTitle("Solitaire", "Solitaire (%remain% seconds left)")
TimeDelay(10)
timer = timer + 10
EndWhile
Return
36
WIL TUTORIAL
The sample script could be considered complete at this point.
However, the For command has yet to be discussed. The For
command is more complex than the previous commands. It
controls the looping of a block of code based on an
incrementing index. This command is handy if you want to
perform a specific code block a particular number of times. The
statement says, "Repeat the block of code for each value of a
variable from the initial value to the final value, incrementing
the variable after each pass of the loop" .
In the sample below, the size of the Solitaire window is
manipulated and displayed 10 times before the window is
zoomed to full screen. Each time the loop is executed, the
coordinate and size variables (j and k) are altered, and then used
in a WinPlace statement ( it's time to start looking up functions
in the reference yourself now) to affect the position and size of
the Solitaire window.
Run("C:\Program Files\Microsoft
Games\Solitaire\Solitaire.exe","")
Tutor Example
continued...
1. Edit tutor.wbt
Add code for the
For statement
directly after the
Run statement.
2. Save the file.
3. Run the wbt by
double-clicking
on the filename.
for i = 0 to 9
j=100-i*10
k=300+i*70
WinPlace(j,j,k,k, "Solitaire")
next
WinZoom("Solitaire")
Note: the case of the window title 'Solitaire' is important. If
Solitaire is spelled with a lower case 's', the program will not
work.
This concludes the first part of our tutorial. You now have the
building blocks you need to create useful WIL programs. In the
second part, which follows, we will look in more detail at some
of the WIL functions which are available for your use.
See the Completed WIL file, tutor.wbt, at the end of the WIL
TUTORIAL (pg. 58).
Exploring WIL
If you take a moment and flip through the WIL Function Reference that takes up
most of the back of this manual, you will notice that WIL uses a very convenient
naming convention. WIL functions are named so that the object affected by the
function is the first word in the function name -- any function dealing with Files
37
WIL TUTORIAL
starts with the word "File", and they can be found clumped together in the
alphabetically arranged function reference. If you think you might want a function
dealing with DDE, simply flip open the manual to the DDE section and scan the
available functions.
What follows is just quick overview of the many functions and commands available
in WIL. These should be sufficient to begin creating versatile and powerful WIL
programs. For complete information on these and all WIL functions and commands,
refer to the WIL Function Reference (pg. 93).
Running Programs
There are several functions that you can use to start an application, most of which
share a common syntax. 32 bit Windows platforms can use file names with
embedded spaces. WIL understands long filenames, however if a long filename with
spaces must be passed as an argument use quotation marks like this:
Run( 'My Program' , '"C:\program files\path"' )
Notice: the use of single quotation marks outside of the double quotation marks.
Run (program-name, params)
We've already seen the Run function. This function starts a program in a "normal"
window. Windows, or the application itself, decides where to place the application's
window on the screen.
Example:
Run("notepad.exe", "myfile.txt")
If the program has an EXE extension, its extension may be omitted:
Run("notepad", "myfile.txt")
Also, you can "run" data files if they have an extension in the Registry which is
associated with an executable program. So, if TXT files are associated with Notepad:
Run("myfile.txt", "")
would start Notepad, using the file MYFILE.TXT.
When you specify a file to run, WIL looks first in the current directory, and then in
the directories on your system path. If the file is not found, WIL will return an error.
You can also specify a full path name for WIL to use, as in:
Run("c:\windows\notepad.exe", "")
RunZoom (program-name, params)
RunZoom is like Run, but starts a program as a full-screen window.
38
WIL TUTORIAL
Example:
RunZoom("excel", "bigsheet.xls")
RunIcon (program-name, params)
RunIcon starts a program as an icon at the bottom of the screen or in the Windows
Taskbar.
Example:
RunIcon("notepad", "")
All these Run functions simply launch the program and continue with WIL
processing. If you need to wait until the program exits before continuing, then there
are a number of other suitable functions also available.
RunWithLogon(program-name, params, directory, display mode,
waitflag, username, domain, password, logon-flags)
Runs a program as a specified user.
RunWait (program-name, params)
RunWait starts a program and waits for it to exit before continuing. This is often
required when the "program" is a DOS batch file.
RunZoomWait (program-name, params)
RunZoomWait starts a program as a full screen window and waits for it to exit
before continuing.
RunIconWait (program-name, params)
RunIconWait starts a program as an icon at the bottom of the screen and waits for it
to exit before continuing.
If all these Run functions are too much for you, there is also the combination
RunShell function, which combines all the capabilities of the Run functions and adds
additional functionality.
RunShell (program-name, params, directory, displaymode, waitflag)
RunShell is an advanced form of the Run function that even allows the specification
of a target/current working directory, along with the window view mode and whether
or not to wait for completion of the run program in a single function.
ShellExecute (program-name, params, directory, displaymode,
operation)
Runs a program via the Windows ShellExecute command.
Display and Input
39
WIIL TUTO
ORIAL
Here we have functions which display information to the user and
a prompt thee user
for innformation, plu
us a couple of relevant
r
system
m functions.
Disp
play (second
ds, title, text))
Displlays a message to the user forr a specified peeriod of time. The
T message w
will
disapppear after the time
t
expires, or after an Enterr keypress or mouse
m
click.
Exam
mple:
Dis
splay(2, "Ple
ease Wait", "Loading
"
Soli
itaire Now")
Message (title, text)
This ccommand disp
plays a messagee box with a tittle and text you
u specify, whicch will
remaiin on the screen
n until the userr presses the OK
O button.
Exam
mple:
Mes
ssage("Sorry"
", "That file
e cannot be found")
f
Pausse (title, textt)
This ccommand is sim
milar to Messaage, except an exclamation-po
oint icon appeaars in
the m
message box, an
nd the user can
n press OK or Cancel.
C
If the user
u presses Caancel, the
WIL program ends (or goes to thee label :cancel, if one is defineed).
mple:
Exam
Pau
use("Delete Backups",
B
"La
ast chance to
o stop!")
; i
if we got thi
is far, the user
u
pressed OK
Fil
leDelete("*.b
bak")
40
WIL TUTORIAL
AskYesNo (title, question)
Displays a dialog box with a given title, which presents the user with three buttons:
Yes, No, and Cancel. If the user presses Cancel, the WIL program ends (or goes to
the label :cancel, if one is defined). Otherwise, the function returns a value of @YES
or @NO.
See THINGS TO KNOW, (pg. 61) for more information on Cancel.
Example:
response = AskYesNo("End Session", "Really quit Windows?")
AskLine (title, prompt, default [, format])
Displays a dialog box with a given title, which prompts the user for a line of input.
Returns the default if the user just presses the OK button.
Example:
yourfile = AskLine("Edit File", "Filename:", "newfile.txt",0)
Run("notepad", yourfile)
41
WIL TUTORIAL
If you specify a default value (as we have with NEWFILE.TXT), it will appear in the
response box, and will be replaced with whatever the user types. If the user doesn't
type anything, the default is used.
Beep
Beeps once.
Beep
And if one beep isn't enough for you:
Beep
Beep
Beep
TimeDelay (seconds)
Pauses WIL program execution.
The TimeDelay function lets you suspend processing for a fixed period of time,
which can be anywhere from 1 to 3600 seconds.
Manipulating Windows
There are a large number of functions which allow you to manage the windows on
your desktop. Here are some of them:
WinZoom (partial-windowname)
Maximizes an application window to full-screen.
WinIconize (partial-windowname)
Turns an application window into an icon.
42
WIL TUTORIAL
WinShow (partial-windowname)
Shows a window in its "normal" state.
These three functions are used to modify the size of an already-running window.
WinZoom is the equivalent of selecting Maximize from a window's control menu,
WinIconize is like selecting Minimize, and WinShow is like selecting Restore.
The window on which you are performing any of these functions does not have to be
the active window. If the specified window is in the background, and a WinZoom or
WinShow function causes the size of the window to change, then the window will be
brought to the foreground. The WinZoom function has no effect on a window which
is already maximized; likewise, WinShow has no effect on a window which is
already "normal."
Each of these functions accepts a partial window name (pg.65) as a parameter. The
windowname is the name which appears in the title bar at the top of the window.
You can specify the full name if you wish, but it may often be advantageous not to
have to do so. For example, if you are editing the file TUTOR.WBT in a Notepad
window, the windowname will be tutor.wbt - Notepad.
You probably don't want to have to hard-code this entire name into your WIL
program as:
WinZoom("tutor.wbt - Notepad")
Instead, you can specify the partial windowname "Notepad":
WinZoom("~Notepad")
Note: the tilde '~' character used in this statement, tells the script to search anywhere
in the window title for the word 'Notepad'. For more information on partial window
names see page 65.
43
WIL TUTORIAL
If you have more than one Notepad window open, WIL will use the one which was
most recently used or started.
Note that WIL matches the partial windowname beginning with the first character, so
that while
WinZoom("tut")
would be correct,
WinZoom("Notepad")
would not result in a match.
Also, the case (upper or lower) of the title is significant, so
WinZoom("TUTOR")
would not work either.
WinActivate (partial-windowname)
Makes an application window the active window.
This function makes a currently-open window the active window. If the specified
window is an icon, it will be restored to normal size; otherwise, its size will not be
changed.
WinClose (partial-windowname)
Closes an application window.
This is like selecting Close from an application's control menu. You will still receive
any closing message(s) that the application would normally give you, such as an
"unsaved-file" dialog box.
WinExist (partial-windowname)
Tells if a window exists.
This function returns @TRUE or @FALSE, depending on whether a matching
window can be found. This provides a way of insuring that only one copy of a given
window will be open at a time.
If you've been following this tutorial faithfully from the beginning, you probably
have several copies of Solitaire running at the moment. (You can check by pressing
Alt-Tab see how many instance are open. You say you've got five Solitaire windows
open? Okay, close them all). Now, let's modify our WIL program. First, trim out the
excess lines so that it looks like this:
Run("C:\Program Files\Microsoft Games\Solitaire\Solitaire.exe", "")
44
WIL TUTORIAL
Now, let's use the WinExist function to make sure that the WIL program only starts
Solitaire if it isn't already running:
If WinExist("~Solitaire") == @FALSE Then Run("C:\Program
Files\Microsoft Games\Solitaire\Solitaire.exe", "")
Note: the tilde '~' character used in the WinExist statement, tells WinExist to search
anywhere in the window title for the word 'Solitaire'. For more information on partial
window names see page 65.
And this should work fine. Run the WIL program twice now, and see what happens.
The first time you run it, it should start Solitaire; the second (and subsequent) time, it
should not do anything.
However, it's quite likely that you want the WIL program to do something if
Solitaire is already running-namely, bring the Solitaire window to the foreground.
This can be accomplished by using the WinActivate function as follows:
If WinExist("~Solitaire") == @TRUE
WinActivate("Solitaire")
Else
Run("C:\Program Files\Microsoft Games\Solitaire\Solitaire.exe",
"")
Endif
Note that we can change this to have WinExist check for a False value instead, by
modifying the structure of the WIL program:
If WinExist("~Solitaire") == @FALSE
Run("C:\Program Files\Microsoft Games\Solitaire\Solitaire.exe",
"")
Else
WinActivate("~Solitaire")
Endif
Either format is perfectly correct, and the choice of which to use is merely a matter
of personal style. The result is exactly the same.
EndSession ( )
Ends the current Windows session.
This does exactly what it says. It will not ask any questions (although you will
receive any closing messages that your currently-open windows would normally
display), so you may want to build in a little safety net:
sure = AskYesNo("End Session", "Really quit Windows?")
If sure == @YES Then EndSession( )
EndSession is an example of a WIL function which does not take any parameters, as
indicated by the empty parentheses which follow it. The parentheses are still
required, though.
45
WIL TUTORIAL
Note: For additional methods of rebooting or restarting Windows, see
IntControl(66,…) , IntControl(67,…) and IntControl(68,…).
Files and Directories
DirChange ([d:]path)
Changes the directory to the pathname specified.
Use this function when you want to run a program which must be started from its
own directory. "Pathname" may optionally include a drive letter
Example:
DirChange("c:\windows\winword")
Run("winword.exe", "")
DirGet ( )
Gets the current working directory.
This function is especially useful in conjunction with DirChange, to save and then
return to the current directory.
Example:
origdir = DirGet( )
DirChange("c:\windows\winword")
Run("winword.exe", "")
DirChange(origdir)
FileCopy (source-list, destination, warning)
Copies files.
If warning is @TRUE, WIL will pop up a dialog box warning you if you are about to
overwrite an existing file, and giving you an opportunity to change your mind, along
with selecting various options for copying the files. If warning is @FALSE, it will
overwrite existing files with no warning.
Example:
FileCopy("win.ini", "*.sav", @TRUE)
Run("notepad.exe", "win.ini")
The asterisk (*) is a wildcard character, which matches any letter or group of letters
in a file name. In this case, it will cause WIN.INI to be copied as WIN.SAV.
FileDelete (file-list)
Deletes files.
Example:
If FileExist("win.bak") == @TRUE Then FileDelete("win.bak")
46
WIL TUTORIAL
FileExist (filename)
Determines if a file exists.
This function will return @TRUE if the specified file exists, @FALSE if it
doesn't exist, and the value 2 if the file is in read-deny mode.
Example:
If FileExist("win.bak") == @FALSE
FileCopy("win.ini", "win.bak", @FALSE)
endif
Run("notepad.exe", "win.ini")
FileRename (source-list, destination)
Renames files to another set of names.
We can illustrate the use of these WIL program functions with a typical WIL
application. Let's suppose that our word processor saves a backup copy of each
document, with a BAK extension, but we want a larger safety net when editing
important files. We want to keep the five most recent versions of the wonderful
software manual we're writing.
Here's a WIL program to accomplish this:
If FileExist("wil.bak") == @TRUE
FileDelete("wil.bk5")
FileRename("wil.bk4", "wil.bk5")
FileRename("wil.bk3", "wil.bk4")
FileRename("wil.bk2", "wil.bk3")
FileRename("wil.bk1", "wil.bk2")
FileRename("wil.bak", "wil.bk1")
Endif
Run("winword.exe", "wil.doc")
If the file WIL.BAK exists, it means that we have made a change to WIL.DOC. So,
before we start editing, we delete the oldest backup copy, and perform several
FileRename functions, until eventually WIL.BAK becomes WIL.BK1.
However, this still isn't quite right. What would happen if the file WIL.BK5 didn't
exist? We would get a FileRename error.
There are two ways that we can handle this. We could use an If FileExist test before
every file operation, and test the returned value for a @TRUE before proceeding.
But this is clumsy, even with such a small WIL program, and would become
unwieldy with a larger one. The other way is by using the ErrorMode function.
Handling Errors
The ErrorMode function lets you decide what will happen if an error occurs during
WIL processing. It is designed to be used around an isolated function, such as the
47
WIL TUTORIAL
FileRename function above, to turn off errors which would prevent a script from
continuing. See Also: IntControl 73, IntControl 38.
ErrorMode (mode)
Specifies how to handle errors.
Parameters:
(i) mode
@CANCEL, @NOTIFY, or @OFF.
Returns:
(i)
previous error setting.
Use this command to control the effects of runtime errors. The default setting is
@CANCEL, meaning the execution of the WIL program will be canceled for any
error.
@CANCEL: All runtime errors will cause execution to be canceled. The user will
be notified which error occurred.
@NOTIFY: All runtime errors will be reported to the user, and they can choose to
continue if it isn't fatal.
@OFF: Minor runtime errors will be suppressed. Moderate and fatal errors will be
reported to the user. User has the option of continuing if the error is not fatal.
As you can see, the default mode is @CANCEL, and it's a good idea to leave it like
this. However, it is quite reasonable to change the mode for isolated sections of your
WIL program where you anticipate errors occurring. This is just what we've done in
our modified WIL program:
Please read examples very carefully before running.
If FileExist("wil.bak") == @TRUE
FileDelete("wil.bk5")
ErrorMode(@OFF) ;turn ErrorMode off
FileRename("wil.bk4", "wil.bk5")
FileRename("wil.bk3", "wil.bk4")
FileRename("wil.bk2", "wil.bk3")
FileRename("wil.bk1", "wil.bk2")
FileRename("wil.bak", "wil.bk1")
ErrorMode(@CANCEL) ;reset ErrorMode to default
Endif
Run("winword.exe", "wil.doc")
Notice how we've used ErrorMode(@OFF) to prevent errors in the If statement
section from aborting the WIL program, and then used ErrorMode(@CANCEL) at
the end of the that section to change back to the default error mode. This is a good
practice to follow.
48
WIL TUTORIAL
In general, you should ONLY put error mode around SINGLE statements where
you are handling the errors yourself. If it is obvious that there is no way a
statement could fail it should be run with ErrorMode(@CANCEL).
Note: Pay close attention when suppressing errors with the ErrorMode function.
When an error occurs, the processing of the ENTIRE line is canceled. Setting the
ErrorMode( ) to @OFF or @NOTIFY allows execution to resume at the next line.
Various parts of the original line may have not been executed.
Please read examples very carefully before running.
ErrorMode(@OFF)
; The FileCopy will cause a file not found error,
; canceling the execution of the whole line.
; The variable A is set to @FALSE by default
A = FileCopy( "xxxxxxxxx", "*.*", @FALSE);
;
;
;
;
;
Now there is a NOT symbol in front of the FileCopy.
Nonetheless, if an error occurs A is still set to @FALSE
not @TRUE as might be assumed. When an error is suppressed
with ErrorMode the line is canceled, and any assignment is
simply set to the default @FALSE value.
A = !FileCopy("yyyyyyyyy", "*.*", @FALSE)
For this reason, ErrorMode( ) must be used with a great deal of care. The function
for which the errors are being suppressed should be isolated from other functions and
operators as much as possible.
e.g.
; INCORRECT USAGE of ErrorMode( )
; In this instance, when the copy has an error, the entire if
; statement is canceled.
; Execution begins (erroneously) at the next line, and states
; that the copy succeeded. Next a fatal error occurs as the
; "else" is found, since it does not have a matching if
ErrorMode(@OFF)
if FileCopy(file1,file2,@FALSE) == @TRUE
Message("Info", "Copy worked")
else
Message("Error", "Copy failed")
endif
;
;
;
;
;
;
;
;
CORRECT USAGE
In this case, the FileCopy is isolated from other statements
and flow control logic. When the statement fails, execution
can safely begin at the next line. The variable "a" will
contain the default value of zero that a failed assignment
returns.
Results are not confused by the presence of other operators.
ErrorMode(@OFF)
49
WIL TUTORIAL
a = FileCopy(file1,file2,@FALSE)
ErrorMode(@CANCEL)
if a == @TRUE
Message("Info", "Copy worked")
else
Message("Error", "Copy failed")
endif
Debugging WIL Scripts
Apparently, there have been sightings of bug free code. However, chances are you
will need to exterminate at least one of your WIL scripts. Luckily, WIL has a handy
debug utility which comes with the WIL Interpreter.
DebugTrace, a WIL function, is invaluable in determining logic errors. When
DebugTrace is initialized, a file is created which logs the execution of each
statement. DebugTrace works line by line through the script, logging the current
statement and its return value.
Initialize DebugTrace by adding DebugTrace(1,"trace.txt") or
DebugTrace(@ON,"trace.txt") to a specific point in your script. Note: For specific
instructions see Debug or DebugTrace in the WIL Function Reference.
Example:
DebugTrace(@on,"trace.txt")
a=TimeYmdHms( )
b=TimeJulianDay(a)
c=(b+5) mod 7
day=ItemExtract(c+1, "Sun Mon Tue Wed Thu Fri Sat", " ")
line=StrCat("Julian Date= ",b,@CRLF,"Day of week= ",day)
Message(TimeDate( ), line)
Selection Methods
So far, whenever we have needed to use a file name, we've hard-coded it into our
WIL programs.
For example:
Run("notepad.exe", "agenda.txt")
Naturally, there should be a way to get this information from the user "on the fly", so
that we wouldn't have to write hundreds of different WIL programs. And there is a
way. Three or four ways, actually. Consider, first, a function that we have already
seen, AskLine:
file = AskLine("Edit File", "Filename:", "newfile.txt", 0)
Run("notepad.exe", file)
This will prompt for a filename, and run Notepad on that file:
50
WIL TUTORIAL
There are only three problems with this approach. First, the user might not remember
the name of the file. Second, the user might enter the name incorrectly. And finally,
modern software is supposed to be sophisticated and user-friendly enough to handle
these things the right way. And WIL certainly can.
There are several functions we can use for an improved file selection routine.
FileItemize (file-list)
Returns a delimited list of files.
This function compiles a list of filenames and separates the names with a delimiter.
There are several variations we can use:
FileItemize("*.doc")
would give us a list of all files in the current directory with a DOC extension,
FileItemize("*.com|*.exe")
would give us a list of all files in the current directory with a COM or EXE
extension.
FileItemize("*.*")
would give us a list of all files in the current directory.
Of course, we need to be able to use this list, and for that we have:
AskItemList (title, list, delimiter, sort mode, select mode [, selectionrequired] )
Displays a list box filled with items from a list you specify in a string. The items are
separated in your string by a delimiter.
51
WIL TUTORIAL
This is the function which actually displays the list box. Remember that FileItemize
returns a file list delimited by a character. If the delimiter is a TAB, the list will look
something like this:
FILE1.TXT{TAB}FILE2.TXT{TAB}FILE3.TXT
When we use AskItemList, we need to tell it that the delimiter is a TAB. We do this
as follows:
files = FileItemize("*.docx|*.txt")
afile = AskItemList("Select File to edit", files, @TAB, @unsorted,
@single, @false)
Run("notepad.exe", afile)
which produces:
First, we use FileItemize to build a list of filenames with DOC and TXT
extensions. We assign this list to the variable files. Then, we use the
AskItemList function to build a list box, passing it the variable files as its
second parameter. The third parameter we use for AskItemList is simply the
@TAB constant; this tells AskItemList that the list in variable files is delimited
by tabs. Using the fourth parameter, set the sort mode to choose how to display
the text, sorted or unsorted. The fifth parameter sets the select mode allowing
you to choose a single item or multiple items from the list. The sixth parameter
is optional, it allows you to specify whether an item must be selected or not.
52
WIL TUTORIAL
Finally, we assign the value returned by AskItemList to the variable afile, and
run Notepad using that file.
In the list box, if the user presses Enter or clicks on the OK button without a
file being highlighted, AskItemList returns a null string. If you want, you can
test for this condition:
files = FileItemize("*.doc|*.txt")
while @TRUE
afile = AskItemList("Select File to edit", files, @TAB,
@unsorted, @single, @false)
If afile != "" Then break
;break terminates the While structure transferring
;control to the statement following the endwhile.
endwhile
Run("notepad.exe", afile)
DirItemize (dir-list)
Returns a delimited list of directories.
This function is similar to FileItemize, but instead of returning a list of files, it
returns a list of directories. Remember we said that FileItemize only lists files in
the current directory. Often, we want to be able to use files in other directories
as well. One way we can do this is by first letting the user select the appropriate
directory, using the DirItemize and AskItemList combination:
DirChange("C:\")
subdirs = DirItemize("*.*")
targdir = AskItemList("Select dir", subdirs, @TAB, @sorted,
@single, @false)
if targdir != "" then DirChange(targdir)
files = FileItemize("*.*")
afile = AskItemList("Select File to edit",files, @TAB, @sorted,
@single, @false)
Run("notepad.exe", afile)
First we change to the root directory. Then we use DirItemize to get a list of all
the sub-directories off of the root directory. Next, we use AskItemList to give
us a list box of directories from which to select. Finally, we change to the
selected directory, and use FileItemize and AskItemList to pick a file.
Although this WIL program works, it needs to be polished up a bit. What
happens if the file we want is in the \WINDOWS\BATCH directory? Our WIL
program doesn't go more than one level deep from the root directory. We want
to continue down the directory tree, but we also need a way of telling when
we're at the end of a branch. As it happens, there is such a way: DirItemize will
return a null string if there are no directories to process. Given this knowledge,
we can improve our file selection logic:
DirChange("C:\")
; Directory selection loop
53
WIL TUTORIAL
while @TRUE
; Loop forever til break do us part
dirs = DirItemize("*")
If dirs == "" Then break
targ = AskItemList("Select dir", dirs, @TAB, @sorted,
@single, @false)
If targ == "" Then break
DirChange(targ)
endwhile
;
; File selection loop
while @TRUE
; Loop forever til break do us part
files = FileItemize("*.*")
afile = AskItemList("Select File to edit", files, @TAB,
@sorted, @single, @false)
If afile != "" Then break
endwhile
Run("notepad.exe", afile)
First of all, we set up a repeating while loop.
While @TRUE
statements
EndWhile
The "While @TRUE" will repeat the loop forever. In the loop itself we use the
break statement to exit the loop. After we use the DirItemize function to try to
get a list of the directories at the current level, we test the returned value for a
null string. If we have a null string, then we know that the current directory has
no sub-directories, and so we proceed to the file selection logic by breaking out
of the directory selection loop. If, however, DirItemize returns a non-blank list,
then we know that there is, in fact, at least one sub-directory. In that case, we
use AskItemList to present the user with a list box of directories. Then, we test
the value returned by AskItemList. If the returned value is a null string, it
means that the user did not select a directory from the list, and presumably
wants a file in the current directory. We happily oblige by breaking out of the
directory selection loop. On the other hand, a non-blank value returned by
AskItemList indicates that the user has selected a sub-directory from the list
box. In that case, we change to the selected directory, and the endwhile causes
the directory selection loop to be repeated. We continue this process until either
(a) the user selects a directory, or (b) there are no directories left to select.
Eventually, we move to the file selection loop.
Nicer File Selection
The function AskFileName is the equivalent of a standard Common Dialog
FileOpen or a FileSave dialog box.
An even more elegant way of selecting a file name is provided by the Dialog Editor,
which also allows the user to select various options via check boxes and radio
54
WIL TUTORIAL
buttons from a custom designed dialog box. The Dialog Editor is installed in the
directory with the Winbatch.exe.
Nicer Messages
Have you tried displaying long messages, and found that WIL didn't wrap the lines
quite the way you wanted? Here are a couple of tricks.
@CRLF
@TAB
@CRLF and @TAB are string constants containing, respectively, a carriage-return
line-feed pair and a tab character.
We want to be able to insert a carriage return/line feed combination at the end of
each line in our output, and the @CRLF string constant will let us do that. For
example, let's say we want to do this:
Message("", "This is line one This is line two")
If we just inserted the variables into the string, as in:
Message("", "This is line one @crlf This is line two")
We would not get the desired effect. WIL would simply treat it as ordinary text:
However, WIL does provide us with a method of performing variable and string
constant substitution such as this, and that is by delimiting the variables or string
constants with percentage signs (%).
If we do this:
Message("", "This is line one%@crlf%This is line two")
we will get what we want:
55
WIL TUTORIAL
Note that there is no space after %@crlf%; this is so that the second line will be
aligned with the first line (every space within the delimiting quote marks of a string
variable is significant).
Running DOS Programs
WIL can run DOS programs, just like it runs Windows programs:
DirChange("c:\game")
Run("scramble.exe", "")
If you want to use an internal DOS command, such as DIR or TYPE, you can do so
by running the DOS command interpreter, COMMAND.COM or CMD.EXE, with
the /c program parameter, as follows:
Run("cmd.exe", "/c type readme.txt")
Everything that you would normally type on the DOS command line goes after the /c
in the second parameter. Here's another example:
Run("cmd.exe ", "/c type readme.txt | more")
These examples assume that CMD.EXE is in a directory on your DOS path. If it
isn't, you could specify a full path name for it:
Run("c:\cmd.exe", "/c type readme.txt | more")
Or, better still, you could use the WIL Environment function.
Environment (env-variable)
Gets a DOS environment variable.
Since DOS always stores the full path and filename of the command processor
in the DOS environment variable COMSPEC, it is an easy matter to retrieve
this information, it can be handled as follows:
56
WIL TUTORIAL
coms = Environment("COMSPEC")
and use it in our WIL program:
coms = Environment("COMSPEC")
Run(coms, "/c type readme.txt")
To get a DOS window, just run CMD.EXE with no parameters:
coms = Environment("COMSPEC")
Run(coms, "")
Sending Keystrokes to Programs
Here we come to one of the most useful and powerful features of WIL: the ability to
send keystrokes to your programs, just as if you were typing them directly from the
keyboard.
SendKeysTo (parent-windowname, sendkey string)
Activates the specified window and sends keystrokes to it.
This is an ideal way to make the computer automatically type the keystrokes that
you enter every time you start a certain program. For example, to start up
Notepad and have it prompt you for a file to open, you would use:
Run("notepad.exe", "")
SendKeysTo("Notepad", "!fo")
The parameters you specify for SendKeysTo are the windowname (or at least
the first unique part of it), and the string that you want sent to the program. This
string consists of standard characters, as well as some special characters which
you will find listed under the entry for SendKey in the WIL Function
Reference (pg. 545). In the example above, the exclamation mark (!) stands for
the Alt key, so !f is the equivalent of pressing and holding down the Alt key
while simultaneously pressing the f key. The o in the example above is simply
the letter o, and is the same as pressing the o key by itself:
57
WIL TUTORIAL
Our Completed WIL File
Here is the final working version of the WIL program that we've slowly been
building throughout this tutorial.
It incorporates many of the concepts that we've discussed so far, as well as using
some arithmetic ( *, -, +, / ) and relational (<) operators that are covered in the
section on the WIL Language (pg. 93).
It can also be improved and customized in a number of ways, but we'll leave that up
to you.
If you can understand and follow the structures and processes illustrated in this
sample file, and can begin to incorporate them into your own WIL programs, you are
well on your way to becoming a true WIL guru!
Clubhouse
Congratulations! You've finished the course.
Let's take a look at the completed script we've been
writing, tutor.wbt. A few things have been added to
polish it up, but the majority of the code should match
your example.
; tutor.wbt
mins = AskLine("Solitaire", "How many mins do you want to play?",
"5", 0)
mins = Int(mins)
Switch mins
case 0
Display(5, "", "Game canceled")
58
WIL TUTORIAL
exit
break
case 1
Message("Only a minute?", "Wow! You've got willpower.")
break
case 2
Message("2 Minutes?", "This isn't much of a break.")
break
case 3
Message("3 Minutes?", "You're barely got time to shuffle")
break
case 4
Message("HA,HA,HA", "I dare you to try to beat me.")
break
case mins ;default case - must be last in the switch
Message("THAT LONG!!!", "Where did you get all that time?")
break
EndSwitch
;;ADDED to demonstrate checking for the existence of a program
;;before running a second occurrence.
If WinExist("Solitaire") == @TRUE
WinActivate("Solitaire")
WinShow("Solitaire")
Else
Run("C:\Program Files\Microsoft Games\Solitaire\Solitaire.exe", "")
Endif
For i = 0 to 9
j=100-i*10
k=300+i*70
WinPlace(j,j,k,k,"Solitaire")
Next
WinZoom("Solitaire")
GoSub dumdedum
mins=AskLine("More Time?", "Enter additional minutes", 0, 0)
If mins!=0 then GoSub dumdedum
;;ADDED as an example of a while loop.
While WinExist("Solitaire")
WinClose("Solitaire")
;Make sure it closes
EndWhile
Message("Time's Up", "Get Back to Work!")
Exit
:dumdedum
goal = mins * 60
timer = 0
While timer < goal
remain = goal - timer
If WinExist("Solitaire")
59
WIL TUTORIAL
WinTitle("Solitaire", "Solitaire (%remain% seconds left)")
Else
exit
Endif
TimeDelay(10)
timer = timer + 10
EndWhile
Return
60
THINGS TO KNOW
THINGS TO KNOW
This section covers some miscellaneous items, of a more advanced nature.
If you've been having trouble with your WIL scripts, or have a question that's
not answered elsewhere, there's a pretty good chance we've answered it here.
Please reference the Windows Interface Language help file for the most current
documentation.
Recovering from Cancel
By default, if a user cancels out of a dialog, the label :CANCEL will be searched for
in the WIL program, and, if found, control will be transferred there. If no label
:CANCEL is found, processing simply stops. This allows the program developer to
perform various bits of cleanup processing after a user presses Cancel.
The function IntControl 72 lets you specify what should happen when the next
Cancel event occurs in the script. This allows the program developer to perform
cancel processing, if a user presses Cancel, in any dialog. When processing goes to
:CANCEL, the following WIL variables are automatically set:
Variable
Meaning
wberrorhandlerline
(s) Cancel line (i.e., line in script that caused Cancel)
wberrorhandleroffset
(i) offset into script of Cancel line, in bytes
wberrorhandlerassignment
(s) variable being assigned on Cancel line, or "" if
none
wberrorhandlerfile
wberrortextstring
wberroradditionalinfo
(s) name of the currently-executing script
(s) description of the WIL error
(s) delimited string of additional error information, if
any. ASCII 160 is delimiter character between each
error incident.
(s) name of the Currently-executing UDF, or a blank
string ("") if not in a UDF.
(i) line number in the currently executing script or 0 if
the cancel cannot be matched to a particular line.
(a) WIL array with the following elements:
wberrorarray[0] = LastError()
wberrorarray[1] = wberrorhandlerline
wberrorarray[2] = wberrorhandleroffset
wberrorarray[3] = wberrorhandlerassignment
wberrorinsegment
wberrorhandlerlinenumber
wberrorarray
61
THINGS TO KNOW
wberrorarray[4] = wberrorhandlerfile
wberrorarray[5] = wberrortextstring
wberrorarray[6] = wberroradditionalinfo
wberrorarray[7] = wberrorinsegment
wberrorarray[8] = wberrorhandlerlinenumber
wberrorarray[9] = line number in the UDF where the
cancel occurred or 0.
wberrorarray[10] = a positive number if reported line
numbers are accurate, zero (0) if possibly inaccurate
or -1 if run from WinBatch Studio, in which case both
wberrorarray[8] and wberrorarray[9] will contain the
line number of the cancel in the UDF.
wberrorarray[11] = used to set return value of the
function the cancel occurred on.
Note: The Windows operating system offers many alternatives, for canceling a
dialog: pressing the Cancel button, typing Esc, Alt-F4, and some others.
See the Basic Script Template for an example of trapping more than one :CANCEL
label.
Basic Script Template
Here is a suggested template of a script handling multiple cancels:
;TITLE:
;DATE:
;AUTHOR:
;VERSION:
;UPDATED:
;PURPOSE:
IntControl(72,2,0,0,0)
abc=Pause("Pause","one")
Message("ABC is",abc)
Exit
:CANCEL
%wberrorhandlerassignment% = 9999
IntControl(72,2,0,0,0)
return
Extenders: Networking, TCP/IP, Microsoft
WIL language extenders enhance Microsoft and TCP/IP networking. They are
among the most useful parts of the WIL language. Network connectivity, special
arithmetic operations, and other capabilities can be added to WIL with extenders.
Other extenders are often available on the web site: http://www.winbatch.com. They
62
THINGS TO KNOW
may be downloaded from there. The most widely used extenders are included on the
distribution CD-ROM.
Software developers who want to create custom extensions to the WIL language may
utilize a development kit called “WIL Extender SDK”. The actual extender must be
written as a DLL using C or C++.
Each individual extender has its own help file, that explains how to use the
functions in it. The example here, comes from the Win32 network extender. It
changes a password under Windows NT:
Syntax:
wntChgPswd(server/domain, user-name, old-password, new-password)
Parameters:
(s) server/domain either a server name (e.g., "\\MYSERVER") or domain name (e.g.,
"SALES") on which the password will be changed, or a blank string ("") for the
current user's login domain.
(s) user-name
the name of the user whose password will be changed, or a blank
string ("") for the current user's login name.
(s) old-password the user's password on "server/domain" or "*UNKNOWN*"(see
below).
(s) new-password the new password to be set or a blank string ("") to indicate no
password is desired.
Returns:
(i)
@TRUE if successful.
Old-password
wntChgPswd can be used to specify a new password without knowing the old
password, if you are a member of the Administrators or Account Operators local
group. To do this, specify "*UNKNOWN*" as the old password. In this case, the
"user" parameter must specify an actual user name (i.e., it cannot be a blank string).
Example:
AddExtender("wwwnt34i.dll")
old=AskPassword("Change Password","Enter old password")
while @TRUE
new1=AskPassword("Change Password","Enter new password")
new2=AskPassword("Change Password","Enter new password again")
if new1==new2 then break
Message("Try Again","The new passwords you entered do not match")
endwhile
rslt=wntChgPswd("", "", old, new1)
if rslt
Message("Password","Successfully changed")
else
Message("Password","Not changed")
63
THINGS TO KNOW
endif
Terminating WIL processing
A currently-executing WIL program can be terminated immediately by pressing the
<Ctrl-Break> key combination. You may need to hold it a second or two.
IntControl 12 can be used to suppress the ability of the user to terminate the batch
file. We suggest the batch file is completely debugged before doing this.
Carriage Return Line Feed
A commonly asked question is, "How do I get my long lines to wrap to the next
line?". One way, besides using the built in @CRLF and @TAB string constants is to
use the functions Num2Char or StrCat to accomplish this.
Example:
cr=Num2Char(13)
; 13 is a carriage-return
lf=Num2Char(10)
; 10 is a line feed
Message("", "This is line one %cr% %lf% This is line two")
or...
cr=Num2Char(13)
lf=Num2Char(10)
crlf=StrCat(cr, lf)
Message("", "This is line one %crlf% This is line two")
Note: @CRLF and @TAB are explained in more detail in the WIL Tutorial section
under the heading Nicer Messages. (pg. 55)
Extension Associations and the Run Functions
The Run function (and most of the related members of the Run... family of
functions) allow you to run a data file if it is associated with a program. They do not
support running programs with unknown extensions.
Debug
WIL has a handy debug utility which comes with the WIL Interpreter. DebugTrace,
a WIL function, is invaluable in determining logic errors. When DebugTrace is
initialized, a file is created which logs the execution of each statement. DebugTrace
works line by line through the script, logging the current statement and its return
value.
Initialize debug by adding DebugTrace(@ON,"trace.txt") to a specific point in
your script.
64
THINGS TO KNOW
Note: For specific instructions see DebugTrace, in the WIL Function Reference.
(pg. 215).
Internal Control Functions
WinBatch has several Internal Control functions, IntControl, which permit
numerous internal operations. If you are having trouble finding a specific command,
you may find a solution here. For example, IntControl 66, 67, 68 can log a user out,
perform a reboot, and shutdown windows. Check out the versatility of IntControl in
the WIL Function Reference. (pg. 398 )
Partial Window Names
When using partial window names as parameters, you can specify the full name if
you wish, but in most circumstances, it isn't necessary. Specify enough characters so
that "partial-windowname" matches only one existing window. If it matches more
than one window, the most recently accessed window which it matches will be
used. The windowname "" may be used as a shorthand way of referring to the WIL
parent application window. Remember that the case (upper or lower) of the title is
significant. If the case is not correct, a match will not be made.
There are a total of four distinct ways to define a partial window name. Decide
which option is best for your particular needs.
Window Name
A partial windowname can be the first few defining characters of a window title.
For example, WinShow("Notepad") would match any window whose title
begins with "Notepad".
Exact Match
Those WIL functions which take a partial windowname as a parameter can be
directed to accept only an exact match by ending the window name with a tilde
(~).
A tilde (~) used as the last character of the window name indicates that the name
must match the window title through to the end of the title. For example,
WinShow("Note~") would only match a window whose title was "Note"; it
would not match "Notepad".
Match Any Window
A tilde (~) used as the first character of the window name, will match any
window containing the specified string anywhere in its title. For example,
WinShow("~Notepad") will match a window title of "(Untitled) - Notepad" and
a window title of "My Notepad Application", as well as a window title of
"Notepad - (Untitled)".
65
THINGS TO KNOW
Window Name Ends With…
A tilde (~) used as the first and last character of the window name, will match any
window containing the specified string anywhere in its title, except at the
beginning. For example, WinShow("~Notepad~") will match a window title of
"Notepad" and a window title of "(Untitled) -Notepad", but will not match a
window title of "Notepad - (Untitled)".
System.ini and its device= lines
The "device=" lines in the System.ini cannot be edited using the normal IniWritePvt
function. See BinaryPokeStr (pg.166) for a complete example of how to write
"device=" lines into the System.ini.
Dividing Floating Point Numbers
This example might not work exactly how you think it will. If you take two integers,
for example, 32 and 37, and divide 32 by 37, you will not necessarily get a floating
point answer. This integer divide will result in an answer of 0. Add 0.0 to one of the
numbers to get a true floating point answer. Another way to deal with this
situation is to first declare floating point variables with statements like this: x=0.0
Example:
;Problem.wbt
a1= "An unexpected problem can occur when dividing numbers."
a2= "The problem is in deciding between an integer divide "
a3= "(where the remainder, if any, is discarded) and a floating "
a4= "point divide (where a floating point number is returned)."
a5= ""
a6= ""
a7= "Let's assume a test. There are 42 questions."
a8= "A student gets 37 of them correct,"
a9= "what is the student's score."
a10= " "
a11= "iQuestions = 42"
a12= "iCorrect = 37"
a13= "Score = iCorrect / iQuestions"
iQuestions = 42
iCorrect = 37
Score = iCorrect / iQuestions
a14= " "
a15= "The unexpected result is that the score is %Score%"
a16= "Reasonable problem? The trap is that WIL will perform an"
a17= "integer divide and return the unexpected answer of Zero."
a18= " "
a19= "To dig your code out of this trap, simply use floating point"
a20= "numbers when you want a floating point answer."
a21 = " "
66
THINGS TO KNOW
a22= "fQuestions = 42.0"
a23= "fCorrect = 37.0"
fQuestions = 42.0
fCorrect = 37.0
Score = fCorrect / fQuestions
a24= "Score = fCorrect / fQuestions"
a25= "The correct score is %Score%"
a26= " "
a27= "Or make the answer look nicer by using the Decimals function"
a28= "and a little formatting."
a29= ""
a30= "Decimals(0)
a31= "Score=Score*100"
Decimals(0)
Score=Score*100
a32= ""
;;;;;;;;use two %'s to get a single % ;;;;;;;;;;;
a33= "The correct score is %Score%%%"
text=""
for i=1 to 15
text=strcat(text,a%i%,@crlf)
next
text2=""
for i=16 to 33
text2=strcat(text2,a%i%,@crlf)
next
Message("Integer Divide Problem",text)
Message("Floating point solution",text2)
File Delimiters
The default file delimiter, used to delimit lists of files and directories, is a TAB.
The following functions, which take file or directory lists as input parameters, expect
the lists to be delimited by the current file delimiter character. However, they also
accept lists delimited with a vertical bar ("|"), which may be easier to code in a WIL
script:
DiskFree
DirItemize
DirRemove
DiskScan
FileAppend
FileAttrSet
FileCopy
FileDelete
67
THINGS TO KNOW
FileItemize
FileMove
FileRename
FileSize
FileSizeEx
FileTimeSet
FileTimeTouch
Note: DiskFree and DiskSize continue to accept space-delimited lists as input.
OLE / COM
The ability to control and assist the movement of data between applications is one of
the key strengths of WIL. There many ways to share data between applications:
using the Clipboard, dynamic data exchange (DDE), Control Manager functions,
SendKey functions and COM.
Now, with support for COM, you can do much more than share data. From within
your WIL script, you can access and manipulate COM objects that are supplied by
other applications. With COM Automation, you can use WIL to produce custom
solutions that utilize data and features from applications that support COM
Automation.
What Is COM Automation?
COM Automation is an industry standard that applications use to expose their COM
objects to development tools, macro languages, and container applications that
support COM Automation.
For example, a spreadsheet application may expose a worksheet, chart, cell, or range
of cells -- all as different types of objects. A word processor might expose objects
such as applications, paragraphs, sentences. bookmarks, or selections.
When an application supports COM Automation, the objects it exposes can be
accessed by WIL. You use WIL scripts to manipulate these objects by invoking
methods (subroutines) on the objects, or by getting and setting the objects' properties
(values).
Accessing COM Objects
You can manipulate other applications' COM objects directly by first opening the
object with the ObjectGet and ObjectCreate functions.
ObjectCreate vs. ObjectGet: What's the Difference?
Besides minor differences in the syntax, the ObjectCreate and ObjectGet functions
are used in different contexts. The differences can be summarized as follows:
п‚·
68
ObjectCreate is used to create an interface to a new instance of an application.
Use ObjectCreate when it's not certain whether the application to integrate is
THINGS TO KNOW
running. For example:
objxl = ObjectCreate ("Excel.Application")
starts Microsoft Excel. The object returned to the variable 'objxl' is a reference
to the Excel.Application object just created. In other words, an object handle.
п‚·
ObjectGet is used with an application that's already running, or to start an
application with a file already loaded. For example:
objxlbook = ObjectGet ("C:\TEST.XLS")
would start Microsoft Excel with the file 'Test.xls' already loaded. The object
returned to the variable 'objxlbook' would be a reference to the Workbook object
representing the just opened 'Test.xls' file.
The ObjectCreate function is used to open the object. This function accepts a string
(ProgId) that indicates the application name and the type of object you want to
create. Use the following syntax to specify an object to create:
Application.ObjectType
For example, let's say there is a orgchart application named ORGCHART.EXE that
supports a single object: an orgchart. Furthermore, the OrgChart object supports two
sub-objects: a box and a line. The object might be defined as:
OrgChart.Chart
Once you know the type of object you want to create, you use the ObjectCreate
function to create the object. Capture the value returned by the ObjectCreate
function to a variable. Here's an example:
objchart = ObjectCreate("OrgChart.Chart")
Once you have the primary object in hand - in the 'objchart' variable in this case, you
can create the sub-objects and assign them to their own variables.
objtopbox = objchart.NewBox
objbottombox = objchart.NewBox
objline = objchart.NewLine
When this code executes, the application providing the object is started (if it is not
already running) and an object is created. The object belongs to the application that
created it. This object can be referenced using the variable you placed the return
value of the ObjectCreate function. For example, after creating the object, you
could write code to open sub-objects, change the background color, set a default
font, set a title, and save the object to a file:
objchart.Color = "White"
objchart.FontName = "Arial"
objchart.FontSize = 12
69
THINGS TO KNOW
objchart.Title = "Deana’s Org Chart"
objtopbox.Position(2,2)
objtopbox.Text = "The Boss"
objbottombox.Position(2,8)
objbottombox.Text = "Deana"
objline.Begin(2,2)
objline.End(2,8)
objchart.SaveAs("C:\ORGCHART\DEANA.ORG")
When creating an object, some applications require that the application providing the
object is either active or on the system's path.
When you are through with an object, set the object equal to a null string ("") or to 0
(zero) to tell the WIL processor that you are done with the object.
objline = ""
objtopbox = ""
objbottombox = ""
objchart = ""
To get a list of objects that an application supports, you must consult that
application's documentation. It may also help to poke around in the Windows
registry. For example check out the HKEY_CLASSES_ROOT key. Be aware,
though, that intentional, unintentional, or accidental changes to the registry may
completely destroy a Windows installation and require a complete re-installation of
ALL your software to recover.
Accessing an Object's Properties
To assign a value to a property of an object, put the object variable and property
name on the left side of an equation and the desired property setting on the right side.
For example:
objchart.Title = "Deana’s Org Chart"
You can also retrieve property values from an object:
TheTitle = objchart.Title
Performing Object Methods
In addition to getting and setting properties, you can manipulate an object using the
methods it supports. Some methods may return a value. Methods that do not return a
value, return 0.
objchart.Position(2,2)
objline.End(2,8)
objchart.SaveAs("C:\ORGCHART\DEANA.ORG")
rslt = objchart.Print( )
If rslt == @FALSE
Message("Error", "Print failed")
endif
70
THINGS TO KNOW
Dealing with Sub-Objects
Some objects contain sub-objects. For example, a box is a sub-object of an orgchart
object. Note: You can include multiple objects, properties and methods on the same
line of code. For example:
objtopbox = objchart.NewBox
Or
objsubbox = objchart.NewBox.SubBox
Collections
A collection represents a set of objects. There are several different ways you can
loop through the elements of a collection. However, the recommended method is to
use the ForEach...Next loop. In this structure, WinBatch repeats a block of
statements for each object in a collection. The following example displays the name
of each worksheet in the WorkSheets collection.
ForEach objWorkSheet In ObjExcel.WorkSheets
Message("WorkSheet Name", objWorkSheet.Name)
Next
Another way to loop through the elements of a collection is to use the Item property
or method and pass the name or index number of the member as the index argument.
For example, in Excel, the following expression returns a reference to an open
workbook by passing its name "Sales.xls" to the Item property and then invokes the
Close method to close it:
objworkbooks.Item("Sales.xls").Close
The Item property or method is the default for most collections.
objworkbooks.Item("Sales.xls")
To reference items in a collection by using an index number, simply pass the number
of the item to the Item property or method of the collection. For example, if Sales.xls
is the second workbook in the Workbooks collection, the following expression will
return a reference to it:
objWorkbooks.Item(2)
Closing an Object
All COM Automation objects support some method that closes the object and the
application that created it. Since COM objects can use a significant amount of
memory, it is a good idea to explicitly close an object when you no longer need it. To
close an object, use the appropriate method (most objects support the Close method
or the Quit method). For example:
;Closes the object.
objchart.Close
;Closes the application that created the object.
71
THINGS TO KNOW
objchart.Quit
When WIL processing for an object is complete, set the object variable to a null
string or 0 (zero) to free WIL processor memory.
objchart = ""
or
objchart = 0
Omitted Optional Positional Parameters
COM functions support 'omitted optional positional parameters', using commas as
placeholders. 'Required parameters' are those that must always be specified.
'Optional parameters' are those that can be skipped using a comma as a placeholder
(when using positional parameters), or simply omitted (when using named
parameters).
For example:
objapp.Display("Hello", 100, 100, , 1)
Named Parameters
COM functions support 'named parameters'. The syntax structure is:
Object.Method(p1, p2 :: n3 = v3, n4 = v4)
Positional Parameters
Positional parameters (shown above as p1 and p2), if any, come first, followed by a
double colon ("::"), and then any named parameters (n3 and n4). Each named
parameter is followed by an equals sign ("=") and then the value for the parameter
(v3 and v4). Whitespace is ignored. Here are some examples:
; 2 positional parameters
objapp.InputBox("My Prompt", "My Title")
; 2 positional parameters and 2 named parameters
objapp.InputBox("My Prompt", "My Title" :: Left = 40, Top = 300)
; no positional parameters and 2 named parameters
;(note the leading colon)
objapp.InputBox(:: Prompt = "My Prompt", Title = "My Title")
COM Types
COM functions allow you to specify a data type for parameters. Normally, when you
specify an value as a parameter to a COM function, WIL passes it as a type VT_I4
(4-byte integer value). If the COM application was expecting the parameter to be a
different type of value, in most cases it will automatically convert it to the desired
type. However, there are some COM applications which don't do this, and return an
error instead.
72
THINGS TO KNOW
In such cases, you can first specify the type using the function ObjectType. Or you
can specify the type, using the following syntax:
Object.Method(p1, type:p2 :: name = value, type:name = value)
The parameter type (shown as 'type') is followed by a single colon (":"), and then the
parameter itself. This can be done for both positional parameters and named
parameters. Whitespace is ignored, and the type names are not case-sensitive.
Types which may be specified:
Type
UI1
UI2
UI4
UI8
I1
I2
I4
I8
BOOL
DATE
DECIMAL
Name
VT_UI1
VT_UI2
VT_UI4
VT_UI8
VT_I1
VT_I2
VT_I4
VT_I8
VT_BOOL
VT_DATE
VT_DECIMAL
CURRENCY
VT_CY
NULL
DISPATCH
VT_NULL
VT_DISPATCH
Meaning
An unsigned 1-byte integer.
An unsigned 2-byte integer.
An unsigned 4-byte integer.
An unsigned 8-byte integer.
A 1-byte integer value.
A 2-byte integer value.
A 4-byte integer value.
A 8-byte integer value.
A Boolean (True/False) value.
A date/time string, in Ymd or YmdHms format.
A decimal value, specified as a string in the form
"#DECIMAL:value".
A currency value, specified as a string in the
form "#CURRENCY:value".
A blank string ("").
A pointer to an object was specified. This object
is known only to implement IDispatch.
Note: The default type for integer values is "I4" (VT_I4).
Here are some examples:
; this function requires a parameter of type VT_I2
objapp.CreateImageViewerObject(I2:1)
; this function requires a (named) parameter of type VT_DATE
objapp.CreateLog("access.log" :: DATE:startdate="97:11:01")
Byte Arrays
COM methods or properties that return byte arrays (variant type = VT_UI1 |
VT_ARRAY), by default will return as WIL array.
73
THINGS TO KNOW
COM 2.0 Limitations in WIL
Some COM objects support features that can't be accessed using WIL. This section
discusses known limitations.
COM method and property names are limited to 256 characters in length.
dotNet
WinBatch supports access to the Microsoft dotNet Framework. WinBatch makes this
possible by hosting the common language runtime (CLR) and exposing functionality
for creating and accessing the members of classes, structures and enumerations of
managed code assemblies (DLLs) that are part of or based on the Framework.
The WinBatch CLR hosting environment works by wrapping Framework based
classes, structures and enumerations in light weight COM Automation objects to take
advantage of the WinBatch interpreter's existing understanding of COM syntax and
semantics. This approach lessens the challenge of using managed objects in
WinBatch script for those already familiar with COM Automation. However, it is
still recommended that you have a basic understanding of object oriented
programming concepts as used by the Framework. It is also important to carefully
read and understand the documentation for a Framework based type before using it
in a WinBatch script.
WinBatch access to the Framework uses COM but it is not completely dependent on
the Framework's COM interop. This is because the WinBatch directly hosts the CLR.
The hybrid approach offers significant advantages over a COM interop only
implementation.
First, assemblies do not need to be registered in the Windows registry to be accessed.
Second, whole classes, class methods and class properties do not need to be
attributed as COM visible to be accessed through WinBatch. Third, WinBatch CLR
hosting is not tied to a specific Framework Class Library (FCL) or CLR version.
WinBatch only requires that the Framework be installed on the system.
ObjectClrNew creates a class, structure or enumeration implemented by a managed
assembly. The function returns a Framework based type as a COM Automation
reference that can be used to access the members of the underlying Framework based
type. The assembly implementing the type specified by 'typename' must be loaded
into the WinBatch process before this function can be called to create the type. The
exceptions to this requirement are types implemented by the "mscorlib" assembly.
This assembly is automatically loaded by WinBatch when the CLR is loaded. All
other assemblies must be loaded into the WinBatch process using the
ObjectClrOption function's Use option.
The Typename passed to ObjectClrNew must be fully qualified by including the dot
(.) separated namespace prefixed to the type's immediate name. The namespace name
and immediate name must also be separated by a dot character. Ctorparm is the
74
THINGS TO KNOW
constructor parameters to be used when creating a type. Since type constructors can
be overloaded, the type and number of these parameters control which constructor
will be used to create the type.
Members of the returned object reference are called using the same variablename+dot+member-name syntax used by standard COM Automation object
references. However, there are some important differences between regular COM
calls and CLR type member calls. The most significant difference is that CLR
constructors and type member names can be overloaded. This means that more than
one member can have the same name. When more than one member has the same
name, WinBatch and the CLR determine which member to call based on the number
and type of the parameters passed in the call statement. The combination of member
name, parameter types and parameter count is called the member's signature. This
means that using the correct type for each parameter is crucial to calling the correct
member.
Both member overloading and the fact that WinBatch cannot query the object for
type information before making a member call as it does with regular COM
Automation references mean that the colon (:) type qualifier needs to be used more
frequently on CLR object member parameters. Fortunately, WinBatch will take
standard variant type names like BSTR, UI8, BOOLEAN, R8, e.g., and convert them
to equivalent Framework types automatically. It will also automatically deduce the
correct Framework type for variant variables passed as parameters to a member
without needing to specify a type with the colon qualifier.
When a Framework based type does not have equivalent variant type, the fully
qualified Framework based type name can be used with colon type qualifier on a
parameter. This is most often necessary when the object member is expecting an upcast or down-cast of Framework based class, when it is expecting a value from a
Framework based enumeration, or when it is expecting an array with elements of a
specific Framework based type.
In the case of arrays, the type qualifier should be the Framework based type of the
elements prefixed to the variable name of a variable that holds either a WIL array or
a variant safearray. No array type information ('ARRAY' or 'System.Array') should
be included in the type qualifier. When using a Framework type name qualifier with
any parameter the type qualifier's assembly must be loaded before the member with
the qualified parameter is called.
Another significant difference between standard COM Automation object and
Framework based wrapped objects is that unlike standard COM Automation objects,
Framework based object member names are case sensitive.
ObjectClrOption sets CLR configuration options before the CLR is loaded and
loads an assembly into the current WinBatch process. Available options are Version,
Appbase or Use.
75
THINGS TO KNOW
Version is used to instruct WinBatch to load a specific version of the CLR. The
option-value parameter string must start with the character "v" followed by the first
three parts of the version number. Currently, Microsoft provides the following CLR
versions "v1.0.3705", "v1.1.4322", "v2.0.50727" and "v4.0.30319". The option must
be set before the first call to ObjectClrOption with the Use option or before the first
call to the ObjectClrNew function. If the Version option is not used before the CLR
is loaded, WinBatch will attempt to load the current system's latest installed version
of the CLR.
Appbase is used to indicate the full file system path that presents the location of
assemblies you plan on using in your script that are not installed into the global
assembly cache (GAC) of the system running the script. This option must be set
before the first call to ObjectClrOption setting a Use option or before the first call
to the ObjectClrNew function.
Use is used to load assemblies into the WinBatch process. Assemblies must be
loaded before the types the assembly implements can be used. The option-value
parameter for the option must be a string variable or literal containing an assembly
name.
If an assembly is stored in the Global Assembly Cache (GAC), it is generally
necessary to use the fully qualified assembly name. The fully qualified assembly
name has the format:
"assembly's name, version=x.x.x.x, culture=xxxx,
PublickeyToken=xxxxxxxxxxxxxxxx".
For example, the fully qualified name of the "System.Data" assembly is
"System.Data, version=1.0.3300.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089"
Full assembly names can be found by using the Mscorcfg.msc tool, by viewing the
global assembly cache directory directly, or by using the Gacutil.exe tool.
ObjectClrType is used to either associate a Framework based type name with a
value, or to up-cast or down-cast Framework based object references. If the second
parameter is a simple string, integer, float, variant that is not a reference to a
Framework based object, the returned reference can only be used as a parameter to a
Framework based object method call, as the right-hand side of a Framework based
object property assignment or a constructor argument in a call to ObjectClrNew. In
other words, the returned reference does not have user callable methods, properties
or fields. On the other hand, if the second parameter is a reference to a Framework
based object and the first parameter is the typename of a base or derived type of that
object then the returned reference can be used to access the members of either the
base or derived type of the input object.
Typename is the name of a Framework based class, structure or enumeration. The
name must be fully qualified by including the dot (.) separated namespace prefixed
76
THINGS TO KNOW
to the type's immediate name. The namespace name and immediate name must also
be separated by a dot character.
Value-reference is value or Framework based object reference to associate with
Typename. If it does not contain a Framework based object reference, the assembly
implementing typename must be loaded before the return reference is used as a
method parameter, property value or constructor argument. If it contains a
Framework based object reference, the assembly implementing typename must be
loaded before ObjectClrType is called.
dotNet Limitations in WIL
While WinBatch CLR hosting has many advantages, it has limitations that should be
considered before deciding whether or not to implement a solution using Framework
based assemblies. The following is a partial listing of those limitations:
п‚·
п‚·
п‚·
п‚·
п‚·
Delegates and event callbacks are not supported. (This limits the
effectiveness of UI related classes.)
Generics can only be used when pre-instantiated with appropriate type
parameters by another CLR object.
Remote access to an assembly running in another process is not supported.
WinBatch scripts cannot be compiled into CLR applications or assemblies.
Framework based object member names are case sensitive.
ObjectClrNew Limitations:
п‚·
п‚·
п‚·
п‚·
п‚·
п‚·
п‚·
WinBatch relies on the CLR hosting's reflection functionality to instantiate
classes.
There are a few classes attributed to block instantiation via reflection.
WinBatch does not support out parameters. Method without parameters can
still be called but out parameter values are not modified on the method's
return.
Class member overloads that rely solely on the return type and name for
their signature cannot be used.
Value types (structures) that only provide a multiple parameter
constructor(s) cannot be used.
A small number of type member names conflict with WinBatch identifier
naming rules and cannot be called directly.
Parameterize properties are not supported.
77
WIL LANGUAGE
WIL LANGUAGE
Language Components
A program written in Windows Interface Language (WIL) consists of a series of
statements. WIL statements are constructed from constants, variables, operators,
functions, commands, and comments.
In addition, WIL scripts can take advantage of advanced techniques such as
substitution, passing parameters, and error handling.
Note: Each line in a WIL program can be up to 2048 characters long.
Constants
Windows Interface Language (WIL) supports three types of constants: floating point,
integer and string constants. In addition, there is an extensive list of predefined
constants to make your scripts easier to read.
Floating Point Constants
Floating Point constants are built from the digits 0 through 9, the plus and minus
signs, a period �.’ and the letter �E’. They can range in magnitude from negative to
positive 1.0E+300 (a very large number). Constants larger than these permissible
magnitudes will produce unpredictable errors. Floating point constants must begin
with a digit.
Examples of floating point constants:
3.14159
-8.92E-45
0.0001724
8.95e294
Integer Constants
Integer constants are built from the digits 0 through 9. They can range in magnitude
from negative to positive 231 - 1 (approximately two billion). Constants larger than
these permissible magnitudes will produce unpredictable results.
64-bit: WinBatch does not currently support 8 byte ( 64-bit ) integers.
Examples of integer constants:
1
-45
79
WIL LANGUAGE
377849
-1999999999
String Constants
String constants are comprised of displayable characters bounded by quote marks.
You can use double quotes ("), single quotes ('), or back quotes (`) to enclose a
string constant, as long as the same type of quote is used to both start and end it.
Examples of string constants:
"a"
'Betty Boop'
`Look at these backquotes`
NOTE: If you need to embed a quote mark inside the string constant, use a different
type of quote mark to delimit the string.
'This constant has an embedded "quote" mark'
If you need to embed the delimiting quote mark inside the string constant, use the
delimiting quote mark twice.
"This constant has an embedded ""quote"" mark"
Predefined Constants
WIL has a number of built-in constants that can be used for various purposes,
including making your scripts easier to read. These start with the @-sign, and are not
case-sensitive.
Some predefined constants:
@FALSE
@NO
@STACK
@TRUE
@YES
@TILE
A list of all the predefined constants can be found in the Appendix (pg. 655).
Identifiers
Identifiers are the names supplied for variables, functions, and commands in your
program. An identifier is a sequence of one or more letters or digits that begins with
a letter. Identifiers may have up to 30 characters.
All identifiers are case insensitive. Upper-case and lower-case characters may be
mixed at will inside variable names, commands or functions.
For example, these statements all mean the same thing:
80
WIL LANGUAGE
AskLine(MyTitle, Prompt, Default, 0)
ASKLINE(MYTITLE, PROMPT, DEFAULT, 0)
aSkLiNe(MyTiTlE, pRoMpT, dEfAuLt, 0)
Variables
A variable may contain an integer, a floating point number, a string, a list, an array,
object reference or a string representing an integer or a floating point number.
Automatic conversions between numbers and strings are performed as a matter of
course during execution.
If a function requires a string parameter and a numeric parameter is supplied, the
variable will be automatically modified to include the representative string.
If a function requires a numeric parameter and a string parameter is supplied, an
attempt will be made to convert the string to the required numeric parameter. If it
does not convert successfully, an error will result.
Arrays are created using the function ArrDimension.
Variable Substitution
The WIL language has a powerful substitution feature which inserts the contents of a
string variable into a statement before the line is parsed. However, substitution
should be used with caution.
In general, do not use variable substitution. Many problems can be created,
simply by using variable substitution. For example, if you have a large string
variable, and you attempt variable substitution, you will receive an error that the line
is too long. This occurs because the contents of the string variable are substituted
into the line before the line gets executed. No single line can exceed 2048 characters.
It is a better idea, to build a string variable using the function StrCat or the ' :'
operator.
Example:
MyName="George"
NewStr=StrCat("Hello, My name is: ", MyName)
Message("Name Tag",NewStr)
Or
MyName="George"
NewStr= "Hello, My name is " : MyName
Message("Name Tag",NewStr)
If it is absolutely necessary to substitute the contents of a variable in the statement,
simply put a percent-sign (%) on both sides of the variable name.
81
WIL LANGUAGE
Example:
mycmd = "DirChange('c:\')" ;set mycmd to a command
%mycmd%
;execute the command
Or consider this one:
IniWrite("PC", "User", "Richard")
name = IniRead("PC", "User", "somebody")
message("", "Thank you, %name%")
will produce this message box:
To put a single percent-sign (%) on a source line, specify a double percent
sign(%%). This is required even inside quoted strings.
Note: The length of a line, after any substitution occurs, may not exceed 2048
characters.
If you choose to put a comment at the end of a line, that includes a percent sign, you
must specify %%.
percent = value * 0.5 ; 50%% of value is
Lists Explained
A list is a string variable which itself contains one or more strings, each of which
is delimited (separated) by a common character. For example, both FileItemize
and WinItemize functions return a list of window names, delimited by tabs. In
order to use functions which accept a list as a parameter, such as AskItemList,
you will need to know what character is being used to delimit the list.
In order to support long file names, which can contain embedded spaces, the
default file delimiter used to delimit lists of files and directories is a TAB. To
change the file delimiter to a character of your own choosing, use IntControl
(29,p1,0,0,0).
82
WIL LANGUAGE
Notes: Single item null lists ("") are not a valid list, therefore many of the
following functions will have no affect. However, if you pass a null string to
ItemInsert, it will insert a value.
Trailing delimiters are significant. This means that the comma-delimited list
"a,b,c," has 4 items in it.
Functions that accept an 'index' allow you to specify -1 to represent the last item in
the list.
If the function is passed a Unicode list then it will return a Unicode list.
Here are a few functions designed to deal with 'lists'.
ItemCount ( list, delimiter )
Returns the number of items in a list.
ItemCountCsv ( line, flags [, delimiter] )
Returns the number of items in a CSV line.
ItemExtract ( index, list, delimiter )
Returns the selected item from a list.
ItemExtractCsv ( index, line, flags [, delimiter] )
Returns the selected item from a CSV line.
ItemInsert ( item, index, list, delimiter )
Adds an item to a list.
ItemLocate ( item, list, delimiter )
Returns the position of an item in a list.
ItemLocateWild ( pattern, list, delimiter, start )
Searches for an item in that list that fully matches a pattern.
ItemRemove ( index, list, delimiter )
Removes an item from a list.
ItemReplace ( item, index, list, delimiter)
Replaces an item in a list.
ItemSort ( list, delimiter )
Sorts a list.
Keywords
Keywords are the predefined identifiers that have special meaning to the
programming language. These cannot be used as variable names.
WIL keywords consist of the functions, commands, and predefined constants.
Some examples of reserved keywords:
83
WIL LANGUAGE
Beep
DirChange
@Yes
FileCopy
Operators
Windows Interface Language operators take one operand ("unary operators") or two
operands ("binary operators").
Unary operators (integers and floating point numbers)
Arithmetic Negation (Two's complement)
+
Identity (Unary plus)
Unary operators (integers only)
~
Bitwise Not. Changes each 0 bit to 1, and vice-versa.
!
Logical Not. Produces 0 (@FALSE) if the operand is
nonzero, else 1 (@TRUE) if the operand is zero.
Unary operators (variable reference)
&
Creates a pointer.
*
References variable via a pointer.
Binary logical operators (integers only)
<<
Left Shift
>>
Right Shift
&
Bitwise And
|
Bitwise Or
^
Bitwise Exclusive Or (XOR)
&&
Logical And
||
Logical Or
Binary arithmetic operators (integers and floating point numbers)
**
Exponentiation
*
Multiplication
/
Division
mod
Modulo
+
Addition
Subtraction
Binary string operators
:
Concatenation
Binary relational operators
>
Greater-than
>=
Greater-than or equal
<
Less-than
<=
Less-than or equal
84
WIL LANGUAGE
==
!= or <>
Equality
Inequality
Assignment operator
=
Assigns evaluated result of an expression to a variable.
Binary compound assignment operators
<<=
Left Shift with Assignment.
>>=
Right Shift with Assignment.
&=
Bitwise AND with Assignment.
|=
Bitwise OR with Assignment.
^=
Bitwise Exclusive with Assignment.
*=
Multiplication with Assignment.
/=
Division with Assignment.
+=
Addition with Assignment.
-=
Subtraction with Assignment.
:=
String Concatenation with Assignment.
mod=
Modulo with Assignment.
Precedence and Evaluation Order
The precedence of the operators affect the evaluation of operands in expressions.
Operands associated with higher-precedence operators are evaluated before the
lower-precedence operators. The table below shows the precedence of the operators.
Where operators have the same precedence, they are evaluated from left to right.
Operator
Description
( )
Parenthetical grouping
& *
Unary pointer operators
~ ! - +
Unary operators
**
Exponentiation
* / mod
Multiplication, Division & Modulo
+ -
Addition & Subtraction
<<
>>
Shift operators
:
Concatenation
< <= == >= > != <>
Relational operators
& ^ |
Bit manipulation operators
85
WIL LANGUAGE
&& ||
Logical operator
= <<= >>= &= |= ^=
Assignment operator and
*= /= += -= := mod=
Binary compound assignment operators
Comments
A comment is a sequence of characters that are ignored when processing a
command. A semi-colon (not otherwise part of a "string constant") indicates the
beginning of a comment. All characters to the right of the semi-colon are considered
comments, and are ignored. Except for percent-signs (%). If you choose to put a
comment at the end of a line, that includes a percent sign, you must specify %%.
Blank lines are also ignored.
Examples of comments:
; This is a comment
abc = 5
; This is also a comment
Assignment Statements
Assignment statements are used to set variables to specific or computed values.
Variables may be set to integers or strings or floating point numbers.
Examples:
a = 5
value = Average(a, 10, 15)
location = "Northern Hemisphere"
world = StrCat(location, " ", "Southern Hemisphere")
Control Statements
Control statements are generally used to execute system management functions and
consist of a call to a command without assigning any return values.
Examples:
Exit
Yield
Break
If
While
Switch
Select
Else
For
EndSwitch
EndSelect
ElseIf
ForEach
Continue
Return
Then
Beep
Next
Goto
EndIf
Case
Endwhile
GoSub
Function Parameters
Most of the functions and commands in the language require parameters. These
come in several types:
Array
Integer
Floating point number
86
WIL LANGUAGE
Huge number
String
List
Variable name
The interpreter performs automatic conversions between strings, integers and
floating point numbers, so that you can use them interchangeably. In general, the
only case to be careful of is comparing two floating point numbers -- floating point
numbers have a habit of never being quite equal when you want them to.
Integer parameters may be any of the following:
An integer (i.e. 23)
A string representing an integer (i.e. "23")
A variable containing an integer
A variable containing a string representing an integer
Floating point parameters may be any of the following:
A floating point number (i.e. 3.141569)
A string representing an integer (i.e. "314.1569E-2")
A variable containing a floating point number
A variable containing a string representing a floating point number
Huge number parameters:
A huge number is a long decimal number string, which may represent a number
too large to be converted to an integer.
String parameters may be any of the following:
A string
An integer
A variable containing a string
A variable containing a list
A variable containing an integer
A variable containing a floating point number
User Defined Functions
WIL support's User-Defined-Functions (UDF's). There are two types of UserDefined-Functions (UDF's):
п‚·
#DefineFunction UDF's, variables are local to the UDF
п‚·
#DefineSubroutine UDF's, variables are global, to the caller.
A #DefineFunction UDF is defined as follows:
87
WIL LANGUAGE
#DefineFunction functname(param1, param2, param3, param4,…param16)
<code>
Return retval
#EndFunction
"#DefineFunction" and "#EndFunction" are the keywords indicating the beginning
and end of the UDF.
"functname" is a placeholder for the name of the function. The function name must
begin with a letter, can contain letters, numbers, and underscores, and can be up to
30 characters long. You may not use a function name that is the same as the name of
a WIL DLL function, but you may override a function name that's in an extender
DLL.
You may specify up to 16 optional parameters. "param1" - "param16" are
placeholders for your actual variable names. These are the names of the variables
that your UDF will receive when it is called.
Between the "#DefineFunction" and "#EndFunction" keywords is the code that
will get executed when the UDF is called. It may contain a Return command
followed by a value (or an expression that evaluates to a value), in which case the
UDF will end and return this value. If you specify a Return command without a
value, the UDF will return 0.
If a UDF does not contain a Return command, it will execute to the end of the UDF
and return 0. An Exit command in a UDF will cause the entire script to end, not just
the UDF.
A UDF may be defined anywhere in a script, as long as it is defined prior to being
used for the first time. A UDF may be defined or used in a separate script that is
called with the Call command, as long as it is defined before it is used. You may not
have nested UDF definitions (i.e., each "#DefineFunction" must be followed by an
"#EndFunction" as a pair).
A #DefineFunction UDF will not have access to any variables in the main WIL
script, other than the variables passed as param1 - param16. Any variables set in a
UDF will be destroyed when the UDF returns, other than the return value of the
UDF. Any percent signs in the UDF code will be expanded at runtime (when the
code is called), not at define time.
You may return a file handle or binary buffer or COM/OLE object from a UDF using
the Return command. However, if you open one of these types of handles in your
UDF and do not return it using the Return command, you are responsible for freeing
it before the UDF returns, using the appropriate WIL function (i.e., FileClose or
BinaryFree or ObjectClose); otherwise, the object represented by the handle will
become an "orphan" and will no longer be accessible and may not be automatically
freed when the script exits.
88
WIL LANGUAGE
Example:
; Define three UDF's
#DefineFunction Done()
Message("All done", "Script processing is complete")
#EndFunction
#DefineFunction Square(number)
Return (number * number)
#EndFunction
#DefineFunction AddListItem(list, newitem, delimiter)
list = ItemInsert(newitem, -1, list, delimiter)
list = ItemSort(list, delimiter)
Return list
#EndFunction
; Now use them
list = "apples,bananas,peaches"
list = AddListItem(list, "cherries", ",")
Message("New list", list)
Message("The square of 5 is", Square(5))
Done()
Exit
See Also:
Call, Return
A #DefineSubroutine UDF is defined as follows:
#DefineSubRoutine functname(param1, param2, param3, param4,…param16)
<code>
Return retval
#EndSubRoutine
The #DefineSubroutine UDF is similar, in most respects, to the #DefineFunction
UDF, except that the variables are global to the calling routine. This means that it
will be able to access and change variables in the calling routine, and any variables it
sets will not be destroyed when it returns.
WARNING: Use at your own risk. The variables used within the
#DefineSubroutine have 'caller' scope, which means the variables are shared with
the calling routine. We suggest using a special naming convention on the variables
inside the #DefineSubroutine. The Drop and DropWild functions, can be used to
dispose of any unwanted variables at the end of the routine.
UDF/ UDS Special Notes:
п‚·
Maximum number of UDF's allowed is 512
п‚·
If you call GoSub from within a User-Defined-Function, the 'label' must
be defined within the User-Defined-Function
89
WIL LANGUAGE
п‚·
If you want to debug the User-Defined-Function, then the debug function
(Debug or Debugtrace), must be defined within the User-DefinedFunction
To include cancel/error handling in a User-Defined-Function, then IntControl 72 /
IntControl 73 must either:
1) Be defined within the User-Defined-Function. The :CANCEL /
:WBERRORHANDLER label must also be contained within the User-DefinedFunction
2) Or p1 must be the value of 3 and p2 must specify the name of the cancel / error
handler UDF.
Example:
#DefineSubRoutine LogErrors(loc_ErrNum)
lastlogtime = TimeYMDHMS()
loc_fh = FileOpen("Errorlog.txt","APPEND")
loc_text="Error":@TAB:loc_ErrNum:": ":Err%loc_ErrNum%:@TAB:"occured
at ":lastlogtime
FileWrite(loc_fh, loc_text)
FileClose(loc_fh)
DropWild("loc_*")
Return lastlogtime
#EndSubRoutine
;Error String Constants
Err1008 = "FileCopy: Failed"
Err1009 = "FileCopy: FROM file open failed"
Err1010 = "FileCopy: TO file open failed"
Err1011 = "FileCopy: I/O error"
starttime = TimeYMDHMS()
ErrorMode(@off)
ret=FileCopy("C:\zipideedodah.txt","C:\tmp\zipideedodah.txt",@FALSE)
ErrorMode(@cancel)
errtime = LogErrors(LastError())
Message("Last error logged at",errtime)
Arrays
Arrays are created using the new ArrDimension function. An array may have from
1 to 5 dimensions, and Arrays can now contain at least 10 million total elements,
although this may be constrained by available memory. Array elements are
referenced with their subscripts enclosed in square brackets. If an array has more
than one dimension, the subscripts are separated with commas.
arrayvar[1]
arrayvar[1, 1]
arrayvar[0, 5, 2]
90
WIL LANGUAGE
Array subscripts are 0-based. Therefore, the first element in an array is array[0].
Array elements can contain any type of WIL value: string, integer, float, etc. You
can have different types of values within an array.
You may not pass an array as a parameter to a WIL function (except for functions
which state they accept an array), or use it in any sort of operation.
For example:
Message("Value is", arrayvar) ; NOT legal
On the other hand, the following are all supported:
arrayvar[0] = 5
x = arrayvar[0]
Message("Value is", arrayvar[0])
arrayvar = 5 ; Redefines the array to integer type variable
x = arrayvar ; Creates a second variable that points to the array
You can pass arrays to User-Defined-Functions, and you can return arrays with the
Return command.
When you pass an array name (i.e., not an array element) as a parameter to a
function, the array gets passed "by reference". That is, the function receives a
pointer to the array, and is therefore able to make changes to it "in place". This is
similar to passing a binary buffer handle to a function, where the function is then
able to make wholesale changes to the binary buffer.
In contrast, passing an array element (i.e., with a subscript) to a function is like
passing a regular string or integer parameter to a function -- it gets passed "by value".
i.e., the function receives the value of the array element, but is not able to modify the
array itself. By the same token, when you pass a string to a function like StrUpper:
newstring = StrUpper(oldstring)
The function does not modify the variable "oldstring" at all. If you want to modify
the existing variable, you can assign to it the return value of the function, e.g.:
mystring = StrUpper(mystring)
array[2] = StrUpper(array[2])
For more information see the following Array functions:
ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv, ArrayFromStr,
ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim, ArrayRemove,
ArrayReverse, ArraySearch, ArraySort, ArraySwapElements, ArrayToStr,
ArrDimension, ArrInfo, ArrInitalize
91
WIL LANGUAGE
Error Handling
There are three types of errors that can occur while processing a WIL program:
Minor, Moderate, and Fatal. What happens when an error occurs depends on the
current error mode setting, which is set with either the ErrorMode function or
IntControl 73 function.
Using ErrorMode
There are three possible modes you can specify:
@CANCEL
User is notified when any error occurs, and then the WIL program is canceled. This
is the default.
@NOTIFY
User is notified when any error occurs, and has the option to continue unless the
error is fatal.
@OFF
User is only notified if the error is moderate or fatal. User has the option to continue
unless the error is fatal.
The function LastError returns the code of the most-recent WIL error encountered
during the currently-executing WIL program.
Minor errors are numbered from 1000 to 1999.
Moderate errors are numbered from 2000 to 2999.
Fatal errors are numbered from 3000 to 3999.
Error handling is reset to @CANCEL at the start of each WIL program.
For an example of trapping an error message, see the function LastError.
Note: You must read the section on the ErrorMode function completely before
attempting to use the function to suppress run-time errors. For an example of using
ErrorMode, see the function LastError.
Using IntControl 73
Regardless of the type of the error, IntControl 73 lets you specify what should
happen when the next error occurs in the script. For more information see
IntControl 73 (pg. 418).
92
Introduction
WIL FUNCTION
REFERENCE
Introduction
The WIL programming language consists of a large number of functions and
commands, which we describe in detail in this section.
We use a shorthand notation to indicate the syntax of the functions. Function names
and other actual characters you type are in boldface. Optional parameters are
enclosed in square brackets "[ ]". When a function takes a variable number of
parameters, the variable parts will be followed by ellipses ("...").
Take, for example, string concatenation:
StrCat (string[, string...])
This says that the StrCat function takes at least one string parameter. Optionally,
you can specify more strings to concatenate. If you do, you must separate the strings
with commas.
For each function and command, we show you the Syntax, describe the Parameters
(if any), the value it Returns (if any), a description of the function, Example code
(shown in Courier type), and related functions you may want to See Also.
The following symbols will be used to indicate a function or a section of the manual
which applies only to a specific implementation of the WIL Interpreter.
{*M} menu-based implementations of WIL Interpreter.
Note: WinBatch is a batch file application, FileMenu, PopMenu and WinBatch
Studio are menu file applications.
Additional Symbols
(i)
(i) indicates an integer parameter or return value.
(s) indicates a string parameter or return value.
(f) indicates a floating point parameter or return value.
(a) indicates an array parameter or return value.
(r) indicates a COM object reference.
(t) indicates a special type described in the function’s text.
(v) indicates variant type.
93
Abs
About
Displays the about message box which gives program information.
Syntax:
About()
Parameters:
(none)
Returns:
(i)
@TRUE.
This function displays a message box containing copyright and version information.
Example:
About( )
See Also:
Version, VersionDLL
Abs
Returns the absolute value of an integer.
Syntax:
Abs(integer)
Parameters:
(i) integer
integer whose absolute value is desired.
Returns:
(i)
absolute value of integer.
This function returns the absolute (positive) value of the integer which is passed to it,
regardless of whether that integer is positive or negative. If a floating point number is
passed as a parameter, it will be converted to an integer.
Example:
y1 = 2003
y2 = 1996
dy = Abs(y1 - y2)
Message("Years", "There are %dy% years between %y1% and %y2%")
See Also:
Average, Fabs, IsNumber, Max, Min
94
AddExtender
Acos
Calculates the arccosine.
Syntax:
Acos(x)
Parameters:
(f) x
floating point number whose arccosine is desired.
Returns:
(f)
the Acos function returns the arccosine result of x.
The Acos function returns the arccosine of x. The value of x must be between -1 and
1; otherwise, a domain error will occur.
Example:
real=AskLine("ArcCos","Enter a real number between -1 and 1","0.5",0)
answer=Acos(real)
Message("Arccos of %real% is",answer)
See Also:
Asin, Atan, Cos, Sin, Tan
AddExtender
Installs a WIL extender Dll.
Syntax:
AddExtender(filename[,version[,alternatefilename]])
Parameters:
(s) filename
WIL extender Dll filename.
(s) extender version [optional] minimum required extender version number.
(s) alternate filename [optional] 64-bit WIL Extender Dll filename. Note that 64bit WinBatch still treats the first parameter as the file name
of a 64-bit extender when no third parameter is present.
Returns:
(i)
@TRUE if function succeeded.
Note: optional parameters are enclosed in square brackets "[ ]".
WIL extender Dlls are special Dlls designed to extend the built-in function set of the
WIL processor. These Dlls typically add functions not provided in the basic WIL set,
such as network commands for particular networks (Novell, Windows, LAN
Manager and others), MAPI, TAPI, and other important Application Program
Interface functions as may be defined by the various players in the computer industry
from time to time. These Dlls may also include custom built function libraries either
95
AddExtender
by the original authors, or by independent third party developers. (An Extender SDK
is available). Custom extender Dlls may add nearly any sort of function to the WIL
language, from the mundane network, math or database extensions, to items that can
control fancy peripherals, including laboratory or manufacturing equipment.
Use this function to install extender Dlls as required. Up to 10 extender Dlls may be
added. The total number of added items may not exceed 500 functions and
constants. The AddExtender function must be executed before attempting to use
any functions in the extender library.
The AddExtender function only needs to be executed once for each extender Dll, in
each WIL script that requires it. If you attempt to load the same extender Dll twice,
using the AddExtender function, the operation will be ignored.
The documentation for the functions added are supplied either in a separate manual
or disk file that accompanies the extender Dll.
The optional 'alternate filename' (third parameter) can be used to specify a file name
for the 64-bit version of an extender. This allows for the specification of both a 32bit and 64-bit extender in a single system architecture independent call to
AddExtender. Specify zero(0) for the second parameter, if version checking is not
needed and you are using the optional third parameter. 64-bit WinBatch still treats
the first parameter as the file name of a 64-bit extender when no third parameter is
present.
Example:
; Add vehicle radar processing Dll controlling billboard visible to
; motorists, and link to enforcement computers.
; The WIL Extender SPEED.DLL adds functions to read a radar speed
; detector(GetRadarSpeed) , put a message on a billboard visible to
; the motorist (BillBoard), take a video of the vehicle (Camera), and
; send a message to alert enforcement personnel (Alert) that a
; motorist in violation along with a picture id number to help
; identify the offending vehicle and the speed which it was going.
;
AddExtender("SPEED.DLL")
BillBoard("Drive Safely")
While @TRUE
; Wait for next vehicle
while GetRadarSpeed( )<5 ; if low, then just radar noise
Yield
; wait a bit, then look again
endwhile
speed=GetRadarSpeed( )
; Something is moving out there
if speed < 58
BillBoard("Drive Safely")
; Not too fast.
else
if speed < 63
BillBoard("Watch your Speed")
; Hmmm a hot one
else
if speed < 66
BillBoard("Slow Down") ; Tooooo fast
96
AppExist
else
BillBoard("Violation Pull Over")
pictnum = Camera( )
; Take Video Snapshot
Alert(pictnum, speed); Pull this one over
endif
endif
endif
endwhile
See Also:
DllCall
AppExist
Tells if an application is running.
Syntax:
AppExist(program-name[,flags[,retries]])
Parameters:
(s) program-name
(i) flags
(i) retries
Returns:
(i)
name of a Windows EXE or DLL file.
[optional] a bitmask of values that may be combined using
the bitwise OR ('|')operator. See below.
[optional] number of retries.
@TRUE if the specified application is running; @FALSE
if the specified application is not running.
Flags
Value
1
2
Meaning
current-session-only.
"program-name" specifies a process ID instead of a program name
Use this function to determine whether a specific Windows application is currently
running. Unlike WinExist, you can use AppExist without knowing the title of the
application's window.
"Program-name" is the name of a Windows EXE or DLL file, including the file
extension (and, optionally, a full path to the file).
In the 32-bit version under Windows NT, this function accepts module names instead
of full program names. The module name is usually the same as the root name of the
program, without the extension. With AppExist and AppWaitClose, any file
extension or path information which is part of the 'program-name' parameter is
ignored; so, for example,
97
AppWaitClose
AppExist("c:\temp\notepad.exe")
will return TRUE, if Notepad is running, regardless of what directory
NOTEPAD.EXE is actually located in
"Retries"is the number of retries. Default is 7 retries (with a half-second delay
between retries) before returning, if the specified application doesn't exist. You can
override this by specifying different value for "retries", which may be >= 0.
Note: AppExist and AppWaitClose are not able to detect the existence of 16-bit
DOS or Windows applications.Windows Vista or newer: This function may require
an Administrator level account, because it relies on performance monitoring.
Example:
If AppExist("notepad.exe")[email protected] Then Run("notepad.exe", "")
See Also:
AppWaitClose, RunWait, RunShell, WinExeName, WinExist
AppWaitClose
Suspends WIL program execution until a specified application has been closed.
Syntax:
AppWaitClose(program-name[,flags[,retries]])
Parameters:
(s) program-name
(i) flags
(i) retries
Returns:
(i)
name of a Windows EXE or DLL file.
[optional] a bitmask of values that may be combined using
the bitwise OR ('|')operator. See below.
number of retries. Default is 7 retries (with a half-second
delay between tries) before returning, if the specified
application doesn't exist. You can override this by
specifying different value for "retries", which may be >= 0
(0 = no retries).
@TRUE if the specified application is running; @FALSE
if the specified application is not running.
Flags
Value
1
2
Meaning
current-session-only.
"program-name" specifies a process ID instead of a program name
Use this function to suspend the WIL program's execution until the user has finished
98
ArrayFileGet
using a given application and has manually closed it. Unlike WinWaitClose, you
can use AppWaitClose without knowing the title of the application's window.
"Program-name" is the name of a Windows EXE or DLL file, including the file
extension (and, optionally, a full path to the file).
Note: In 32-bit versions of WIL, only 32-bit applications will be detected AppExist
and AppWaitClose are not able to detect the existence of 16-bit DOS or Windows
applications.
In the 32-bit version under Windows NT, this function accepts module names instead
of full program names. The module name is usually the same as the root name of the
program, without the extension. With AppExist and AppWaitClose, any file
extension or path information which is part of the 'program-name' parameter is
ignored; so, for example,
AppExist("c:\temp\notepad.exe",@FALSE)
will return TRUE, if Notepad is running, regardless of what directory
NOTEPAD.EXE is actually located in.
Windows Vista or newer: This function may require an Administrator level
account, because it relies on performance monitoring.
Example:
Run("notepad.exe", "")
Display(4, "Note", "Close Notepad to continue")
AppWaitClose("notepad.exe",@FALSE)
Message("Continuing...", "Notepad closed")
See Also:
AppExist, TimeDelay, RunShell, RunWait, WinExeName, WinWaitClose,
WinWaitExist, Yield
ArrayFileGet
Converts a file to a one-dimension array.
Syntax:
ArrayFileGet(filename[,null-char[,extra-alloc]])
Parameters:
(s) filename
(s) null-char
(i) extra-alloc
path and file name of the file.
[optional] specifies the character which NULL bytes in
the file will be replaced with in the array. If omitted or a
blank string(""), then NULL bytes will be removed.
[optional] specifies the number of additional elements to
add to the end of the array. If omitted, it will be 0.
99
ArrayFileGetCsv
Returns:
(a)
a one dimensional array.
By default, the maximum supported file line length is 4096. This can be increased
using IntControl 65.
Example:
filename = "c:\temp\test.txt"
array = ArrayFileGet (filename , "" , 0)
linecount = ArrInfo(array,6)
Message("Number of lines in the file",linecount)
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim,
ArrayRemove, ArrayReverse, ArraySearch, ArraySort, ArraySwapElements,
ArrayToStr, ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop, IntControl 39
ArrayFileGetCsv
Converts a comma separated values (.CSV) file to a two-dimension array.
Syntax:
ArrayFileGetCsv(filename,flags[,delimiter[,extra-rows[,extra-columns]]])
Parameters:
(s) filename
(i) flags
(s) delimiter
(i) extra-rows
(i) extra-columns
Returns:
(a)
path and file name of the file.
see below.
[optional] specifies the character used to separate values
on each line of the file. It can be any single printable
character, numbered from 32 to 126 (decimal), except
a space(32) or double quotation mark(34). If omitted, a
comma will be used as the delimiter.
[optional] specifies the number of additional elements to
add to the end of dimension 1 of the array. If omitted, it
will be 0.
[optional] specifies the number of additional elements to
add to the end of dimension 2 of the array. If omitted, it
will be 0.
a two dimensional array.
Note: A comma separated values (.CSV) file is a file format used as a portable
representation of a database. Each line is one entry or record and the fields in a
record are separated by commas. Commas may be followed by arbitrary space and/or
100
ArrayFilePut
tab characters which are ignored. If field includes a comma, the whole field must be
surrounded with double quotes.
Line break handling within CSV files: WinBatch will not handle a line break within
a field. WinBatch considers a line feed to be the end of a line. In this case, the layout
of the CSV file will be disrupted or broken.
Flags can be set to 0, or can specify one or more of the following values combined
with the bitwise OR ('|') operator:
Value
1
Meaning
treat leading and trailing whitespace as significant
This function creates a two-dimension array and stores each line of the specified
CSV file as rows and columns in the array. The first item on line 1 of the file is
stored as array[0, 0], the second item on line 1 of the file is stored as array[0, 1], the
first item on line 2 of the file is stored as array[1, 0], and so on.
By default, the maximum supported file line length is 4096. This can be increased
using IntControl 65.
The file may not contain any NULL characters.
Example:
filename = "c:\temp\test.csv"
array = ArrayFileGetCsv(filename, 0, ",", 0, 0)
rowcount = ArrInfo(array,1)
colcount = ArrInfo(array,2)
Message(StrCat("Number of Rows in the file ",rowcount)
StrCat("Number of Columns in the file ",colcount))
Message(StrCat("Number of Columns in the file ", colcount)
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim,
ArrayRemove, ArrayReverse, ArraySearch, ArraySort, ArraySwapElements,
ArrayToStr, ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop, IntControl 39
ArrayFilePut
Writes a one-dimension array to a file.
Syntax:
ArrayFilePut(filename,array[,write-undef])
Parameters:
(s) filename
(a) array
(i) write-undef
path and file name of the file to create.
specifies an array.
[optional] see below.
101
ArrayFilePutCsv
Returns:
(i)
the number of bytes written to the file.
If "write-undef" is @TRUE, then uninitialized elements in the array will be written
as blank lines in the file. If "write-undef" is @FALSE, then uninitialized elements
will not be written.
This function writes a one-dimension array to a file, one element per line. If
"filename" exists, it will be overwritten.
By default, each line in the file will be terminated with a CR/LF. This can be
changed using IntControl 53.
Example:
outputfile = "c:\temp\output.txt"
filelist = FileItemize(StrCat(DirWindows(0),"*.*"))
array = Arrayize(filelist,@tab)
ArrayFilePut(outputfile, array, @TRUE)
Message("Done","one-dimension array written to file")
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim,
ArrayRemove, ArraySearch, ArraySort, ArraySwapElements, ArrayToStr,
ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop, IntControl 40
ArrayFilePutCsv
Writes a two-dimension array to a comma separated values (.CSV) file.
Syntax:
ArrayFilePutCsv(filename,array[,delimiter[,write-undef[,flags]])
Parameters:
(s) filename
(a) array
(s) delimiter
(i) write-undef
(i) flags
Returns:
(i)
102
path and file name of the file to create.
specifies an array.
[optional] specifies the character used to separate values
on each line of the file. It can be any single printable
character, numbered from 32 to 126 (decimal), except
a space(32) or double quotation mark(34). If omitted, a
comma will be used as the delimiter.
[optional] see below.
[optional] see below.
the number of bytes written to the file.
ArrayFromStr
If "write-undef" is @TRUE, then uninitialized elements in the array will be written
as blank values in the file. If "write-undef" is @FALSE, then uninitialized elements
will not be written.
"flags" can be set to 0, or can specify one or more of the following values combined
with the bitwise OR ('|') operator:
Value
2
Meaning
Do not do CSV file double quote type processing. This should only be
used in cases where you are sure the 'delimiter' will be found nowhere
in the data.
By default, each line in the file will be terminated with a CR/LF. This can be
changed using IntControl 53.
Line break handling within CSV files: WinBatch will not handle a line break within
a field. WinBatch considers a line feed to be the end of a line. In this case, the layout
of the CSV file will be disrupted or broken.
Example:
outputfile = "c:\temp\output.csv"
array = ArrDimension(10,10)
For x = 0 to 9
For y = 0 to 9
array[x,y] = x*y
Next
Next
ArrayFilePutCsv(outputfile, array, ",",@TRUE,0)
Message("Done","Two-dimension array written to file")
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim,
ArrayRemove, ArraySearch, ArraySort, ArraySwapElements, ArrayToStr,
ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop,IntControl 40, IntControl 53
ArrayFromStr
Accepts a text string and returns a one dimension array with one string character per
array element.
Syntax:
ArrayFromStr(string)
Parameters:
(s) string
string of characters to convert to an array.
Returns:
(a) array
a one dimensional array.
103
ArrayInsert
This function takes a string and creates a one-dimension array with the same number
of elements as the number of characters in the string.
Example:
strName = AskLine('ArrayFromStr','Type in your name','Joe Blow')
arrName = ArrayFromStr( strName )
count = ArrInfo(arrName, 1 )
Pause( 'Your Name: ' : strName, 'Has ': count : ' characters in it.')
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim,
ArrayRemove, ArraySearch, ArraySort, ArraySwapElements, ArrayToStr,
ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop
ArrayInsert
Performs in-place insertion of an element into a single dimension array, or the inplace insertion of a row or column into a two dimension array.
Syntax:
ArrayInsert(array,sub[,dim[,value]])
Parameters:
(a) array
(i) sub
(i) dim
(u/s/i/f) value
Returns:
(i) returns
specifies an array.
subscript of the element to insert into single dimension
array. Subscript of the row or column to insert into a two
dimension array.
[optional] must be 1 or omitted for single dimension arrays.
Must be either 1 to insert an array row or 2 to insert an array
column into a two dimension array.
[optional] initial value of inserted element(s).
@TRUE.
Multidimensional arrays in WinBatch use 'Row Major' format. For Example:
arrMyArray[ row_index , column_index ]
Example:
strList = 'a b c A B C 1 0 -1'
value = 'D' ; (uppercase letter D)
; Create an array to Insert data
arrList = Arrayize( strList, ' ' )
; insert value in the array
result = ArrayInsert(arrList,6,1,value)
strNewList = ArrayToStr(arrList)
; Display results
Pause( 'ArrayInsert of value: ' : value, strNewList)
104
Arrayize
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim,
ArrayRemove, ArraySearch, ArraySort, ArraySwapElements, ArrayToStr,
ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop
ArrayItemize
Converts an array to a delimited list.
Syntax:
ArrayItemize (list,delimiter)
Parameters:
(a)array
(s)delimiter
an array.
list delimiter.
Returns:
(a)
delimited list.
Converts a WIL array or variant safearray into a delimited item list. Each array
element is converted to its string representation before being added as an item to the
delimited list. Any element that does not have a string representation or does not
have any value is ignored. This means that it is possible to have fewer items in the
delimited list than elements in the passed in array. It is also possible to have more
items in the delimited list than elements in the array because an array element may
contain an embedded delimiter. The function's return value is the delimited list
representation of the passed in array.
Example:
arrName = ArrayFromStr( 'Apples Bananas Cherries' )
strList = ArrayItemize( arrName )
AskItemList( 'Fruits', strList, @tab, @sorted, @single )
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, Arrayize, ArrayLocate, ArrayRedim, ArrayRemove,
ArraySearch, ArraySort, ArraySwapElements, ArrayToStr, ArrDimension, ArrInfo,
ArrInitalize, ArrRemove, Drop
Arrayize
Converts a delimited list to an array.
Syntax:
Arrayize(list,delimiter)
105
ArrayLocate
Parameters:
(s)list
(s)delimiter
delimited list.
list delimiter.
Returns:
(a)
a one dimensional array.
This function takes a delimited list, and creates a one-dimension array with the same
number of elements as the number of items in the list, setting each element to the
value of the corresponding item in the list. i.e., it converts a delimited list to an
array.
Example:
list=FileItemize("*.*")
array=Arrayize(list,@tab)
For request = 1 to 6
info = ArrInfo (array, request)
Message("Array info: Request %request%", info )
Next
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim,
ArrayRemove, ArraySearch, ArraySort, ArraySwapElements, ArrayToStr,
ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop
ArrayLocate
Searches an array for an element that matches a value.
Syntax:
ArrayLocate(array,value[,sub1[,sub2[,sub3[,sub4[,sub5]]]]])
Parameters:
(a) array
(s) value
(i) sub1
(i) sub2
(i) sub3
(i) sub4
(i) sub5
106
specifies an array.
case sensitive value to search for in "array".
[optional] subscript of first element (dimension 1) to search.
The default is zero.
[optional] subscript of first element (dimension 2) to search
The default is zero.
[optional] subscript of first element (dimension 3) to search.
The default is zero.
[optional] subscript of first element (dimension 4) to search.
The default is zero.
[optional] subscript of first element (dimension 5) to search.
The default is zero.
ArrayRedim
Returns:
(a) array
a single dimensioned array with one element per dimension
of the searched array. Each element of the returned array
holds one subscript of the element with the value when
found and -1 if the value is not found.
Example:
strList = 'a b c A B C 1 0 -1'
value = 'C' ; (uppercase letter C)
sub1 = 2 ; Start on the third element of the first dimension
; Create an array to search
arrList = Arrayize( strList, ' ' )
; Search array starting on the third element of the first dimension
arrRslt = ArrayLocate(arrList,value,sub1)
; Read result from the array
result = arrRslt[0]
; Display results ( expect 5 )
Pause('ArrayLocate of value: ':value,'Element number: ':result)
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim,
ArrayRemove, ArraySearch, ArraySort, ArraySwapElements, ArrayToStr,
ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop
ArrayRedim
Changes array dimensions in-place.
Syntax:
ArrayRedim(array,dim[,dim2[,dim3[,dim4[,dim5]]]])
Parameters:
(a) array
(i) "dim1"- "dim5"
Returns:
(i)
array to re-dimension.
specifies the new "array" of up to 5 dimensions or -1 to
keep existing dimensions. The default for "dim2" through
"dim5" is 0 which deletes the existing dimension. Once an
array dimension is set to 0, all subsequent array dimensions
must be set to 0 or omitted. -1 can also be used for
subsequent dimensions if current corresponding dimension
is already 0.
returns @TRUE.
ArrayRedim changes array dimensions in-place. When used to increase array
dimensions, preserves all array content. When any array dimension is reduced in
size, the array content referenced by the eliminated indices is lost even if the overall
107
ArrayRemove
array size remains unchanged or increases, due to increases in the size of other
dimensions.
ArrayRedim takes a variable number of parameters, with the first two parameters
being required, and last four optional.
Note: If you shrink the array, the data in the removed dimensions will be lost.
For example:
1-dimension
2-dimension
3-dimension
4-dimension
5-dimension
array:
array:
array:
array:
array:
ArrayRedim(array1, 10)
ArrayRedim(array2,10, 10)
ArrayRedim(array3, 10, 10, 10)
ArrayRedim(array4, 10, 10, 10, 10)
ArrayRedim(array5, 10, 10, 10, 10, 10)
Example:
; Allocate an array with 6 elements.
array = ArrDimension( 5 )
ArrInitialize( array, 0 )
Pause( 'Array Element Count', ArrInfo( array, 1 ) )
; Resize the array
ArrayRedim( array, 10 )
Pause( 'Array Element Count', ArrInfo( array, 1 ) )
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim,
ArrayRemove, ArraySearch, ArraySort, ArraySwapElements, ArrayToStr,
ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop
ArrayRemove
Performs in-place removal of an element from a single dimension array, or the in
place removal of a row or column from a two dimension array.
Syntax:
ArrayRemove( array, sub, [ dim ] )
Parameters:
(a) array
(i) sub
(i) dim
108
array in which to remove an element, row, or column.
subscript of the element to remove in single dimension array
or the subscript of the row or column to remove in a two
dimension array.
[optional] must be 1 or omitted for one dimension arrays.
Must be either 1 to delete an array row or 2 to delete an
array column from a two dimension array.
ArrayRemove
Returns:
(i)
returns @TRUE.
Note: This function cannot be used to remove a single element from a two
dimensional array.
Multidimensional arrays in WinBatch use 'Row Major' format. For Example:
arrMyArray[ row_index , column_index ]
Example:
; SINGLE DIMENSION - Remove a single element
; Allocate a single dimension array with 6 elements.
array = ArrDimension( 6 )
ArrInitialize( array, 0 )
Pause( 'Array Element Count', ArrInfo( array, 1 ) )
; Remove the first element
ArrayRemove( array, 0)
Pause( 'Array Element Count', ArrInfo( array, 1 ) )
; Remove the 3rd element
ArrayRemove( array, 2)
Pause( 'Array Element Count', ArrInfo( array, 1 ) )
; Remove the last element
ArrayRemove( array, ArrInfo( array, 1 ) - 1 )
Pause( 'Array Element Count', ArrInfo( array, 1 ) )
; TWO DIMENSION - Remove a row.
; Allocate a two dimensional array with
array = ArrDimension( 6, 6 )
ArrInitialize( array, 0 )
Pause( 'Array Element Count', 'Rows: ':
'Columns: ': ArrInfo( array, 2 ))
; Remove the first row
ArrayRemove( array, 0, 1)
Pause( 'Array Element Count', 'Rows: ':
'Columns: ': ArrInfo( array, 2 ))
; Remove the 3rd row
ArrayRemove( array, 2, 1)
Pause( 'Array Element Count', 'Rows: ':
'Columns: ': ArrInfo( array, 2 ))
; Remove the last row
ArrayRemove( array, ArrInfo( array, 1 )
Pause( 'Array Element Count', 'Rows: ':
'Columns: ': ArrInfo( array, 2 ))
6 elements in each dimension.
ArrInfo( array, 1 ): @CRLF :
ArrInfo( array, 1 ): @CRLF :
ArrInfo( array, 1 ): @CRLF :
- 1 , 1)
ArrInfo( array, 1 ): @CRLF :
; TWO DIMENSION - Remove a column.
; Allocate a two dimensional array with 6 elements in each dimension.
array = ArrDimension( 6, 6 )
ArrInitialize( array, 0 )
Pause( 'Array Element Count', 'Rows: ': ArrInfo( array, 1 ): @CRLF :
'Columns: ': ArrInfo( array, 2 ))
; Remove the first column
ArrayRemove( array, 0, 2)
109
ArrayReverse
Pause( 'Array Element Count', 'Rows: ':
'Columns: ': ArrInfo( array, 2 ))
; Remove the 3rd column
ArrayRemove( array, 2, 2)
Pause( 'Array Element Count', 'Rows: ':
'Columns: ': ArrInfo( array, 2 ))
; Remove the last column
ArrayRemove( array, ArrInfo( array, 2 )
Pause( 'Array Element Count', 'Rows: ':
'Columns: ': ArrInfo( array, 2 ))
ArrInfo( array, 1 ): @CRLF :
ArrInfo( array, 1 ): @CRLF :
- 1 , 2)
ArrInfo( array, 1 ): @CRLF :
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim,
ArrayRemove, ArraySearch, ArraySort, ArraySwapElements, ArrayToStr,
ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop
ArrayReverse
.
Syntax:
ArrayReverse( array, [, dimension ] )
Parameters:
(a) array
(i) dimension
Returns:
(i)
array to reverse elements.
[optional] array dimension to reverse 0 (default). Valid
values are 1 to the number of dimensions in the passed in
array or 0 to reverse the array without regard to dimension.
returns @TRUE.
Reverses the order of the elements in a WIL array or a variant safearray in place.This
function is primarily intended for use on single dimension arrays but it also accepts
multi-dimensional arrays. When the optional dimension parameter is used on a
multi-dimensional array the reversal process is performed on blocks of elements
within the array. The elements within each block are not reversed relative to each
other. For example, this feature can be used to reverse the perceived order of the
columns in a two dimension array without changing the order of the elements within
each column. The function always returns 1..
Example:
arrName = ArrayFromStr( 'Apples Bananas Cherries Grapes Lemons Limes
Nectarines Oranges
Raspberries Strawberries Watermelon' )
ArrayReverse( arrName )
strName = ArrayItemize( arrName )
110
ArraySearch
AskItemList('Fruit list reversed', list, @tab, @sorted, @single )
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim,
ArrayRemove, ArrayReverse, ArraySearch, ArraySort, ArraySwapElements,
ArrayToStr, ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop
ArraySearch
Searches a one or two dimension array for an element that matches a value.
Syntax:
ArraySearch(array,value[,options[,search-column[,start-sub[,end-sub]]]])
Parameters:
(a) array
(s) value
(i) options
(i) search-column
(i) start-sub
(i) end-sub
Returns:
(i) index
specifies an array.
value to search for in "array".
[optional]
0 linear search matching case (the default).
1 binary fast search on a sorted "search-column".
2 linear search ignoring case.
3 binary fast search ignoring case.
[optional] subscript of column to search for twodimensional arrays. The default is zero. Always use
zero when searching one dimensional arrays.
[optional] subscript of first element or row to include
in search. The default is zero.
[optional] subscript of last element or row to include in
search. The default is ArrInfo(array,1)-1.
the index of the found element of a single dimension array,
the index of the row containing the found element of a two
dimension array, or -1 if the value is not found.
Fast Binary Search Options 1 & 3
This function can optionally search using a fast binary search but the array must first
be sorted on "search-column' using the ArraySort function.
Duplicates
This function will not necessarily locate the item with the lowest index of a set of
duplicates. To find every occurrence of a duplicate value, you must search in both
directions from the first found item. A linear search is the preferred method to find
every occurrence of a value, unless you have a very large data set.
111
ArraySort
Multidimensional arrays in WinBatch use 'Row Major' format. For example:
arrMyArray[ row_index , column_index ]
Example:
strList = 'a b c A B C 1 0 -1'
value = 'C' ; (uppercase letter C)
; Create an array to search
arrList = Arrayize( strList, ' ' )
; Search the array
result = ArraySearch( arrList, value, 0, 0, 0, ArrInfo(arrList,1)-1)
; Display results ( expect 5 )
Pause('ArraySearch of value: ':value, 'Element number:':result)
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim,
ArrayRemove, ArrayReverse, ArraySearch, ArraySort, ArraySwapElements,
ArrayToStr, ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop
ArraySort
Performs an in-place sort of arrays with one or two dimensions.
Syntax:
ArraySort(array[,options[,sort-column[,start-sub[,end-sub]]]])
Parameters:
(a) array
(i) options
(i) sort-column
(i) start-sub
(i) end-sub
Returns:
(i)
array to sort.
[optional] @ASCENDING for an ascending sort (the
default) or @DESCENDING for a descending sort.
[optional] subscript of column to sort on for twodimensional arrays. The default is 0. Always use 0 for one
dimensional arrays.
[optional] subscript of first row to include in sort. The
default is 0.
[optional] subscript of last row to include in sort. The
default is ArrInfo(array,1) - 1.
returns @TRUE.
Important: this function performs an in-place sort of an array.
This function sorts a list, using an "ANSI Collating Sequence" sort, also known as a
"dictionary sort" or "word sort". This means, among other things, that the hyphen
and the apostrophe are not treated like other non alphanumeric characters. See
ItemSort.
112
ArraySwapElements
Example:
strList = 'a b c A B C 1 0 -1'
outfile = DirScript() : 'ArraySort.txt'
;Create an array to sort
arrList = Arrayize( strList, ' ' )
; Sort the array using an ascending dictionary sort
ArraySort( arrList, @ASCENDING, 0, 0, ArrInfo(arrList,1)-1 )
; Write Results out to a file
ArrayFilePut( outfile, arrList )
; Display results
Run( outfile, '' )
; Clean up
FileDelete( outfile )
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, Arrayize, ArrayLocate, ArrayRedim, ArrayRemove,
ArraySearch, ArraySort, ArraySwapElements, ArrayToStr, ArrDimension, ArrInfo,
ArrInitalize, ArrRemove, Drop, ItemSort
ArraySwapElements
Swaps elements in an array.
Syntax:
ArraySwapElements(array,subA1,subA2,subA3,subA4,subA5,subB1,subB2,
subB3,subB4,subB5)
Parameters:
(a) array
(i) subA1
(i) subA2
(i) subA3
(i) subA4
(i) subA5
(i) subB1
(i) subB2
(i) subB3
(i) subB4
(i) subB5
specifies an array.
subscript (dimension 1) of element 'A' or zero.
subscript (dimension 2) of element 'A' or zero.
subscript (dimension 3) of element 'A' or zero.
subscript (dimension 4) of element 'A' or zero.
subscript (dimension 5) of element 'A' or zero.
subscript (dimension 1) of element 'B' or zero.
subscript (dimension 2) of element 'B' or zero.
subscript (dimension 3) of element 'B' or zero.
subscript (dimension 4) of element 'B' or zero.
subscript (dimension 5) of element 'B' or zero.
Returns:
(i)
returns @TRUE.
This function swaps the values of two elements in an array. "subA1" to "subA5"
specify the subscripts of element "A". "subB1" to "subB5" specify the subscripts of
element "B".
113
ArrayToStr
Specify "0" for unused dimensions. For example, to identify the array element
"arr[1,5]", subA1 is 1 and subA2 is 5.
Example:
myarray=ArrDimension(2)
myarray[0] = 1
myarray[1] = 2
ArraySwapElements( myarray,0,0,0,0,0,1,0,0,0,0 )
Message("ArraySwapElements","myarray[0] = ": myarray[0] :@CRLF:
"myarray[1] = ":myarray[1])
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim,
ArrayRemove, ArrayReverse, ArraySearch, ArraySort, ArraySwapElements,
ArrayToStr, ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop
ArrayToStr
Accepts a single dimension array and returns a text string constructed from the
concatenation of each array element.
Syntax:
ArrayToStr(array)
Parameters:
(a) array
a one dimensional array.
Returns:
(s) string
string of characters.
This function takes a one dimension array and creates a string with the same number
of characters as there are elements in the array.
Example:
arrName=ArrayFromStr(AskLine('ArrayFromStr','Type in your name','Joe
Blough'))
strName = ArrayToStr( arrName )
count = ArrInfo(arrName, 1 )
Pause( 'Your Name: ':strName ,'Has ':count:' characters in it.')
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim,
ArrayRemove, ArrayReverse, ArraySearch, ArraySort, ArraySwapElements,
ArrayToStr, ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop
114
ArrDimension
ArrDimension
Creates an array.
Syntax:
ArrDimension(dim1[,dim2[,dim3[,dim4[,dim5]]]])
Parameters:
(i) "dim1"- "dim5"
an array of up to 5 dimensions.
Returns:
(a)
array that was created.
Optional parameters are enclosed in square brackets "[ ]". ArrDimension takes a
variable number of parameters, the variable parts will be followed by ellipses ("...").
The ArrDimension function takes at least one parameter. Optionally, you can
specify up to five. If you do, you must separate the integers with commas.
For example:
1-dimension array:
2-dimension array:
3-dimension array:
4-dimension array:
5-dimension array:
array1 = ArrDimension(10)
array2 = ArrDimension(10, 10)
array3 = ArrDimension(10, 10, 10)
array4 = ArrDimension(10, 10, 10, 10)
array5 = ArrDimension(10, 10, 10, 10, 10)
ArrDimension(10) creates a 1-dimension array with a size of 10 (10 elements).
Since array subscripts are 0-based, the first element is arrayvar[0] and the last
element is arrayvar[9].
An array can theoretically contain up to 200,000,000 elements in total. Of course this
will be further limited by your available system memory.
You can not create embedded arrays (i.e., an array within an array).
You can use the Drop command to free an array. This will also Drop any
COM/OLE object handles within the array, as well as any WIL string variables. It
will NOT close any file handles or binary buffers.
Example:
totalfortunes=10
fortune=ArrDimension(totalfortunes)
fortune[0] = "All your hard work will soon pay off."
fortune[1] = "Winbatch will save you time."
fortune[2] = "Your present plans are going to succeed."
Fortune[3] = "You will live a long time."
Fortune[4] = "One learns when teaching others."
fortune[5] = "Success means competition."
fortune[6] = "Your example Will inspire others."
fortune[7] = "One must be available, alert, active, and adaptable."
fortune[8] = "If you have many best friends, you have no friends."
115
ArrInfo
fortune[9] = "Mountains can move, but not your character."
:Start
;Initialize the dialog
BoxesUp("200,200,800,800", @zoomed)
BoxCaption(1, "Pick a Fortune cookie")
BoxColor(1,"201,200,150",0)
BoxDrawRect(1,"0,0,1000,1000",2)
dice=0
retry=0
ONCANCEL="Goto Shutdown"
dice=askline("Pick a Fortune cookie","Enter a number between 1 and
%totalfortunes%",1,0)
If (dice >= 1 && dice <= totalfortunes)
;Display the fortune
BoxCaption(1, "Your Fortune cookie says")
BoxTextColor(1, "128,0,128")
BoxTextFont(1, "Book Antiqua", 50, 10, 16)
BoxDrawText(1, "0,200,1000,800", fortune[dice-1], @TRUE, 1)
Timedelay(2)
Else
message("Your Fortune cookie says","Unfortunately...%@CRLF%You
picked a wrong number.")
Endif
retry=AskYesNo("Pick a Fortune cookie","Do you want to try again")
if retry == 1 then goto start
exit
:Cancel
IntControl(72, 2, 0, 0, 0);Sets cancel processing
%ONCANCEL%
return
:Shutdown
retry=AskYesNo("Pick a Fortune cookie","Do you really want to EXIT?")
if retry == 1 then exit
Goto start
SeeAlso:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim,
ArrayRemove, ArrayReverse, ArraySearch, ArraySort, ArraySwapElements,
ArrayToStr, ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop
ArrInfo
Gets information about an array.
Syntax:
ArrInfo(array,request)
116
ArrInitialize
Parameters:
(a) array
(i) request
specifies an array.
a flag specifying the information to retrieve (see below).
Returns:
(i)
depends on request.
Request
-1
0
1
2
3
4
5
6
Returns
checks if array is valid. Returns @TRUE if valid, @FALSE if
invalid.
number of dimensions in the array
number of elements in dimension 1
number of elements in dimension 2 (or 0 if unused)
number of elements in dimension 3 (or 0 if unused)
number of elements in dimension 4 (or 0 if unused)
number of elements in dimension 5 (or 0 if unused)
number of elements in the entire array
Example:
myarray=ArrDimension(1,2,3,4,5)
For request = 0 to 6
info = ArrInfo (myarray, request)
Message("Array info: Request %request%", info )
Next
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim,
ArrayRemove, ArraySearch, ArraySort, ArraySwapElements, ArrayToStr,
ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop
ArrInitialize
Initializes an array.
Syntax:
ArrInitialize(array,value)
Parameters:
(a) array
(i/f/s) value
Returns:
(i)
specifies an array.
specifies an integer, floating point, or string value.
always @TRUE.
This function sets all elements of "array" to "value".
117
ArrRemove
Example:
myarray=ArrDimension(1,0,0,0,0)
ArrInitialize(myarray, 0)
message("Array","Initialized")
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim,
ArrayRemove, ArrayReverse, ArraySearch, ArraySort, ArraySwapElements,
ArrayToStr, ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop
ArrRemove
Performs in-place removal of an element from a single dimension array, or the inplace removal of a row or column from a two dimension array.
Syntax:
ArrayRemove(array,sub[,dim ])
Parameters:
(a) array
(i) sub
(i) dim
Returns:
(i)
the array in which to remove an element, row, or column.
subscript of the element to remove in single dimension
array or the subscript of the row or column to remove in
a two dimension array.
[optional] must be 1 or omitted for one dimension
arrays. Must be either 1 to delete an array row or 2
to delete an array column from a two dimension
array.
returns @TRUE.
Note: This function cannot be used to remove a single element from a two
dimensional array.
Multidimensional arrays in WinBatch use 'Row Major' format. For Example:
arrMyArray[ row_index , column_index ]
Example:
;-----------------------------------------------------; SINGLE DIMENSION - Remove a single element
;-----------------------------------------------------; Allocate a single dimension array with 6 elements.
array = ArrDimension(6)
ArrInitialize(array,0)
Pause('Element Count',ArrInfo(array,1))
; Remove the first element
ArrayRemove(array,0)
Pause('Element Count',ArrInfo(array,1))
118
Asin
;-----------------------------------------------------; TWO DIMENSION - Remove a row
;-----------------------------------------------------; Allocate a two dimensional array with 6 elements in each dimension.
array = ArrDimension(6,6)
ArrInitialize(array,0)
Pause('Element Count','Rows: ':ArrInfo(array,1):@CRLF:'Columns: ':
ArrInfo(array,2))
; Remove the first row
ArrayRemove(array,0,1)
Pause('Element Count','Rows: ':ArrInfo(array,1):@CRLF:'Columns: ':
ArrInfo(array,2))
;-----------------------------------------------------; TWO DIMENSION - Remove a column
;-----------------------------------------------------; Allocate a two dimensional array with 6 elements in each dimension.
array = ArrDimension(6,6)
ArrInitialize(array,0)
Pause('Element Count','Rows: ':ArrInfo(array,1):@CRLF:'Columns:
':ArrInfo(array,2))
; Remove the first column
ArrayRemove(array,0,2)
Pause('Element Count','Rows: ':ArrInfo(array,1):@CRLF:'Columns:
':ArrInfo(array,2))
See Also:
Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv,
ArrayFromStr, ArrayInsert, ArrayItemize, Arrayize, ArrayLocate, ArrayRedim,
ArrayRemove, ArrayReverse, ArraySearch, ArraySort, ArraySwapElements,
ArrayToStr, ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop
Asin
Calculates the arcsine.
Syntax:
Asin(x)
Parameters:
(f) x
floating point number whose arcsine is desired.
Returns:
(f)
the Asin function returns the arcsine result of x.
The Asin function returns the arcsine of x in the range -пЃђ/2 to пЃђ/2 radians. The
value of x must be between -1 and 1 otherwise a domain error will occur.
Example:
real=AskLine("ArcSin", "Enter a real number between -1 and 1",
"0.5",0)
119
AskColor
answer=Asin(real)
Message("Arcsin of %real% is", answer)
See Also:
Acos, Atan, Cos, Sin, Tan
AskColor
Displays a color selection dialog box, and returns the selected color.
Syntax:
AskColor(default-color,reg-key,format)
Parameters:
(s) default-color
(s) reg-key
(i) format
Returns:
(s)
specifies an RGB color value in the form "#RRGGBB".
specifies the name of a user-defined registry key under
"HKEY_CURRENT_USER\Software\Wilson
WindowWare" where persistent state information will be
stored. It will be created if it does not already exist. If "" is
specified, persistent state information will not be stored.
specifies the format in which the selected color will be
returned. See below.
RGB color value in requested format.
default-color
Specifies an RGB color value in the form "#RRGGBB", where "RR" is the red
component in hex (00-FF), "GG" is the green component in hex (00-FF), and "BB" is
the blue component in hex (00-FF). This will be the color initially selected in the
dialog. You may specify "" for a default of gray.
Format
Meaning
0
RGB color value in the form "#RRGGBB" (see above).
1
RGB color value in the form "R|G|B", where "R", "G", and"B" are the
respective red, green, and blue components, in decimal.
Example:
color0=AskColor("","test",0)
Message("Color in #808080 format",color0)
color1=AskColor("","test",1)
Message("Color in 128|128|128 format",color1)
See Also:
AskFont
120
AskDirectory
AskDirectory
Displays a directory browse dialog box, and returns the selected directory name.
Syntax:
AskDirectory(prompt,browse-root,start-dir,confirm-prompt,flags)
Parameters:
(s) prompt
(s) browse-root
(s) start-dir
(s) confirm-prompt
(i) flags
Returns:
(s)
Flags
Prompt to be displayed in the dialog box above the list of
directories. This can be a blank string ("") if no prompt is
desired. Note that the title of the dialog box ("Browse for
Folder") cannot be changed.
Directory under which the user can browse for directories.
The user will not be able to browse above this level. You
can specify a blank string ("") to allow the entire file system
(all drives, directories, and network shares) to be browsed.
Directory which will be selected by default when the dialog
box is initially displayed. This can be a blank string (""), in
which case the top of the tree will be selected (same as
'browse-root').
The title of the confirmation message box (see 'flags' #2,
below).
One or more of the optional flags (see below), combined
using the binary OR ("|") operator, or 0 if none are desired.
the string containing the directory path selected in the
browse dialog. If the user presses "Cancel", standard WIL
":cancel" processing will be performed.
Meaning
0
None of the following apply.
1
Display an edit field in the dialog box, in which the user can type
the name of a directory which may or may not exist. This name
will be relative to the currently selected directory name in the
browse list.
121
AskDirectory
2
If the user types a name in the edit field (see flag #1), of a
directory which does not exist, this flag causes a confirmation
message box to be displayed, showing the name of the directory
that would be returned by the function, and containing three
buttons: Yes, No, and Cancel.
If the user selects 'Yes', the function returns. If the user selects
'No', the directory browse dialog remains displayed, and the user
can re-edit the name or select a different directory. 'Cancel'
causes the function to return, and standard WIL ":cancel"
processing to be performed.
4
Use the new user interface. Setting this flag provides the user
with a larger dialog box that can be resized. The dialog box has
several new capabilities including: drag and drop capability
within the dialog box, shortcut menus, new folders, delete, and
other shortcut menu commands.
8
Do not include the "New Folder" button in the browse dialog box
NOTE: This is supported only in Windows XP or newer. In older
versions of Windows, this flag is ignored.
16
Suppress "Drive not ready" errors.
The title of the message box is specified by 'confirm-prompt'.
Example:
flags=1|2
dir1=AskDirectory("Select Working Directory for Winbatch",
"C:\Program Files\WinBatch", "","Are you sure?",flags)
Message("Directory Path selected was", dir1)
122
AskFileName
and then:
See Also:
AskFileText, AskItemList, AskLine, AskFileName
AskFileName
Returns the filename as selected by a File Open dialog box.
123
AskFileName
Syntax:
AskFileName(title,directory,filetypes,default filename,flag)
Parameters:
(s) title
(s) directory
(s) filetypes
(s) default filename
(i) flag
title of the file name select box.
initial drive and directory.
file type selection definition (see below).
default filename or mask.
see below.
Returns:
(s)
a string containing the filename and path.
This function is the equivalent of a standard Common Dialog File Open or a File
Save dialog box. The initial drive and directory is logged, and either a File Save or a
File Open dialog box is presented to the user.
The default filename or mask is filled in, as well as a selection of filetypes.
The user can either type in a filename or select one via the file list box.
File types displayed may be selected from the File Type drop down list box. The File
Type drop down list box is specified via the filetypes parameter. The filetype
parameter is defined as follows:
filetypes := Description|Mask| [ Description|Mask| ...]
Description := Any human readable string
Mask := filespec [; filespec ...]
filespec := DOS File wildcard mask
Basically, a description - visible to the user in the drop down list box, followed by
the vertical bar symbol(|), followed by a file mask - for the computer, followed by
another vertical bar. This description may be repeated for each desired file type
selection.
124
Flag
Meaning
0
Save style
1
Open style
2
Open style, allowing multiple files to be selected. **
3
Save style, with no "Replace" confirmation.
100
[Vista or newer] Save style *
101
[Vista or newer] Open style *
102
[Vista or newer] Open style, allowing multiple files to be
AskFileName
selected.* / **
103
[Vista or newer] Save style, with no "Replace" confirmation.*
* Vista or newer : The new dialog style can be invoked by adding 100 to the values
passed in the function's 'flag' parameter. Each of the four values 100, 101, 102 and
103 otherwise have the same effect as the corresponding 0, 1, 2, and 3 values. If one
of the 100-plus values is used on a system running a version of Windows predating
Vista, the added 100 is ignored and the function reverts to the older common file
dialog style.
** If the "flag" specified is 2 or 102 (Open Style, allowing multiple files to be
selected), the selected files will be returned as a delimited list.
The combined file names selected cannot exceed 2048 characters, otherwise the
AskFileName dialog will be re-displayed. In other words, the number of files that
can be selected is limited. Do not use this function to select multiple files, if the
potential number of files to be selected, could exceed this maximum.
IMPORTANT: AskFileName changes the current working directory to that of
the selected file.
Example:
types="All Files|*.*|WIL Files|*.wbt;*.mnu|Text Files|*.txt|"
fn1=AskFileName("SelectFile", "C:\Program Files (x86)\WinBatch\",
types, "sol.wbt", 1)
Message("File selected was", fn1)
which produces:
125
AskFileText
and then:
See Also:
AskFileText, AskItemList, AskLine, AskDirectory
AskFileText
Allows the user to choose an item from a list box initialized with data from a file.
Syntax:
AskFileText(title,filename,sort mode,select mode[,selection-required])
Parameters:
(s) title
(s) filename
126
title of the list box.
path and filename of file to display.
AskFont
(i) sort mode
@sorted for an alphabetic list. @unsorted to display the
text as is.
(i) select mode
@single to limit selection to one item.
@multiple allow selection of more than one item.
@extended to allow selection of multiple items by
extending the selection with the mouse or shift key.
(i) selection-required [optional] @TRUE the OK button will be greyed out until
an item is selected in the listbox, @FALSE default.
Returns:
(s)
the selected item or items. If more than one item is selected
it will be returned as a tab delimited list.
This function loads a file into a Windows list box, either as is or sorted
alphabetically, and displays the list box to the user. The line or lines highlighted by
the user (if any) will be returned to the program as a tab delimited list. AskFileText
has two primary uses:
First, it can be used to display multi-line messages to the user. In addition, because
of its ability to return selected lines, it may be used as multiple choice question box.
If the user does not make a selection, a null string ("") is returned.
If disk drive and path are not part of the filename, the current directory will be
examined first, and then the Environment PATH path will be searched to find the
desired file.
The function IntControl 63 can be used to set the coordinates for AskFileText,
AskItemList and AskTextBox windows.
AskItemList and AskFileText support multiple selection up to 32,767 items.
AskFileText uses the line length set by IntControl 65 (4096 characters by default).
Example:
A=AskFileText("win.ini", "c:\windows\win.ini", @unsorted, @single,
@FALSE)
Message("The line chosen was", A)
See Also:
AskItemList, AskFileName, AskLine, AskDirectory
AskFont
Displays a font selection dialog box, and returns information on the selected font.
Syntax:
AskFont(type,flags,reg-key,format)
Parameters:
(i) type
specifies the type of fonts to be listed.
127
AskFont
(i) flags
(s) reg-key
(i) format
Returns:
(s)
restricts the fonts that are listed.
specifies the name of a user-defined registry key under
"HKEY_CURRENT_USER\Software\Wilson
WindowWare" where persistent state information will be
stored. It will be created if it does not already exist. If "" is
specified, persistent state information will not be stored.
specifies the format in which the selected font will be
returned. See below.
RGB color value in requested format.
Type
Specifies the type of fonts to be listed, and can be one of the following values:
Value
Meaning
0
Screen fonts
1
Printer fonts
2
Both screen and printer fonts
If "type" is 1 or 2, a default printer must be installed, otherwise an error will occur.
Flags restricts the fonts that are listed, and can be 0 or more of the following values
combined with the bitwise OR ('|') operator.
Value
Meaning
1
List only script fonts (exclude OEM and Symbol character sets)
2
List only non-vector fonts
4
List only fixed-pitch fonts
8
List only fonts available on both the printer and the display
16
List only scalable fonts
32
List only TrueType fonts
64
List only horizontally oriented fonts
If flag 8 is specified, "type" will automatically be set to 2.
Format specifies the format in which information about the selected font will be
returned:
Value
0
Meaning
Tab-delimited string in the format:
LogFont[@TAB]PointSize[@TAB]Color[@TAB]FontType
LogFont
a vertical-bar delimited string containing font attributes. See the
Windows Interface Language help file for a description of the
LOGFONT format string.
128
AskItemList
PointSize
the font size in 1/10 of a point.
Color
the font color, as an RGB color value in the form "#RRGGBB". See
the AskColor function for a description.
FontType
a bitmask specifying the font type, consisting of one or more of the
following values which can be extracted with the bitwise AND ('&')
operator:
Value
256
512
1024
8192
16384
32768
Meaning
The font weight is bold
The italic font attribute is set
The font weight is normal
The font is a screen font
The font is a printer font
The font is simulated by the graphics device interface (GDI)
Example:
type=0
flags=0
customkeyword="test"
format=0
MyFont=AskFont( type, flags, customkeyword, format )
Message("AskFont return value is",MyFont)
See Also:
AskColor
AskItemList
Allows the user to choose an item from a list box initialized with a list variable.
Syntax:
AskItemList(title,list variable,delimiter,sort mode,select mode
[,selection-required])
Parameters:
(s) title
(s) list variable
(s) delimiter
(i) sort mode
title of the list box.
a string containing a list of items.
a character to act as a delimiter between items in the list.
@sorted for an alphabetic list.
@unsorted to display the list of items as is.
129
AskItemList
(i) select mode
@single to limit selection to one item.
@multiple to allow selection of more than one item.
@extended to allow selection of multiple items by
extending the selection with the mouse or shift key.
(i) selection-required [optional] @TRUE the OK button will be greyed out
until an item is selected in the listbox, @FALSE default.
Returns:
(s)
blank string if no items were selected, or the selected
item(s).
This function displays a list box. The list box is filled with a list of items, sorted or
unsorted, taken from a string you provide to the function. Each item in the string
must be separated ("delimited") by a character, which you also pass to the function.
The user selects one of the items by either double clicking on it, or single-clicking
and pressing OK. The item is returned as a string.
If you create the list with the FileItemize or DirItemize functions your delimiter will
be a tab-delimited list. For more information on delimiters see File Delimiters, (pg.
67).
The line(s) highlighted by the user (if any) will be returned to the program. If
multiple lines are selected, they will be separated by the specified delimiter. If the
user does not make a selection, a null string ("") is returned.
The function IntControl 45 can be used to set the coordinates for AskFileText,
AskItemList and AskTextBox windows.
AskItemList and AskFileText support multiple selection up to 32,767 items.
To change the file delimiter to a character of your own choosing, using IntControl
(29,p1,0,0,0).
The function IntControl 63 can be used to set the coordinates for AskFileText,
AskItemList and AskTextBox windows.
Example:
;Prompts user to chose a color from a list
list = StrCat("Red",@tab,"Blue",@tab,"Yellow",@tab,"Green")
A = AskItemList("Colors", list, @tab, @sorted, @single, @FALSE)
Message("The item selected is", A)
produces:
130
AskLine
See Also:
AskFileText, AskFileName, AskDirectory
AskLine
Prompts the user for one line of input.
Syntax:
AskLine(title,prompt,default[,format])
Parameters:
(s) title
(s) prompt
(s) default
(i) format
title of the dialog box.
question to be put to the user.
default answer.
[optional] specifies the format of the returned string.
Returns:
(s)
user response.
'Format' specifies the format of the returned string.
Format
0
1
2
Meaning
ANSI string (default)
Unicode string
hex string, with four hex bytes per Unicode character.
131
AskLine
Use this function to query the user for a line of data. The entire user response will be
returned if the user presses the OK button or the Enter key. If the user presses the
Cancel button or the Esc key, the processing of the WIL program is canceled.
Example:
name = AskLine("Game", "Please enter your name", "", 0)
game = AskLine("Game", "Favorite game?", "Solitaire",0)
message(StrCat(name,"'s favorite game is "), game)
produces:
And then…
And then, if Richard types "Scramble" and clicks on the OK button:
132
AskPassword
See Also:
AskPassword, AskYesNo, Dialog, Display, AskItemList, Message, Pause,
AskFileText, AskDirectory
AskPassword
Prompts the user for a password.
Syntax:
AskPassword(title,prompt)
Parameters:
(s) title
(s) prompt
title of the dialog box.
question to be put to the user.
Returns:
(s)
user response.
Pops up a special dialog box to ask for a password. An asterisk (*) is echoed for each
character that the user types; the actual characters entered are not displayed. The
entire user response will be returned if the user presses the OK button or the Enter
key. If the user presses the Cancel button or the Esc key, the processing of the WIL
program is canceled.
Example:
pw = AskPassword("Security check", "Please enter your password")
If StriCmp(pw, "Erin") == 0
Run(Environment("COMSPEC"), "")
Exit
else
Pause("Security breach", "Invalid password entered")
endif
See Also:
AskLine, AskYesNo, Dialog, AskDirectory
133
AskTextBox
AskTextBox
Prompts the user for multiple lines of input.
Syntax:
AskTextBox(title,prompt,default,flags,reserved)
Parameters:
(s) title
(s) prompt
(s) default
(i) flags
(i) reserved
title of the dialog box.
question to be put to the user.
default answer.
see below.
reserved for future use, should be set to 0.
Returns:
(s)
the text input by user.
"default" can contain multiple lines of text, using embedded @CRLF's.
"flags" can be set to 0, or can specify one or more of the following values combined
with the bitwise OR ('|') operator:
Value
0
1
2
Meaning
none of the following apply
do not automatically wrap text
place cursor at end of default text (instead of highlighting it)
The return value is whatever the user enters in the edit box. If multiple lines of text
are entered, they will be delimited in the returned string with @CRLF's.
Note: a horizontal scroll bar is added if "flag" number 1 is specified. Also, the
cursor is scrolled into view if "flag" number 2 is specified.
The function IntControl 63 can be used to set the coordinates for AskFileText,
AskItemList and AskTextBox windows.
Example:
ret=AskTextBox( "User satisfaction","Please type any comments here",
"NOCOMMENT", 0, 0)
if ret=="NOCOMMENT"
message("User input","Default returned. No user input" )
else
message("User input",ret)
endif
See Also:
AskLine, AskYesNo, Dialog
134
AskYesNo
AskYesNo
Prompts the user for a Yes or No answer.
Syntax:
AskYesNo(title,question)
Parameters
(s) title
(s) question
title of the question box.
question to be put to the user.
Returns:
(i)
@YES or @NO, depending on the button pressed.
This function displays a message box with three pushbuttons - Yes, No, and Cancel.
Example:
q = AskYesNo('Testing', 'Please press "YES"')
If q == @YES Then Exit
Display(3, 'ERROR', 'I said press "YES"')
produces:
... and then, if the user presses No:
See Also:
AskLine, AskPassword, Dialog, Display, AskItemList, Message, Pause, AskFileText
135
Beep
Atan
Calculates the arc tangent.
Syntax:
Atan(x)
Parameters:
(f) x
floating point number whose arc tangent is desired.
Returns:
(f)
the arc tangent result of x.
The Atan function calculates the arc tangent of x. If x is 0 a domain error occurs.
Example:
real=AskLine("ArcTan", "Enter a real number ", "34.6", 0)
answer=Atan(real)
Message("ArcTan of %real% is", answer)
See Also:
Acos, Asin, Cos, Sin, Tan
Average
Returns the average of a list of numbers.
Syntax:
Average(list)
Parameters:
(f) list
comma delimited floating point numbers to be averaged.
Returns:
(f)
the average of the numbers.
Use this function to compute the mean average of a series of numbers, delimited by
commas. It adds the numbers provided as parameters, and then divides by the
number of parameters. This function returns a floating point value.
Example:
avg = Average(1.7, 2.6, 3, 4, 5, 6, 7, 8, 9, 10.6, 11, 12)
Message("The average is", avg)
See Also:
Abs, Fabs, Max, Min, Random
Beep
Beeps once.
136
Binary Operations
Syntax:
Beep
Parameters:
(none)
Returns:
(not applicable)
Use this command to produce a short beep, generally to alert the user to an error
situation or to get the user's attention.
Example:
Beep
Pause("WARNING!!!", "You are about to destroy data!")
See Also:
PlayMedia, PlayMidi, PlayWaveForm, Sounds
Binary Operations
WIL contains a number of functions designed to allow direct access to areas - buffers
- of computer memory. By managing and working with these buffers using the
assorted Binary functions provided, you can implement a number of operations that
otherwise would be tedious and time consuming. Using the Binary functions, you
can perform edits on any sort of file, build new files, build data structures, and do
high-speed editing of multiple files. If you understand the structure of a data file, you
can perform fast look-ups of data with these functions.
The principal, required Binary functions are BinaryAlloc and BinaryFree. The
BinaryAlloc function allows you to allocate a buffer of almost any size. You may
have up to 128 separate buffers allocated at one time. When operations are complete
with a particular buffer, the BinaryFree function is used to return it to the system.
There are BinaryRead and BinaryWrite functions to read files into allocated
buffers, and to write the contents of buffers back to files. A BinaryCopy function
can move sections of one buffer to another, allowing buffers to be broken up and recombined in different fashions.
A set of peek and poke functions, BinaryPeek, BinaryPeekStr, BinaryPoke, and
BinaryPokeStr allow direct editing and modification of the buffers. These functions
can initialize a buffer that can be passed to a third party Dll via the DllCall function.
A BinaryIndex function is available to assist in searching buffers for known data
patterns. Some of these functions require you pass an offset parameter. Please note:
The offset is a 'pointer' that represents some distance from the start of the binary
buffer (which is zero). The BinaryStrCnt function can quickly scan a buffer and
return the number of occurrences of particular data patterns. A couple of functions to
get and set the End-of-Data point of each buffer (which is automatically tracked),
137
BinaryAlloc
BinaryEodGet and BinaryEodSet, and the average unreconstructed hacker has all
the tools necessary to become a real hazard to the community at large.
BinaryAlloc
Allocates a memory buffer of the desired size.
Syntax:
BinaryAlloc(size)
Parameters:
(i) size
Returns:
(i)
size in bytes of the desired memory buffer.
a handle to a buffer of the desired size, or @FALSE if the
allocation fails.
Use this function to allocate a memory buffer for Binary operations. Up to 128
separate buffers may be allocated concurrently. Nearly any reasonably sized buffer
may be allocated. Windows users may allocate over 10 million bytes, assuming
sufficient system memory and page file space is available. While users of 32 bit
Windows versions may allocate, theoretically, over 2 billion bytes, the real, practical
bounds are not established and will vary with system configuration.
When operations on a particular buffer are complete, it should be released with the
BinaryFree function.
Example:
; This example edits the Config.sys file
; by adding a new line to the bottom of the file.
;
fs=FileSize("C:\CONFIG.SYS")
; Allocate a buffer the size of your file + 100 bytes.
binbuf = BinaryAlloc(fs+100)
if binbuf == 0
Message("Error", "BinaryAlloc Failed")
else
; Read the file into the buffer.
BinaryRead(binbuf, "C:\CONFIG.SYS")
; Append a line to the end of the file in buffer.
BinaryPokeStr(binbuf, fs, "DEVICE=C:\FLOOGLE.SYS%@crlf%")
; Write modified file back to the file from the buffer.
BinaryWrite(binbuf, "C:\CONFIG.SYS")
binbuf=BinaryFree(binbuf)
endif
Message("BinaryAlloc", "Done.")
See Also:
BinaryAllocArray, Binary Operations, BinaryBufInfo, BinaryCopy, BinaryFree,
BinaryRead, DllCall
138
BinaryAllocArray
BinaryAllocArray
Allocates a memory buffer and copies the contents of an array.
Syntax:
BinaryAllocArray(array)
Parameters
(a) array
Specifies an array.
Returns:
(i)
a handle to a buffer that contains a copy of the array.
This function is intended to convert binary data from an array of binary data, such as
an image returned by a OLE/COM function to it's original form, so that it may be
subsequently written to disk.
Use this function to allocate a memory buffer that contains a copy of the contents of
an array. The memory buffer’s size is automatically set to hold a copy of the entire
array.
The array elements must be integers, floating point numbers or one of the COM
Automation types from the list below:
Variant-type
I1
I2
I4
I8
UI1
UI2
UI4
UI8
R4
R8
BOOL
CY
DATE
INT
UINT
DECIMAL
Value to specify
A 1-byte integer value
A 2-byte integer value
A 4-byte integer value
A 8-byte integer value
A 1-byte unsigned integer value
A 2- byte unsigned integer value
A 4- byte unsigned integer value
A 8- byte unsigned integer value
32-bit IEEE floating point value.
64-bit IEEE floating point value.
A Boolean (True/False) value
A currency value, specified as a string in the form
"#CURRENCY:value".
A date/time value, specified as a string in Ymd or YmdHms
format
4-byte signed integer value (equivalent to I4).
4-byte unsigned integer (equivalent to VT_UI4).
A decimal value, specified as a string in the form
"#DECIMAL:value".
139
BinaryAllocArray
You can use the ObjectTypeGet function to determine the type of a COM array
element.
All array elements must be of the exact same type. For example, the function will
fail, if the array elements are both integers and floating point numbers.
Text array elements are not supported.
If you want to create an integer array from scratch where each array element is
treated as a one or two byte value, use ObjectType with the first parameter set to
"U1" or "U2" respectively. For example,
aBytes = ArrDimension(2)
aBytes[0] = ObjectType("U1",65 )
aBytes[1] = ObjectType("U1", 90)
will create a byte array with two elements.
This function only accepts single dimensional arrays.
The following example uses the BinaryAllocArray function to copy an image to a
binary buffer so that it can be saved to a local file. The image is retrieved from a
host internet site as an array of bytes or “ARRAY|U1” as returned by
ObjectTypeGet.
Example:
; Create a local file name.
path = "c:\temp\"
imagefile = "http://www.google.com/images/logo.gif"
localname = StrCat(path, ItemExtract(ItemCount(imagefile, "/"),
imagefile, "/"))
; Get an image from the internet.
WinHttpReq = ObjectCreate("WinHttp.WinHttpRequest.5.1");WinXP SP 1
WinHttpReq.Open("GET", imagefile, @FALSE)
WinHttpReq.Send
x = WinHttpReq.ResponseBody
; Convert to binary buffer.
BinBuf = BinaryAllocArray(x)
; Write binary buffer to a file.
BinaryWrite(BinBuf, localname)
; Cleanup
WinHttpReq = 0
BinaryFree(BinBuf)
See Also:
BinaryAlloc, BinaryWrite, Binary Operations, ObjectType, ObjectTypeGet
140
BinaryAnd
BinaryAnd
Performs a bitwise AND on portions of two binary buffers.
Syntax:
BinaryAnd(target-handle,target-offset,source-handle,source-offset,count)
Parameters:
(i) target-handle
(i) target-offset
(i) source-handle
(i) source-offset
(i) count
Returns:
(i)
handle of target buffer.
zero-based offset into the target buffer specifying where the
data to be processed starts, and where the result of the
operation should be placed.
handle of source buffer.
zero-based offset into the source buffer specifying where
the data to be processed starts.
the number of bytes to process.
returns @TRUE.
The specified sections of the buffers are processed on a byte-by-byte basis, and the
results are written to the buffer specified by "target-handle". i.e., the byte at "sourceoffset" is AND'ed with the byte at "target-offset", and the result of the AND
operation is stored in the byte at "target-offset", then the bytes at "source-offset + 1"
and "target-offset + 1" are AND'ed, and so on.
"target-handle" and "source-handle" may both reference the same buffer, in which
case two sections of the buffer can be processed.
Example:
buf1 = BinaryAlloc(10)
buf2 = BinaryAlloc(10)
for i = 0 to 9
BinaryPoke(buf1, i, 5)
BinaryPoke(buf2, i, 6)
next
; this stuffs 5's into buf1
; this stuffs 6's into buf2
rc = BinaryAnd(buf1, 0, buf2, 0, 3)
a=BinaryPeek(
b=BinaryPeek(
c=BinaryPeek(
d=BinaryPeek(
e=BinaryPeek(
buf1,
buf1,
buf1,
buf1,
buf1,
0
1
2
3
4
; This replaces values in buf1
)
)
)
)
)
binaryWrite(buf1, "zzbin1.txt") ; if you want to see the values
; you can write it out with BinaryWrite
binaryWrite(buf2, "zzbin2.txt")
; AND LOGIC:
141
BinaryCheckSum
;
;
;
;
5 = 0101
6 = 0110
========
4 = 0100
= result
Message("Variables a, b, and c should now = 4", "a = %a%%@crlf%b =
%b%%@crlf%c = %c%%@crlf%")
See Also:
Binary Operations, BinaryAlloc, BinaryCopy, BinaryFree, BinaryRead, DllCal,
BinaryCompare
BinaryBufInfo
Returns information about the binary buffer.
Syntax:
BinaryBufInfo(handle,request)
Parameters:
(i) handle
(i) request
handle of binary buffer.
-1,0,1, or 2. see below.
Returns:
(i)
depends on request.
Request
-1
0
1
2
Description
Checks if binary buffer handle is valid. Returns @TRUE if valid,
@FALSE if invalid.
Get the size of the allocated binary buffer.
Get the address of a pointer to a binary buffer. See also IntControl 42.
Get a pointer to the beginning of the free area just past the already
initialized data in a buffer. See also BinaryEodGet.
Example:
fs = FileSize( "C:\CONFIG.SYS" )
binbuf = BinaryAlloc( fs )
size = BinaryBufInfo(binbuf, 0)
BinaryFree(binbuf)
Message("Size of Binary Buffer", size)
See Also:
Binary Operations, BinaryAlloc, BinaryEodGet, IntControl 42
BinaryCheckSum
Returns the MD5 digest (fingerprint) or simple CRC of a binary buffer.
142
BinaryClipGet
Syntax:
BinaryCheckSum(handle,request)
Parameters:
(i) handle
(i) request
handle of buffer.
specifies the type of digest or CRC to generate. See below.
Returns:
(s)
a hex-value string.
Request specifies the type of digest or CRC to generate, and can be one of the
following values:
Request
0
1
2
Meaning
MD5 digest
16-bit CRC
32-bit CRC
Return String Format (x=hex character)
"xxxxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxx"
"xxxx"
"xxxxxxxx"
Example:
fn="C:\testfile.txt"
fs=FileSize(fn)
bb=BinaryAlloc(fs)
BinaryRead(bb,fn)
MD5=BinaryChecksum(bb,0)
BinaryFree(bb)
Message("MD5 Fingerprint",strcat(fn,@crlf,MD5))
See Also:
BinaryAlloc, BinaryFree
BinaryClipGet
Reads the contents of the Windows clipboard into a binary buffer.
Syntax:
BinaryClipGet(handle,format)
Parameters:
(i) handle
(i) format
handle of buffer.
format of clipboard data.
Returns:
(i)
the number of bytes read from the clipboard.
Note: 0 in the first parameter of BinaryClipGet returns the size of buffer needed for
a subsequent BinaryAlloc, but doesn't attempt to place the contents of clipboard into
a buffer.
143
BinaryClipGet
The following is a list of possible clipboard formats. Note that some of them may
not be supported, because the clipboard contains a pointer or handle to external data
instead of the data itself.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
128
129
130
131
142
F_TEXT
F_BITMAP
(not supported)
F_METAFILEPICT
F_SYLK
F_DIF
CF_TIFF
CF_OEMTEXT
CF_DIB
CF_PALETTE
CF_PENDATA
CF_RIFF
CF_WAVE
CF_UNICODETEXT
CF_ENHMETAFILE
CF_HDROP
CF_LOCALE
CF_OWNERDISPLAY
CF_DSPTEXT
CF_DSPBITMAP
CF_DSPMETAFILEPICT
CF_DSPENHMETAFILE
Example:
;Takes a bitmap snapshot of the screen and pastes it to the
clipboard.
Snapshot(0)
;returns the size of buffer needed for a subsequent BinaryAlloc,
;but doesn't attempt to place the contents of clipboard into a buffer
size=BinaryClipGet(0,8)
;allocates a data buffer
bb=BinaryAlloc(size)
;read file format type CF_DIB
BinaryClipGet(bb,8)
; need to add first 14 bytes to make it
; a BMP file format
bmpdatasize=14
bb2=BinaryAlloc(size + bmpdatasize)
;The characters identifying the bitmap.'BM'
BinaryPokeStr(bb2, 0, "BM")
;Complete file size in bytes.
BinaryPoke4(bb2,2,size + bmpdatasize)
;Reserved
BinaryPoke4(bb2,6,0)
;Data offset
headersize=BinaryPeek4(bb,0)
144
BinaryClipPut
dataoffset = headersize + bmpdatasize
BinaryPoke4(bb2,10,dataoffset)
BinaryCopy(bb2,bmpdatasize,bb,0,size)
BinaryWrite(bb2,"c:\temp\screenshot.bmp")
BinaryFree(bb)
BinaryFree(bb2)
Message("All","Done")
See Also:
BinaryClipPut, BinaryPoke, BinaryAlloc, ClipGet, ClipGetEx
BinaryClipPut
Writes a binary buffer to the Windows clipboard.
Syntax:
BinaryClipPut(handle,format)
Parameters:
(i) handle
(i) format
handle of buffer.
format of clipboard data.
Returns:
(i)
returns @TRUE.
Note: that this function destroys the previous contents of the clipboard.
The following is a list of possible clipboard formats. Note that some of them may
not be supported, because the clipboard contains a pointer or handle to external data
instead of the data itself.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
128
F_TEXT
F_BITMAP
(not supported)
F_METAFILEPICT
F_SYLK
F_DIF
CF_TIFF
CF_OEMTEXT
CF_DIB
CF_PALETTE
CF_PENDATA
CF_RIFF
CF_WAVE
CF_UNICODETEXT
CF_ENHMETAFILE
CF_HDROP
CF_LOCALE
CF_OWNERDISPLAY
145
BinaryCompare
129
130
131
142
CF_DSPTEXT
CF_DSPBITMAP
CF_DSPMETAFILEPICT
CF_DSPENHMETAFILE
Example:
file = "c:\b\1clip.bmp"
format = 8
size = FileSize(file)
buf = BinaryAlloc(size)
BinaryRead(buf, file)
rc = BinaryClipPut(buf, format)
Message("BinaryClipPut returned", rc)
See Also:
BinaryClipGet, BinaryPoke, BinaryAlloc
BinaryCompare
Compares portions of two binary buffers.
Syntax:
BinaryCompare(handle1,offset1,handle2,offset2,count)
Parameters:
(i) handle1
(i) offset1
(i) handle2
(i) offset2
(i) count
Returns:
(i)
handle of first buffer.
zero-based offset into the first buffer specifying where the
data to be compared starts.
handle of second buffer.
zero-based offset into the second buffer specifying where
the data to be compared starts.
the number of bytes to compare.
@TRUE if the sections are identical; @FALSE otherwise.
The specified sections of the buffers are compared on a byte-by-byte basis. This
function is case-sensitive.
"handle1" and "handle2" may both reference the same buffer, in which case two
sections of the buffer can be compared.
Example:
buf1 = BinaryAlloc(10)
buf2 = BinaryAlloc(10)
BinaryPokeStr(buf1, 0, "Hello")
BinaryPokeStr(buf2, 0, "Hello")
rc = BinaryCompare(buf1, 0, buf2, 0, 4)
Message("BinaryCompare returned", rc)
146
BinaryConvert
See Also
Binary Operations, BinaryAlloc, BinaryCopy, BinaryFree, BinaryRead, DllCall
BinaryConvert
Converts a binary buffer.
Syntax:
BinaryConvert(handle,source-type,target-type,code-page,flags)
Parameters:
(i) handle
(i) source-type
(i) target-type
(i) code-page
(i) flags
handle of buffer.
format of existing data in buffer.
format of data which the buffer will be converted to.
any valid code page on your system.
additional options.
Returns:
(i)
the new binary EOD (end of data) for the buffer.
This function can be used to perform the following types of conversions:
8-bit <-> Unicode
Multibyte <-> Unicode
ANSI <-> OEM
-> Uppercase
-> Lowercase
"Source-type" and "target-type" can be one of the following:
Type
0
1
2
3
Meaning
8-bit ANSI
8-bit OEM
Multibyte (e.g., double-byte)
Unicode
Conversions from 8-bit (types 0 or 1) to or from multibyte (type 2) are not supported.
If you need to perform this type of conversion, you can do it in two steps, using
Unicode as an intermediate stage (e.g., ANSI to Unicode, then Unicode to
multibyte).
For conversions to or from Unicode, a code page must be specified for the 8-bit
(non-Unicode) character set.
"Code-page" can be any valid code page on your system, or one of the following
default code pages:
147
BinaryCopy
Type
0
1
2
Meaning
ANSI
OEM
Macintosh
For conversions which don't involve Unicode, "code-page" is ignored.
"Flags" can be one of the following:
Flag
1
2
Meaning
Convert to uppercase
Convert to lowercase
Note: that Unicode uses two bytes for each character. Therefore, for conversions to
Unicode, the binary buffer must be large enough to hold at least twice as much data
as is currently in the buffer. i.e., if you are trying to convert a buffer which contains
a 40-character string to Unicode, the buffer must be at least 80 bytes in size, because
the resulting Unicode string will be 80 bytes long.
Example:
buf = BinaryAlloc(20)
BinaryPokeStr(buf, 0, "HelloГџ")
rc = ""
string = BinaryPeekStr(buf, 0, BinaryEodGet(buf))
Message(rc, string)
rc = BinaryConvert(buf, 2, 3, 0, 1)
string = BinaryPeekStr(buf, 0, BinaryEodGet(buf))
Message(rc, string)
See Also:
Binary Operations, BinaryAlloc, BinaryCopy, BinaryFree, BinaryRead, DllCall
BinaryCopy
Copies bytes of data from one binary buffer to another.
Syntax:
BinaryCopy(handle targ,offset targ,handle src,offset src,count)
Parameters:
(i) handle targ
(i) offset targ
(i) handle src
(i) offset src
(i) count
148
handle of target buffer.
zero-based offset into the target buffer specifying where the
data to be copied should be placed.
handle of the source buffer.
zero-based offset into the source buffer specifying where
the data to be copied starts.
the number of bytes to copy.
BinaryEodGet
Returns:
(i)
number of bytes actually copied. The byte count may be
lower than that specified in the command if the source block
does not contain sufficient data.
Use this function to move blocks of data from one binary buffer to another one.
"Count" bytes are transferred from the "handle-src" buffer starting at "offset-src" to
the "handle-targ" buffer starting at "offset-targ".
Example:
; This example edits the config.sys file
; and adds a new line at the top of the file.
fs1 = FileSize("C:\CONFIG.SYS")
binbuf1 = BinaryAlloc(fs1)
BinaryRead(binbuf1, "C:\CONFIG.SYS")
binbuf2=binaryalloc(fs1 + 200)
n = BinaryPokeStr(binbuf2, 0, "Rem Note new line at top")
a2=BinaryCopy(binbuf2, n, binbuf1, 0, fs1)
BinaryWrite(binbuf2, "C:\CONFIG.SYS")
binbuf2 = BinaryFree(binbuf2)
binbuf1 = BinaryFree(binbuf1)
Message("BinaryCopy", "Done.")
See Also:
Binary Operations, BinaryAlloc, BinaryFree, BinaryRead, BinaryReadEx
BinaryWrite, BinaryWriteEx
BinaryEodGet
Returns the offset of the free byte just after the last byte of stored data.
Syntax:
BinaryEodGet(handle)
Parameters:
(i) handle
handle of buffer.
Returns:
(i)
offset of the free byte just after the last byte of stored data.
Use this function to determine the beginning of the free area just past the already
initialized data in a buffer. This value is automatically set by any Binary function
that modifies the buffer.
Example:
; This example adds three lines to the end of the
; config.sys file.
fs1 = FileSize( "C:\CONFIG.SYS" )
binbuf1 = BinaryAlloc( fs1 + 100 )
BinaryRead( binbuf1, "C:\CONFIG.SYS" )
a = BinaryEodGet( binbuf1 )
149
BinaryFree
BinaryPokeStr( binbuf1, a, "REM ADDING FIRST NEW LINE TO END%@CRLF%")
a = BinaryEodGet( binbuf1 )
BinaryPokeStr( binbuf1, a, "REM ADDING SECOND LINE TO END%@CRLF%" )
a = BinaryEodGet( binbuf1 )
BinaryPokeStr( binbuf1, a, "REM ADDING THIRD LINE TO END%@CRLF%")
BinaryWrite( binbuf1, "C:\CONFIG.SYS")
BinaryFree( binbuf1 )
Message("BinaryEODGet", "Done.")
See Also:
Binary Operations, BinaryAlloc, BinaryEodSet, BinaryIndex, BinaryIndexNc
BinaryEodSet
Sets the EOD (end of data) value of a buffer.
Syntax:
BinaryEodSet(handle,offset)
Parameters:
(i) handle
(i) offset
handle of buffer.
desired offset to set the end-of-data value to.
Returns:
(i)
previous value.
Use this function to update the EOD value. This can be done when data at the end of
a buffer is to be discarded, or when the buffer has been modified by an external
program - such as via a DllCall.
Example:
; This function extracts the first line from the
; config.sys file and writes it to a new file.
fs1 = FileSize("C:\CONFIG.SYS")
binbuf1 = binaryalloc( fs1 + 100)
BinaryRead(binbuf1, "C:\CONFIG.SYS")
a = BinaryIndex(binbuf1, 0, @CRLF, @FWDSCAN)
; we just found the end of first line
a = a + 2
; add 2 to skip crlf
BinaryEodSet(binbuf1, a)
BinaryWrite(binbuf1, "firstlin.txt")
binbuf1 = BinaryFree(binbuf1)
Message("BinaryEODSet", "Done.")
See Also:
Binary Operations, BinaryAlloc, BinaryEodGet, BinaryIndex, DllCall
BinaryFree
Frees a buffer previously allocated with BinaryAlloc.
150
BinaryHashRec
Syntax:
BinaryFree(handle)
Parameters:
(i) handle
handle of buffer to free.
Returns:
(i)
@FALSE.
Use this function to free a binary buffer previously allocated by the BinaryAlloc
function. After freeing the buffer, no further operations should be performed on the
buffer or its handle.
Example:
fs=FileSize("C:\CONFIG.SYS")
binbuf = BinaryAlloc(fs+100)
if binbuf == 0
Message("Error", "BinaryAlloc Failed")
else
BinaryRead(binbuf, "C:\CONFIG.SYS")
BinaryPokeStr(binbuf, fs, "DEVICE=C:\FLOOGLE.SYS%@crlf%")
BinaryWrite(binbuf, "C:\CONFIG.SYS")
binbuf=BinaryFree(binbuf)
endif
Message("BinaryFree", "Done.")
See Also:
Binary Operations, BinaryAlloc
BinaryHashRec
Returns a pointer to a record in a binary buffer.
Syntax:
BinaryHashRec(handle,recsize,key offset,key size,key value)
Parameters:
(i) handle
(i) recsize
(i) key offset
(i) key size
(i) key value
Returns:
(i)
handle of buffer.
specifies the fixed length of each record.
the offset within a record of the key field (where the first
byte in the record is 0).
specifies the size of the key field, in bytes.
the value of the key field to be searched for.
the starting position of a record in a binary buffer.
This function uses a hashing algorithm to calculate a hash value for the specified
"key value", which provides an offset into the binary buffer. It starts searching at that
offset for either (1) a record with a key field whose first byte is a 0, or (2) a record
151
BinaryHashRec
with a key field whose value is the same as "key value". For case (1), it stores "key
value" in the key field of the found record, and returns the offset of the beginning of
that record. For case (2), the offset of the record is returned but not stored. If an
appropriate record cannot be found (i.e., if the buffer is full), it returns an error.
Note: The binary buffer must consist of fixed-length records. Each record must
contain a fixed-length key field in a fixed position.
Example:
; In this example, we are going to choose a bunch of fruits
; at random, look the fruit up in a hash table, increment How many
; times each fruit occurs, sort the table when we are done, and write
; a report to a file.
fruits="apple pear banana apricot kiwi orange peach grape grapefruit"
fruitcount=ItemCount(fruits," ")-1
namesize=20
countsize=4
recsize=namesize+countsize
nameoffset=0
countoffset=20
tableentries=100 ; note hash tables should be 20-40 percent bigger
than your data
tablesize=tableentries*recsize
hash=BinaryAlloc(tablesize)
For x=1 to 1000
afruit=ItemExtract(Random(fruitcount)+1,fruits," ")
offset=BinaryHashRec(hash,recsize,nameoffset,namesize,afruit)
BinaryIncr4(hash,offset+countoffset)
next
BinarySort(hash,recsize,countoffset,countsize,@WORD4|@ASCENDING)
offset=0
Report=""
While offset<tablesize
if offset==0
if BinaryPeek(hash,0)==0
offset=BinaryIndex(hash,recsize,"",@FWDSCAN)
endif
else
offset=BinaryIndex(hash,offset,"",@FWDSCAN)
endif
if offset==0 then break
afruit=BinaryPeekStr(hash,offset,namesize)
acount=BinaryPeek4(hash,offset+countoffset)
offset=offset+recsize
Report=strcat(report,afruit," ",acount,@crlf)
endwhile
BinaryFree(hash)
Message("Random Fruit Report",Report)
152
BinaryIndex
See Also:
BinarySort, BinaryIncr, BinaryPeek, BinaryPoke
BinaryIncr
Peeks at a value, increments the value by 1 then pokes the value back into the buffer.
Syntax:
BinaryIncr(handle,offset)
BinaryIncr2(handle,offset)
BinaryIncr4(handle,offset)
BinaryIncrFlt(handle,offset)
Incr an 8 bit value.
Incr a 16 bit value.
Incr a 32 bit value.
Incr a 64 bit floating point number.
Parameters:
(i) handle
(i) offset
handle of buffer.
offset in the buffer to obtain bytes from.
Returns:
(i/f)
new byte value.
BinaryIncr is equivalent to doing a BinaryPeek, incrementing the extracted value
by 1, and then doing a BinaryPoke to store the new value.
Example:
Binbuf=BinaryAlloc(10)
BinaryPoke( binbuf, 5, -14 ) ;Pokes a new value into the buffer.
a=BinaryPeek( binbuf, 5 )
;Finds the value of a byte.
Message("Hmmm", "Returned value is %a%" )
; Value will be 242 which is (256 - 14). 242 and -14 map
; to the same 8bit number.
See Also:
Binary Operations, BinaryCopy, BinaryPeekStr, BinaryPoke, BinaryPokeStr
BinaryIndex
Searches a buffer for a string. (case sensitive)
Syntax:
BinaryIndex(handle,offset,string,direction)
Parameters:
(i) handle
(i) offset
(s) string
(i) direction
handle of buffer.
zero-based offset in the buffer to begin search.
the string to search for within the buffer.
the search direction. @FWDSCAN searches forwards,
while @BACKSCAN searches backwards.
153
BinaryIndexBin
Returns:
(i)
offset of string within the buffer, or 0 if not found.
This function searches for a "string" within a buffer. Starting at the "offset" position,
it goes forwards or backwards depending on the value of the "direction" parameter. It
stops when it finds the "string" within the buffer and returns the string's beginning
offset.
Notes: BinaryIndex has been superseded with the function BinaryIndexEx.
The string parameter may be composed of any characters except the null (00)
character. A blank string ("") can be specified for the "string" parameter, in which
case the function will return the offset of the first non-NULL character found,
starting at "offset".
The return value of this function is possibly ambiguous. A zero return value may
mean the string was not found, or it may mean the string was found starting at offset
0.
If there is a possibility that the string to be searched for could begin at the beginning
of the buffer, you must determine some other way of resolving the ambiguity, such
as using BinaryPeekStr.
The string being searched for has to appear in the file 'as is'. In some files, such as
word processing documents or spreedsheets the string you see in the application may
not exist in searchable form in the file.
This function does not support Unicode files.
Example:
; Find line number of line in config.sys where HIMEM occurs
fs1 = FileSize( "C:\CONFIG.SYS" )
binbuf1 = binaryalloc( fs1 )
a1 = BinaryRead( binbuf1, "C:\CONFIG.SYS" )
a = BinaryIndexNc( binbuf1, 0, "HIMEM", @FWDSCAN ) ; find HIMEM
if a == 0
Message("Hmmm", "HIMEM not found in CONFIG.SYS file")
else
c = BinaryStrCnt( binbuf1, 0, a, @CRLF) + 1
Message("Hmmm", "HIMEM found on line %c%")
endif
See Also:
Binary Operations, BinaryCopy, BinaryEodGet, BinaryEodSet, BinaryIndexBin,
BinaryIndexEx, BinaryIndexNc, BinaryStrCnt
BinaryIndexBin
Searches a buffer for an item.
154
BinaryIndexEx
Syntax:
BinaryIndexBin(handle,offset,item,direction,match-case)
Parameters:
(i) handle
(i) offset
(s/i) item
(i) direction
(i) match-case
Returns:
(i) offset
handle of buffer.
zero-based offset in the buffer to begin search.
specifies the item to be searched for. It may be either a
hex string indicating the bytes to search for (two hex
characters per byte), or the handle of a binary buffer
containing the bytes to search for. If "item" is a blank string
or an empty binary buffer, "offset" will be returned.
the search direction. @FWDSCAN searches
forwards, while @BACKSCAN searches backwards.
specify 1 for a case-sensitive search, or 0 for a caseinsensitive search.
offset where the item was found, or -1 if not found.
This function is like BinaryIndexEx, but can search for strings containing NULL
bytes.
Example:
; Search a (Unicode) .REG file for a string
regfile = "C:\TEST.REG"
lookfor = "00"
fs1 = FileSize( regfile )
binbuf1 = binaryalloc( fs1 )
a1 = BinaryRead( binbuf1, regfile )
a = BinaryIndexBin( binbuf1, 0, lookfor, @FWDSCAN ,0);find HIMEM
if a == -1
Message("Hmmm", StrCat("String not found in ", regfile," file"))
else
c = BinaryStrCnt( binbuf1, 0, a, @CRLF) + 1
Message("Hmmm", StrCat(lookfor," found on line ",c))
endif
See Also:
BinaryCopy, BinaryIndex, BinaryIndexNc, BinaryEodGet, BinaryEodSet,
BinaryStrCnt.
BinaryIndexEx
Searches a buffer for a string. This function is very similar to BinaryIndex and
BinaryIndexNc, except this function will return -1, if the specified string was not
found.
155
BinaryIndexEx
Syntax:
BinaryIndexEx(handle,offset,string,direction,match-case)
Parameters:
(i) handle
(i) offset
(s) string
(i) direction
(i) match-case
Returns:
(i)
handle of buffer.
zero-based offset in the buffer to begin search.
the string to search for within the buffer.
the search direction. @FWDSCAN searches forwards,
while @BACKSCAN searches backwards.
This function is almost the same as BinaryIndex (if
"match-case"=1) and BinaryIndexNc (if "match-case =0).
offset of string within the buffer, if the specified string is
not found, this function returns -1 (unlike BinaryIndex and
BinaryIndexNc , which return 0).
Note: This function is almost the same as BinaryIndex (if "match-case" = @TRUE)
and BinaryIndexNc (if "match-case" = @FALSE). The one difference: if the
specified string is not found, this function returns -1 (unlike those other functions,
which return 0).
The string parameter may be composed of any characters except the null (00)
character. A blank string ("") can be specified for the "string" parameter, in which
case the function will return the offset of the first non-NULL character found,
starting at "offset".
The string being searched for has to appear in the file 'as is'. In some files, such as
word processing documents or spreedsheets the string you see in the application may
not exist in searchable form in the file.
This function does not support Unicode files.
Example:
fs1 = FileSize( "C:\CONFIG.SYS" )
binbuf1 = binaryalloc( fs1 )
a1 = BinaryRead( binbuf1, "C:\CONFIG.SYS" )
a = BinaryIndexEx( binbuf1, 0, "HIMEM", @FWDSCAN ,0);find HIMEM
if a == -1
Message("Hmmm", "HIMEM not found in CONFIG.SYS file")
else
c = BinaryStrCnt( binbuf1, 0, a, @CRLF) + 1
Message("Hmmm", "HIMEM found on line %c%")
endif
See Also:
Binary Operations, BinaryCopy, BinaryEodGet, BinaryEodSet, BinaryIndex,
BinaryIndexBin, BinaryIndexNc, BinaryStrCnt
156
BinaryIndexNc
BinaryIndexNc
Searches a buffer for a string, ignoring case.
Syntax:
BinaryIndexNc(handle,offset,string,direction)
Parameters:
(i) handle
(i) offset
(s) string
(i) direction
Returns:
(i)
handle of buffer.
zero-based offset in the buffer to begin search.
the string to search for within the buffer.
the search direction. @FWDSCAN searches forwards,
while @BACKSCAN searches backwards.
offset of string within the buffer, or 0 if not found.
This function is like BinaryIndex, but performs a case-insensitive search for a
"string" within a buffer. Starting at the "offset" position, it goes forwards or
backwards depending on the value of the "direction" parameter. It stops when it finds
the "string" within the buffer and returns the string's beginning offset.
Notes: BinaryIndexNc has been superseded with the function BinaryIndexEx.
The string parameter may be composed of any characters except the null (00)
character. A blank string ("") can be specified for the "string" parameter, in which
case the function will return the offset of the first non-NULL character found,
starting at "offset".
The return value of this function is possibly ambiguous. A zero return value may
mean the string was not found, or it may mean the string was found starting at offset
0. If there is a possibility that the string to be searched for could begin at the
beginning of the buffer, you must determine some other way of resolving the
ambiguity, such as using BinaryPeekStr.
The string being searched for has to appear in the file 'as is'. In some files, such as
word processing documents or spreedsheets the string you see in the application may
not exist in searchable form in the file.
This function does not support Unicode files.
Example:
; Find line number of line in config.sys where HIMEM occurs
fs1 = FileSize( "C:\CONFIG.SYS" )
binbuf1 = binaryalloc( fs1 )
a1 = BinaryRead( binbuf1, "C:\CONFIG.SYS" )
a = BinaryIndexNc( binbuf1, 0, "HIMEM", @FWDSCAN ) ; find HIMEM
if a == 0
Message("Hmmm", "HIMEM not found in CONFIG.SYS file")
else
c = BinaryStrCnt( binbuf1, 0, a, @CRLF) + 1
157
BinaryOleType
Message("Hmmm",
"HIMEM found on line %c%")
endif
See Also:
Binary Operations, BinaryCopy, BinaryIndex, BinaryIndexBin, BinaryIndexEx,
BinaryEodGet, BinaryEodSet, BinaryStrCnt
BinaryOleType
Specifies how a binary buffer will be used by COM/OLE functions.
Syntax:
BinaryOleType(handle,type,reserved-1,reserved-2,reserved-3)
Parameters:
(i) handle
(i) type
(i) reserved-1
(i) reserved-2
(i) reserved-3
Returns:
(i)
handle of buffer.
specifies what type of parameter the buffer will represent,
see below.
reserved for future use, specify as 0.
reserved for future use, specify as 0.
reserved for future use, specify as 0.
@TRUE if successful; @FALSE if unsuccessful.
BinaryOleType defines the attributes of the binary buffer specified by "handle",
which determines what happens when you use the binary buffer handle as a
parameter to an COM/OLE object (i.e., one created with the ObjectOpen function).
When a binary buffer is created with BinaryAlloc, it has a "type" of 0 (undefined).
You must use BinaryOleType to set the buffer's type before using it as a parameter
to an COM/OLE object. This function does not modify any data in the binary buffer
itself.
When an COM/OLE object is called, and one of the parameters is a binary buffer
handle, the following actions are automatically taken:
1. An internal COM/OLE buffer is created which is (at least) as large as the
binary buffer.
2. If the binary buffer is defined as an input (or input/output) parameter (see
"type" parameter), any data in the binary buffer (up to the binary EOD) is
converted as necessary to the specified format and copied to the COM/OLE
buffer.
3. The COM/OLE buffer is passed to the COM/OLE object.
When the COM/OLE object returns:
158
BinaryOleType
4. If the binary buffer is defined as an output (or input/output) parameter (see
"type" below), then any data in the COM/OLE buffer is copied back to the
binary buffer. If it is possible to determine how much data was returned in the
COM/OLE buffer, then the binary EOD is set to the end of the data;
otherwise, the binary EOD is set to the end of the binary buffer.
5. The COM/OLE buffer is freed.
TYPE
"type" specifies what type of parameter the buffer will represent, and whether it will
be used as an input or output parameter (or both). It consists of one entry from each
of the following groups, added together:
data type:
0
1
2
3
4
5
6
7
8
9
10
11
undefined
BSTR (VT_BSTR)
BSTR* (VT_BSTR | VT_BYREF)
byte array (VT_UI1 | VT_ARRAY)
I1 pointer (VT_I1 | VT_BYREF)
I2 pointer (VT_I2 | VT_BYREF)
I4 pointer (VT_I4 | VT_BYREF)
UI1 pointer (VT_UI1 | VT_BYREF)
UI2 pointer (VT_UI2 | VT_BYREF)
UI4 pointer (VT_UI4 | VT_BYREF)
R4 pointer (VT_R4 | VT_BYREF)
R8 pointer (VT_R8 | VT_BYREF)
direction:
100
200
300
input parameter
output parameter
input/output parameter
Example:
;Wake on LAN example
#DefineFunction Hex2Dec(hex)
str="0123456789ABCDEF"
hex=StrTrim(StrUpper(hex))
hexlen=StrLen(hex)
dec=0
for x=1 to hexlen
dec=(dec*16) + StrIndex(str,strsub(hex,x,1),0,@fwdscan) -1
next
return(dec)
#EndFunction
BCastAddr="10.10.10.255"
; Set network broacast address here
MacAddress="11:22:33:44:55:66" ; Set MAC address of machine to wake
up here
159
BinaryOr
bbpacket=BinaryAlloc( (6*33) + 6)
BinaryOLEType(bbpacket,103,0,0,0)
BinaryPoke(bbpacket,0,255)
BinaryPoke(bbpacket,1,255)
BinaryPoke(bbpacket,2,255)
BinaryPoke(bbpacket,3,255)
BinaryPoke(bbpacket,4,255)
BinaryPoke(bbpacket,5,255)
For yy=0 to 15
For xx=1 to 6
mm=ItemExtract(xx,MacAddress,":")
mm=Hex2Dec(mm)
BinaryPoke(bbpacket,5+xx+(yy*6),mm)
next
next
;The WinSock OCX has a distribution problem in that
;it sometimes is not installed properly. This is
;reported to fix it...
if RegExistKey(@REGCLASSES,"Licenses\2c49f800-c2dd-11cf-9ad60080c7e7b78d") == @FALSE
ErrorMode(@off)
flag=RegSetValue(@REGCLASSES,"Licenses\2c49f800-c2dd-11cf-9ad60080c7e7b78d","mlrljgrlhltlngjlthrligklpkrhllglqlrk")
ErrorMode(@cancel)
if flag==0
Message("Error","Admin access required to set registry key.")
exit
endif
endif
objSocket = ObjectCreate("MSWinsock.Winsock")
objSocket.Protocol = 1
;UDP
objSocket.RemoteHost = BCastAddr
objSocket.SendData(bbpacket)
objSocket = 0
BinaryFree(bbpacket)
Message("All","Doned")
See Also:
Binary Operations, BinaryAlloc, BinaryCopy, BinaryFree, BinaryRead,
BinaryReadEx, DllCall
BinaryOr
Performs a bitwise OR on portions of two binary buffers.
Syntax:
BinaryOr(target-handle,target-offset,source-handle,source-offset,count)
160
BinaryOr
Parameters:
(i) target-handle
(i) target-offset
(i) source-handle
(i) source-offset
(i) count
Returns:
(i)
handle of target buffer.
zero-based offset into the target buffer specifying where the
data to be processed starts, and where the result of the
operation should be placed.
handle of source buffer.
zero-based offset into the source buffer specifying where
the data to be processed starts.
the number of bytes to process.
returns @TRUE.
The specified sections of the buffers are processed on a byte-by-byte basis, and the
results are written to the buffer specified by "target-handle". i.e., the byte at "sourceoffset" is OR'ed with the byte at "target-offset", and the result of the OR operation is
stored in the byte at "target-offset", then the bytes at "source-offset + 1" and "targetoffset + 1" are OR'ed, and so on.
"target-handle" and "source-handle" may both reference the same buffer, in which
case two sections of the buffer can be processed.
Example:
buf1 = BinaryAlloc(10)
buf2 = BinaryAlloc(10)
for i = 0 to 9
BinaryPoke(buf1, i, 5)
; this stuffs 5's into buf1
BinaryPoke(buf2, i, 6)
; this stuffs 6's into buf2
next
BinaryOr(buf1, 0, buf2, 0, 3)
; This replaces values in buf1
a=BinaryPeek( buf1, 0 )
b=BinaryPeek( buf1, 1 )
c=BinaryPeek( buf1, 2 )
d=BinaryPeek( buf1, 3 )
e=BinaryPeek( buf1, 4 )
;BinaryWrite(buf1, "zzbin1.txt") ; if you want to see the values
;BinaryWrite(buf2, "zzbin2.txt") ; you can write it out with
BinaryWrite
; OR LOGIC:
; 5 = 0101
; 6 = 0110
; ========
; 7 = 0111
Message("Variables a, b, and c should now = 7", "a = %a%%@crlf%b =
%b%%@crlf%c = %c%%@crlf%")
161
BinaryPeekHex
See Also:
Binary Operations, BinaryAlloc, BinaryCopy, BinaryFree, BinaryRead,
BinaryReadEx, BinaryCompare, BinaryAnd
BinaryPeek
Returns the value of a byte from a binary buffer.
Syntax for BinaryPeek Functions:
BinaryPeek(handle,offset)
BinaryPeek2(handle,offset)
BinaryPeek4(handle,offset)
BinaryPeekFlt(handle,offset)
Peeks an 8 bit value.
Peeks a 16 bit value.
Peeks a 32 bit value.
Peeks a 64 bit floating point
number.
Parameters:
(i) handle
(i) offset
handle of buffer.
zero-based offset in the buffer to obtain bytes from.
Returns:
(i/f)
new byte value.
Use these functions to return the value of a number in the binary buffer. The
BinaryPeek's extract 8, 16, or 32 bytes (respectively) beginning at "offset".
BinaryPeekFlt treats the 64 bytes it extracts as a 8 byte floating point number.
Example:
binbuf=BinaryAlloc(10)
BinaryPoke( binbuf, 5, -14 ) ;Pokes a new value into the buffer.
a=BinaryPeek( binbuf, 5 )
;Finds the value of a byte.
Message("Hmmm", "Returned value is %a%" )
; Value will be 242 which is (256 - 14). 242 and -14 map
; to the same 8bit number.
See Also:
Binary Operations, BinaryCopy, BinaryPeekStr, BinaryPoke, BinaryPokeStr
BinaryPeekHex
Extracts data from a binary buffer as a hex string.
Syntax:
BinaryPeekHex(handle,offset,count)
Parameters:
(i) handle
(i) offset
(i) count
162
handle of buffer.
zero-based offset in the buffer to obtain byte from.
specifies the number of bytes to read from the buffer.
BinaryPeekStr
Returns:
(s)
a hex string, containing 2 hex characters for each byte read
from the buffer.
Example:
binbuf=BinaryAlloc(1)
BinaryPokeStr( binbuf, 0, "A" ) ;Pokes a new value into the buffer
ret=BinaryPeekHex( binbuf, 0, 1) ;Finds the hex value of the letter A
Message("Hmmm", "Hex value of A is %ret%" )
See Also:
Binary Operations, BinaryPokeHex, BinaryCopy, BinaryIncr, BinaryPeekStr,
BinaryPoke, BinaryPokeStr
BinaryPeekStr
Extracts a string from a binary buffer.
Syntax:
BinaryPeekStr(handle,offset,maxsize)
Parameters:
(i) handle
(i) offset
(i) maxsize
Returns:
(s)
handle of buffer.
offset in the buffer the string starts at.
maximum number of bytes in string.
string starting at "offset" location in binary buffer. String
consists of all non-zero bytes up to the first zero byte or
"maxsize" number of bytes.
This function is used to extract string data from a binary buffer. The desired starting
"offset" and a "maxsize" are passed to the function. The function returns a string of
bytes, starting at the specified "offset", and continuing until either a zero byte is
found (which terminates the string) or the "maxsize" number of bytes have been
copied into the return string.
Example:
; This example searches the Config.sys for the first
; occurrence of the string HIMEM. It then extracts
; the line containing the string and prints it out.
fs = FileSize( "C:\CONFIG.SYS" )
binbuf = BinaryAlloc( fs )
BinaryRead( binbuf, "C:\CONFIG.SYS" )
; Search for first occurrence of HIMEM.
himem = BinaryIndex( binbuf, 0, "HIMEM", @FWDSCAN)
; Single out beginning of line which contains HIMEM string,
; skipping over the @crlf.
linebegin = BinaryIndex( binbuf, himem, @CRLF, @BACKSCAN) + 2
; Search for the end of the line which contains the HIMEM string.
163
BinaryPeekStrW
lineend = BinaryIndex( binbuf, himem, @CRLF, @FWDSCAN)
linelen = lineend-linebegin+1
; Extract the line with HIMEM string.
linedata=BinaryPeekStr(binbuf, linebegin, linelen)
binbuf=BinaryFree(binbuf)
Message("Himem.sys line in config.sys reads", linedata)
See Also:
Binary Operations, BinaryCopy, BinaryPeek, BinaryPeekStrW, BinaryPoke,
BinaryPokeStr
BinaryPeekStrW
Extracts a Unicode string from a binary buffer.
Syntax:
BinaryPeekStrW(handle,offset,maxsize[,reverse-bytes])
Parameters:
(i) handle
(i) offset
(i) maxsize
(i) reverse bytes
Returns:
(s)
handle of buffer.
zero-based offset in the buffer where the string starts.
maximum number of bytes in string. Must be an even
number.
@FALSE default. @TRUE the bytes in each Unicode
character are reversed from the normal byte order.
Unicode string.
This function is used to extract Unicode string data from a binary buffer. The
desired starting offset and a maxsize are passed to the function. The function returns
a Unicode string of bytes, starting at the specified offset and continuing until the end
of the string is reached, when a Unicode NULL character is found (which terminates
the string) or the maxsize number of bytes have been copied into the return string.
Example:
unicodestr = ChrHexToUnicode("480065006C006C006F00");Hello
bytecnt = StrByteCount ( unicodestr, 1)
buf = BinaryAlloc(bytecnt)
BinaryPokeStrW( buf, 0, unicodestr)
unicodestr = BinaryPeekStrW( buf, 0, bytecnt )
BinaryFree(buf)
Message("Unicode String", unicodestr)
See Also:
Binary Operations, BinaryCopy, BinaryPeek, BinaryPeekStr, BinaryPoke,
BinaryPokeStr
164
BinaryPokeHex
BinaryPoke
Pokes a new value into a binary buffer at offset returning the previous value.
Syntax for BinaryPoke Functions:
BinaryPoke(handle,offset,value)
BinaryPoke2(handle,offset,value)
BinaryPoke4(handle,offset,value)
BinaryPokeFlt(handle,offset,value)
Pokes an 8 bit value.
Pokes a 16 bit value.
Pokes a 32 bit value.
Pokes a 64 bit floating
point number.
Parameters:
(i) handle
(i) offset
(i)/(f) value
handle of buffer.
zero-based offset in the buffer to store byte(s).
value to store.
Returns:
(i/f)
previous value.
This function pokes a value into the binary buffer at the offset specified.
Example:
BinaryPoke( binbuf, 5, -14 ) ;Pokes a new value into the buffer.
a=BinaryPeek( binbuf, 5 )
;Finds the value of a byte.
Message("Hmmm", "Returned value is %a%" )
; Value will be 242 which is (256 - 14). 242 and -14 map
; to the same 8bit number.
See Also:
Binary Operations, BinaryPokeHex, BinaryPokeStr, BinaryPokeStrW
BinaryPokeHex
Writes data in a hex string form into a binary buffer.
Syntax:
BinaryPokeHex(handle,offset,hex-string)
Parameters:
(i) handle
(i) offset
(s) hex-string
Returns:
(i)
handle of buffer.
zero-based offset in the buffer to store string.
is a hex string, containing 2 hex characters for each byte
that will be written to the buffer.
number of bytes stored.
165
BinaryPokeStr
Example:
binbuf=BinaryAlloc(1)
BinaryPokeHex( binbuf, 0, "41" )
ret=BinaryPeekStr( binbuf, 0, 1)
Message("Hmmm", "String value of hex 41 is %ret%" )
See Also:
Binary Operations, BinaryPoke, BinaryPoke2, BinaryPoke4, BinaryPokeFlt,
BinaryPokeStr, BinaryPokeStrW
BinaryPokeStr
Writes a string into a binary buffer.
Syntax:
BinaryPokeStr(handle,offset,string)
Parameters:
(i) handle
(i) offset
(s) string
handle of buffer.
offset in the buffer to store string.
string to store into buffer.
Returns:
(i)
number of bytes stored.
This function is used to write string data into a binary buffer. There must be
sufficient space in the buffer between the offset and the allocated end of the buffer to
accommodate the string.
Note: The string parameter may be composed of any characters except the null (00)
character. If a null character is found, it will be assumed that the string ends at that
point. If you need to store a null character into a binary buffer, use the BinaryPoke
function.
Example:
; This example writes a new device= line to SYSTEM.INI
; It is *very* fast
NewDevice = "DEVICE=COOLAPP.386";
; Change to the Windows Directory
DirChange(DirWindows(0))
; Obtain filesize and allocate binary buffers
fs1=FileSize("SYSTEM.INI")
srcbuf = BinaryAlloc(fs1)
editbuf = BinaryAlloc(fs1+100)
; Read existing system.ini into memory
BinaryRead( srcbuf, "SYSTEM.INI")
; See if this change was already installed. If so, quit
a = BinaryIndexNc( srcbuf, 0, "COOLAPP.386", @FWDSCAN)
if a != 0 then goto AlreadyDone
; Find 386Enh section.
a = BinaryIndexNc( srcbuf, 0, "[386Enh]", @FWDSCAN)
166
BinaryPokeStrW
; Find beginning of next line ( add 2 to skip over our crlf )
cuthere = BinaryIndexNc( srcbuf, a, @CRLF, @FWDSCAN) + 2
; Copy data from beginning of file to just after [386Enh}
; to the edit buffer
BinaryCopy( editbuf, 0, srcbuf, 0, cuthere)
; Add the device= line to the end of the edit buffer, and add a CRLF
BinaryPokeStr(editbuf,BinaryEodGet(editbuf), Strcat(NewDevice,@CRLF))
; Copy remaining part of source buffer to the edit buffer
a = BinaryEodGet(editbuf)
b = BinaryEodGet(srcbuf)
BinaryCopy( editbuf, a, srcbuf, cuthere, b-cuthere);
; Save file out to disk. Use system.tst until it is
; completely debugged
BinaryWrite( editbuf, "SYSTEM.TST")
; Close binary buffers
:AlreadyDone
BinaryFree(editbuf)
BinaryFree(srcbuf)
Message("BinaryPokeStr", "Done.")
See Also:
Binary Operations, BinaryPoke, BinaryPoke2, BinaryPoke4, BinaryPokeFlt,
BinaryPokeHex, BinaryPokeStrW
BinaryPokeStrW
Writes a Unicode string into a binary buffer.
Syntax:
BinaryPokeStrW(handle,offset,string[,reverse-bytes])
Parameters:
(i) handle
(i) offset
(s) string
(i) reverse bytes
Returns:
(i)
handle of buffer.
zero-based offset in the buffer to store string.
string to store into buffer.
@FALSE default. @TRUE the bytes in each Unicode
character are reversed from the normal byte order.
number of bytes stored.
This function is used to write Unicode string data into a binary buffer. There must
be sufficient space in the buffer between the offset and the allocated end of the buffer
to accommodate the string. Each character in a Unicode-string requires 2 bytes in
the buffer. The return value is the number of bytes written.
Example:
unicodestr = ChrHexToUnicode("480065006C006C006F00");Hello
bytecnt = StrByteCount ( unicodestr, 1)
buf = BinaryAlloc(bytecnt)
167
BinaryReadEx
BinaryPokeStrW( buf, 0, unicodestr)
unicodestr = BinaryPeekStrW( buf, 0, bytecnt )
BinaryFree(buf)
Message("Unicode String", unicodestr)
See Also:
Binary Operations, BinaryPoke, BinaryPoke2, BinaryPoke4, BinaryPokeFlt,
BinaryPokeHex, BinaryPokeStr
BinaryRead
Reads a file into a binary buffer.
Syntax:
BinaryRead(handle,filename)
Parameters:
(i) handle
(s) filename
handle of buffer.
file to read into buffer.
Returns:
(i)
the number of bytes read.
This function reads the entire contents of a file into a buffer then returns the number
of bytes read. The buffer must be large enough to hold the entire file. The file is
placed into the buffer starting at offset 0.
Example:
; This example edits the Config.sys file by adding a line
; to the bottom of the file.
fs=FileSize("C:\CONFIG.SYS")
binbuf = BinaryAlloc(fs+100)
if binbuf == 0
Message("Error", "BinaryAlloc Failed")
else
BinaryRead(binbuf, "C:\CONFIG.SYS")
BinaryPokeStr(binbuf, fs, "DEVICE=C:\FLOOGLE.SYS%@crlf%")
BinaryWrite(binbuf, "C:\CONFIG.SYS")
binbuf=BinaryFree(binbuf)
endif
Message("BinaryRead", "Done.")
See Also:
Binary Operations, BinaryAlloc, BinaryFree, BinaryReadEx, BinaryWrite,
BinaryWriteEx, IntControl 39
BinaryReadEx
Reads a portion of a file into a binary buffer.
168
BinaryReadEx
Syntax:
BinaryReadEx (handle,binary-offset,filename,file-offset,count)
Parameters:
(i) handle
(i) binary-offset
(i) filename
(i/t) file-offset
(i) count
Returns:
(i)
handle of buffer.
zero-based offset into the buffer specifying where the data
should be stored.
file to read into buffer.
zero-based offset into the file specifying
where the data to be read starts. This parameter accepts a
huge number data type.
the number of bytes to read.
the number of bytes read.
This function reads "count" bytes from "filename", beginning at "file-offset". It then
writes the data to the buffer specified by "handle", beginning at "binary-offset". Any
existing data in the buffer within the range "binary-offset + count" is overwritten
with the new data; any existing data outside that range is left untouched.
If "file-offset" + "count" is larger than the file size, or if "count" is -1, "count" will be
ignored and it will be treated as a request to read from "file-offset" to the end of the
file.
file-offset
BinaryReadEx and BinaryWriteEx accept a huge number for the "file-offset". A
huge number is a long decimal number string, which may represent a number too
large to be converted to an integer.
Example:
file = "hello.txt"
buf = BinaryAlloc(100)
BinaryPokeStr(buf, 0, "12345")
rc = BinaryReadEx(buf, 2, file, 4, 1)
Message("BinaryReadEx returned", rc)
eod = BinaryEodGet(buf)
Message("BinaryEod is", eod)
string = BinaryPeekStr(buf, 0, eod)
Message("BinaryPeekStr returned", string)
See Also:
Binary Operations, BinaryAlloc, BinaryFree, BinaryWrite, BinaryWriteEx,
BinaryRead, IntControl 39
169
BinarySort
BinaryReplace
Replaces strings in a binary buffer.
Syntax:
BinaryReplace(handle,search-string,replace-string,match-case)
Parameters:
(i) handle
(s) search string
(s) replace-string
(i) match-case
Returns:
(i)
handle of buffer.
specifies the string to be replaced. Specify a
blank string ("") to indicate that the search string is a
NULL character.
specifies the string with which "search-string" will be
replaced. Specify a blank string ("") to indicate that
"search-string" should be removed and not replaced with
anything.
@TRUE to indicate that "search-string" is case-sensitive, or
@FALSE if case should be ignored.
number of occurrences of "search-string" that were
replaced.
This function searches a binary buffer, and replaces all occurrences of "searchstring" with "replace-string". Each time an occurrence of "search-string" is replaced,
processing continues right after the replacement string that was inserted in its place.
If "replace-string" is longer than "search-string", the binary buffer must be large
enough for all the new strings to fit.
Example:
str="hello"
rep="goodbye"
dafile="C:\Temp\myfile.txt"
fs = FileSize( dafile )
binbuf = binaryalloc( fs+100 )
ret = BinaryRead( binbuf, dafile )
num = BinaryReplace( binbuf, str, rep ,0)
Message( "Number of '%str%' strings replaced", num )
BinaryWrite( binbuf, dafile )
BinaryFree( binbuf)
See Also:
BinaryAlloc, BinaryIndexEx, BinaryIndexNC
BinarySort
Sorts records in a binary buffer.
170
BinarySort
Syntax:
BinarySort(handle,recsize,key offset,key size,flags)
Parameters:
(i) handle
(i) recsize
(i) key offset
handle of buffer.
specifies the size of each record.
the offset within a record of the key field (where the first
byte in the record is 0).
specifies the size of the key field, in bytes.
see below.
(i) key size
(i) flags
Returns:
(i)
@TRUE if successful; @FALSE if unsuccessful.
BinarySort sorts records in a binary buffer in place, updating the existing buffer.
String sorts are case-insensitive. The flags consist of a maximum of one value from
each of the following groups, combined with the binary OR ("|") operator. If either
(or both) is not specified, the default value will be used:
Flags:
Sort sequence:
@ASCENDING
(default)
@DESCENDING
Key type:
@STRING
(default)
@WORD1
BYTE - 8 bit integer
@WORD2
WORD - 16 bit integer
@WORD4
DWORD - 32 bit integer
@FLOAT8
8 byte floating point number
Note: The binary buffer must consist of fixed-length records. Each record must
contain a fixed-length key field in a fixed position.
Example:
fh=FileOpen("test.in","WRITE")
; Note: Each record is 40 chars (recsize+crlf)
;
11111111112222222222333333333344444444444
;offsets
01234567890123456789012345678901234567890
FileWrite(fh,"0001 Flintstone Fred
(111)222-1334")
FileWrite(fh,"0002 Duck
Donald (271)333-2334")
FileWrite(fh,"0003 Duck
Daffy
(222)444-3334")
171
BinaryStrCnt
FileWrite(fh,"0004 Hedgehog
Sonic
(215)555-4334")
FileWrite(fh,"0005 Mario
Super
(212)666-5334")
FileWrite(fh,"0006 Kent
Clark
(234)777-6334")
FileWrite(fh,"0007 Lane
Lois
(987)888-7334")
FileWrite(fh,"0008 Mouse
Mickey (765)999-8334")
FileWrite(fh,"0009 Coyote
Wiley
(853)111-9334")
; length
1234567890123456789012345678901234567890
; Note that offset position and ordinal position are
; not the same.
FileClose(fh)
RecSize=40
NameOffset=5
NameSize=20
dbsize=FileSize("test.in")
db=BinaryAlloc(dbsize)
BinaryRead(db,"test.in")
BinarySort(db,RecSize,NameOffset,NameSize,@STRING|@ASCENDING)
BinaryWrite(db,"test.out")
BinaryFree(db)
Message("Sort Complete","Launching Notepad")
Run("notepad.exe","test.in")
Run("Notepad.exe","test.out")
See Also:
BinaryHashRec
BinaryStrCnt
Counts the occurrences of a string in some or all of a binary buffer.
Syntax:
BinaryStrCnt(handle,start-offset,end-offset,string)
Parameters:
(i) handle
(i) start-offset
(i) end-offset
(s) string
handle of buffer.
zero-based offset for start of search.
zero-based offset for end of search.
case-sensitive string to search for.
Returns:
(i)
number of occurrences of string found.
This function will search all or a portion of a binary buffer for a string and will return
a count of the occurrences of the string found.
The buffer will be searched from the start-offset to the end-offset.
Note: The string parameter may be composed of any characters except the null (00)
character. This function cannot process a null character.
172
BinaryTagExtr
Example:
; Find number of Device, DEVICE= and device= lines in config.sys
fs1 = FileSize( "C:\CONFIG.SYS" )
binbuf1 = binaryalloc( fs1 )
BinaryRead( binbuf1, "C:\CONFIG.SYS" )
a = BinaryStrCnt( binbuf1, 0, fs1, "Device=")
b= BinaryStrCnt( binbuf1, 0, fs1, "DEVICE=")
c= BinaryStrCnt( binbuf1, 0, fs1, "device=")
BinaryFree( binbuf1 )
d = a + b + c
Message( "Hmmm", "Total Device= lines found in Config.Sys is %d% " )
See Also:
Binary Operations, BinaryEodGet, BinaryEodSet, BinaryIndex, BinaryPeek,
BinaryPeekStr, BinaryPoke, BinaryPokeStr
BinaryTagExtr
Returns the text between the last-returned pair of binary tags.
Syntax:
BinaryTagExtr(tag-struct,flags)
Parameters:
(s) tag-struct
(i) flags
Structure returned from BinaryTagInit.
see below.
Returns:
(s)
the text, or "" on failure.
Flags
0
1
Meaning
Default.
Strip out tabs, carriage returns, and line feeds.
Note: This function is useful for editing HTML.
Example:
;BinaryTag Example 3 - Replace <b>xxx</b> in HTML files with
;<strong>xxx</strong> per html style guidelines
;Set up test case
;Setup input and output file names
filedata=AskFilename("HTML file to convert","","HTML
files|*.html;*.htm","*.html",1)
filerslt=FileMapName(filedata,"*.new")
; Allocate a buffer much larger than required.
fsize=Filesize(filedata)
bb=BinaryAlloc(fsize+10000)
173
BinaryTagFind
;Find <b> and </b> for open and close tags around strings.
;Note BinaryTagFind is NOT case sensitive
structure=BinaryTagInit(bb,"<b>","</b>")
;Not necessary in this example, but allows reuse of a
;BinaryBuffer if this code is placed in a loop editing
;multiple files.
BinaryEODSet(bb,0)
;Read data into the BinaryBuffer
BinaryRead(bb,filedata)
while 1
structure=BinaryTagFind(structure)
if structure=="" then break ; All done
strongdata=BinaryTagExtr(structure,1)
Value=strcat("<STRONG>",strongdata,"</STRONG>")
structure = BinaryTagRepl(structure,Value)
endwhile
BinaryWrite(bb,filerslt)
BinaryFree(bb)
Message("Result in",filerslt)
See Also:
BinaryTagInit, BinaryTagFind, BinaryTagRepl
BinaryTagFind
Finds the next binary tag.
Syntax:
BinaryTagFind(tag-struct)
Parameters:
(s) tag-struct
Structure returned from BinaryTagInit.
Returns:
(s)
a binary tag structure string, or "" on failure.
Note: This function is useful for editing HTML.
Example:
;BinaryTag Example 2 - Substitution in GoSubs
;Set up test case
;Setup input and output file names
filedata=strcat(DirGet(),"filedata.txt")
filerslt=strcat(DirGet(),"filerslt.txt")
;Set up a sample file for this example.
;Presumably you could have a library of these
174
BinaryTagFind
;to choose from, making form letters easy to
;automate.
fhandle=FileOpen(filedata,"WRITE")
FileWrite(fhandle,"{{date}}")
FileWrite(fhandle,"")
FileWrite(fhandle,"Dear {{name}}")
FileWrite(fhandle,"Thank you for your recent purchase of")
FileWrite(fhandle,"our new {{product}}.")
FileWrite(fhandle,"")
FileWrite(fhandle,"Please feel free to call if you have ")
FileWrite(fhandle,"any questions.")
FileWrite(fhandle,"")
FileWrite(fhandle,"{{salesperson}}")
FileWrite(fhandle,"{{salespersonphone}}")
FileClose(fhandle)
; Allocate a buffer much larger than required.
bb=BinaryAlloc(10000)
;Using {{ and }} for open and close tags around keywords
structure=BinaryTagInit(bb,"{{","}}")
;Not necessary in this example, but allows reuse of a
;BinaryBuffer if this code is placed in a loop editing
;multiple files.
BinaryEODSet(bb,0)
;Read data into the BinaryBuffer
BinaryRead(bb,filedata)
while 1
structure=BinaryTagFind(structure)
if structure=="" then break ; All done
keyword=BinaryTagExtr(structure,1)
Value="???"
; keyword not found error value
gosub %keyword%
structure = BinaryTagRepl(structure,Value)
endwhile
BinaryWrite(bb,filerslt)
BinaryFree(bb)
Message("Result in",filerslt)
exit
:date
Value=TimeDate()
return
:name
Value="Ms. Jamie Dough"
return
:product
175
BinaryTagIndex
Value="Analog Osscilosophilator"
return
:salesperson
Value="Fred Ficklemeyer"
return
:salespersonphone
Value="888.555.1234"
return
See Also:
BinaryTagInit, BinaryTagExtr, BinaryTagRepl
BinaryTagIndex
Returns the offset of a binary tag in a buffer.
Syntax:
BinaryTagIndex(tag-struct,mode)
Parameters:
(s) tag-struct
(i) mode
Returns:
(i)
structure returned from BinaryTagInit.
0 offset of text
1 offset of start tag
the offset where the binary tag was found.
Note: This function is useful for editing HTML.
This function can be used after a successful BinaryTagFind, to return the offset
where the binary tag was found. It must be used before any subsequent
BinaryReplace, since BinaryReplace will change the tag structure.
Example:
;BinaryTag Advanced functions
;Note: The BinaryTagIndex and BinaryTagLen
;functions are not generally required or
;used by most scripts using the BinaryTag
;functions. That are provided for the
;unusual case of a requirement to mix
;normal Binary functions with BinaryTag
;functions.
;Set up test case
;Setup input and output file names
filedata=strcat(DirGet(),"filedata.txt")
;Set up a sample file for this example.
;Presumably you could have a library of these
;to choose from, making form letters easy to
;automate.
176
BinaryTagInit
fhandle=FileOpen(filedata,"WRITE")
FileWrite(fhandle,"{{date}}")
FileWrite(fhandle,"")
FileWrite(fhandle,"Dear {{name}}")
FileWrite(fhandle,"Thank you for your recent purchase of")
FileWrite(fhandle,"our new {{product}}.")
FileWrite(fhandle,"")
FileWrite(fhandle,"Please feel free to call if you have ")
FileWrite(fhandle,"any questions.")
FileWrite(fhandle,"")
FileWrite(fhandle,"{{salesperson}}")
FileWrite(fhandle,"{{salespersonphone}}")
FileClose(fhandle)
; Allocate a buffer much larger than required.
bb=BinaryAlloc(10000)
;Using {{ and }} for open and close tags around keywords
structure=BinaryTagInit(bb,"{{","}}")
;Read data into the BinaryBuffer
BinaryRead(bb,filedata)
while 1
structure=BinaryTagFind(structure)
if structure=="" then break ; All done
blen=BinaryTagLen(structure,1)
bindex=BinaryTagIndex(structure,1)
keyword=BinaryTagExtr(structure,1)
Pause("After
find",strcat(keyword,@crlf,"len=",blen,@crlf,"index=",bindex))
structure = BinaryTagRepl(structure,"dummy data")
blen=BinaryTagLen(structure,1)
bindex=BinaryTagIndex(structure,1)
Pause("After
replace",strcat(keyword,@crlf,"len=",blen,@crlf,"index=",bindex))
endwhile
BinaryFree(bb)
See Also:
BinaryTagInit, BinaryTagFind, BinaryTagExtr, BinaryTagRepl
BinaryTagInit
Initializes a binary tag operation.
Syntax:
BinaryTagInit(handle,start-tag,end-tag)
Parameters:
(i) handle
handle of buffer. (handle returned from BinaryAlloc).
177
BinaryTagInit
(s) start-tag
(s) end-tag
Returns:
(s)
specifies what beginning string (tag) to search for
( i.e. "{{" )
specifies what ending string (tag) to search for
( i.e. "}}" )
a binary tag structure string, or "" on failure.
Note: This function is useful for editing HTML.
It searches the buffer for the start and end tags and returns a binary tag structure
string that is used with the other binary tag functions.
Example:
;BinaryTag Example 1 - Basic Code
;Set up test case
;Setup input and output file names
filedata=strcat(DirGet(),"filedata.txt")
filerslt=strcat(DirGet(),"filerslt.txt")
;Set up a sample file for this example.
;Presumably you could have a library of these
;to choose from, making form letters easy to
;automate.
fhandle=FileOpen(filedata,"WRITE")
FileWrite(fhandle,"{{date}}")
FileWrite(fhandle,"")
FileWrite(fhandle,"Dear {{name}}")
FileWrite(fhandle,"Thank you for your recent purchase of")
FileWrite(fhandle,"our new {{product}}.")
FileWrite(fhandle,"")
FileWrite(fhandle,"Please feel free to call if you have ")
FileWrite(fhandle,"any questions.")
FileWrite(fhandle,"")
FileWrite(fhandle,"{{salesperson}}")
FileWrite(fhandle,"{{salespersonphone}}")
FileClose(fhandle)
; Allocate a buffer much larger than required.
bb=BinaryAlloc(10000)
;Using {{ and }} for open and close tags around keywords
structure=BinaryTagInit(bb,"{{","}}")
;Not necessary in this example, but allows reuse of a
;BinaryBuffer if this code is placed in a loop editing
;multiple files.
BinaryEODSet(bb,0)
;Read data into the BinaryBuffer
BinaryRead(bb,filedata)
while 1
structure=BinaryTagFind(structure)
if structure=="" then break ; All done
keyword=BinaryTagExtr(structure,1)
178
BinaryTagLen
Value="???"
; keyword not found error value
if keyword=="date" then Value=TimeDate()
if keyword=="name" then Value="Ms. Jamie Dough"
if keyword=="product" then Value="Analog Osscilosophilator"
if keyword=="salesperson" then Value="Fred Ficklemeyer"
if keyword=="salespersonphone" then Value="888.555.1234"
structure = BinaryTagRepl(structure,Value)
endwhile
BinaryWrite(bb,filerslt)
BinaryFree(bb)
Message("Result in",filerslt)
See Also:
BinaryTagFind, BinaryTagExtr, BinaryTagRepl
BinaryTagLen
Returns the length of a binary tag.
Syntax:
BinaryTagLen(tag-struct,mode)
Parameters:
(s) tag-struct
(i) mode
Returns:
(s)
Structure returned from BinaryTagInit.
0 length of text
1 length of text + tags
the length of the text that was found.
Note: This function is useful for editing HTML.
This function can be used after a successful BinaryTagFind, to return the length of
the text that was found. It must be used before any subsequent BinaryReplace,
since BinaryReplace will change the tag structure.
Example:
;BinaryTag Advanced functions
;Note: The BinaryTagIndex and BinaryTagLen
;functions are not generally required or
;used by most scripts using the BinaryTag
;functions. That are provided for the
;unusual case of a requirement to mix
;normal Binary functions with BinaryTag
;functions.
;Set up test case
179
BinaryTagLen
;Setup input and output file names
filedata=strcat(DirGet(),"filedata.txt")
;Set up a sample file for this example.
;Presumably you could have a library of these
;to choose from, making form letters easy to
;automate.
fhandle=FileOpen(filedata,"WRITE")
FileWrite(fhandle,"{{date}}")
FileWrite(fhandle,"")
FileWrite(fhandle,"Dear {{name}}")
FileWrite(fhandle,"Thank you for your recent purchase of")
FileWrite(fhandle,"our new {{product}}.")
FileWrite(fhandle,"")
FileWrite(fhandle,"Please feel free to call if you have ")
FileWrite(fhandle,"any questions.")
FileWrite(fhandle,"")
FileWrite(fhandle,"{{salesperson}}")
FileWrite(fhandle,"{{salespersonphone}}")
FileClose(fhandle)
; Allocate a buffer much larger than required.
bb=BinaryAlloc(10000)
;Using {{ and }} for open and close tags around keywords
structure=BinaryTagInit(bb,"{{","}}")
;Read data into the BinaryBuffer
BinaryRead(bb,filedata)
while 1
structure=BinaryTagFind(structure)
if structure=="" then break ; All done
blen=BinaryTagLen(structure,1)
bindex=BinaryTagIndex(structure,1)
keyword=BinaryTagExtr(structure,1)
Pause("After
find",strcat(keyword,@crlf,"len=",blen,@crlf,"index=",bindex))
structure = BinaryTagRepl(structure,"dummy data")
blen=BinaryTagLen(structure,1)
bindex=BinaryTagIndex(structure,1)
Pause("After
replace",strcat(keyword,@crlf,"len=",blen,@crlf,"index=",bindex))
endwhile
BinaryFree(bb)
See Also:
BinaryTagFind, BinaryTagInit, BinaryTagExtr, BinaryTagRepl
180
BinaryTagRepl
BinaryTagRepl
Replaces a binary tag with text.
Syntax:
BinaryTagRepl(tag-struct,new-string)
Parameters:
(s) tag-struct
(s) new-string
Structure returned from BinaryTagInit.
text string to replace binary-tag with.
Returns:
(s)
a binary tag structure string, or "" on failure.
Note: This function is useful for editing HTML.
The BinaryTagRepl ignores overruns of the binary buffer, therefore make sure to
allocate a large enough binary buffer.
Example:
;BinaryTag Example 4 - Replace - passing parameters and other tricks
;Set up test case
;Setup input and output file names
filedata=strcat(DirGet(),"filedata.txt")
filerslt=strcat(DirGet(),"filerslt.txt")
;Set up a sample file for this example.
;Presumably you could have a library of these
;to choose from, making the generation of
;customized HTML pages easy to automate.
fhandle=FileOpen(filedata,"WRITE")
FileWrite(fhandle,"<HTML>")
FileWrite(fhandle,"<HEAD><TITLE>{{Title}}</TITLE></HEAD>")
FileWrite(fhandle,"<BODY>")
FileWrite(fhandle,"<p>Random number in range 0 thru 10 = {{RANDOM 0
10}}")
FileWrite(fhandle,"<p>Random number in range 92 thru 114 = {{RANDOM
92 114}}")
FileWrite(fhandle,"<p>Random number in range -20 thru 4 = {{RANDOM 20 4}}")
FileWrite(fhandle,"<p>Value of <b>filedata</b> variable=<br>{{VALUE
filedata}}")
FileWrite(fhandle,"<p>Value of <b>filerslt</b> variable=<br>{{VALUE
filerslt}}")
FileWrite(fhandle,"<p>Current time/date in YmdHms format = {{DATE
YMDHMS}}")
FileWrite(fhandle,"<p>Current time/date in display format = {{DATE
DISPLAY}}")
FileWrite(fhandle,"</BODY>")
FileWrite(fhandle,"</HTML>")
FileClose(fhandle)
181
BinaryTagRepl
; Allocate a buffer much larger than required.
bb=BinaryAlloc(10000)
;Using {{ and }} for open and close tags around keywords
structure=BinaryTagInit(bb,"{{","}}")
;Not necessary in this example, but allows reuse of a
;BinaryBuffer if this code is placed in a loop editing
;multiple files.
BinaryEODSet(bb,0)
;Read data into the BinaryBuffer
BinaryRead(bb,filedata)
while 1
structure=BinaryTagFind(structure)
if structure=="" then break ; All done
;Get tag with any extra spaces removed
extract=strtrim(BinaryTagExtr(structure,1))
ParseData(extract)
HTMLValue="???"
gosub %param1%
; keyword not found error value
structure = BinaryTagRepl(structure,HTMLValue)
endwhile
BinaryWrite(bb,filerslt)
BinaryFree(bb)
Message("Result in",filerslt)
exit
:Value
; Use WinBatch substitution to capture variable contents
HTMLValue = %param2%
return
:TITLE
HTMLValue="BinaryTagRepl Example"
return
:DATE
if param2=="YMDHMS"
HTMLValue=TimeYmdHms()
else
if param2=="DISPLAY"
HTMLValue=TimeDate()
else
HTMLValue="???Unknown DATE format???
endif
endif
return
:RANDOM
182
BinaryWriteEx
randomlow=param2
randomhigh=param3
randomrange=randomhigh-randomlow
HtmlValue=Random(randomrange)+randomlow
return
See Also:
BinaryTagInit, BinaryTagFind, BinaryTagExtr
BinaryWrite
Writes a binary buffer to a file.
Syntax:
BinaryWrite(handle,filename)
Parameters:
(i) handle
(s) filename
handle of buffer.
filename to write buffer to.
Returns:
(i)
number of bytes written.
This function writes the contents of a binary buffer out to a file and returns the
number of bytes written. Data written to the file starts at offset 0 in the buffer and
extends to the end of data - not necessarily the end of the buffer. The end of data may
be inspected or modified with the BinaryEodGet and BinaryEodSet functions.
Example:
; This example edits the Config.sys file by adding a line
; to the bottom of the file.
fs=FileSize("C:\CONFIG.SYS")
binbuf = BinaryAlloc(fs+100)
if binbuf == 0
Message("Error", "BinaryAlloc Failed")
else
BinaryRead(binbuf, "C:\CONFIG.SYS")
BinaryPokeStr(binbuf, fs, "DEVICE=C:\FLOOGLE.SYS%@crlf%")
BinaryWrite(binbuf, "C:\CONFIG.SYS")
binbuf=BinaryFree(binbuf)
endif
Message("BinaryWrite", "Done.")
See Also:
Binary Operations, BinaryAlloc, BinaryFree, BinaryRead, BinaryReadEx,
BinaryWriteEx, IntControl 40
BinaryWriteEx
Writes a portion of a binary buffer to a file.
183
BinaryWriteEx
Syntax:
BinaryWriteEx(handle,binary-offset,filename,file-offset,count)
Parameters:
(i) handle
(i) binary-offset
(i) filename
(i/t) file-offset
(i) count
Returns:
(i)
handle of buffer.
zero-based offset into the buffer specifying where the data
to be read starts.
file to write to.
zero-based offset into the file specifying where the data
should be stored.This parameter accepts a huge number
data type.
the number of bytes to write, or -1 to specify new end of
file marker.
the number of bytes written.
This function reads "count" bytes from the buffer specified by "handle", beginning at
"binary-offset". It then writes the data to "filename", beginning at "file-offset". Any
existing data in the file within the range "file-offset + count" is overwritten with the
new data; any existing data outside that range is left untouched.
If the data being written to the file is being written to the end of the file, and the data
that is being replaced is greater than the new data you will need to create a new end
of file marker. To create the new end of file marker, specify -1 for "count". "handle"
and "binary-offset" will be ignored. The file will be trucated at the "file-offset".
If "filename" does not exist, it will be created. If the existing file is smaller than
"file-offset", NULL bytes will be added to the end of the file to increase its size to
"file-offset", and then the specified data will be written beginning at "file-offset".
File-offset
BinaryReadEx and BinaryWriteEx accept a huge number for the "file-offset". A
huge number is a long decimal number string, which may represent a number too
large to be converted to an integer.
Example:
file = "1binout.txt"
buf = BinaryAlloc(10)
BinaryPokeStr(buf, 0, "01234")
rc = BinaryWriteEx(buf, 1, file, 50, 3)
Message("BinaryWriteEx returned", rc)
See Also:
Binary Operations, BinaryAlloc, BinaryFree, BinaryRead, BinaryReadEx,
BinaryWrite, IntControl 40
184
BinaryXlate
BinaryXlate
Converts a binary buffer using a translation table.
Syntax:
BinaryXlate(data-buffer,table-buffer,mode)
Parameters:
(i) data-buffer
(i) table-buffer
(i) mode
a binary buffer containing data to be converted.
a binary buffer containing a translation table.
see below.
Returns:
(i)
new EOD of the buffer.
Mode
0
1
2
3
Source buffer
byte
byte
word
word
Target buffer
byte
word
byte
word
Table size
256
512
65536
131072
This function looks up a byte or word in "data-buffer", uses that number to compute
an index into "table-buffer", looks up the byte or word there, and places the result in
a temporary buffer. It does this for each byte or word in "data-buffer". When it's
finished processing "data-buffer", it copies the new (temporary) buffer back to "databuffer", and sets the binary EOD appropriately.
For mode 1, "data-buffer" must be large enough to hold at least twice as much data
as is currently in the buffer.
Example:
;EBCDIC to
;Codes 0
row0 ="000
row1 ="016
row2 ="032
row3 ="032
row4 ="032
row5 ="038
row6 ="045
row7 ="032
row8 ="032
row9 ="032
row10="032
row11="032
row12="123
row13="125
row14="092
row15="048
ASCII translation table
1
2
3
4
5
6
001 002 003 032 009 032
017 018 019 032 032 008
032 028 032 032 010 023
032 022 032 032 030 032
032 032 032 032 032 032
032 032 032 032 032 032
047 032 032 032 032 032
032 032 032 032 032 032
097 098 099 100 101 102
106 107 108 109 110 111
126 115 116 117 118 119
032 032 032 032 032 032
065 066 067 068 069 070
074 075 076 077 078 079
032 083 084 085 086 087
049 050 051 052 053 054
7
127
032
027
004
032
032
032
032
103
112
120
032
071
080
088
055
8
032
024
032
032
032
032
032
032
104
113
121
032
072
081
089
056
9
032
025
032
032
032
032
032
032
105
114
122
032
073
082
090
057
A
032
032
032
032
155
033
124
058
032
032
032
032
032
032
032
032
B
011
032
032
032
046
036
044
035
032
032
032
032
032
032
032
032
C
012
032
032
020
060
042
037
064
032
032
032
032
032
032
032
032
D
013
032
005
021
040
041
095
039
032
032
032
032
032
032
032
032
E
014
032
006
032
043
059
062
061
032
032
032
032
032
032
032
032
F
015"
032"
007"
032"
032"
191"
063"
034"
032"
032"
032"
032"
032"
032"
032"
032"
185
BinaryXor
;Allocate 256 bytes for a 1:1 translation table
bbxlate=BinaryAlloc(256)
;load translation table from ROW variables above.
; Could have loaded it from a file also
for rowdigit=0 to 15
for coldigit= 0 to 15
BinaryPoke(bbxlate,(rowdigit*16)+coldigit,ItemExtract(coldigit+1,row%
rowdigit%," "))
next
next
;Ask user for a file name of an EBCDIC file
fn=AskFileName("EBCDIC -> ASCII", "", "EBCDIC files|*.ebc|All
Files|*.*","*.*",1)
;Generate corresponding *.asc name
fnout=FileMapName(fn,strcat(FilePath(fn),"*.asc"))
;Get size of source file
fs=FileSize(fn)
;Allocate a binary buffer that size
bb=BinaryAlloc(fs)
;Read source file into binary buffer
BinaryRead(bb,fn)
;Perform the magic Xlate function
BinaryXlate(bb,bbxlate,0)
;Write result file do the output file
BinaryWrite(bb,fnout)
;Free binary buffers
BinaryFree(bb)
BinaryFree(bbxlate)
;claim victory
Message("All","Done"))
See Also:
Binary Operations, BinaryAlloc, BinaryCopy, BinaryFree, BinaryRead
BinaryXor
Performs a bitwise XOR (exclusive OR) on portions of two binary buffers.
Syntax:
BinaryXor(target-handle,target-offset,source-handle,source-offset,count)
Parameters:
(i) target-handle
(i) target-offset
(i) source-handle
186
handle of target buffer.
zero-based offset into the target buffer specifying where the
data to be processed starts, and where the result of the
operation should be placed.
handle of source buffer.
Break
(i) source-offset
(i) count
Returns:
(i)
zero-based offset into the source buffer specifying where
the data to be processed starts.
the number of bytes to process.
returns @TRUE.
The specified sections of the buffers are processed on a byte-by-byte basis, and the
results are written to the buffer specified by "target-handle". i.e., the byte at "sourceoffset" is XOR'ed with the byte at "target-offset", and the result of the XOR
operation is stored in the byte at "target-offset", then the bytes at "source-offset + 1"
and "target-offset + 1" are XOR'ed, and so on.
"target-handle" and "source-handle" may both reference the same buffer, in which
case two sections of the buffer can be processed.
Example:
buf1 = BinaryAlloc(10)
buf2 = BinaryAlloc(10)
for i = 0 to 9
BinaryPoke(buf1, i, 0)
BinaryPoke(buf2, i, 1)
next
BinaryPoke(buf1, 0, 1)
rc = BinaryXor(buf1, 0, buf2, 0, 3)
binaryWrite(buf1, "zzbin1")
binaryWrite(buf2, "zzbin2")
Message("BinaryXor returned", rc)
See Also:
Binary Operations, BinaryAlloc, BinaryOr, BinaryCopy, BinaryFree, BinaryRead,
DllCall, BinaryCompare, BinaryAnd
Break
The Break statement is used to exit a While, Switch, Select, or For/Next structure.
Syntax:
break
Parameters:
(none)
Use the Break statement to exit a While, Switch, Select, or For/Next structure. It
transfers control to the statement immediately following the nearest enclosing
EndWhile, EndSwitch, EndSelect, or Next. It is used to terminate loops and to exit
Switch statements - usually just before the next case statement.
187
ButtonNames
Example:
a=15
b=21
while (a<100)
a=a+1
if a==4 then break
b=b+1
endwhile
Message("Break", "It Broke.")
See Also:
Continue, For, While, Switch, Select
ButtonNames
Changes the names of the buttons which appear in WIL dialogs.
Syntax:
ButtonNames(OK-name,Cancel-name)
Parameters:
(s) OK-name
(s) Cancel-name
new name for the OK button.
new name for the Cancel button.
Returns:
(i)
@TRUE.
This function allows you to specify alternate names for the OK and/or Cancel
buttons which appear in many of the dialogs displayed by the WIL Interpreter. Each
use of the ButtonNames statement only affects the next WIL dialog which is
displayed.
You can specify a null string ("") for either the OK-name or Cancel-Name
parameter, to use the default name for that button (i.e., "OK" or "Cancel").
You can place an ampersand before the character which you want to be the
underlined character in the dialog.
Note: ButtonNames does not change the name in all functions which display
buttons. Supported functions are: AskLine, AskFileText, AskItemList,
AskPassword.
Example:
ButtonNames("", "&Abort")
user = AskLine("Hello", "What is your name", "", 0)
Message("Hello", user)
would produce:
188
Call
Call
Calls a WIL batch file as a subroutine.
Syntax:
Call(filename,parameters)
Parameters:
(s) filename
(s) parameters
Returns:
(i)
the WIL batch file you are calling (including extension).
the parameters to pass to the file, if any, in the form
"p1 p2 p3 ... pn". (maximum value of n = 9 )
can return a value, by specifying a value after the Return
keyword in the called script. If no Return is specified the
called script will return 0.
This function is used to pass control temporarily to a secondary WIL batch file. The
main WIL program can optionally pass parameters to the secondary WIL batch file.
All variables are common (global) between the calling program and the called WIL
batch file, so that the secondary WIL batch file may modify or create variables. The
secondary WIL batch file should end with a Return statement, to pass control back
to the main WIL program.
If a string of parameters is passed to the secondary WIL batch file, it will
automatically be parsed into individual variables with the names param1, param2,
etc.. The variable param0 will be a count of the total number of parameters in the
string.
The Return command can return a value, by specifying a value (or an expression
that evaluates to a value) after the "Return" keyword. The value or expression may
optionally be enclosed in parentheses. This feature can be used with the Call
189
Call
command, and with the new User-Defined-Functions. It does not affect the Gosub
command.
Note: To debug into a 'called' WinBatch script or User-Defined-Function, make sure
to add the corresponding debug command, to the 'called script' or User-DefinedFunction.
Examples:
Return
Return
Return
Return
Return
(10)
"Okay"
myvariable * 10
(ItemCount(list, @TAB))
A script run with the Call command can return a value by using a Return command
with a value (see above). If a Return command Without a value is used, or the called
script does not contain a Return command, the called script will return 0.
result = Call("other.wbt", "")
Example:
; File MAIN.WBT
;
; This example asks for user input, their name and age,
; and then calls another WinBatch job to verify if their
; age is between 0 & 150.
name = AskLine("", "What is your name?", "", 0)
age = AskLine("", "How old are you?", "", 0)
valid = @NO
Call("chek-age.wbt", age)
If valid == @NO Then Message("", "Invalid age")
Exit
; File CHEK-AGE.WBT
;
; This subroutine checks if the age inputted is between 0 & 150.
; If this is true, a global parameter is set to a value of 1.
userage = param1
really = AskYesNo("", "%name%, are you really %userage%?")
If really == @YES
If (userage > 0) && (userage < 150)
valid = @YES
endif
endif
Return
See Also:
ParseData, Return
190
Char2Num
Ceiling
Calculates the ceiling of a value.
Syntax:
Ceiling(x)
Parameters:
(f) x
value Ceiling is calculated from.
Returns:
(f)
a floating point number whose value represents the smallest
integer that is greater than or equal to x (rounds up to the
nearest integer#).
Use this function to calculate the ceiling of a value.
Example:
; This example accepts a value from the user to calculate
; the ceiling and floor.
a=AskLine("Ceiling and Floor", "Please enter a number", "1.23", 0)
c=Ceiling(a)
f=Floor(a)
Message("Ceiling and Floor of %a%", "Ceiling: %c%
Floor: %f%")
A=
25.2
25.7
24.9
-14.3
Ceiling=
26.0
26.0
25.0
-14.0
Floor=
25.0
25.0
24.0
-15.0
See Also:
Abs, Fabs, Floor, Min, Max
Char2Num
Converts the first character of a string to its numeric equivalent.
Syntax:
Char2Num(string)
Parameters:
(s) string
any text string. Only the first character will be converted.
Returns:
(i)
ANSI character code.
This function returns the 8-bit ANSI code corresponding to the first character of the
string parameter.
191
ChrHexToString
Note: For the commonly-used characters (with codes below 128), ANSI and ASCII
characters are identical.
Example:
; Show the hex equivalent of entered character
inpchar = AskLine("ANSI Equivalents", "Char:", "", 0)
ansi = StrSub(inpchar, 1, 1)
ansiequiv = Char2Num(InpChar)
Message("ANSI Codes", "%ansi% => %ansiequiv%")
See Also:
IsNumber, Num2Char
ChrGetCodePage
Gets the current code page.
Syntax:
ChrGetCodePage(request)
Parameters:
(i) request
specifies the code page to be returned. See below.
Returns:
(i)
the requested code page.
Request
Meaning
0
WIL code page being used for Unicode conversions
1
ANSI code page associated with the default system locale
2
ANSI code page associated with the default user locale
Example:
wilcodepg = ChrGetCodePage( 0 )
Message("WIL code page being used for Unicode conversions",wilcodepg)
See Also:
ChrSetCodePage, IsNumber, Num2Char
ChrHexToString
Converts a hex string to a string.
Syntax:
ChrHexToString(hex-string)
Parameters:
(s) hex-string
192
a hex-string.
ChrSetCodePage
Returns:
(s)
returns a string.
Example:
str = ChrHexToString("48656C6C6F");Hello
Message("String", str)
See Also:
ChrStringToHex
ChrHexToUnicode
Converts a hex string to a Unicode string.
Syntax:
ChrHexToUnicode(hex-string [, flag ])
Parameters:
(s) hex-string
(i) flag
Returns:
(s)
a Unicode string in hex format with four hex bytes per
Unicode character.
[optional] 0 (default) or 1 to reverse the byte order of each
"hex-string" byte pair before converting to a Unicode
character.
returns a Unicode string.
"Hex-string" specifies a Unicode string in hex format, with four hex bytes per
Unicode character (eg, "480065006C006C006F00").
Example:
unicodestr = ChrHexToUnicode("480065006C006C006F00",0);Hello
Message("Unicode String", unicodestr)
See Also:
ChrUnicodeToHex
ChrSetCodePage
Sets the current WIL code page.
Syntax:
ChrSetCodePage(code page)
Parameters:
(i) code page
specifies the code page to be returned. See below.
Returns:
(i)
previous WIL code page.
193
ChrStringToUnicode
"code page" specifies a valid available code page, or one of the following system
default code pages:
Value
0
1
2
3
42
65000
65001
Meaning
ANSI code page
OEM code page
Macintosh code page
The current thread's ANSI code page
Symbol code page
Translate using UTF-7
Translate using UTF-8
Example:
ChrSetCodePage( 0 )
See Also:
ChrGetCodePage, IsNumber, Num2Char
ChrStringToHex
Converts a string to a Hex string.
Syntax:
ChrStringToHex(string)
Parameters:
(s) string
specifies a string.
Returns:
(s)
a hex string with two hex bytes per character.
Example:
hexstr = ChrStringToHex ("Hello")
Message("Hex String", hexstr)
See Also:
ChrStringToHex, ChrStringtoUnicode
ChrStringToUnicode
Converts an ANSI string to a Unicode string.
Syntax:
ChrStringToUnicode(string)
194
ChrUnicodeToString
Parameters:
(s) string
specifies a string.
Returns:
(s)
a Unicode string.
Example:
; Step through this code in WinBatch Studio to see the
; variable str change type from String to String_Unicode
str = "Hello"
str = ChrStringToUnicode(str)
See Also:
ChrUnicodetoString
ChrUnicodeToHex
Converts a Unicode string to a Hex string.
Syntax:
ChrUnicodeToHex(Unicode string[,flag])
Parameters:
(s) Unicode string
(i) flag
Returns:
(s)
specifies a Unicode string.
[optional] 0 (default) or 1 to reverse the byte order of each
"hex-string" byte pair returned.
a hex string, with four hex bytes per Unicode character.
Example:
unicodestr = ChrStringToUnicode("Hello")
hexstr = ChrUnicodeToHex(unicodestr,0)
Message("Hex String", hexstr)
See Also:
ChrHextoUnicode
ChrUnicodeToString
Converts a Unicode string to an ANSI string.
Syntax:
ChrUnicodeToString(Unicode string)
Parameters:
(s) Unicode string
specifies a Unicode string.
Returns:
(s)
an ANSI string.
195
ClipGet
Example:
unicodestr = ChrHexToUnicode("480065006C006C006F00");Hello
ansistr = ChrUnicodeToString( unicodestr )
Message("String", ansistr)
See Also:
ChrStringtoUnicode
ClipAppend
Appends a string to the Clipboard.
Syntax:
ClipAppend(string)
Parameters:
(s) string
Returns:
(i)
text string to add to Clipboard.
@TRUE if string was appended; @FALSE if Clipboard
ran out of memory.
Use this function to append a string to the Windows Clipboard. The Clipboard must
either contain text data or be empty for this function to succeed.
Example:
; This code will append 2 copies of the
; Clipboard contents back to the Clipboard, resulting
; in 3 copies of the original contents with a CR/LF
; between each copy.
a = ClipGet( )
ClipAppend(@crlf)
ClipAppend(a)
ClipAppend(@crlf)
ClipAppend(a)
Message("ClipAppend", "Clip Appended.")
See Also:
ClipGet, ClipPut
ClipGet
Returns the contents of the Clipboard.
Syntax:
ClipGet()
Parameters:
(none)
196
ClipGetEx
Returns:
(s)
clipboard contents.
Use this function to copy text from the Windows Clipboard into a string variable.
Note: If the Clipboard contains an excessively large string, a (fatal) out of memory
error may occur.
Example:
; The code below will convert Clipboard contents to
; uppercase
ClipPut(StrUpper(ClipGet( )))
a = ClipGet( )
Message("UPPERCASE Clipboard Contents", a)
See Also:
ClipAppend, ClipPut, BinaryClipGet, ClipGetEx
ClipGetEx
Returns the contents of the Windows clipboard in a specified format.
Syntax:
ClipGetEx(format)
Parameters:
(i) format
format in which the text is returned. See below.
Returns:
(s)
the contents of the Windows clipboard in a specified format.
Format
1
7
13
Meaning
(CF_TEXT) Standard ANSI text (same as ClipGet).
(CF_OEMTEXT) Text containing characters in the OEM character set.
(CF_UNICODETEXT) Unicode text format (Windows NT only)
Note: If the clipboard contains an excessively large string a (fatal) out of memory
error may occur.
Example:
ClipPut("abc")
ret = ClipGetEx(1)
Message( "ClipGetEx Returns:", ret)
See Also:
ClipGet, ClipAppend, ClipPut, BinaryClipGet
197
ClipHasFormat
ClipHasFormat
Determines if the clipboard contains a particular format.
Syntax:
ClipHasFormat(format)
Parameters:
(i) format
Returns:
(i)
format of clipboard data.
returns @TRUE if the clipboard contains data in the format
specified by "format", or @FALSE if it does not.
The following is a list of possible clipboard formats.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
128
129
130
131
142
F_TEXT
F_BITMAP
F_METAFILEPICT
F_SYLK
F_DIF
CF_TIFF
CF_OEMTEXT
CF_DIB
CF_PALETTE
CF_PENDATA
CF_RIFF
CF_WAVE
CF_UNICODETEXT
CF_ENHMETAFILE
CF_HDROP
CF_LOCALE
CF_OWNERDISPLAY
CF_DSPTEXT
CF_DSPBITMAP
CF_DSPMETAFILEPICT
CF_DSPENHMETAFILE
Example:
;This code will snapshot the screen to the clipboard,
;and check the format of the clipboard contents
Snapshot(0)
format = 2 ; bmp
ret = ClipHasFormat(format)
if ret == 1
message("Clipboard format","Clipboard contains a bitmap")
else
message("Clipboard format","Clipboard does not contain a bitmap")
endif
198
ComputerNameGet
See Also:
Binary Operations, BinaryAlloc, BinaryWrite, BinaryFree, BinaryClipGet,
BinaryClipPut, ClipGet, ClipGetEx
ClipPut
Copies a string to the Clipboard.
Syntax:
ClipPut(string)
Parameters:
(s) string
Returns:
(i)
any text string.
@TRUE if string was copied; @FALSE if Clipboard ran
out of memory.
Use this function to copy a string to the Windows Clipboard. The previous Clipboard
contents will be lost.
Example:
; The code below will convert Clipboard contents to
; lowercase
ClipPut(StrLower(ClipGet( )))
a = ClipGet( )
Message("lowercase Clipboard Contents", a)
See Also:
ClipAppend, ClipGet, SnapShot
ComputerNameGet
Gets the name associated with the local computer.
Syntax:
ComputerNameGet(format)
Parameters:
(i) format
Returns:
(s)
specifies what value to return. See below.
returns computername in specified format. Returns an ANSI
string in Windows 95/98/ME, and a Unicode string in
Windows NT and newer.
In Windows 95/98/ME, "format" must be 0. In Windows NT and newer, "format"
can be one of the following values:
199
ComputerNameSet
Value
0
100
101
102
103
104
105
106
107
Meaning
The NetBIOS name of the local computer.
The NetBIOS name of the local computer. If the local computer is a
node in a cluster, returns the NetBIOS name of the cluster virtual server.
The DNS host name of the local computer. If the local computer is a
node in a cluster, returns the DNS host name of the cluster virtual
server.
The name of the DNS domain assigned to the local computer. If the
local computer is a node in a cluster, returns the DNS domain name of
the cluster virtual server.
The fully qualified DNS name that uniquely identifies the local
computer. This name is a combination of the DNS host name and the
DNS domain name, using the form HostName.DomainName. If the
local computer is a node in a cluster, returns the fully qualified DNS
name of the cluster virtual server.
The NetBIOS name of the local computer. If the local computer is a
node in a cluster, returns the NetBIOS name of the local computer, not
the name of the cluster virtual server.
The DNS host name of the local computer. If the local computer is a
node in a cluster, returns the DNS host name of the local computer, not
the name of the cluster virtual server.
The name of the DNS domain assigned to the local computer. If the
local computer is a node in a cluster, returns the DNS domain name of
the local computer, not the name of the cluster virtual server.
The fully qualified DNS name that uniquely identifies the computer. If
the local computer is a node in a cluster, returns the fully qualified DNS
name of the local computer, not the name of the cluster virtual server.
The fully qualified DNS name is a combination of the DNS host name
and the DNS domain name, using the form HostName.DomainName.
Example:
result = ComputerNameGet( 0 )
Message( "The NetBIOS name of the local computer.", result )
See Also:
ComputerNameSet
ComputerNameSet
Sets the name associated with the local computer.
Syntax:
ComputerNameSet(new name,format)
200
Continue
Parameters:
(s) new name
(i) format
new computer name.
specifies what value to set. See below.
Returns:
(i)
@TRUE on success and @FALSE on failure.
In Windows 95/98/ME, "format" must be 0. In Windows NT and newer, "format"
can be one of the following values:
Value
0
104
105
106
Meaning
In Windows 95/98/ME, sets the NetBIOS name. In Windows NT and
newer, same as 105 (below).
Sets the NetBIOS name. The name cannot exceed 15 characters.
Warning: Using this option to set the NetBIOS name breaks the
convention of interdependent NetBIOS and DNS names. Applications
that use the DnsHostnameToComputerName function to derive the
NetBIOS name from the first label of the DNS name will fail if this
convention is broken.
Sets the NetBIOS and the Computer Name (the first label of the full
DNS name). If the name exceeds 15 characters, the NetBIOS name is
truncated to 15 characters.
Sets the primary DNS suffix of the computer.
Changes do not take effect until the computer is restarted.
If the computer is a member of the domain: use the wntUserRename() function
in the NT extender to rename the machine account. Remember that machine
accounts are hidden [e.g. they have a trailing "$" in the name] and they are are
always in lowercase. Remember that you must have appropriate rights in order to set
the computer name and to rename the computer's machine account in the domain.
Windows Vista or newer: This function may require an Administrator level
account.
Example:
result = ComputerNameSet( "OZWEEGO", 0 )
Message( "ComputerNameSet", "Set the NetBIOS & Computer name of the
local computer.")
See Also:
ComputerNameGet
Continue
The Continue statement in a While or For loop causes a transfer of control back to
the beginning of the loop so that the controlling expressions can be re-evaluated. In a
201
Cos
Switch or Select statement, execution of a particular case is terminated and a search
for the next matching case is initiated.
Syntax:
Continue
Parameters:
(none)
In While or For statements, use the Continue statement to immediately stop
execution and re-evaluate the While or For statement to determine if the loop should
be repeated. In For statements, the index variable is also incremented. In Switch or
Select statements, if a case is being executed, execution of that case is terminated,
and a search is started for another case statement whose expression evaluates to the
same integer as the expression controlling the Switch or Select statement.
Example:
a=0
b=0
while (a<100)
a=a+1
if a>10 then continue
b=b+1
endwhile
Message("Continue","Continued")
See Also:
Break, For, While, Switch, Select
Cos
Calculates the cosine.
Syntax:
Cos(x)
Parameters:
(f) x
angle in radians.
Returns:
(f)
the Cos function returns the cosine of x.
Calculates the cosine. If x is large, a loss in significance in the result or a significance
error may occur.
Note: To convert an angle measured in degrees to radians, simply multiply by the
constant @Deg2Rad.
202
CurrentFile {*M}
Example:
real=AskLine("Cosine","Enter an angle in degrees(0 to 360)","45",0)
answer=cos(real * @Deg2Rad)
Message("Cosine of %real% degrees is",answer)
See Also:
Acos, Asin, Atan, Cosh, Sin, Tan
Cosh
Calculates the hyperbolic cosine.
Syntax:
Cosh(x)
Parameters:
(f) x
angle in radians.
Returns:
(f)
the Cosh function returns the hyperbolic cosine of x.
Calculates the hyperbolic cosine. If the result is too large, the function will return an
error.
Note: To convert an angle measured in degrees to radians, simply multiply by the
constant @Deg2Rad.
Example:
real=AskLine("Cosh", "Enter an angle in degrees (0 to 360)", "45", 0)
answer=cosh(real * @Deg2Rad)
Message("Hyperbolic cosine of %real% degrees is",answer)
See Also:
Acos, Asin, Atan, Cos, Sin, Sinh, Tan, Tanh
CreateObject
Pseudonym for ObjectCreate. Creates and returns a reference to a COM/OLE
object.
See ObjectCreate.
See Also:
ObjectGet, ObjectCreate
CurrentFile {*M}
Returns the selected filename.
203
CurrentPath {*M}
Syntax:
CurrentFile()
Parameters:
(none)
Returns:
(s)
currently-selected file's name.
When a WIL menu shell displays the files in the current directory, one of them may
be "selected". This function returns the name of that file, if any.
This is different than a "highlighted" file. When a file is highlighted, it shows up in
inverse video (usually white-on-black). To find the filenames that are highlighted,
see FileItemize.
Note: This command is not part of the WIL Interpreter package, but is documented
here because it has been implemented in many of the explorer shell or file managertype applications which use the WIL Interpreter. See FileMenu in the WinBatch
Users Guide.
Example:
;The CurrentFile function is designed for menu based
;implementations of WIL, such as FileMenu. It is not
;supported in the WinBatch Product.
;Ask which program to show (default = current file)
;Edit Current File
thefile = AskLine("Show File", "Program:",CurrentFile( ), 0)
Run("browser.exe",thefile)
See Also:
CurrentPath, DirGet, DirItemize, FileItemize
CurrentPath {*M}
Returns path of the selected filename.
Syntax:
CurrentPath()
Parameters:
(none)
Returns:
(s)
path of currently-selected file.
When a WIL menu shell displays the files in the current directory, one of them may
be "selected." This function returns the drive and path of that file, if any.
204
CurrFilePath {*M}
This is different than a "highlighted" file. When a file is highlighted, it shows up in
inverse video (usually white-on-black). To find the filenames that are highlighted,
see FileItemize.
Note: This command is not part of the WIL Interpreter package, but is documented
here because it has been implemented in many of the explorer shell or file managertype applications which use the WIL Interpreter. See FileMenu in the WinBatch
Users Guide.
Example:
; Builds full filename before changing directories.
; For Menu based systems only
;Build FileName
myfile = StrCat(CurrentPath( ), CurrentFile( ))
DirChange("c:\temp")
Run("notepad.exe", myfile)
See Also:
CurrentFile, DirGet, FilePath
CurrFilePath {*M}
Returns the full path plus filename of the currently-selected file.
Syntax:
CurrFilePath()
Parameters:
(none)
Returns:
(s)
path and filename of currently-selected file.
Note: This command is not part of the WIL Interpreter package, but is documented
here because it has been implemented in many of the explorer shell or file managertype applications which use the WIL Interpreter. See FileMenu in the WinBatch
Users Guide.
Example:
;The CurrFilePath function is designed for menu based
;implementations of WIL, such as FileMenu. It is not
;supported in the WinBatch Product.
;Get the filename before changing directories.
;Edit Current File
myfile=CurrFilePath( )
DirChange("c:\temp")
Run("notepad.exe", myfile)
See Also:
CurrentFile, CurrentPath
205
DDEExecute
DataCast
Converts or casts a value from one data type to another.
Syntax:
DataCast(value,mode)
Parameters:
(f) value
(i) mode
specifies the value to be converted or cast.
specifies the operation to perform:
Returns:
(f)
depends on mode specified. See below.
Mode
0
Meaning
Cast single-precision floating point to double-precision floating point.
"value" specifies a single-precision (32-bit) floating point value,
represented as a WIL long value containing the same bit sequence as
the float value.
Returns a WIL floating point value (64-bit).
1
Cast double-precision floating point to single-precision floating point.
"value" specifies a WIL floating point value (64-bit).
Returns a single-precision (32-bit) floating point value, represented as
a WIL long value containing the same bit sequence as the float value.
Casting a value involves changing it from one data type to another, and may involve
a loss of precision depending on the type of cast.
Example:
single_precision = 1077936128
;Cast single-precision to double-precision floating point.
double_precision = DataCast(single_precision,0)
Message(single_precision, double_precision)
;Cast double-precision to single-precision floating point.
single_precision = DataCast(double_precision,1)
Message(double_precision, single_precision )
See Also:
DllCall, DllCallCdecl
DDEExecute
Sends commands to a DDE server application.
Syntax:
DDEExecute(channel,command string)
206
DDEInitiate
Parameters:
(i) channel
(s) command string
Returns:
(i)
same integer that was returned by DDEInitiate.
one or more commands to be executed by the
server app.
@TRUE if successful; @FALSE if unsuccessful.
Use the DDEInitiate function to obtain a channel number.
In order to use this function successfully, you will need appropriate documentation
for the server application you wish to access, which must provide information on the
DDE functions that it supports and the correct syntax to use.
Example:
Run("report.exe", "sales.dat")
;Run Report
channel = DDEInitiate("report", "YTD")
;Initialize DDE
;If DDE OK Execute DDE Command
If channel != 0
result = DDEExecute(channel, '[Act:p="ABCco", t=580.00]')
;Close DDE
DDETerminate(channel)
;Close Report
WinClose("Reports")
If result == @FALSE
Message("DDE Execute", "Failed")
else
Message("DDE Execute", "Operation complete")
Exit
endif
else
Message("DDE operation unsuccessful", "Check your syntax")
endif
See Also:
DDEInitiate, DDEPoke, DDERequest, DDETerminate, DDETimeout
DDEInitiate
Opens a DDE channel.
Syntax:
DDEInitiate(app name,topic name)
Parameters:
(s) app name
(s) topic name
name of the application (without the EXE extension).
name of the topic you wish to access.
Returns:
(i)
communications channel, or 0 on error.
207
DDEPoke
This function opens a DDE communications channel with a server application. The
communications channel can be subsequently used by the DDEExecute, DDEPoke,
and DDERequest functions. You should close this channel with DDETerminate
when you are finished using it. If the communications channel cannot be opened as
requested, DDEInitiate returns a channel number of 0.
You can call DDEInitiate more than once, in order to carry on multiple DDE
conversations (with multiple applications) simultaneously.
In order to use this function successfully, you will need appropriate documentation
for the server application you wish to access, which must provide information on the
DDE functions that it supports and the correct syntax to use.
Example:
Run("report.exe", "sales.dat")
;Run Report
channel = DDEInitiate("report", "YTD") ;Initialize DDE
;If DDE OK Execute DDE Command
If channel != 0
result = DDEExecute(channel, '[Act:p="ABCco", t=580.00]')
DDETerminate(channel)
;Close DDE
WinClose("Reports")
;Close Report
If result == @FALSE
Message("DDE Execute", "Failed")
else
Message("DDE Execute", "Operation complete")
Exit
endif
else
Message("DDE operation unsuccessful", "Check your syntax")
endif
See Also:
DDEExecute, DDEPoke, DDERequest, DDETerminate, DDETimeout
DDEPoke
Sends data to a DDE server application.
Syntax:
DDEPoke(channel,item name,item value)
Parameters:
(i) channel
(s) item name
(s) item value
same integer that was returned by DDEInitiate.
identifies the type of data being sent.
actual data to be sent to the server.
Returns:
(i)
@TRUE if successful; @FALSE if unsuccessful.
Use the DDEInitiate function to obtain a channel number.
208
DDERequest
In order to use this function successfully, you will need appropriate documentation
for the server application you wish to access, which must provide information on the
DDE functions that it supports and the correct syntax to use.
Example:
;Run Reminder and Initialize DDE
Run("reminder.exe", "")
channel = DDEInitiate("Reminder", "items")
If channel != 0
;If DDE OK
;Do DDE Poke
result = DDEPoke(channel, "all", "11/3/92 Misc Vote!!!!")
DDETerminate(channel)
;Close DDE
WinClose("Reminder")
;Close Application
If result == @FALSE
Message("DDE Poke", "Failed")
else
Message("DDE Poke", "Operation complete")
Exit
endif
else
Message("DDE operation unsuccessful", "Check your syntax")
endif
See Also:
DDEExecute, DDEInitiate, DDERequest, DDETerminate, DDETimeout
DDERequest
Gets data from a DDE server application.
Syntax:
DDERequest(channel,item name)
Parameters:
(i) channel
(s) item name
Returns:
(s)
same integer that was returned by DDEInitiate.
identifies the data to be returned by the server.
information from the server if successful,
"***NACK***" on failure.
Use the DDEInitiate function to obtain a channel number.
In order to use this function successfully, you will need appropriate documentation
for the server application you wish to access, which must provide information on the
DDE functions that it supports and the correct syntax to use.
Example:
;Run Report and Initialize DDE
Run("report.exe", "sales.dat")
channel = DDEInitiate("report", "YTD")
209
DDETerminate
If channel != 0
;If DDE OK
;Do DDE Request
result = DDERequest(channel, 'TotalSales')
DDETerminate(channel)
;Close DDE
WinClose("Reports")
;Close Report
If result == @FALSE
Message("DDE Execute", "Failed")
else
Message("DDE Request", "Total Sales is %result%")
Exit
endif
else
Message("DDE operation unsuccessful", "Check your syntax")
endif
See Also:
DDEExecute, DDEInitiate, DDEPoke, DDETerminate, DDETimeout
DDETerminate
Closes a DDE channel.
Syntax:
DDETerminate(channel)
Parameters:
(i) channel
same integer that was returned by DDEInitiate.
Returns:
(i)
@TRUE.
This function closes a communications channel that was opened with DDEInitiate.
Example:
Run("report.exe", "sales.dat")
channel = DDEInitiate("report", "YTD")
If channel != 0
;Run Report
;Initialize DDE
;If DDE OK
;Do DDE Request
result = DDERequest(channel, 'TotalSales')
DDETerminate(channel)
;Close DDE
WinClose("Reports")
;Close Report
If result == @FALSE
Message("DDE Execute", "Failed")
else
Message("DDE Request", "Total Sales is %result%")
Exit
endif
else
Message("DDE operation unsuccessful", "Check your syntax")
endif
210
DDETimeout
See Also:
DDEExecute, DDEInitiate, DDEPoke, DDERequest, DDETimeout
DDETimeout
Sets the DDE timeout value.
Syntax:
DDETimeout(value)
Parameters:
(i) value
DDE timeout time.
Returns:
(i)
previous timeout value.
Sets the timeout time for subsequent DDE functions to specified value in
milliseconds (1/1000 second). Default is 3000 milliseconds (3 seconds). If the time
elapses with no response, the WIL Interpreter will return an error.
The value set with DDETimeout stays in effect until changed by another
DDETimeout statement or until the WIL program ends, whichever comes first.
Example:
;Set Timeout to 5 secs
DDETimeOut(5000)
;Run Report
Run("report.exe", "sales.dat")
channel = DDEInitiate("report", "YTD")
;Initialize DDE
If channel != 0
;If DDE OK
;Do DDE Request
result = DDERequest(channel, 'SortByCity')
DDETerminate(channel)
;Close DDE
WinClose("Reports")
;Close Report
If result == @FALSE
Message("DDE Execute", "Failed")
else
Message("DDE Request", "Database sorted")
Exit
endif
else
Message("DDE operation unsuccessful", "Check your syntax")
endif
See Also:
DDEExecute, DDEInitiate, DDEPoke, DDERequest, DDETerminate
211
Debug
Debug
Controls the debug mode.
Syntax:
Debug(mode[,init-string])
Parameters:
(i) mode
(s) init-string
Returns:
(i)
@ON or @OFF
[optional] the string placed in the edit field of the debug
dialog when the dialog is initialized.
previous debug mode.
Use this function to turn the debug mode on or off. The default is @OFF.
When debug mode is on, the WIL Interpreter will display the statement just
executed, its result (if any), any error conditions, and the next statement to execute.
Debug will attempt to display the entire statement, but if the line does not fit in the
display window, it will be truncated at the last character that does fit. The exact
number of characters displayed depends on video drivers, screen resolution, etc.
The statements are displayed in a special dialog box which gives the user four
options: Next, Run, Cancel and Show Var.
Next executes the next statement and remains in debug mode.
Run exits debug mode and runs the rest of the program normally.
Cancel terminates the current WIL program.
Show Var displays the contents of a variable whose name the user entered in the
edit box.
Note: To debug into a 'called' WinBatch script or User-Defined-Function, make sure
to add the corresponding debug command, to the 'called script' or User-DefinedFunction.
Example:
Debug(@ON)
a = 6
q = AskYesNo("Testing Debug Mode", "Is the Pope Catholic")
Debug(@OFF)
b = a + 4
212
Debug
... then, if the user presses Next:
... and presses Next again:
... and then presses Yes:
213
DebugData
etc. (If the user had pressed No it would have said "VALUE=>0".)
See Also:
ErrorMode, DebugData, DebugTrace, LastError
DebugData
Writes data via the Windows OutputDebugString function to the default destination.
Syntax:
DebugData(string,string)
Parameters:
(s) string
(s) string
desired data.
more desired data.
Returns:
(i)
@FALSE.
Writes data via the Windows OutputDebugString function to the default destination.
The function is generally only useful if you have the proper tools and hardware to
debug Windows applications. In general, for standard retail Windows, the default
destination is COM1. The Windows SDK provides tools (DBWIN) to allow you to
capture the debug data to an alternate device or to a special window.
Use of this function in standard retail Windows may interfere with any device, such
as a mouse or modem connected to COM1.
For users without sophisticated (and expensive) debugging tools, the WIL Debug,
DebugTrace, or the Message function work incredibly well.
Example:
a=45
DebugData("Value of a is", a)
; or for those without expensive tools
Message("Value of a is", a)
214
DebugTrace
See Also:
Debug, DebugTrace, Message
DebugTrace
Controls and customizes the WIL debugging trace logs.
Syntax:
DebugTrace(requestcode[,parm1[,parm2 ]])
Parameters:
(i) requestcode
(s/i) parm1
(s/i) parm2
numeric code indicating desired action (see below)
[optional] depends on requestcode
[optional] depends on requestcode
Returns:
(i)
DebugTrace mode state:
0 = Off
1 = Statement by statement Tracing enabled.
DebugTrace will create a file showing each line executed and the return value of the
line. It will consume considerable processing time and is generally reserved for
particularly hard-to-debug problems.
DebugTrace will append to the end of the file you specify. You may want to delete
the file, if it already exists.
To debug into a 'Called' WinBatch script, User-Defined-Function or User-DefinedSubroutine, make sure to add the corresponding debug command, to the 'called
script', User-Defined-Function or User-Defined-Subroutine.
Note: For requests which take a file name, if "filename" is "*DEBUGDATA*" then
debug output will be written to the system debugger using the OutputDebugString
Windows API (see WIL DebugData function).
Request codes fall into one of three categories.
Category
Modes
Mode Option Flags
Immediate Action
Codes
Description
These control the DebugTrace line by line logging.
These control the log file names, formatting, and content.
These cause additional data to be immediately written to
the Debug Trace log file.
Modes
Request
code
Meaning
Parm1
Parm2
215
DebugTrace
0
(@OFF)
1 (@ON)
Stops statement by statement
debug tracing.
Starts or Resumes statement by
statement debug tracing.
Optional filename to
set/change the current
debug trace log file. If no
previous debug trace file
has been specified, then a
filename is required.
Output filename may be
specified by a previous
@ON, 10, 100, or 101.
Same as 1 (@ON) with the
addition that if the output file
exists, one attempt will be made
to delete the file before
continuing.
Allow DebugTrace continuation
22
(inherit the debug mode from
the caller). By default, when the
code enters a UDF, UDS or
Call'ed script file, statement by
statement debugging is
suppressed until the script
returns.
Adding DebugTrace(22) to a
UDF, UDS, or called script will
resume statement by statement
debugging *IF* it was active on
entry.
Mode Option Flags
10
Request
code
100
101
102
216
Meaning
Parm1
Specify output file name
for subsequent debug trace
logging.
Same as 100 with the
addition that if the output
file exists, one attempt
will be made to delete the
file before continuing.
Dump WIL variable table
to the debug trace log file
when a terminal error
occurs.
Required filename parameter
0 - Do NOT dump variable
table to debug trade log file.
(default)
1 - Dump WIL variable table to
Parm2
DebugTrace
103
Dump internal debug data
for each keyword lookup.
104
Suppress statement
timestamp information.
the debug trace log file if a
terminal error occurs.
0 - Do NOT dump debug data
for keyword lookups. (default)
1 - Dump debug data for
keyword lookups.
0 - Include statement timing
information (default).
1 - Suppress statement timing
information.
Note: This option is useful
when creating multiple debug
trace log files that you plan to
compare with one another using
a file-compare type program.
As statement timing will vary
slightly, this option allows
statement timing information to
be skipped to avoid nonrelevant differences in the
generated log files.
Immediate Action Codes:
Note: DebugTrace(@OFF) does not suppress the execution of these codes.
In the case of where a code would output information to the debug trace log file, if
the file is defined, then an attempt will be made to write data to it.
Request
code
200
Meaning
Parm1
Reset. Turns off
statement by statement
tracing, and resets all the
Mode Option Flags to the
default values
Optionally set new
debug trace file name.
If there is no optional
parm parameter, or it is
set to a null string, the
output filename
parameter will be
cleared.
Specifies a string to be
written to the debug
trace log file.
Specifies a string to be
written to the debug
203
Write a string to the
debug trace log file.
204
Write a string, surrounded
by "$" signs to the debug
Parm2
217
DebugTrace
205
206
207
208
277
trace log file.
Dump WIL and loaded
extender function tables
to the debug trace log file.
Dump WIL variable table
to the debug trace log file.
Includes values for
simple variable types.
Note: Only the first part
of long strings will be
dumped. Complex
variable types (Arrays,
Binary Buffers, etc) will
not have variables
dumped.
Dump stack info to the
debug trace log file.
Dump machine
information block.
Dump formatted internal
debugging information to
the debug trace log file.
Much of the same
information as provided
by IntControl 77 is
available.
Example:
DT_OFF
DT_ON
DT_ON_DEL
DT_RESUME
=
=
=
=
0
1
10
22
DT_FILENAME
DT_FILENAME_DEL
DT_VARS_ON_ERR
DT_KEY_LOOKUP
DT_TIMING
=
=
=
=
=
100
101
102
103
104
DT_RESET
DT_LOG
DT_LOG_MARK
DT_VARTABLE
DT_STACK
=
=
=
=
=
200
202
205
206
207
218
trace log file.
Missing or "" - Display
select internal
information
Numeric value Displays more detailed
information regarding a
specific IntControl 77
request.
Additional
information as
needed by
IntControl 77
request. For
example request
code 63 needs
additional
information.
Decimals
DT_HEADERS
DT_DEBUGINFO
= 208
= 277
#DefineFunction MyUDF()
DT_RESUME = 22
DebugTrace( DT_RESUME )
ccc = 1
ccc = 2
ccc = 3
ccc = 5
return
#EndFunction
a = 1
; start debug tracing.
; if the output file exists, one attempt will be
; made to delete the file before continuing.
DebugTrace( DT_ON_DEL , "DTT_TEST.TXT" )
aa = 1
aa1 = 1
aa2 = 2
aa3 = 3
aa4 = 4
zz = MyUDF ()
bb1 = 1
; Display select internal information
DebugTrace( DT_DEBUGINFO )
; tab-delimited list of application function table entries
DebugTrace( DT_DEBUGINFO , 101 )
bb2 = 2
See Also:
ErrorMode, Debug, DebugData IntControl 77
Decimals
Sets the number of decimal places to be used when displaying floating point
numbers.
Syntax:
Decimals(places)
Parameters:
(i) places
number of decimals to be displayed.
Returns:
(i)
previously set value.
219
Dialog
Use this function to set the number of decimal places to be displayed when viewing a
floating point number. The floating point number will be rounded to the specified
number of decimals. If you require special formatting, use the following:
Special Formatting (places):
-3
Always use scientific format
-2
Use alternate method of converting to strings, with no trailing zeros
-1
Full precision, dropping of trailing zeros.
2
Computations on US currency -- mortgage or financial calculations
Note: The Decimals function only affects a floating point number when it gets
converted to a string.
This includes:
Using variable substitution.
Any string function is used.
Dialog or Message box.
Passed as a string parameter to any function.
Example:
a=1.23456789
for d = 0 to 10
Decimals(d)
Message("Decimals = %d%", a)
Next
Dialog
Displays a user-defined dialog box.
Syntax:
Dialog(dialog-name[,ignore-flag])
Parameters:
(s) dialog-name
(i) ignore-flag
Returns:
(i)
name of the dialog box.
[optional] 1 to display dialog, or 0 to skip. Note: If not
specified one (1) is assumed.
value of the pushbutton used to close the dialog box.
Note: The Dialog Editor has been included to create your dialogs. Most of the
following information is for technical reference only. Please see the WinBatch
Users Guide for more information on the WIL Dialog Editor.
The text which follows describes how to define a dialog box for use by the Dialog
function. Please refer to your product-specific documentation for any additional
information which may supplement or supersede that which is described here.
220
Dialog
Before the Dialog function is called, you must include a section of code in your WIL
program which will define the characteristics of the dialog box to be displayed. First
of all, the dialog must be declared, and a name must be assigned to it. This is done
with a line of the following format:
<dlg-variable>Format="WWWDLGED,6.2"
where <dlg-variable> is the dialog name. "WWWDLGED,6.2" is the hard coded
format which identifies this dialog box as using the WIL Dialog Type 6.2. This
should follow the standard rules for WIL variable names, and may not exceed 19
characters in length.
Next, the format of the dialog box is defined, as follows:
<dlg-variable>Caption = <box-caption>
<dlg-variable>X = <x-origin>
<dlg-variable>Y = <y-origin>
<dlg-variable>Width = <box-width>
<dlg-variable>Height = <box-height>
<dlg-variable>MinWidth = <min-box-width>
[optional]
<dlg-variable>MinHeight = <min-box-height> [optional]
<dlg-variable>NumControls = <ctrl-count>
<dlg-variable>Procedure = <procedure-name>
<dlg-variable>Font = <font>
<dlg-variable>TextColor = <textcolor>
<dlg-variable>Background = <background>
<dlg-variable>Config = <config>
where:
<dlg-variable>
<box-caption>
<x-origin>
<y-origin>
<box-width>
<box-height>
<min-box-width>
is the internal name of the dialog box, as described above.
is the text which will appear in the title bar of the dialog
box.
is the horizontal coordinate of the upper left corner of dialog
box. Note: specify 9999 to always force the dialog to center,
or specify -1 to center but remember user placement for
redisplay.
is the vertical coordinate of the upper left corner of the
dialog box. Note: specify 9999 to always force the dialog to
center, or specify -1 to center but remember user placement
for redisplay.
is the width of the dialog box.
is the height of the dialog box.
[optional] indicates the approximate minimum width of the
dialog window that can be set by dragging the dialog's
boarders. The value is assumed to be in dialog units. When
this variable is present in a dialog template, the dialog
becomes re-sizable by either directly dragging the dialog's
boarder or by using the 'Size' system menu.
221
Dialog
<min-box-height>
<ctrl-count>
<procedure-name>
[optional] indicates the approximate minimum height of the
dialog window that can be set by dragging the dialog's
boarders. The value is assumed to be in dialog units and to
not include the height of the title and menu bars. When this
variable is present in a dialog template, the dialog becomes
re-sizable by either directly dragging the dialog's boarder or
by using the 'Size' system menu.
is the total number of controls in the dialog box (see below).
a User-Defined-Subroutine or function name. Use the same
name you use as part of a #DEFINEFUNCTION or
#DEFINESUBROUTINE statement. Your User-DefinedFunction/subroutine must have five parameters. You do not
have to include the parameters, commas or parentheses
when you make the name assignment to this dialog
definition variable. However, the complete
function/subroutine definition must appear in your script
before the WIL Dialog command that launches your dialog.
The function/subroutine is called one or more times while
the dialog is displayed. This procedure is used to respond to
user interactions with the dialog without having to redisplay
the dialog.
The first call to the function/subroutine is made just before
the dialog is displayed. Use this initial call to specify events
you wish to monitor.
You can find more information on the User Defined Dialog
procedure in later sections of this document.
<font>
222
The default text font for all controls that accept a font. A
control will use this font, if its font attribute is not specified
or set to DEFAULT. This font is not used on the dialog’s
title text, however. Dialog’s always use the system font in
their titles. The font is specified as a string of vertical bar (|)
delimited fields. The field values need to be set in such a
way that the font will display properly on many different
systems. You should use the WIL Dialog Editor to create
values for this dialog attribute. WARNING: If a font is
selected that doesn't exist on the users system, a substitution
will be made. We recommend using commonly available
fonts.
Dialog
<textcolor>
This is the default text color for all controls that accept text
color. A control will use this color when its text color
attribute is not specified or is set to DEFAULT. The text
color is not used by the dialog’s title. It is specified by three
vertical bar (|) delimited numbers ranging from 0 to 255.
The numbers represent one of the RGB colors: red, green or
blue in that order. The default is color black. Here are some
other sample colors:
BLACK="0,0,0"
WHITE="255,255,255"
RED="255,0,0"
GREEN="0,255,0"
DKGRAY="128,128,128"
GRAY="192,192,192"
DKRED="128,0,0"
DKGREEN="0,128,0"
BLUE="0,0,255"
PURPLE="255,0,255"
YELLOW="255,255,0"
CYAN="0,255,255"
DKBLUE="0,0,128"
DKPURPLE="128,0,128"
DKYELLOW="128,128,0"
DKCYAN="0,128,128"
<background>
This is the dialog’s background bitmap. Specify the bitmap
by file name and path enclosed in single quotes. If this value
is set to DEFAULT, the system dialog background color
will be used. Note: This variable can contain a three field
color, a bitmap file path, or both. To specify both, separate
the bitmap and color attributes with a comma and make sure
the bitmap’s file name and path is enclosed in quotes. When
both are specified WinBatch will always attempt to load the
bitmap first. If this fails, the color will be used as the dialog
background. See the discussion under the heading
<textcolor> for more information about color specification.
<config>
This controls how the Dialog Editor creates the WIL
Dialog command in your template. If the variable is given a
value of one (1), the editor will create a return variable
name that includes the dialog name (<dlg-variable>). For
example, if your dialog name is MyDialog, the dialog
statement would be:
MyDialogPushbutton=Dialog("MyDialog", 1)
Without this setting the dialog statement would be:
Pushbutton=Dialog("MyDialog", 1)
If the variable is given a value of two (2), the Dialog Editor
will place a zero (0) in the optional second parameter of the
Dialog statement when it creates your dialog template. This
223
Dialog
optional parameter tells WinBatch to ignore the Dialog
statement when it processes a script containing the dialog
template. The Dialog Editor, on the other hand, will not
ignore the dialog statement so that you can reload the
template into the editor at any time. If you do not specify
this configuration option, the Dialog Editor will create a
dialog statement with the second parameter set to one (1).
This tells WinBatch to process the Dialog statement by
loading and displaying the dialog template.
You can combine the values 1 and 2 using the binary OR(|)
operator to enable both features.
Finally, you will need to define the objects, or controls, which will appear inside the
dialog box. Each control is defined with a line of the following format:
;The following should all be on a single line
<dlg-variable>nn = `x, y, width, height, type, control-name,
var/license-string/parentname, text/pre-selected
item/progid/classid/moniker, value, taborder/position, style, font, textcolor,
backgroundcolor`
where:
dlg-variable
nn
is the name of the dialog box, as described above.
is the ordinal position of the control in the dialog box
(starting with 1).
x
is the horizontal coordinate of the upper left corner of the
control.
y
is the vertical coordinate of the upper left corner of the
control.
width
is the width of the control.
height
is the height of the control. [This should be DEFAULT for
all controls except file-list boxes and item boxes.]
type
is the type of control, (see below).
control-name
name used to identify the control in a User-DefinedCallback Procedure. The name cannot be more than 30
characters in length and MUST be unique. ( This attribute
can only be used with 6.2 or later dialog formats.)
var/license string/parent name
224
Dialog
var: the name of the variable affected by the control.
license string: If you are specifying a COMCONTROL
control and it requires a license string, the quoted license
string should be placed here. If you have a machine license
installed on all computers that run your script, you can place
an empty string in this field. The Dialog function will then
interrogate the system for the control’s license. Use the
DEFAULT keyword as a placeholder if the control does not
require a license.
parent name: When you specify a MENUITEM this
attribute is used to indicate the name of the control, menu
bar, or MENUITEM that hosts this menu item. If you place
the DEFAULT keyword in this attribute the item will be a
menu item on the dialog's context menu. Likewise, placing
the name of a control in this attribute will make the item a
menu item of the named control's context menu. Placing the
name of the MENUBAR control here will cause the item's
text to be displayed in the dialog's menu bar. If you use the
name of another MENUITEM, the menu item becomes a
menu choice on either a drop-down in the case of top level
MENUBAR items or a sub-menu displayed by the menu
item named.
text/pre-selected item/progid/classid/moniker
text: if supported by the control, is the description which
will be displayed with the control. [Use an empty string
("") if the control should appear blank.]
You can associate a shortcut key with a MENUITEM in
this attribute by following the item's text with a back slash
(\) and a key combination. The key combination is
indicated by using the same key descriptions used with the
SendKey function.
Note: Short-cut key combination should not be used with
menu items that display drop-down menus or sub-menus.
It is not considered good UI design and the menu caption
may not display correctly.
pre-selected item, if supported by the control, is used to
indicate which item in a list or range is the default item
for the control. Use this attribute with ITEMLIST and
FILELIST controls to have the control initially display
225
Dialog
selection coloring behind the pre-selected item. In order
for the Pre-selected Item to work properly it must be one
of the items listed in the controls variable.
Use this attribute with the new DROPLISTBOX control
to have a pre-selected value appear in the text box portion
of the control. The pre-selected value does not have to be
among the values listed in the controls variable.
The SPINNER control accepts a pre-select item as its
initial value. It will be the displayed value in the text box
when the dialog is displayed. Like with other controls it
will be the value in the Spinner’s variable, if the user does
not make changes. In order for the Pre-selected Item to
work properly, it must fall within the range of values
specified in the control’s variable.
Progid is used with COMCONTROL controls and is the
programmatic identifier of an ActiveX , OLE or COM
component control that supports integration into an
automation client container. It is usually in the form
servername.classname. Classid can be used as alternative
to a control’s progid. It is a sequence of hexadecimal
numbers that must be quoted and enclosed in a curly brace
({}) pair. It is usually in the form “{XXXXXXXX-XXXXXXXX-XXXX-XXXXXXXXXXXX}” were each �X’ is a
hexadecimal digit.
ClassID can be used as alternative to a controls ProgID. It
is a sequence of hexadecimal numbers that must be quoted
and enclosed in a curly brace ({}) pair. It is usually in the
form"{XXXXXXXX-XXXX-XXXX-XXXXXXXXXXXXXXXX}" were each X is a hexadecimal digit.
Moniker: Two special monikers can be used in this
attribute to implicitly use the WebBrowser control or
MSHTML COM component provided by Internet
Explorer. You can use the WebBrowser control by
placing a quoted URL moniker recognized by Internet
Explorer in the attribute. The URL can point to either a
local file or a document on the Internet. Use the
Document control by specifying the programmatic
identifier “MSHTML:” in this attribute. You can
optionally add valid html text after the colon (:) and the
MSHTML document object will parse and render the html
in its window.
See the discussion under the topic “Using the Internet
226
Dialog
value
tab-order/position
Explorer Based Control in WIL Dialogs” (pg. 250) for
more information.
is the value returned by the control. [Use only for
pushbuttons, radiobuttons, and checkboxes.] Note: should
be within the range of 0 - 127.
Tab order: allows you to specify a control's tab order
independently of a control's position or name in the dialog
template. Tab-order controls the order in which controls are
accessed when the keyboard is used to navigate the dialog.
It also influences which control is on top when controls
have overlapping positions in the dialog. It can be any
positive integer, but each control should have a unique
number.
When you navigate through a dialog using the tab key,
lower number controls will be given the keyboard focus
before higher controls. Likewise, low-numbered
overlapping controls will appear on top of higher numbered
controls. If you specify the DEFAULT keyword for this
attribute or if you give two controls the same tab order, a tab
order will be arbitrarily assigned to the control.
Note: The dialog function, under certain circumstances,
may change the tab order you specify. The GROUPBOX
controls tab order may be adjusted so that it is smaller than
any of the controls it contains. In addition, the tab order of
the controls inside the GROUPBOX may be adjusted so that
they are consecutive.
Position: Used with MENUITEM controls, this attribute
indicates the display order of the control on a menu relative
to other menu items on the same menu.
style
allows you to control the initial appearance and behavior of
your control.
Numbers represent each style and they can be combined,
using the bit-wise OR (|) operator, to set multiple styles.
The following table lists the style numbers, their meanings,
and the controls that they have an effect on.
Style
Meaning
Controls
1
Control is invisible
All
2
Control has disabled appearance and
PUSHBUTTON
does not accept any user input, it
RADIOBUTTON
227
Dialog
would otherwise accept input.
CHECKBOX
PICTUREBUTTON
EDITBOX
MULTILINEBOX
ITEMBOX
FILELISTBOX
CALENDAR
DROPLISTBOX
REPORTVIEW
SPINNER
GROUPBOX
MENUITEM
4
Control will only accept values
DROPLISTBOX
already in the drop down list portion
of the control
8
The controls text cannot be changed
EDITBOX
by typing in new text when the
MULTILINEBOX
control has the input focus. (Note:
SPINNER
The user can still change the value in
a SPINNER controls by using the up
and down arrows.)
16
Displays all characters as an asterisk
EDITBOX
(*) as they are typed into the control.
32
A button with this style is the default
PUSHBUTTON
button when no push or picture button PICTUREBUTTON
has the input focus. The user can
select this button by pressing the
enter key if no button has the input
focus. You should only give one
button this style. If you give the style
to more than one button, only the first
button (in the tab order) will have the
style. Generally, give this style to the
button that is the most likely option in
your dialog.
64
Allows only digits to be entered into
EDITBOX
the edit type controls. (Note: even
MULTILINEBOX
with this set, it is still possible to
paste non-digits into the edit control.)
128
Creates a button with a flat
PUSHBUTTON
appearance. All aspects of the
PICTUREBUTTON
button's border are removed
228
Dialog
including the 3d shadowing.
256
Turns off automatic height
ITEMBOX
adjustment feature of item and file
FILELISTBOX
box controls. Normally, these
controls adjust their height so that
they do not display partial items.
This style turns off this feature.
512
Centers text horizontally in the
VARYTEXT
control’s rectangle. (Cannot be used
STATICTEXT
with style 1024.)
1024
Displays text flush-right in the
VARYTEXT
control’s rectangle. (Cannot be used
STATICTEXT
with style 512.)
2048
Prevents text selection when control
EDITBOX
gets the input focus. Cursor is placed
MULTILINEBOX
to the left of any existing text in the
control.
4096
Prevents text selection when control
EDITBOX
gets the input focus. Cursor is placed
MULTILINEBOX
to the right of any existing text in the
control.
8192
Display Security Shield icon on
button (Vista or newer)
PUSHBUTTON
32768
Adds a check mark to the left of a
menu item
MENUITEM
65536
Adds a radio button-like dot graphic
to the left of a menu item
MENUITEM
131072
Causes a separator bar graphic to
display instead of text at the menu
item's location in the menu
Causes a column break to occur at
the specific item when used with
drop-down, context, or sub-menus.
Causes a line break (new row) with
menu items hosted directly by the
MENUBAR
The header bar is not displayed
across the top of the control.
The first row of the source array or
file is treated as column header text.
The control displays vertical and
horizontal lines to form a grid.
Only one row can be selected at a
time.
MENUITEM
262144
524288
1048576
2097152
4194304
PICTUREBUTTON
MENUITEM
REPORTVIEW
REPORTVIEW
REPORTVIEW
REPORTVIEW
229
Dialog
8388608
16777216
33554432
67108864
134217728
268435456
Selection highlighting extends to all
sub items in the selected row.
(sortascending) The control is
populated with rows ordered from
lowest to highest first column
values. Sorts using an "intuitive"
sort (See ArraySort for details).
The user can reorder control rows
based on any column's values by
clicking on the column header.
(sortdescending) The control is
populated with rows ordered from
highest to lowest first column
values. Sorts using an "intuitive"
sort (See ArraySort for details).
The user can reorder control rows
based on any column's values by
clicking on the column header.
Note: if both sortascending and
sortdecending are used,
sortascending takes precedence.
The first column text can be edited
in place.
Enables check boxes for each first
column item in the control.
Column header text is added as the
first row of the array returned from
an item search request, a selected or
checked item request, or a request
for all items of the control. This
style will also cause the control's
associated variable to contain the
column header text as the first row
of the array referenced by the
variable.
REPORTVIEW
REPORTVIEW
REPORTVIEW
REPORTVIEW
REPORTVIEW
REPORTVIEW
Note: Specifying 0 for this attribute is equivalent to using the DEFAULT keyword
and means that the control will exhibit default behavior.
font
230
is the font used to display a control's text. The font
description should be delimited by double quote (") marks
unless the attribute is set to DEFAULT. If this attribute is
set to DEFAULT, the font specified as the value of the main
dialog font will be used. If the main dialog font is set to
DEFAULT, the system font is used. You do not need to
provide any value for this attribute unless you are also
specifying text or background color. WARNING: If a font
is selected that doesn't exist on the user's system, a
substitution will be made. We recommend using commonly
available fonts.
Dialog
textcolor
is the color of text associated with a control. Color is
specified by three vertical bar (|) delimited numbers ranging
from 0 to 255. The numbers represent one of the RGB
colors: red, green or blue, in that order. The complete color
specification must be surrounded by double quotes (")
unless the DEFAULT key word is used. If this attribute is
set to DEFAULT, the color listed In the main dialog's
textcolor will be used. If a color is not specified for the
dialog, the system text color will be used.
backgroundcolor
used to change the color displayed behind a control’s text or
to specify the background bitmap for controls that display
them. Color is specified by three vertical bar (|) delimited
numbers ranging from 0 to 255. The numbers represent one
of the RGB colors (red, green or blue, in that order). The
complete color specification must be surrounded by double
quotes (") unless the DEFAULT keyword is used. If no
color is specified or the DEFAULT keyword is used the
system background color will be used. Specify a bitmap by
a file name and path enclosed in single quotes. You can
only place a bitmap in this attribute if the control supports
bitmap display. If a control displays a bitmap you cannot
place a color specification in the attribute.
Note: The numbers used for "x-origin", "y-origin", "box-width", "box-height", "x",
"y", "width," and "height" are expressed in a unit of measure known as "Dialog
Units."
Basically speaking:
1 width unit
1 height unit
4 units wide
8 units high
=
=
=
=
1/4 width of system font.
1/8 height of system font.
Average width of the system font.
Average height of the system font.
The following types of controls are available:
CALENDAR
The Calendar control has a calendar-like user interface.
This provides the user with a very intuitive and
recognizable method of entering or selecting a date. A
user can select a day from the current month and year by
simply clicking on a day number. A user can scroll the
months of the year by clicking the arrow buttons in the
top left or top right of the control. To select a nonadjacent month, the user can click the name of a displayed
month, and a pop-up menu appears that lists all months
within the year. The user can select a month on the list. If
231
Dialog
the user clicks the year displayed next to a month name, a
Spinner control appears in place of the year. The user can
change the year with this control.
The Calendar control will return the user’s selection in the
variable you supply as the Variable attribute in the
control’s definition. The date will be returned in the
standard WIL YYYY:MM:DD:HH:MM:SS date time
format.
You can also change the control’s font by providing a font
string in the Font attribute. However, you cannot change
the text or background color of this control.
CHECKBOX
A square box, in which an "X" appears when selected. A
check box can have a value of 0 (unchecked) or 1
(checked). Each checkbox in a dialog should use a unique
variable.
Normally, when a dialog box opens, every checkbox
defaults to being unchecked. You can change this by
assigning a value of 1 to the variable before calling the
Dialog function.
Note: for advanced users only: it is possible to define a
group of checkboxes which have the same "var". Each
box in the group must have a unique value, which must be
a power of 2 (1, 2, 4, etc.). The user can check and
uncheck individual checkboxes in the group, and when
the Dialog function exits, the value of the variable will be
equal to the values of all the checkboxes in the group
combined using the bitwise OR operator (|).
COMCONTROL
Use COMCONTROL in your dialog template to tell the
dialog function to host an ActiveX, OLE, VB, or COM
component control. You indicate the specific control by
placing a programmatic identifier (progid), class identifier
(classid) or moniker in the text attribute of the
COMCONTROL definition string.
If the control requires a license, place the license string in
the var attribute. If all computers that execute your script
have a machine license then you can set the var attribute
to an empty string (""). The DEFAULT keyword should
be used as a placeholder in the var attribute position when
the control does not require a license.
232
Dialog
You can include text font, text color and background
color information in the appropriate attribute fields of the
control definition string. However, many COM based
controls ignore this information. As an alternative, many
controls provide properties and method to change the
appearance and behavior of the control. To use these
properties and methods you can use the DialogObject
function to obtain a reference to the control in the
initialization (0) call to a user defined dialog callback
procedure. Once you have the control reference, you can
directly access the properties and methods of the control
using standard COM dot notation.
Many COM controls support COM events. Events are
notifications passed back to the control's container when a
use action occurs or a control's state changes. COM
events often provide detailed information about the event
and some even allow you to pass information back to
control. You can receive COM events and related
information in your dialog's callback procedure by using
the DialogObject function to indicate which control
events should cause your dialog callback procedure to be
invoked by the control. You can find more information
about event handling, including an example, under the
DialogObject help topic.
You can also find more information about using the
Internet Explorer based WebBrowser and MSHTML:
controls under the help topic “Using the Internet
Explorer Based Controls in WIL Dialogs” (pg. 250).
DROPLISTBOX
The DROPLISTBOX control is made up of two parts: an
EDITBOX and a drop-down ITEMBOX. A user can enter
a value in the EDITBOX or select a suggested value from
the drop-down items. The drop-down ITEMBOX is
displayed by clicking on the arrow next to the EDITBOX.
Generally, a DROPLISTBOX is appropriate when there is
a list of suggested choices, and an ITEMBOX is
appropriate when you want to limit input to what is on the
list. In addition, DROPLISTBOX controls save space on
your dialog, because the full list is not displayed until the
user clicks the down arrow.
233
Dialog
You specify the items for the DROPLISTBOX list by
placing a delimited list of values in the variable named in
the control's Variable attribute. You can give the
EDITBOX portion of the control an initial value by
placing a string in the Text attribute of the control’s
definition. The user’s choice is placed in the variable
named in the Variable attribute when the dialog is
dismissed.
EDITBOX
A box in which text can be typed. Whatever the user types
in the editbox will be assigned to the defined variable.
Normally, when a dialog box opens, editboxes are empty.
You can change this by assigning a value to the string
variable before calling the Dialog function, in which case
the value of the variable will be displayed in the editbox.
Note: variable names that begin with "PW_", will be
treated as password fields causing asterisks to be echoed
for the actual characters that the user types.
Limit for EDITBOX controls on Windows NT and newer
is the lesser of approximately 2147483646 characters or
available memory.
FILELISTBOX
A file selection list box will allow the user to select a file
from any directory or drive on the system. The value of
"var" will be set to the selected filename; if you need to
know what directory the file is in, use the DirGet
function after the Dialog function exits.
Normally, when a dialog box opens, file list boxes display
files matching a filemask of "*.*" (i.e., all files). You can
change this by assigning a different filemask value to the
string variable before calling the Dialog function.
Normally, if a dialog contains a FILELISTBOX, you
must select a file from the list box before you can exit the
dialog. You can change this behavior by placing the
statement IntControl(4, 0, 0, 0, 0) anywhere in your WIL
program prior to the Dialog statement.
In combination with the FILELISTBOX, you can include
an EDITBOX control which has the same variable name
as the file list box. If you do, the user can type a filemask
into the edit box (e.g., "*.TXT"), which will cause the file
234
Dialog
list box to be redrawn to display only those files which
match the specified filemask.
Also in combination with the file list box, you can include
a VARYTEXT control which has the same variable name
as the file list box. If you do, this control will show the
name of the directory currently displayed in the file list
box. For FILELISTBOXes, "text" should be DEFAULT.
Note: You can have only one file list box in a dialog.
GROUPBOX
The GROUPBOX control is a rectangle that surrounds a
set of controls, such as check boxes or radio buttons, with
text in its upper left corner. The sole purpose of a Group
control is to organize controls related by a common
purpose (usually indicated by the text).
Along with text, you can specify font, text color and a
background color for the control. The background color
applies to the area immediately behind the text in the
upper left corner. It does not change the background in
the majority of the control.
ITEMBOX
A selection list box. The variable is assumed to contain a
tab delimited list. The list is loaded into the list box in the
original order (Use the ItemSort function if a sorted list is
desired.). The user may choose none, one, or more items
in the list. When the dialog box is closed, the selected
items are returned via the variable as a tab delimited list.
MENUBAR
A MENUBAR is a horizontal bar that appears at the top
of your dialog just below the title bar. A menu bar
contains menu items. Generally, menu items displayed in
the menu bar cause drop-down menus to be displayed
when selected by the user.
MENUITEM
MENUITEMs can be displayed on a menu bar or as a
menu item associated with a drop-down, context menu
or sub-menu. Drop-down menus are created by placing
the name of a MENUITEM displayed in the menu bar
in the parent attribute of the menu item's template entry.
A sub-menu is started by placing the name of a
MENUITEM other than a menu bar displayed menu
item in the parent attribute.
Context menus are usually activated by right-clicking
the client area of a control or dialog. Create context
menus by specifying the name of a control in the parent
235
Dialog
attribute. If you use the DEFAULT key word as the
MENUITEM parent, the context menu will by
associated with the dialog and display when the user
right clicks on an 'empty' area of the dialog or on any
control that does not already have a system or template
supplied context menu.
MULTILINEBOX As the name suggests, the MULTILINEBOX control
allows a user to enter multiple lines of text. In all other
respects, it behaves like an EDITBOX control.
Note: MULTILINEBOX controls on Windows NT and
newer are only limited by available memory.
PICTURE
The PICTURE control is a simple control you use to
display a bitmap. You indicate the bitmap to display by
placing the bitmap file name and, optionally, the file path
in the Background attribute parameter of the control’s
definition. If you supply a file path, WinBatch will check
in the indicated path for the bitmap file before checking
other locations. If it does not find the file there or if you
do not supply a path, WinBatch will search the current
directory, the windows directory and the WinBatch
directory for the bitmap file.
Your bitmap does not need to be the same size as your
PICTURE control. The appropriate stretch or compress is
applied to the bitmap so that the entire image is displayed.
However, if the aspect ratio of your control is
significantly different from the bitmap’s aspect ratio, your
image may appear distorted.
Although the control does not normally display text, you
can still place text in the Text attribute. WinBatch will
display the text when it cannot find the bitmap indicated
in the "background" attribute while loading the dialog
template.
PICTUREBUTTON The Picture Button control is a push button that displays a
bitmap on its face instead of text and a background color.
Dialog Editor places your indicated bitmap file name and
path in the Background parameter. This parameter is used
for background color in most other controls. Although
the control does not normally display text, you can place a
text string in Text attribute. WinBatch will display the
text when it cannot find the bitmap indicated in the
236
Dialog
Background attribute while loading the dialog template.
Also, if you include an ampersand in the text, your users
will be able to use an accelerator key to navigate to
buttons just like they can with regular push buttons.
PUSHBUTTON
A button, which can be labeled and used as desired.
When the user presses a pushbutton, the Dialog function
will exit and will return the "value" assigned to the button
which was pressed. Therefore, you should assign a unique
"value" to each pushbutton in a dialog.
A pushbutton with the value of 0, has special meaning. If
the user presses a pushbutton which has a value of 0, the
WIL program will be terminated (or will go to the label
marked ":CANCEL", if one is defined); this corresponds
to the behavior of the familiar Cancel button.
The default pushbutton, that is selected if the user presses
the Enter key; is the pushbutton with the focus or, if no
button has the focus, the default button specified with the
style bit.)
An ampersand in the button text, acts as an accelerator
key for button navigation.
For pushbuttons, "var" should be DEFAULT.
Note: Every dialog box must contain at least one
pushbutton.
RADIOBUTTON
One of a group of circular buttons, only one of which can
be "pressed" (filled in) at any given time. You can have
more than one group of radio buttons in a dialog box, but
each group must use a different variable. When the
Dialog function exits, the value of the variable will be
equal to the "value" assigned to the radio button which is
pressed. Therefore, you should assign a unique "value" to
each radio button in a group.
Normally, when a dialog box opens, the default radio
button in each group (i.e., the one which is pressed) is the
first radio button, "called" in each group. You can change
this by assigning a default "value" to the variable before
calling the Dialog function.
REPORTVIEW
The Report View control is a ListView common control
with the 'report' Windows style. It can be used as either a
237
Dialog
simple grid control when a full featured grid control is not
needed or as an advanced version of the WIL dialog
ITEMBOX control.
The variable, defined in the controls Variable attribute, is
assumed to contain an array of values to display in the
control. When the variable is used to populate the control,
the control will have a column for each column in the
array. The array can optionally contain text for each
column heading in the first row of the array. See the Style
attribute for details. Note that the array variable contents
will only be used to populate the control when the Text
attribute is set to 'DEFAULT'. Upon return of the Dialog
this variable will contain an array of user selected rows
from the control.
The Text attribute can either be set to 'DEFAULT' or set
to the path and file name of a CSV file used to populate
the control. The file must meet the same CSV file
requirements specified for the ArrayFileGetCsv function
and the value separator must be a comma (,). The first line
of the file can optionally contain column headings. See
the Style attribute for details.
SPINNER
The SPINNER control has a pair of arrow buttons which
the user can click to increment or decrement a value
displayed in a small edit box connect to the arrow buttons.
Use the control’s variable attribute to set the range of
values that the control will display. The variable should
contain a vertical bar (|) delimited list with two or three
items.
"{minimum}|{maximum}|{increment/decrement}"
Make the first item the minimum value and the second the
maximum value. The minimum value can be greater than
the maximum value, but both values must be in the range
of -32768 to 32767, and the difference between the values
cannot exceed 32767. The third value indicates the
amount to add or subtract from the displayed number each
time the user clicks an up or down arrow (or presses the
arrow keys when the control has the input focus.) The
control adds or subtracts one (1) each time, if you do not
supply the third value. The final value selected by the
user is placed in the "variable" when the Dialog function
returns.
238
Dialog
You can indicate the initial value for your control by
placing a number in the text attribute of the control
definition. The control will default to the minimum value
if you do not indicate an initial value, or if your initial
value does not fall within the range you have selected in
the "variable" attribute.
STATICTEXT
Descriptive text, which does not change. This can be used
to display titles, instructions, etc. For static text controls,
the variable should be DEFAULT.
VARYTEXT
Variable text. The current value of the variable is
displayed. If a variable is not assigned a value in the WIL
program before calling the Dialog function, the "text"
field of the control definition will be used.
The following table is a complete list of controls. Controls are identified by their
type name along the left side of the table. Control attributes are named along the top
of the table. A check mark indicates that the control in the row has the attribute in
the column.
Controls and Their Attributes
Variable/
License String /
Parent Name
[*]
Pushbutton
Picture
CheckBox
PictureButton
EditBox
MultiLineBox
GroupBox
ItemBox
FileListBox
RadioButton
Spinner
StaticText
VaryText
Calendar
DropListBox
ComControl
MenuItem
MenuBar
ReportView
V
V
V
V
V
V
V
V
V
V
L
PN
PN
V
Text/
pre-sel/
moniker
[**]
T
T
T
T
T
T
T
P
P
T
T
T
T
P
P
M
T
Value Style
пѓј
пѓј
пѓј
пѓј
T
пѓј
пѓј
пѓј
пѓј
пѓј
пѓј
пѓј
пѓј
пѓј
пѓј
пѓј
пѓј
пѓј
пѓј
пѓј
пѓј
пѓј
Tab Font Text Back
Ord /
color ground
Pos
[****]
[***]
пѓј
пѓј
TO
C
TO
B
пѓј
пѓј
TO
C
TO
B
пѓј
пѓј
TO
C
пѓј
пѓј
TO
C
пѓј
пѓј
TO
C
пѓј
пѓј
TO
C
пѓј
пѓј
TO
C
пѓј
пѓј
TO
C
пѓј
пѓј
TO
C
пѓј
пѓј
TO
C
пѓј
пѓј
TO
C
пѓј
TO
пѓј
пѓј
TO
C
пѓј
пѓј
TO
C
RP
TO
пѓј
пѓј
C
[*] V = variable, L = license string, PN = parent name
239
Dialog
[**] T = control text, P = pre-selected value, M = progid/classid/moniker
[***] TO = tab order, RP = relative position
[****] B = bitmap, C= color spec.
Notes: You can have a maximum of 300 controls in a dialog.
When the Dialog function encounters a dialog template line that it cannot parse you
will receive an error. You can access the template line and error number by clicking
on the 'More Error Info' button on the error dialog.
Dynamic Dialogs
Some WIL functions have been added to support the Dynamic Dialog feature of the
Dialog function. In order to take advantage of this feature, you will also need to
create your own User-Defined-Callback Procedure. This procedure allows you to
modify the appearance of your dialog and execute WIL commands while your dialog
remains on the screen.
WinBatch Studio provides a right click context menu that helps generate a UserDefined-Callback Procedure template based on your dialog. To have WinBatch
Studio generate the User-Defined-Callback Procedure template code, you simply
highlight your Dialog code, top to bottom, starting with the line:
MyDialogFormat="WWWDLGED,6.2"
all the way down to and including the following line:
ButtonPushed=Dialog( "MyDialog" )
Next, right-click anywhere in the WinBatch Studio edit window, then select the
menu items:
Code Blocks
Create Dialog Callbacks in Clipboard
Function with Constants
When it is complete it copies the template code to the clipboard. Simply paste the
generated template code into your script, usually above your Dialog code or at the
beginning of your script.
User-Defined-Callback Function or Subroutine
Syntax:
UserDefinedCallback(dialog-handle,event-code,control-name,event-info,changeinfo)
Parameters:
(i) dialog-handle
(i) event-code
(i) control-name
240
handle to dialog.
event code for event that produced call to UDC.
name of control associated with event.
Dialog
(i) event-info
(a/s) change-info
Returns:
(i)
event information object (valid only when event-code = 14).
format depends on the event-code.
0 cancels dialog without updating control variables
-1 Dialog performs usual processing after return
-2 Dialog will not terminate. (Note: control variables will
not get updated until the Dialog exits.) Use
DialogControlGet and DialogControlSet, to get and
set values.
n (positive integer) performs usual processing and exits
dialog and the number n is the return value of the Dialog
statement as it exits.
“UserDefinedCallback” is a placeholder for the name of a function or subroutine you
place after the #DEFINEFUNCTION or #DEFINESUBROUTINE reserved words
in your WIL scripts. Your implementation must accept five (5) parameters as
shown.
dialog-handle
The first parameter is a handle to the Dialog associated with the procedure by
assigning the routine's name to the <dlg-variable>procedure variable.
event-code
The second parameter is an event code that tells your procedure which event
triggered the latest call.
control-name
The third parameter indicates the name of the control associated with the event in
parameter two. This is the same name that appears as the name attribute of the
control in the control's definition (legacy dialog formats, i.e. earlier than 6.2, used the
control's number in this parameter.)
event-info
When the second parameter has the value COM-event (14), the fourth parameter
contains a reference to an event information object. An event information object is a
WinBatch generated COM object that contains information about the COM event
that is calling to your User-Defined-Function.
The event-info object has the following properties
Identifier
This is the user defined identification number originally passed as the fifth
parameter to the DialogObject function.
Eventname
241
Dialog
This is the name of the event you obtained from the controls documentation
and passed as the fourth parameter to the DialogObject function.
Count
This property contains the number of parameters associated with the event. It
also indicates the number of Parameter objects in the Parameters property.
Count is zero (0) when the event does not have any parameters.
Parameters(index)
This indexed property returns one Parameter object for each parameter
associated with the event. The index parameter indicates which event
parameter you wish to access and should be a number between one (1) and
Count. The parameter object has Value as its only property. You can use the
value property to either access the information associated with the event
parameter or return information to the control by assignment. To access an
event parameter value you can do the following
; The "MSCAL.Calendar" control's "KeyPress" event had 1
; parameter – the code for the key pressed by the user.
nKey = EventInfo.Parameters(1).value
message("Key code", nKey)
You can return information to a control
; The "MSCAL.Calendar" control's "BeforeUpdate" event had 1
; parameter. You can use it to cancel a control change.
EventInfo.Parameters(1).value = @True
change-info
The format of this parameter is dependant on the specified event code.
Event Code
Return Value
17
Dialog Resize: A space delimited list of items that represent the
change in width and height of the dialog resulting from resizing
activity is passed to the callback UDF/UDS in the callback's fifth
parameter. The space delimited list items represent the delta (change
in width and height) of the dialog that resulted from resizing activity
and the client height and width that represents the internally
maintained size of the dialog's client area.
{delta_width}{delta_height}{client_width}{client_height}
The delta width and height supplied are in dialog units and can be
either negative or positive numbers. The client area is the area of a
window used to display controls and its size does not include the
dialog window's borders, menu bar, nor title bar.
The dialog template must use the <dlg-variable>MinWidth and/or
242
Dialog
<dlg-variable>MinHeight variables in order to use this option. The
last parameter is reserved for future development.
18
Item Select Row: The text of the first column of the selected row is
passed to the callback UDF/UDS in the callback's fifth parameter.
19
Double-Clicked Row: The text of the first column of the doubleclicked row is passed to the callback UDF/UDS in the callback's fifth
parameter.
20
Checked/Unchecked Item: The text of the checked item is passed
to the callback UDF/UDS in the callback's fifth parameter.
21
Item Text: The user modified text of the item is passed to the
callback UDF/UDS in the callback's fifth parameter.
Note that if more than one first column item of a control contains the
same value, it is possible for the fifth parameter to contain a tab
delimited list of multiple occurrences of the targeted item's text. The
number items in the list indicates which instance of the item is the
target of the event.
22
Column Click: User has used the mouse to click a column header of
a REPORTVIEW control. The one based column number of the
clicked column is passed to the callback UDF/UDS in the callback's
fifth parameter. The event is fired before the indicated column is
sorted so the sort direction can be controlled by setting or changing
the sort direction style of the control during the callback. Sorting is
effectively cancelled by removing both sorting related styles from
the control.
If you make the associations between your procedure and the Dialog via a dialog
variable assignment, your procedure will always be called at least once.
This initial call occurs after your dialog has been created but just before it is
displayed. This initial call (event-code = 0) is good place to inform the dialog about
other events you would like to handle. You can do this by making one call to the
DialogProcOptions or DialogObject function for each event you wish to handle in
your procedure. After you make one or more calls to DialogProcOptions or
DialogObject, each specified event will generate a call to your procedure with the
event-code parameter set to the triggering event and the control-name parameter set
to the control associated with the event.
This table provides the list of dialog event codes that your dialog procedure can
receive through the event-code parameter (parameter two). Conveniently, these
event-codes can also be used in calls to the DialogProcOptions function to indicate
that you want to process the event.
243
Dialog
Codes
0
1
2
3
4
5
6
7
8
9
10
11
12
13
15
Meaning
Initialization: Dialog has been created but not displayed. This
event is only generated once per Dialog session.
Timer: Set a Timer event
Pushbutton or Picturebutton Pushed: User has pressed a
PUSHBUTTON or PICTUREBUTTON control.
Radiobutton Selected: User has selected a RADIOBUTTON.
Checkbox Checked/Unchecked: User has checked or unchecked
a CHECKBOX control.
Changed text in Editbox or Multilinebox: User has changed the
text in an EDITBOX or MULTILINEBOX control
Filelistbox File Selected: User has selected a file in a
FILELISTBOX control
Itembox Item Selected: User has selected one or more items in a
ITEMBOX control.
Droplistbox/Combobox Item Change: User has changed the text
appearing at the top of a DROPLISTBOX. This event can be
triggered by the user picking a new item from the list portion of
the control or by the user typing new text into the control.
Calendar Date Change: User has selected a new date in a
CALENDAR control.
Spinner Number Change: User has changed the value of a
SPINNER control.
Close: User has selected the Close command from the system
menu. This event only applies to dialog's with system menus
enabled by a call to DialogProcOption code 1002.
Filelistbox File Double-Clicked: the user has used the mouse to
double-click an item in an FILELISTBOX.
Itembox Item Double-Clicked: the user has used the mouse to
double-click an item in an ITEMBOX.
Menu item selected: The user has used the mouse, an
access key or hot-key to select a MENUITEM.
Note: The user-defined callback is not called in response to the mouse
selection of a menu item that has associated drop-down menus or submenus. The associated drop-down or sub-menu is displayed instead. Hotkeys should not be used with menu items that display a drop-down or submenu.
16
Menu Item Initialization: The user has selected a dropdown menu, sub-menu or context menu. The name of the
menu hosting control or menu item is passed to the userdefined callback as the value of its third parameter.
For example: This event be used to dynamically modify
244
Dialog
17
the menu itself.
Dialog Resize: The user has resized the dialog. When the UserDefined-Callback is called with this request, the fifth parameter
to the User-Defined-Callback procedure contains a space
delimited list of items that represent the change in width and
height of the dialog that resulted from the resizing activity and
the client width and height.
{delta_width}{delta_height}{client_width}{client_height}
The delta width and height supplied are in dialog units and can
be either negative or positive numbers. The client area is the
area of a window used to display controls and its size does not
include the dialog window's borders, menu bar, nor title bar.
18
19
20
21
22
The dialog template must use the <dlg-variable>MinWidth
and/or <dlg-variable>MinHeight variables in order to use this
option. The DialogProcOptions function will error, if this
request code is used with a dialog template that does not contain
at least one of these variables.
Item Select Row: User has selected row in the REPORTVIEW
control. The text of the first column of the selected row is passed
to the callback UDF/UDS in the callback's fifth parameter.
Double-Clicked Row: User has used the mouse to double-click
a row in the REPORTVIEW control. The text of the first column
of the double-clicked row is passed to the callback UDF/UDS in
the callback's fifth parameter.
Checked/Unchecked Item: User has checked or unchecked an
item in a REPORTVIEW control with the 'checkbox' style. The
text of the checked item is passed to the callback UDF/UDS in
the callback's fifth parameter.
Item Text: User has changed the text of a first column item in a
REPORTVIEW control. The user modified text of the item is
passed to the callback UDF/UDS in the callback's fifth
parameter. Note that if more than one first column item of a
control contains the same value, it is possible for the fifth
parameter to contain a tab delimited list of multiple occurrences
of the targeted item's text. The number items in the list indicates
which instance of the item is the target of the event.
Column Click: User has used the mouse to click a column
header of a REPORTVIEW control. The one based column
number of the clicked column is passed to the callback
UDF/UDS in the callback's fifth parameter. The event is fired
before the indicated column is sorted so the sort direction can be
controlled by setting or changing the sort direction style of the
control during the callback. Sorting is effectively cancelled by
245
Dialog
removing both sorting related styles from the control.
Other events NOT supported by DialogProcOptions:
14
COM-Event: This event is not supported by DialogProcOptions.
Use DialogObject to monitor for COM events.
Other NON-events supported by DialogProcOptions:
1000
1001
1002
1003
1004
1005
1007
Dialog Disable: Grey the dialog's title bar and redraw dialog as
necessary. Optionally, display the system's "wait cursor".
Note: If you have code that may take a long time to execute in a
callback, you may need to temporarily disable the dialog. Don't
forget to enable after the process is complete.
Change Background: Change the dialog's background bitmap or
color.
Change System Menu: Change the dialog’s title bar system
menu. Note: this dialog option overrides the system menu settings
established with IntControl 49.
Change Dialog Title: Change the dialog’s title. Note: the
maximum dialog title length is 254 characters.
Get Control Name: Returns the name of the control associated
with the number.
Get Control Number: Returns the control number associated with
the name.
Get Client Area: Return internally maintained width and height of
the dialog's client area in dialog-units as a space delimited list. The
returned client area dimensions are the dialog's size not including
the width and height of borders, the height of the menu bar, nor
the height of the title bar. The third parameter to
DialogProcOptions must be set to -1 when using this request
code.
Procedure return values
In addition to the processing you perform in response to events, your procedure's
return value has an important impact on the behavior of your dialog. For example,
usually any button process will terminate a dialog, but by returning minus two (-2) in
response to an event-code of 2 you can force the dialog to stay on the screen. (Of
course, you still need to provide a way for the user to dismiss the dialog so you may
want to turn on system menus with DialogProcOptions code 1002 or return minus
one (-1) when one of the dialog's buttons is pressed.) The return value of zero will
cancel the entire script, unless the cancel is handled with the :cancel label and/or
with IntControl 72.
246
Dialog
Dynamic Dialog Example:
PROCOPT_INIT = 0 ; Dialog created.
PROCOPT_PUSH = 2 ; Pass push/picture button presses.
#DefineSubRoutine ExampleProc(DialogHandle, EventCode, ControlName,
Res4, Res5)
Switch( EventCode)
Case PROCOPT_INIT
DialogProcOptions(DialogHandle, PROCOPT_PUSH, 1)
break
Case PROCOPT_PUSH
If ControlName == "Pushbutton_Hello"
Display(2,"","Hello World")
Return -2 ; Don't termnate the dialog
endif
If ControlName == "Pushbutton_Bye"
Display(2,"","Goodbye World")
Return -1
endif
EndSwitch
Return -1
#EndSubRoutine
ExampleOneFormat=`WWWDLGED,6.2`
ExampleOneCaption=`Simple Callback Example`
ExampleOneX=029
ExampleOneY=060
ExampleOneWidth=174
ExampleOneHeight=094
ExampleOneNumControls=002
ExampleOneProcedure=`ExampleProc`
ExampleOneFont=`DEFAULT`
ExampleOneTextColor=`DEFAULT`
ExampleOneBackground=`DEFAULT,DEFAULT`
ExampleOneConfig=0
ExampleOne001=`029,051,034,014,PUSHBUTTON,"Pushbutton_Hello",DEFAULT,
"Hello",1,1,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
ExampleOne002=`093,051,034,014,PUSHBUTTON,"Pushbutton_Bye",DEFAULT,"G
ood Bye",0,2,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
ButtonPushed=Dialog("ExampleOne",1)
Simple Example:
MyDialogFormat=`WWWDLGED,6.2`
MyDialogCaption=`Edit INI file`
MyDialogX=069
MyDialogY=124
MyDialogWidth=176
MyDialogHeight=184
MyDialogNumControls=014
MyDialogProcedure = `DEFAULT`
MyDialogFont=`DEFAULT`
MyDialogTextColor=`DEFAULT`
MyDialogBackground=`DEFAULT`
MyDialogConfig=0
247
Dialog
MyDialog001=`109,157,58,14,PUSHBUTTON,"PushButton_Cancel",DEFAULT,"&C
ancel",0,1,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
MyDialog002=`111,77,60,14,PUSHBUTTON,"PushButton_Notepad",DEFAULT,"&N
otepad",1,2,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
MyDialog003=`111,95,60,14,PUSHBUTTON,"PushButton_WBS",DEFAULT,"&WinBa
tch Studio",2,3,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
MyDialog004=`111,113,60,14,PUSHBUTTON,"PushButton_Write",DEFAULT,"Wri
&te",3,4,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
MyDialog005=`111,131,60,14,PUSHBUTTON,"PushButton_WinWord",DEFAULT,"W
inW&ord",4,5,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
MyDialog006=`111,35,58,14,RADIOBUTTON,"RadioButton_Normal",state,"No&
rmal",1,6,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
MyDialog007=`111,49,58,14,RADIOBUTTON,"RadioButton_Zoomed",state,"&Zo
omed",2,7,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
MyDialog008=`111,63,58,14,RADIOBUTTON,"RadioButton_Iconized",state,"&
Iconized",3,8,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
MyDialog009=`111,21,58,14,CHECKBOX,"CheckBox_BAK",backup,"Make
&BAK",1,9,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
MyDialog010=`5,3,34,14,STATICTEXT,"StaticText_Directory:",DEFAULT,"&D
irectory:",DEFAULT,10,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
MyDialog011=`41,3,130,20,VARYTEXT,"VaryText_FileName",editfile,"*EMPT
Y*",DEFAULT,11,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
MyDialog012=`5,15,18,12,STATICTEXT,"StaticText_File:",DEFAULT,"&File:
",DEFAULT,12,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
MyDialog013=`5,35,100,140,FILELISTBOX,"FileListBox_Files",editfile,DE
FAULT,DEFAULT,13,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
MyDialog014=`5,25,100,10,EDITBOX,"EditBox_File",editfile,"None
Selected",DEFAULT,14,
DEFAULT,DEFAULT,DEFAULT,DEFAULT`
DirChange(DirWindows(0))
editfile = "*.INI"
; Set default mask for filelistbox
backup = 1
; Set the checkbox to be on by default
state = 2
; Set the 2nd radio button as the default
:DISPLAY_DLG
ButtonPushed = Dialog("MyDialog",1)
; If the user didn't select a valid file, re-display the dialog
If !FileExist(editfile) Then Goto DISPLAY_DLG
; Find out if the checkbox was checked, and proceed accordingly
If backup == 1
bakfile = StrCat(FileRoot(editfile), ".BAK")
FileCopy(editfile, bakfile, @TRUE)
endif
; Find out which radio button was pressed, and set the variable
; "runcmd" to the name of the appropriate member of the Run "family"
Switch state
case 1
runcmd = "Run"
break
248
Dialog
case 2
runcmd = "RunZoom"
break
case 3
runcmd = "RunIcon"
break
endswitch
; Set the variable "editor", based on the pushbutton that was pressed
Switch ButtonPushed
case 1
editor = FileLocate("notepad.exe")
break
case 2
editor = FileLocate("WinBatch Studio.exe")
break
case 3
editor = FileLocate("write.exe")
break
case 4
editor = FileLocate("winword.exe")
break
endswitch
; Execute the appropriate command (using variable substitution)
%runcmd%(editor, editfile)
Exit
:cancel
; If we got here, it means the user pressed the Cancel pushbutton
Message(MyDialogCaption, "Operation cancelled")
249
Dialog
Using Internet Explorer Controls in WIL Dialogs
You can display rendered HTML in WIL Dialogs using either the WebBrowser
Control or the MSHTML component of Internet Explorer.
In order to use Internet Explorer controls in WIL dialogs you must have at least
version 4.0 of Internet Explorer installed on the system. Some features shown in the
accompanying examples may require an even more recent version of Internet
Explorer.
Choosing the Correct Component
The WebBrowser Control adds browsing, document viewing, and data downloading
capabilities to your WIL dialogs. The Web Browser Control also acts as a
container for the MSHTML component which provides parsing and rendering of
HTML.
The WebBrowser Control and the MSHTML component each have their own
events and MSHTML document events do not bubble up to the WebBrowser
Control. This means that you cannot set your dialog callback procedure as the event
handler for MSHTML component events when it is hosted by the WebBrowser
Control. Therefore, if you wish to handle html document events like onClick or
onkeypress in your dialog callback, you should use the MSHTML component. On
250
Dialog
the other hand, if you wish to simply add web or local file browsing to your dialog,
consider the WebBrowser Control.
It is still possible to handle MSHTML component events when MSHTML is hosted
by the WebBrowser control. However, it requires using the ObjectEventAdd
function with a separate event handling User-Defined-Function or subroutine for
each event.
Using the MSHTML Component
You use the MSHTML component by specifying the programmatic identifier with
colon “MSHTML:” in the text attribute of a COMCONTROL control definition
string. Optionally, you can add standard html following the colon. The added html
will be parsed and rendered by the component. For example, the following control
definition will display a gif image in a dialog
; (Note: control definition strings must be on a single line.)
Exam001=`001,001,327,161,COMCONTROL,"Com_Mshtml",DEFAULT,MSHTML:<IMG
SRC="C:\Projects\Example\nebula.gif">,DEFAULT,1,DEFAULT,DEFAULT,DEFAU
LT,DEFAULT`
More sophisticated html content can become problematic because it needs to
conform to both html and WIL dialog template syntax in the control definition string.
Also, the amount of html is restricted by WinBatch line limit. For these reasons, it is
recommended that you dynamically create html content for an MSHTML control
when the content involves more than a simple, single tag.
You can create html dynamically by placing a “MSHTML:” without any html text
in the control's definition string. You then add html text using the MSHTML
object's writeln or write method in the initialization (0) call to the dialog callback
procedure.
Here is a simple example that illustrates creating html dynamically to produce a
visual affect not possible with standard WIL dialogs.
#DefineSubRoutine ExamProc(Exam_Handle,Exam_Message,Exam_ControlName,
Exam_EventInfo, Reserved)
;DialogprocOptions Constants
MSG_INIT=0 ; The one-time initialization
; New options for DialogObject
DLGOBJECT_ADDEVENT = 1 ;DialogObject add event
DLGOBJECT_REMOVEVENT = 2 ;DialogObject remove event
DLGOBJECT_GETOBJECT = 3 ;DialogObject get reference to object
DLGOBJECT_GETPICTURE = 4 ;DialogObject get a picture object
; New callback message
MSG_COMEVENT = 14 ;COM control event fired
Switch Exam_Message
Case MSG_INIT
; Get the control's object
251
Dialog
objHtmlDoc=DialogObject(Exam_Handle,"Com_Mshtml",
DLGOBJECT_GETOBJECT)
objHtmlDoc.write('<HTML>')
objHtmlDoc.write('<HEAD>')
objHtmlDoc.write('<TITLE>MSHTML Example</TITLE>')
objHtmlDoc.write('<STYLE> .textRed { COLOR: red }');Requires IE 5
objHtmlDoc.write('.textBlue { COLOR: blue } </STYLE>')
objHtmlDoc.write('</HEAD>')
objHtmlDoc.write('<BODY>')
objHtmlDoc.write(`<H1 class="textBlue"
onmouseover="this.className='textRed'"`)
objHtmlDoc.write(`onmouseout="this.className='textBlue'">`)
objHtmlDoc.write('Mouse over this text to see the color change ')
objHtmlDoc.write('from blue to red and back to blue')
objHtmlDoc.write('</H1>')
objHtmlDoc.write('<INPUT id="Button1" type="button" value="OK"
name="Button1"')
objHtmlDoc.write('style="Z-INDEX: 101; LEFT: 168px; WIDTH: 72px;')
objHtmlDoc.write('POSITION: relative">')
objHtmlDoc.write('</BODY>')
objHtmlDoc.write('</HTML>')
; Add an event
DialogObject(Exam_Handle,"Com_Mshtml",DLGOBJECT_ADDEVENT,"onclick",1)
Return(-1)
Case MSG_COMEVENT
; Test in case more events or COM controls are added later
If Exam_EventInfo.identifier==1 && Exam_ControlName=="Com_Mshtml"
; Get event source object associated with the event
objSource = objHtmlDoc.parentWindow.event.srcElement
; Button clicked?
If objSource.tagName == "INPUT"
If objSource.value == "OK" ; In case more added later.
; Release object references
objSource = 0
objHtmlDoc = 0
Exam_EventInfo = 0
Return(1) ; Quit dialog
EndIf
EndIf
EndIf
EndSwitch ; Exam_Message
Return(-1) ; Do default processing
#EndSubRoutine ; End of Dialog Callback ExamProc
252
Dialog
ExamFormat=`WWWDLGED,6.2`
ExamCaption=`MSHTML Example`
ExamX=021
ExamY=058
ExamWidth=179
ExamHeight=147
ExamNumControls=001
ExamProcedure=`ExamProc`
Exam001=`002,001,178,145,COMCONTROL,"Com_Mshtml",DEFAULT,"mshtml:",DEFA
ULT,1,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
ButtonPushed=Dialog("Exam")
Events and the MSHTML Component
While most COM controls use the dialog callback procedure's Event Information
Object parameter to pass event information to your callback procedure, the
MSHTML component uses a different mechanism. This means that the Event
Information Object passed to your dialog callback will have values for the Identifier
and EventName properties but the Count property will be set to zero (0) and the
Parameters property will not have any values. Instead, the MSHTML component
provides its own event object. The object contains event information; such as the
element in which the event occurred, the state of the keyboard keys, the location of
the mouse and the state of the mouse buttons.
Accessing the MSHTML Event Object
The event object is accessed via the event property of a window object that represents
a window associated with the MSHTML component. Typically, the component
creates one window object when it opens an HTML document. However, if a
document defines one or more frames, the component creates one window object for
the original document and one additional window object for each frame. Here is an
example that illustrates how to access the event object of the main window from
inside your dialog callback
; Get the MSHTML component's object
objHtmlDoc = DialogObject(Dlg_Handle, "Com_Mshtml",
DLGOBJECT_GETOBJECT)
; Access the event object for a main window event
objEvent = objHtmlDoc.parentWindow.event
Using the MSHTML Event Object
The event object is provided by the MSHTML component for all events but its use
can vary depending on the event being handled. All event properties are available to
all event objects, but some properties might not have meaningful values during some
events. For example, the fromElement and toElement properties are meaningful only
when processing the onmouseover and onmouseout events. For this reason it is
important to examine the srcElement property of the event object to identify the
253
Dialog
HTML element that is associated with the event before using other properties of the
event object. Also keep in mind that the properties of the object returned by
srcElement will vary with the type of element.
You can find more information on the objects, properties and methods of the event
object on Microsoft's MSDN web site.
Using the WebBrowser Control
The WebBrowser control contains the MSHTML component plus additional
features including navigation, hyperlinking, history lists and favorites. You add the
WebBrowser control to a dialog by placing a quoted URL moniker in the text
attribute of a COMCONTROL control definition string. The moniker can be a URL
to a World Wide Web site, a local file path/name or any other moniker recognized by
Internet Explorer.
While the WebBrowser control does contain an MSHTML component, MSHTML
events do not bubble up to the WebBrowser control. This means that the dialog
callback procedure can be used to handle events fired by the WebBrowser control
but it cannot be used to handle events fired by the MSMTHML component when
the component is hosted by the WebBrowser control.
The following example uses the URL to the WinBatch Technical Database Web site
to initialize a WebBrowser control in a WIL dialog. The newWindow2 and the
commandStateChange WebBrowser events are used to control navigation and
update the state of other dialog controls respectively. For demonstration purposes
the initial URL only points to the left hand frame of the site's page. This is done to
illustrate a technique for handling navigation to a nonexistent frame as happens if a
user clicks on a search result after executing a Tech Data Base search. Special
handling is necessary because the WebBrowser control will create a new unhosted
window when there is targeted navigation to a frame name that does not yet exist.
"Unhosted" means that the new window is not displayed as part of the dialog and the
dialog procedure will not receive the new window's events.
Several things can be done to prevent the creation of an unhosted window. You
could simply set the second parameter of the newWindow 2 event to @TRUE to
cancel the window
Exam_EventInfo.Parameters(2).value == @True
However, this not only cancels the window, it also cancels the navigation. If you
want the user to be able to navigate to a targeted frame from your dialog's
WebBrowser control, you need a second dialog control to serve as a navigation
target. In the example, this is accomplished by creating a hidden second
WebBrowser control and assigning its reference to the first parameter of the
newWindow2 event.
Exam_EventInfo.Parameters(1).value = DialogObject(Exam_Handle,
nHidden, DLGOBJECT_GETOBJECT)
254
Dialog
Now when the newWindow2 event fires, the second WebBrowser control is made
visible and accepts the navigation request.
Notice that since the controls occupy the same location on the dialog, the original
control's style is changed to invisible. Also notice that the second parameter of the
event is not changed. This is because the default setting for this parameter is
@FALSE which tells the control not cancel new window navigation.
The dialog also handles the commandStateChange event. The event is used to adjust
the state of the Forward and Back dialog buttons to match the presence or absence of
the corresponding navigation history.
#DefineSubroutine ExamProc(Exam_Handle,Exam_Message,Exam_ControlName,
Exam_EventInfo, reserved)
; Dialog constants
MSG_INIT
MSG_BUTTONPUSHED
DCSTATE_ADDSTYLE
DCSTATE_REMOVESTYLE
DCSTYLE_INVISIBLE
DCSTYLE_DISABLED
=
=
=
=
=
=
; New message.
MSG_COMEVENT
= 14 ;COM control event fired.
0
2
3
4
1
2
;
;
;
;
;
;
The one-time initialization
Pushbutton or Picturebutton
Add control style
Remove control style
Set Control Invisible
Disable control
; New - options for DialogObject
DLGOBJECT_ADDEVENT
= 1 ; DialogObject
DLGOBJECT_REMOVEVENT = 2 ; DialogObject
DLGOBJECT_GETOBJECT = 3 ; DialogObject
DLGOBJECT_GETPICTURE = 4 ; DialogObject
add event.
remove event.
get reference to object.
get a picture object.
; WebBrowser state change constants.
CSC_NAVIGATEFORWARD = 1
CSC_NAVIGATEBACK
= 2
switch Exam_Message
case MSG_INIT
; Initialize variable used to track hidden browser window.
sVisible = "ComControl_1"
sHidden = "ComControl_2"
; Want button messages.
DialogProcOptions(Exam_Handle, MSG_BUTTONPUSHED, 1)
; Add a COM event for both WebBrowser controls
DialogObject(Exam_Handle, "ComControl_1", DLGOBJECT_ADDEVENT,
"CommandStateChange",1)
DialogObject(Exam_Handle, "ComControl_2", DLGOBJECT_ADDEVENT,
"CommandStateChange",1)
DialogObject(Exam_Handle, "ComControl_1", DLGOBJECT_ADDEVENT,
"NewWindow2", 2)
DialogObject(Exam_Handle, "ComControl_2", DLGOBJECT_ADDEVENT,
"NewWindow2", 2)
255
Dialog
return(-1)
case MSG_COMEVENT ; COM event message
; Test in case more events or COM controls are added later
if Exam_ControlName == "ComControl_1" || Exam_ControlName ==
"ComControl_2"
switch Exam_EventInfo.identifier
case 1 ; CommandStateChange - use to update button status
; Event parameter 1 contains the command that is about to change
if Exam_EventInfo.Parameters(1).value == CSC_NAVIGATEFORWARD
sControl = "PushButton_Forward" ; Forward button
else
if Exam_EventInfo.Parameters(1).value == CSC_NAVIGATEBACK
sControl = "PushButton_Back" ; Back button
else
break ; Do nothing.
endif
endif
; Event parameter 2 indicates whether the command is
; being activated or deactivated
if Exam_EventInfo.Parameters(2).value
nRequest = DCSTATE_REMOVESTYLE ; Command active
else
nRequest = DCSTATE_ADDSTYLE ; Command inactive
endif
DialogControlState( Exam_Handle, sControl, nRequest ,
DCSTYLE_DISABLED)
Break
case 2 ; NewWindow2 - catches new window launches
; Set event parameter 1 to the other window to prevent IE creating
; an unhosted window
Exam_EventInfo.Parameters(1).value = DialogObject(Exam_Handle,
sHidden, DLGOBJECT_GETOBJECT)
; Change visibility of WebBrowser controls
DialogControlState(Exam_Handle,nHidden,DCSTATE_REMOVESTYLE,DCSTYLE_IN
VISIBLE )
DialogControlState(Exam_Handle,
Exam_ControlName,DCSTATE_ADDSTYLE,DCSTYLE_INVISIBLE)
; Update hidden variable to reflect change.
sVisible = sHidden
sHidden = Exam_ControlName
DialogControlState(Exam_Handle, "PushButton_Other",
DCSTATE_REMOVESTYLE, DCSTYLE_DISABLED)
Break
endswitch
endif
break
case MSG_BUTTONPUSHED ; Navigation buttons
if Exam_ControlName == "PushButton_Back" ; Back button
objWebBrowser = DialogObject(Exam_Handle, sVisible,
DLGOBJECT_GETOBJECT)
objWebBrowser.GoBack()
objWebBrowser = 0
256
Dialog
return -2 ; Don't quit.
endif
if Exam_ControlName == 004 ; Forward button
objWebBrowser = DialogObject(Exam_Handle, sVisible,
DLGOBJECT_GETOBJECT)
objWebBrowser.GoForward()
objWebBrowser = 0
return -2 ; Don't quit.
endif
if Exam_ControlName == "PushButton_Other" ; Other Window button switch controls
DialogControlState(Exam_Handle, sVisible, DCSTATE_ADDSTYLE,
DCSTYLE_INVISIBLE )
DialogControlState(Exam_Handle, sHidden,
DCSTATE_REMOVESTYLE,DCSTYLE_INVISIBLE )
objWebBrowser = DialogObject(Exam_Handle, sVisible,
DLGOBJECT_GETOBJECT)
objWebBrowser.stop
objWebBrowser = DialogObject(Exam_Handle, sHidden,
DLGOBJECT_GETOBJECT)
objWebBrowser.Refresh2(1) ; 1 means normal refresh
objWebBrowser = 0
sTemp
= sHidden
sHidden = sVisible
sVisible = sTemp
return -2 ; Don't quit.
endif
if Exam_ControlName == "PushButton_Quit" ; Quit button
Exam_EventInfo = 0 ; Free reference - appropriate when using
subroutine
break ; Done
endif
break
endswitch
; Exam_Message
return(-1)
; Do default processing
#EndSubroutine
; End of Dialog Callback ExamProc
ExamFormat=`WWWDLGED,6.2`
ExamCaption=`WebBrowser Example`
ExamX=021
ExamY=058
ExamWidth=350
ExamHeight=240
ExamNumControls=006
ExamProcedure=`ExamProc`
Exam001=`001,001,343,214,COMCONTROL,"ComControl_1",DEFAULT,"http://tech
supt.winbatch.com/webcgi/webbatch.exe?techsupt/tsleft.web",DEFAULT,1,0,
DEFAULT,DEFAULT,DEFAULT`
Exam002=`001,001,343,214,COMCONTROL,"ComControl_2",DEFAULT,"about:blank
",DEFAULT,1,0,DEFAULT,DEFAULT,DEFAULT`
257
Dialog
Exam003=`014,222,041,010,PUSHBUTTON,"PushButton_Back",DEFAULT,"Back",1,
3,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Exam004=`063,222,041,010,PUSHBUTTON,"PushButton_Foreward",DEFAULT,"Fore
ward",2,4,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Exam005=`126,222,041,010,PUSHBUTTON,"PushButton_Other",DEFAULT,"Other
Window",3,5,2,DEFAULT,DEFAULT,DEFAULT`
Exam006=`295,222,041,010,PUSHBUTTON,"PushButton_Quit",DEFAULT,"Quit",4,
6,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
ButtonPushed=Dialog("Exam")
WIL Additional Properties for Internet Explorer Components
WinBatch adds several properties to the programming models of Internet Explorer
components. These properties give you additional control over the appearance and
behavior of both the WebBrowser Control and the MSHTML component.
Gaining Access to Additional Properties
To access the properties when using the MSHTML component use the
DialogObject function to obtain a references to the component for inside the dialog
callback procedure. You then need to obtain a reference to the parent window of the
MSHTML component by calling the parentWindow property and then the window
object's external property to get and set the WIL supplied additional properties. Here
is an example
; Get the control's object.
objHtmlDoc = DialogObject(Dialog_Handle, "ComControl_1",
DLGOBJECT_GETOBJECT)
; Turn off context menus.
objHtmlDoc.parentWindow.external.ContextMenu = @FALSE
Since the WebBrowser control hosts the MSHTML component you need to use the
document property to reference the MSHTML component before accessing WIL
provided properties. Here is an example
; Get the control's object.
objWebBrowser = DialogObject(Dialog_Handle, "ComControl_1",
DLGOBJECT_GETOBJECT, "", 0)
; Turn off context menus.
objWebBrowser.document.parentWindow.external.contextMenu = @false
The WebBrowser’s document property does not automatically return a valid object
when the control is created because the document object is not instantiated until
after the contents of the document are loaded into the control. This means you
should not set WIL additional properties from case zero (0) of your dialog procedure
as you can with the MSHTML component. The best time to set these properties is
when your dialog procedure is called by the DownloadComplete event. This insures
that document creation is completed and the document property will return a valid
258
DialogControlGet
object reference. See the Dialog function topic for more information on control
events.
The Additional Properties
The following properties are provided by WIL to modify the behavior and
appearance both of the WebBrowser Control and the MSHTML component.
Scrollable
Set this property to @TRUE to allow the user to scroll the content displayed by the
control. The user cannot scroll the content of the control when the property is set to
@FALSE. When set to @TRUE scroll bars are displayed in the control. The default
for this property is @TRUE.
FlatScrollBars
When this property is set to @TRUE control scrollbars have a flat appearance. This
property has no effect unless the Scrollable property is set to @TRUE. The
FlatScroollBars property is set to @FALSE by default.
ContextMenu
This property controls the display of context menus when a user right-clicks on the
control. When set to @TRUE the control’s context menu is displayed. When set to
@FALSE a right-click has no effect. The default for this property is @TRUE.
ThreeDBorder
Use this property to control the appearance of the control’s border. This property
affects the displayed documents border and any framesets within the document. Set
the property to @TRUE to turn on 3-D borders. This property’s default is @FALSE.
See Also:
AskLine, AskPassword, AskYesNo, IntControl, AskItemList, DialogProcOptions,
DialogControlState, DialogControlGet, DialogControlSet, DialogObject
DialogControlGet
Returns text and state information associated with a control.
Syntax:
DialogControlGet(dialog-handle,control-name,request-code[,request-value])
Parameters:
(i) dialog-handle
(s) control-name
(i) request-code
(s) request-value
handle to dialog.
name of control to retrieve information from.
information to return.
depends on request code. see below.
259
DialogControlGet
Returns:
(a/s/i)
requested information.
The DialogControlGet function returns text and state information associated with a
control.
dialog-handle
The dialog-handle passed as the first parameter to your dialog procedure.
control-name
Name of the control you wish to retrieve information from (for legacy dialog
formats, i.e. earlier than 6.2, use the control's number in this parameter.)
request code
A request code. The request code depends on the type of the control you are
querying. The following table shows the possible request codes, the control they
apply to, and the returned information.
Request
1
Applicable Controls
CHECKBOX
REPORTVIEW
2
RADIOBUTTON
3
EDITBOX
MULTILINEBOX
PICTURE
RADIOBUTTON
CHECKBOX
PICTUREBUTTON
VARYTEXT
STATICTEXT
GROUPBOX
PUSHBUTTON
MENUITEM
ITEMBOX
FILELISTBOX
4
5
260
Function Return Values
CHECKBOX
(i) 1 box checked, 0 box unchecked.
REPORTVIEW
(i) 1 if the REPORTVIEW control has the
checkbox(134217728) style and the
indicated item is checked, 0 for
unchecked. The functions optional fourth
parameter (request-value) must be used
to indicate the text of the item to test.
(i) 1 button is dotted, 0 button is not
dotted.
(s) All text currently in the control.
(s) Control’s title.
ITEMBOX, FILELISTBOX and
DROPLISTBOX: (s) Tab delimited list of
DialogControlGet
DROPLISTBOX
REPORTVIEW
6
ITEMBOX
FILELISTBOX
DROPLISTBOX
REPORTVIEW
7
CALENDAR
8
9
SPINNER
10
ITEMBOX
FILELISTBOX
MULTILINEBOX
RADIOBUTTON
CHECKBOX
VARYTEXT
STATICTEXT
GROUPBOX
PUSHBUTTON
ITEMBOX
FILELISTBOX
DROPLISTBOX
REPORTVIEW
SPINNER
EDITBOX
MULTILINEBOX
COMCONTROL
PICTURE
PICTUREBUTTON
11
12
all the items currently in the control, or a
File wildcard mask if a FILELISTBOX is
specified (i.e., "c:\temp\*.*").
REPORTVIEW: (a) One or two
dimension array containing the contents of
a REPORTVIEW control. Supports
variant safe arrays.
ITEMBOX, FILELISTBOX and
DROPLISTBOX: (s) Tab delimited list of
the currently selected item(s) in the
control. An empty string, if no item is
selected.
REPORTVIEW: (a) One or two
dimension array containing all selected
rows of a REPORTVIEW control.
(s) The date shown in the control in
YYYY:MM:DD:HH:MM:SS format.
(s) Current value displayed in control.
No operation. Valid for DialogControlSet
only.
(i) One-based index of the first currently
visible item in the list. (1 is the first item
in the list.)
(s) Control's background color specified
by three vertical bar (|) delimited numbers
ranging from 0 to 255. If the control is
using the system default color, the string
"DEFAULT" is returned.
(s) The file specification of the controls
currently displayed bitmap. If the control
is not displaying a bitmap, the
261
DialogControlGet
13
14
15
16
RADIOBUTTON
CHECKBOX
VARYTEXT
STATICTEXT
GROUPBOX
PUSHBUTTON
ITEMBOX
FILELISTBOX
DROPLISTBOX
REPORTVIEW
SPINNER
EDITBOX
MULTILINEBOX
RADIOBUTTON
"DEFAULT" key string is returned.
(s) Control's text color specified by three
vertical bar (|) delimited numbers ranging
from 0 to 255. If the control is using the
dialog's default text color, the string
"DEFAULT" is returned.
Valid only for DialogControlSet.
Valid only for DialogControlSet.
(i) Control-name (control-number for
legacy dialogs) of the radio button from a
group of radio buttons with the dot. If no
radio button of the group has the dot, an
empty string ("") or zero (0) for legacy
dialogs is returned. The function’s second
parameter can be the control-name of any
radio button in the target group. (Radio
buttons are grouped together by giving
each button the same variable attribute.)
17
ALL CONTROLS
(Except MENUBAR and
MENUITEM)
(s) Space delimited list of a control's
position and size in dialog units relative to
the dialog's client area. The first two
numbers are the horizontal and vertical
location of the upper-left corner of the
control while the third and fourth numbers
are the width and height of the control.
18
ALL CONTROLS
(Except GROUPBOX)
(s) Tab delimited list of menu item names
associated with the control, menu item or
menu bar.
19
ALL CONTROLS
(Except MENUBAR and
MENUITEM)
(i) Window handle of a dialog control.
Note: The request cannot be used on
MENUITEM and MENUBAR controls
because these controls are not windows.
262
DialogControlGet
20
REPORTVIEW
(s) Tab delimited list of REPORTVIEW
column headings.
21
REPORTVIEW
(s) Space delimited list of the width of
each REPORTVIEW column in dialog
units.
22
Valid only for DialogControlSet.
23
Valid only for DialogControlSet.
24
REPORTVIEW
(a) One or two dimension array containing
all REPORTVIEW rows which have first
column text matching one of the items
specified as a tab delimited list in the
functions (request-value) fourth
parameter.
25
REPORTVIEW
(i) 1 if the next user edit of an item will be
canceled upon completion. This request
code only applies to REPORTVIEW
controls with the edit item (67108864)
style.
26
REPORTVIEW
(a) One or two dimension array containing
all checked rows of a REPORTVIEW
control. This request code is only relevant
when a REPORTVIEW control has the
checkbox (134217728) style.
27
REPORTVIEW
(s) Space delimited list of format
specification for each REPORTVIEW
column. The returned values have the
following meanings:
0 - left justify text
1 - center justify text
2 - right justify text
Example:
#DEFINESUBROUTINE
GetExample(Handle,DialogMessage,DialogControlID,param4,param5)
switch (DialogMessage)
case 0
DialogProcOptions(Handle, 7, 1); Pass item listbox selection
changes.
break;
case 7
sSelection = DialogControlGet(Handle,"Itembox_Colors",6); Get
selection
263
DialogControlSet
DialogControlSet(Handle,"Static_Color",4,sSelection); Set text
break;
endswitch
return -1
#ENDSUBROUTINE
ItemList =
"Red%@Tab%Green%@Tab%Blue%@Tab%Yellow%@Tab%Cyan%@Tab%Magenta"
GetExampleFormat=`WWWDLGED,6.2`
GetExampleCaption=`Control Get Example`
GetExampleX=529
GetExampleY=060
GetExampleWidth=206
GetExampleHeight=122
GetExampleNumControls=004
GetExampleProcedure=`GetExample`
GetExampleFont=`DEFAULT`
GetExampleTextColor=`DEFAULT`
GetExampleBackground=`DEFAULT,DEFAULT`
GetExampleConfig=0
GetExample001=`023,099,160,014,PUSHBUTTON,"PushButton_1",DEFAULT,"Ok
Already",1,1,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
GetExample002=`111,031,054,012,STATICTEXT,"Label_1"DEFAULT,"Your
Selection:",DEFAULT,2,0,"Modern|8192|40|65330","0|0|0",DEFAULT`
GetExample003=`111,045,078,010,STATICTEXT,"Static_Color",DEFAULT,"",D
EFAULT,3,0,"Modern|6656|40|65330","0|0|0",DEFAULT`
GetExample004=`005,011,068,072,ITEMBOX,"Itembox_Colors",ItemList,DEFA
ULT,DEFAULT,4,0,DEFAULT,DEFAULT,DEFAULT`
ButtonPushed=Dialog("GetExample",1)
See Also:
DialogProcOptions, DialogControlState, DialogControlSet
DialogControlSet
Changes the text or appearance of a control.
Syntax:
DialogControlSet(dialog-handle,control-name,request-code,set-info)
Parameters:
(i) dialog-handle
(s) control-name
(i) request-code
(a/s/i) set-info
handle to dialog
name of control to modify
control property to set
information to set
Returns:
(i)
@TRUE if successful otherwise @FALSE.
264
DialogControlSet
Use the DialogControlSet function to change the text or appearance of a control.
dialog-handle
The dialog-handle passed as the first parameter to your dialog procedure.
control-name
Name of the control you wish to modify (for legacy dialog formats, i.e. earlier than
6.2, use the control's number in this parameter.)
request-code
A request code. The request code depends on the type of the control you are
changing.
set-info
Place new text or state information in the fourth parameter. The type of information
you place in the fourth parameter is dependent on the request code you use in the
third parameter. The following table shows the possible request codes, the control
they apply to, and the type information that you need to supply in parameter four.
Request
1
Applicable Controls
CHECKBOX
REPORTVIEW
2
RADIOBUTTON
3
EDITBOX
MULTILINEBOX
PICTURE
RADIOBUTTON
CHECKBOX
PICTUREBUTTON
VARYTEXT
STATICTEXT
GROUPBOX
PUSHBUTTON
MENUITEM
ITEMBOX
4
5
Set-info
CHECKBOX: (i) 1 means check the box, 0
means uncheck the box.
REPORTVIEW: (s) Checks or unchecks an
item in a REPORTVIEW control. Use the
function's set-info (fourth) parameter to
indicate the first column text of the row to
check or uncheck. The text can be a
delimited list to indicate which row should
be checked or unchecked when multiple
rows have the same first column text.
(i) 1 means select button, 0 means clear the
selection.
(s) Text replaces the existing text.
(s) Text replaces the existing title.
ITEMBOX and DROPLISTBOX: (s) Tab
265
DialogControlSet
DROPLISTBOX
FILELISTBOX
REPORTVIEW
6
ITEMBOX
DROPLISTBOX
FILELISTBOX
REPORTVIEW
7
CALENDAR
8
9
SPINNER
MULTILINEBOX
266
delimited list of items to replace the
existing list displayed by the control.
FILELISTBOX: (s) File mask to change or
modify the default of “*.*”
REPORTVIEW: (a/s) Replaces the
contents of the REPORTVIEW control.
The function's fourth parameter must
contain either a CSV file path+name, or a
one or two dimension array that will be
used to replace the existing contents of the
control. Supports variant safe arrays.
ITEMBOX, FILELISTBOX and
DROPLISTBOX: (s) Tab delimited list of
one or more items you wish to be
highlighted/selected. Use an empty string
to cancel an existing selection. (Multiple
item selection only applies to ITEMBOXs
when multi-select is turned on. See
IntControl (4, p1, 0, 0, 0) function
documentation for information on multiselect.)
REPORTVIEW: (s) Toggles the selection
state of a row in a REPORTVIEW control.
Use the function's set-info (fourth)
parameter to indicate the first column text
of the row to select or unselect. The text
can be a delimited list to indicate which
row should be selected when multiple rows
have the same first column text. Use an
empty string to unselect all selected rows
of a control. Note that the control
automatically unselects a selected row
when a new row is selected when the
control has the single select (4194304)
style.
(s) Date shown in the control in
YYYY:MM:DD:HH:MM:SS format.
(i) Displayed value of control.
(s) Tab delimited list of one or more
numbers that indicate tab stop distances. If
the list contains 1 item, tab stops are set at
every n dialog template units, where n is
DialogControlSet
10
11
12
13
ITEMBOX
FILELISTBOX
MULTILINEBOX
REPORTVIEW
RADIOBUTTON
CHECKBOX
VARYTEXT
STATICTEXT
GROUPBOX
PUSHBUTTON
ITEMBOX
FILELISTBOX
DROPLISTBOX
REPORTVIEW
SPINNER
EDITBOX
MULTILINEBOX
COMCONTROL
PICTURE
PICTUREBUTTON
RADIOBUTTON
CHECKBOX
VARYTEXT
STATICTEXT
the distance indicated by the single item. If
the list contains more than 1 item, tab stops
are set at each indicated distance. The list
item values must be in dialog template
units, which are the same units used to
specify the size of the control.
ITEMBOX, FILELISTBOX and
MULTILINEBOX: (i) One-based index of
the list item to be scrolled to the top of the
control's viewing area. If n is greater than
the number of items in the list or less than
1, the list will be scrolled so that the last
items in the list are in the control's viewing
area.
REPORTVIEW: (s) Scrolls a
REPORTVIEW control row into view. Use
the function's set-info (fourth) parameter to
indicate the first column text of the row to
scroll to.
(i) Background color. The color is
specified by three vertical bar (|) delimited
numbers ranging from 0 to 255. To give
the control the system default background
color, use an empty string ""or the
"DEFAULT "key string for this parameter.
(s) The file specification of a bitmap. You
can use this request to change the bitmap
the control is displaying, or you can force
the control to display it's text instead of a
bitmap, by setting the parameter to an
empty string "" or the "DEFAULT" key
string.
(s) Text color. The color is specified by
three vertical bar (|) delimited numbers
ranging from 0 to 255.
267
DialogControlSet
14
15
16
17
268
GROUPBOX
PUSHBUTTON
ITEMBOX
FILELISTBOX
DROPLISTBOX
REPORTVIEW
SPINNER
EDITBOX
MULTILINEBOX
ITEMBOX
DROPLISTBOX
FILELISTBOX
REPORTVIEW
ITEMBOX
DROPLISTBOX
FILELISTBOX
REPORTVIEW
ALL CONTROLS
(Except MENUBAR
and MENUITEM)
To give the control the dialog's default text
color, use an empty string ""or the
"DEFAULT "key string for this parameter.
ITEMBOX, FILELISTBOX and
DROPLISTBOX: (s) Text added as an
item to the list displayed by the control. If
the items in the control are sorted, the new
item will be inserted in sort order.
REPORTVIEW: (a/s) Adds a row to a
REPORTVIEW control. The functions
function's set-info(fourth) parameter can be
an array or delimited list. If the delimited
list lacks enough items or the array lacks
enough columns the remaining columns of
the control will be left empty. If either the
list or array has too many items or columns,
the extra text will be ignored. If an array
parameter contains multiple rows, all array
rows will be added to the control. Supports
variant safe arrays.
ITEMBOX, FILELISTBOX and
DROPLISTBOX: (s) Text of item to be
removed from the list displayed by the
control. The text need not match the list
item's case but must otherwise be an exact
match.
REPORTVIEW: (s) Removes a row from a
REPORTVIEW control. Use the function's
set-info (fourth) parameter to indicate the
first column text of the row to remove.
The text can be a delimited list to indicate
which row to remove when multiple rows
have the same first column text.
Valid only for DialogControlGet.
(s) Space delimited list of a control's
position and size in dialog units relative to
the dialog's client area. The first two
DialogControlSet
numbers are the horizontal and vertical
location of the upper-left corner of the
control while the third and fourth numbers
are the width and height of the control.
18
Valid only for DialogControlGet.
19
Valid only for DialogControlGet.
20
REPORTVIEW
(s) Changes the column headings text of a
REPORTVIEW control. Place a tab
delimited list of the new column headings,
one for each column, in the function's setinfo (fourth) parameter.
21
REPORTVIEW
(s) Specify a new width in dialog units for
each REPORTVIEW column as a space
delimited list in the function's set-info
(fourth) parameter. Column widths can be
set to -1 to cause a column's width to fit the
column contents. -2 can be used to set a
column's width to match the column's
header text. Setting the farthest right
column to -2 causes that column to fill the
remaining width of the control.
22
REPORTVIEW
(s) Adds a new column to the far right side
of a REPORTVIEW control. Indicate the
columns header text in the function's setinfo (fourth) parameter.
23
REPORTVIEW
(i) Remove a column from a
REPORTVIEW control. The function's
set-info parameter should contain one
based number from left to right of the
column to remove. Note that column 1, the
left most column, cannot be removed from
the control.
25
REPORTVIEW
(i) Toggles canceling of a pending or the
next edit of a REPORTVIEW control item.
The set-info parameter should be @TRUE
to turn on edit canceling and @FALSE to
turn off canceling. The function returns the
previous edit cancel setting.
26
Valid only for DialogControlGet.
269
DialogControlSet
27
REPORTVIEW
(s) Specify the format for each
REPORTVIEW column as a space
delimited in the function's set-info
parameter. Valid values and meanings:
0 - left justify text
1 - center justify text
2 - right justify text
* Note that the above functions apply case insensitive text comparisons when
identifying items in a REPORTVIEW control.
Example:
#DefineSubRoutine SetExample(Handle,Msg,Id,EventInfo,param5)
Switch (Msg)
Case 0
DialogProcOptions(Handle, 10, 1) ; Spinner selection changed.
; Get spinner value
nSelection = DialogControlGet(Handle,"Spinner_1",8)
; Set text
DialogControlSet(Handle,"StaticText_2",4,Num2Char(nSelection))
break;
Case 10
; Get spinner value
nSelection = DialogControlGet(Handle,"Spinner_1",8)
; Set text
DialogControlSet(Handle,"StaticText_2",4,Num2Char(nSelection))
break;
EndSwitch
Return -1
#EndSubRoutine
SpinnerRange = "0|255|1"
SetExampleFormat=`WWWDLGED,6.2`
SetExampleCaption=`Convert Number to ASCII Character`
SetExampleX=155
SetExampleY=060
SetExampleWidth=187
SetExampleHeight=120
SetExampleNumControls=005
SetExampleProcedure=`SetExample`
SetExampleFont=`DEFAULT`
SetExampleTextColor=`DEFAULT`
SetExampleBackground=`DEFAULT,DEFAULT`
SetExampleConfig=0
SetExample001=`022,086,137,014,PUSHBUTTON,"PushButton_OK",DEFAULT,"OK
",1,1,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
SetExample002=`017,025,030,017,SPINNER,"Spinner_1",SpinnerRange,"48",
DEFAULT,2,0,"Microsoft Sans Serif|10752|40|34","0|0|0",DEFAULT`
270
DialogControlState
SetExample003=`017,015,049,008,STATICTEXT,"StaticText_1",DEFAULT,"Sel
ect a &Number:",DEFAULT,3,0,DEFAULT,DEFAULT,DEFAULT`
SetExample004=`100,028,032,025,STATICTEXT,"StaticText_2",DEFAULT,DEFA
ULT,DEFAULT,4,0,"Microsoft Sans Serif|18944|40|34","0|0|0",DEFAULT`
SetExample005=`100,015,043,009,STATICTEXT,"StaticText_3",DEFAULT,"ASC
II Letter:",DEFAULT,5,0,DEFAULT,DEFAULT,DEFAULT`
ButtonPushed=Dialog("SetExample")
See Also:
DialogProcOptions, DialogControlState, DialogControlGet
DialogControlState
Changes a control’s style or give control input focus.
Syntax:
DialogControlState(dialog-handle,control-name,request-code,style)
Parameters:
(i) dialog-handle
(s) control-name
(i) request-code
(i) style
Returns:
(i/s)
handle to dialog
name of control to change
1 = give control focus
2 = query control’s style
3 = add control styles
4 = remove control styles
5 = get control that has focus
6 = position mouse cursor over control
style to change
@TRUE success, @FALSE failure, or a controls style.
Use this function to get a control's style, change a control’s style, assign a control the
input focus, or retrieve the number of the control with the focus.
dialog-handle
The dialog-handle passed as the first parameter to your dialog procedure.
control-name
The name of the control you wish to modify. Unless you are using request code five
(5). In which case this parameter is ignored (for legacy dialog formats, i.e. earlier
than 6.2, use the control's number in this parameter.)
request-code
Set the request-code to one (1), if you want to give a control the input focus. Set it to
two (2) to have the function return a control's style. Use three (3) to add one or more
271
DialogControlState
styles to a control and four (4) to remove styles. Use five (5), if you want the name
(or number for legacy dialogs) of the control with the input focus. To position the
mouse cursor in the center of the control indicated by control-name set it to six (6).
Note: When you are using request code five (5) the function will return an empty
string ("") (or zero (0) for legacy dialogs), if no control in your dialog has the input
focus at the time of the function call. In most cases, it is not necessary to use this
request code to determine which control has the input focus from within your UserDefined-Callback Procedure. This is because most callbacks occur only when a
control has the input focus and because the number of the control that caused the
callback and, therefore, has the focus, is passed as a parameter to your procedure.
The DialogProcOption event-codes 0, 1, 11, 1000, 1001, 1002 and 1003 are the
exceptions because these events are not associated with any dialog controls.
Request-code
1
2
3
4
5
6
style
Meaning
Give a control the input focus
Query a control's style
Add one or more styles to a control
Remove styles from a control
Get control that has focus
Position mouse cursor over control
This parameter is ignored when you are giving a control the input focus (1), fetching
a controls style (2), getting the name of the control with the input focus (5), or
positioning the mouse cursor (6). Otherwise, it should contain the styles you wish to
add or remove. The style values are the same as those used in the control style
attribute of the dialog template. More than one style can be added or removed in a
single function call by using the bit wise OR (|) operator to construct a bitmask of
targeted styles.
Note: The exceptions are the 'List Only style' (4) of a DROPLISTBOX and the 'No
Auto-resize' (256) of ITEMBOX and FILELISTBOX controls. These styles can only
be set in the dialog template.
Style
Meaning
Controls
1
Control is invisible
All
2
Control has disabled appearance and does
not accept any user input, if it would
otherwise accept input.
PUSHBUTTON
RADIOBUTTON
CHECKBOX
PICTUREBUTTON
EDITBOX
MULTILINEBOX
ITEMBOX
FILELISTBOX
272
DialogControlState
CALENDAR
DROPLISTBOX
REPORTVIEW
SPINNER
GROUPBOX
VARYTEXT
STATICTEXT
MENUITEM
4
Note: Not supported in this function. This
style can only be set in the dialog
template.
DROPLISTBOX
Control will only accept values already in
the drop down list portion of the control
8
The controls text cannot be changed by
typing in new text when the control has
the input focus. (Note: The user can still
change the value in a SPINNER control
by using the up and down arrow.)
EDITBOX
MULTILINEBOX
SPINNER
16
Displays all characters as an asterisk (*)
as they are typed into the control.
EDITBOX
32
A button with this style is the default
button when no push or picture button has
the input focus. The user can select this
button by pressing the enter key if no
button has the input focus. You should
only give one button this style. If give
the style to more than one button, only
the first button (in the tab order) will have
the style. Generally, give this style to the
button that is the most likely option in
your dialog.
PUSHBUTTON
PICTUREBUTTON
64
Allows only digits to be entered into the
edit type controls. Note: even with this
set, it is still possible to paste non-digits
into the edit control.
EDITBOX
MULTILINEBOX
128
Creates a button with a flat appearance.
All aspects of the button's border are
removed including the 3d shadowing.
PUSHBUTTON
PICTUREBUTTON
256
Note: Not supported. This style can only
be set in the dialog template.
ITEMBOX
FILELISTBOX
273
DialogControlState
512
Centers text horizontally in the control’s
rectangle. (Cannot be used with style
1024)
VARYTEXT
STATICTEXT
1024
Displays text flush-right in the control’s
rectangle. (Cannot be used with style
512)
VARYTEXT
STATICTEXT
2048
Prevents text selection when control gets
the input focus. Cursor is placed to the
left of any existing text in the control.
EDITBOX
MULTILINEBOX
4096
Prevents text selection when control gets
the input focus. Cursor is placed to the
right of any existing text in the control.
EDITBOX
MULTILINEBOX
8192
Display Security Shield icon on button
(Vista or newer).
PUSHBUTTON
PICTUREBUTTON
32768
Adds a check mark to the left of a menu
item.
MENUITEM
65536
Adds a radio button-like dot graphic to
the left of a menu item.
MENUITEM
131072
Causes a separator bar graphic to display
instead of text at the menu item's location
in the menu.
MENUITEM
262144
Causes a column break to occur at the
specific item when used with drop-down,
context, or sub-menus. Causes a line
break (new row) with menu items hosted
directly by the MENUBAR.
MENUITEM
524288
The header bar is not displayed across the
top of the control.
The first row of the source array or file is
treated as column header text.
The control displays vertical and
horizontal lines to form a grid.
Only one row can be selected at a time.
REPORTVIEW
Selection highlighting extends to all sub
items in the selected row.
Sort ascending. The control is populated
with rows ordered from lowest to highest
first column values. Sorts using an
"intuitive" sort (See ArraySort for
REPORTVIEW
1048576
2097152
4194304
8388608
16777216
274
REPORTVIEW
REPORTVIEW
REPORTVIEW
REPORTVIEW
DialogControlState
33554432
67108864
134217728
268435456
details). The user can reorder control
rows based on any column's values by
clicking on the column header.
Sort descending. The control is populated
with rows ordered from highest to lowest
first column values. Sorts using an
"intuitive" sort (See ArraySort for
details). The user can reorder control
rows based on any column's values by
clicking on the column header.
Note: if both sortascending and
sortdecending are used, sortascending
takes precedence.
The first column text can be edited in
place.
Enables check boxes for each first
column item in the control.
Column header text is added as the first
row of the array returned from an item
search request, a selected or checked item
request, or a request for all items of the
control. This style will also cause the
control's associated variable to contain
the column header text as the first row of
the array referenced by the variable.
REPORTVIEW
REPORTVIEW
REPORTVIEW
REPORTVIEW
Example:
#DEFINESUBROUTINE
Flash(Handle,DialogMessage,DialogControlID,param4,param5)
switch (DialogMessage)
case 0 ; Initialization
DialogProcOptions(Handle, 1, 250) ; Set a 1 quarter second
timer.
break;
case 1 ; Timer
nStyle = DialogControlState(Handle,"staticText_1",2,0)
if nStyle & 1
DialogControlState(Handle,"StaticText_1",4,1) ; Clear the
invisible bit
else
DialogControlState(Handle,"StaticText_1",3,1) ; Set the
invisible bit
endif
break
endswitch
return -1
#ENDSUBROUTINE
FlasherFormat=`WWWDLGED,6.2`
275
DialogObject
FlasherCaption=`Flasher`
FlasherX=329
FlasherY=060
FlasherWidth=178
FlasherHeight=078
FlasherNumControls=002
FlasherProcedure=`Flash`
FlasherFont=`DEFAULT`
FlasherTextColor=`DEFAULT`
FlasherBackground=`DEFAULT,DEFAULT`
FlasherConfig=0
Flasher001=`069,053,034,014,PUSHBUTTON,"PushButton_Stop",DEFAULT,"Sto
p!",1,1,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Flasher002=`064,013,044,030,STATICTEXT,"StaticText_1",DEFAULT,DEFAULT
,DEFAULT,2,0,DEFAULT,DEFAULT,"255|0|0"`
ButtonPushed=Dialog("Flasher",1)
See Also:
DialogProcOptions, DialogControlGet, DialogControlSet, User-Defined-Subroutine
DialogObject
Interacts with COM controls in a dialog callback procedure.
Syntax:
DialogObject (dialog-handle,control-name,request-code[,event-name/imagefile[,event-id]])
Parameters
(i) dialog-handle
(s) control-name
(i) request-code
(s) event-name
(i) event-id
Returns:
(r)
handle to dialog.
name of a COM control or 0 (depends on request-code.)
number of task to perform
[optional] name of control event, image file or do not
specify (depends on request-code)
[optional] number to associate with an event or do not
specify (depends on request-code)
@TRUE or object reference on success (depends on
request-code), @FALSE on failure.
DialogObject is a multi-purpose function that you can call from within your dialog
callback procedure to interact with COM controls embedded in your dialog. The
function’s main purpose is to allow you to instruct a COM control to call your dialog
callback procedure when a supported event occurs within the control. But you can
also use the function to obtain a COM object reference to a control and you can even
276
DialogObject
use it to create Picture objects that some COM controls display as part of their user
interface.
dialog-handle The first parameter must be the dialog-handle passed as the first
parameter to your dialog procedure.
control-name Name of the COM control from which you wish to receive events or
obtain an object reference. This parameter should be set to zero (0) when requestcode 4 is used in the third parameter. (for legacy dialog formats, i.e. earlier than 6.2,
use the control's number in this parameter.)
request-code The third parameter determines the action taken by the function.
Currently, there are four possible values
Request-code
1
2
3
4
Meaning
Call dialog callback when the specified event occurs
Stop calling dialog callback when an event previously requested
with request-code 1 occurs
Return an object references to the specified control
Create and return an object reference to a picture object
event-name Almost all COM controls provide events. Events are usually fired in
response to a user action, like a mouse button click on the control, but they can also
be fired as the result of some action taken by your script. When an event is fired by
the control, you can instruct the control to make a call to your dialog callback
procedure so that you can do additional processing. In order to have your dialog
procedure called by the control you need to call DialogObject with a request code of
one (1) and specify the name of the event in the fourth parameter. To stop a control
calling your dialog procedure for an event, specify the event name in this parameter
and set the request-code to two (2).
This parameter is also used with request-code 3 to obtain a reference to a picture
object. When you use request code 3 the parameter must contain the file name and
path to a file that contains a BMP (bitmap), JPEG, WMF (metafile), ICO (icon) or
GIF format image. Some COM controls accept picture objects for use as part of the
control’s on screen appearance.
Here is a summary of the event-name parameter’s usage
Request-code
1, 2
Event-name
Name of an event supported by the control indicated in the
second parameter
3
File name and path of BMP (bitmap), JPEG, WMF (metafile),
ICO (icon) or GIF format image file
4
Do not specify this parameter.
277
DialogObject
event-id You can associate a number with a particular control event with this
parameter. The number can later be used inside the dialog callback procedure to
uniquely identify which control event is currently calling your procedure. This is
because it becomes the Identifier property of the EventInfo object passed to your
procedure each time an event is fired. The number should be unique for each event
in the control and can be made unique for all control events monitored by your
procedure.
Only specify this parameter for request code 1.
Example:
This example uses the DialogObject function to cause a dialog to
receive mouse button click events from a Microsoft calendar COM
control. DialogObject is also used to obtain a reference to the
calendar control. The reference is then used to obtain and set
properties of the control before and during control event processing.
To use this example, the Microsoft calendar control and the Microsoft
concatenated speech synthesis (or text-to-speech) engine must be
installed and registered on the computer running this script. The
computer must also have appropriate sound hardware and drivers.
#DefineSubRoutine DlgObjExamProc(Dlg_Handle, Dlg_Message, Dlg_ID,
Dlg_EventInfo, Reserved)
; Dialog messages.
MSG_INIT = 0 ; The one-time initialization.
MSG_BUTTONPUSHED = 2 ; Button press.
MSG_COMEVENT = 14 ; COM control event fired.
; Options for DialogObject function.
DLGOBJECT_ADDEVENT = 1 ;DialogObject add event.
DLGOBJECT_GETOBJECT = 3 ;DialogObject get reference to object.
MSCAL_CLICK = 1 ; User specified identifier for "click" event.
Switch Dlg_Message
Case MSG_INIT
DialogProcOptions( Dlg_handle, MSG_BUTTONPUSHED, 1 )
; Handle mouse click events.
DialogObject(Dlg_Handle, "ComControl_1", DLGOBJECT_ADDEVENT,
"Click", MSCAL_CLICK )
; Get an object reference to the calendar control.
objCal = DialogObject(Dlg_Handle, "ComControl_1",
DLGOBJECT_GETOBJECT)
; Create a voice object
objVoice = ObjectCreate("Sapi.SpVoice.1")
objVoice.volume = 100 ; Loud!
Break
Case MSG_COMEVENT
; Correct COM control and event?
If (Dlg_ID == "ComControl_1") && (Dlg_EventInfo.identifier ==
MSCAL_CLICK)
278
DialogProcOptions
; Speak the date.
sSpeach = StrCat('<context ID ="date_mdy">',objCal.month)
sSpeach =
StrCat(sSpeach,'/',objCal.day,'/',objCal.year,'</context>')
sSpeach = StrCat('<voice required="Gender=Male;Name=Microsoft
Sam">',sSpeach)
objVoice.Speak(sSpeach, 9) ; 9 = SPF_ASYNC|SPF_IS_XML
EndIf
Break
Case MSG_BUTTONPUSHED
; Release Objects.
Dlg_EventInfo = 0
objVoice = 0
objCal = 0
Break
EndSwitch
Return(-1) ; Do default processing.
#EndSubRoutine ; End of Dialog Callback.
DlgObjExFormat=`WWWDLGED,6.2`
DlgObjExCaption=`Dialog Object Example`
DlgObjExX=035
DlgObjExY=105
DlgObjExWidth=200
DlgObjExHeight=181
DlgObjExNumControls=002
DlgObjExProcedure=`DlgObjExamProc`
DlgObjExFont=`DEFAULT`
DlgObjExTextColor=`DEFAULT`
DlgObjExBackground=`DEFAULT,DEFAULT`
DlgObjExConfig=0
DlgObjEx001=`031,161,133,011,PUSHBUTTON,"PushButton_1",DEFAULT,"Enoug
h Already",1,1,32,DEFAULT,DEFAULT,DEFAULT`
DlgObjEx002=`015,015,169,126,COMCONTROL,"ComControl_1",DEFAULT,"MSCAL
.Calendar",DEFAULT,3,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
ButtonPushed=Dialog("DlgObjEx")
See Also:
Dialog
DialogProcOptions
Controls when the User-Defined-Callback Procedure is called by its associated
dialog.
Syntax:
DialogProcOptions(dialog-handle,event-option-code,event-option-value)
279
DialogProcOptions
Parameters:
(i) dialog-handle
handle to dialog.
(i) event-option-code event code for event, or dialog option code that produces
call to the User-Defined-Callback Procedure.
(i) event-option-value depends on event-option-code.
Returns:
(i)
previous setting for event-code.
Use the DialogProcOptions function to control when your Use-Defined-Callback
procedure is called by its associated dialog. You can also use it to control your
dialog's behavior, while your procedure is executing. You usually establish callback
events during the first call to the procedure i.e., event 0, but this can be done during
any call.
dialog-handle
The dialog-handle is the first parameter to your dialog procedure.
event-option-code
The second parameter can be one of the events or options listed in the table below.
This table provides the list of events and options codes that can be used as the second
parameter to the DialogProcOptions. The event codes correspond to the number
passed as the second parameter to your User-Defined-Callback Procedure.
Event-Option-Code Values and Meanings
Codes Meaning
Event-option-value
0
Initialization: dialog has been created but
not displayed. This event is only generated
once per dialog session.
n/a
1
Timer: Set a Timer event
(i)
> 0 - milliseconds between
callbacks
0 - turn off timer
1 - return current setting
2
Pushbutton or Picturebutton Pushed:
User has pressed a PUSHBUTTON or
PICTUREBUTTON control.
(i)
1- turn on event callback
0 - turn off callback
-1 - return current setting
3
Radiobutton Selected: User has selected a
RADIOBUTTON.
(i)
1- turn on event callback
0 - turn off callback
-1 - return current setting
4
Checkbox Checked/Unchecked: User has
checked or unchecked a CHECKBOX
(i)
1- turn on event callback
280
DialogProcOptions
control.
0 - turn off callback
-1 - return current setting
5
Changed text in Editbox or Multilinebox:
User has changed the text in an EDITBOX
or MULTILINEBOX control
(i)
1- turn on event callback
0 - turn off callback
-1 - return current setting
6
Filelistbox File Selected: User has selected
a file in a FILELISTBOX control
(i)
1- turn on event callback
0 - turn off callback
-1 - return current setting
7
Itembox Item Selected: User has selected
one or more items in a ITEMBOX control.
(i)
1- turn on event callback
0 - turn off callback
-1 - return current setting
8
Droplistbox/Combobox Item Change:
User has changed the text appearing at the
top of a DROPLISTBOX. This event can be
triggered by the user picking a new item
from the list portion of the control or by the
user typing new text into the control.
(i)
1- turn on event callback
0 - turn off callback
-1 - return current setting
9
Calendar Date Change: User has selected a
new date in a CALENDAR control.
(i)
1- turn on event callback
0 - turn off callback
-1 - return current setting
10
Spinner Number Change: User has
changed the value of a SPINNER control.
(i)
1- turn on event callback
0 - turn off callback
-1 - return current setting
11
Close: User has selected the Close command
from the system menu. This event only
applies to dialog's with system menus
enabled by a call to IntControl 49 or
DialogProcOption code 1002.
(i)
1- turn on event callback
0 - turn off callback
-1 - return current setting
12
Filelistbox File Double-Clicked: the user
has used the mouse to double-click an item
in an FILELISTBOX.
(i)
1- turn on event callback
0 - turn off callback
-1 - return current setting
13
Itembox Item Double-Clicked: the user has
used the mouse to double-click an item in an
ITEMBOX.
(i)
1- turn on event callback
0 - turn off callback
-1 - return current setting
14
COM-Event: COM control event fired.
(i)
281
DialogProcOptions
15
16
17
Menu Item Selection: the user has clicked a
menu item using the mouse, has pressed a
menu item's access key while its menu is
displayed or the user has pressed a menu
item's hot-key combination.
Note: The user-defined callback is not called
in response to the selection of menu items
via mouse or access key when the menu item
has an associated drop-down or sub-menu.
The associated drop-down or sub-menu is
displayed instead.
Menu Item Initialization: the user has
selected a drop-down menu, sub-menu or
context menu. The name of the menu hosting
control or menu item is passed to the userdefined callback as the value of its third
parameter.
For example: This event be used to
dynamically modify the menu itself.
Dialog Resize: The user has resized the
dialog. When the User-Defined-Callback is
called with this request, the fifth parameter
to the User-Defined-Callback procedure
contains a space delimited list of items that
represent the change in width and height of
the dialog that resulted from the resizing
activity and the client width and height.
{delta_width}{delta_height}
{client_width}{client_height}
The delta width and height supplied are in
dialog units and can be either negative or
positive numbers. The client area is the
area of a window used to display controls
and its size does not include the dialog
window's borders, menu bar, nor title bar.
The dialog template must use the <dlgvariable>MinWidth and/or <dlgvariable>MinHeight variables in order to use
this option. The DialogProcOptions function
282
1- turn on event callback
0 - turn off callback
-1 - return current setting
(i)
1- turn on event callback
0 - turn off callback
-1 - return current setting
(i)
1- turn on event callback
0 - turn off callback
-1 - return current setting
(i)
1- turn on event callback
0 - turn off callback
-1 - return current setting
DialogProcOptions
18
19
20
21
1000
will error, if this request code is used with a
dialog template that does not contain at least
one of these variables.
Item Select Row: User has selected row in
(i)
the REPORTVIEW control. The text of
1- turn on event callback
the first column of the selected row is
0 - turn off callback
passed to the callback UDF/UDS in the
-1 - return current setting
callback's fifth parameter.
Note:This event will only trigger if the user
clicks on the first column. If you
want to select anywhere on the row, you
need to use the full row select style.
Double-Clicked Row: User has used the
(i)
mouse to double-click a row in the
1- turn on event callback
REPORTVIEW control. The text of the
0 - turn off callback
first column of the double-clicked row is
-1 - return current setting
passed to the callback UDF/UDS in the
callback's fifth parameter.
Checked/Unchecked Item: User has
(i)
checked or unchecked an item in a
1- turn on event callback
REPORTVIEW control with the
0 - turn off callback
'checkbox' style. The text of the checked
-1 - return current setting
item is passed to the callback UDF/UDS in
the callback's fifth parameter.
(i)
Item Text: User has changed the text of a
1- turn on event callback
first column item in a REPORTVIEW
0 - turn off callback
control. The user modified text of the item
-1 - return current setting
is passed to the callback UDF/UDS in the
callback's fifth parameter. Note that if
more than one first column item of a
control contains the same value, it is
possible for the fifth parameter to contain a
tab delimited list of multiple occurrences
of the targeted item's text. The number
items in the list indicates which instance of
the item is the target of the event.
Other non-events supported by DialogProcOptions:
Dialog Disable: Grey the dialog's title bar
and redraw dialog as necessary. Optionally,
display the system's "wait cursor".
Note: If you have code that may take a long
time to execute in a callback, you may need
to temporarily disable the dialog. Don't
forget to enable after the process is
complete.
(i)
1 - disable dialog
2 - disable and wait cursor
0 - enable dialog
-1 - return current setting
283
DialogProcOptions
1001
Change Background: Change the dialog's
background bitmap or color.
(s)
bitmap file name or RBG
color string
(i)
-1 - return current
background
1002
Change System Menu: Change the dialog’s
title bar system menu. Note: this dialog
option overrides the system menu settings
established with IntControl 49.
(i)
0 - no menus
1 - close
2 - close and minimize
3 - close and maximize
4 - close, minimize and
maximize
-1 - return current setting
1003
Change Dialog Title: Change the dialog’s
title. Note: the maximum dialog title length
is 254 characters.
(i)
-1 – return current title
(s) new dialog title
1004
Get Control Name: Returns the name of the
control associated with the control number.
(i)
control number
(s)
control name
1005
Get Control Number: Returns the control
number associated with the control name.
(s)
control name
(i)
control number
1007
Get Client Area: Return internally
maintained width and height of the dialog's
client area in dialog-units as a space
delimited list. The returned client area
dimensions are the dialog's size not
including the width and height of borders,
the height of the menu bar, nor the height of
the title bar. The third parameter to
DialogProcOptions must be set to -1 when
using this request code.
(i)
-1 – return client area
Note: Although you can set the second parameter to zero (0), it will have no effect,
because event 0 only happens once.
For events codes, turn on the event by setting the third parameter to one (1). Turning
on the indicated event causes a call to your dialog procedure each time the event
284
DialogProcOptions
occurs. When your dialog procedure is called because of the event, the event code
will appear in the second parameter of the procedure. Turn off an event by setting
the third parameter to zero (0). You can programmatically determine the current
setting for an event code or option by setting the second parameter to the event or
option of interest and setting the third parameter to minus one (-1). The function
returns the current setting without changing it.
Notes - Option 1000:You can change your dialog's behavior during a callback by
using this function with the second parameter set to dialog option 1000 and
specifying one (1) or two (2) as the third parameter. This gives the dialog's title bar
the appearance of an inactive window. It also allows your dialog to redraw itself if it
becomes covered and then uncovered by another window while the callback
procedure performs a lengthy task. When you place a two (2) in the third parameter,
you get the above-mentioned changes and in addition, the mouse cursor will become
the system defined "wait cursor" when the user moves it over the dialog. Dialog
option 1000 is best used before your dialog callback performs lengthy processing or
when it calls any WIL function that suspends the execution of your dialog procedure.
RunWait and TimeDelay are two examples of functions that suspend script execute.
Dialog option 1000 takes effect immediately after the DialogProcOptions statement
but it is cancelled automatically when the current call to your dialog procedure
returns. You can manually cancel option 1000 by making a DialogProcOptions call
with the second parameter set to 1000 and the third parameter set to zero (0).
Notes - Option 1001:Use dialog option 1001 to dynamically change your dialog's
background to the bitmap or color placed in the functions third parameter. You can
use a three-field color specification, a bitmap file name or the DEFAULT key word
to set the background to a specific color, a picture or the system default color for
dialogs. You can discover the current dialog background by setting the third
parameter to minus one (-1).
event-option-value
The third parameter depends on which event-option-code was specified. See the
table of event-option-codes for valid event-option-values.
Example:
;Here is an example of using a one second timer event.
#DefineFunction
TimerCallbackProc(Timer_Handle,Timer_Message,Timer_Name,
Timer_EventInfo,rsvd)
MSG_INIT = 0
TimerTick = 1
switch Timer_Message; Switch based on Dialog Message type
case MSG_INIT
; Standard Initialization message
;enable 1 second timer events
DialogProcOptions(Timer_Handle,TimerTick,1000)
return(-1)
case TimerTick
Clock=DialogControlGet(Timer_Handle,"VaryText_1",4)
285
DirAttrGet
Clock=Clock-1
if Clock==0 then return(2) ; exit
DialogControlSet(Timer_Handle,"VaryText_1",4,Clock)
return(-1)
endswitch; Timer_Message
return(-1)
#EndFunction ; End of Dialog Callback TimerCallbackProc
TimerFormat=`WWWDLGED,6.2`
TimerCaption=`Timer Example`
TimerX=078
TimerY=129
TimerWidth=120
TimerHeight=117
TimerNumControls=003
TimerProcedure=`TimerCallbackProc`
TimerFont=`DEFAULT`
TimerTextColor=`DEFAULT`
TimerBackground=`DEFAULT,DEFAULT`
TimerConfig=0
Timer001=`013,083,034,014,PUSHBUTTON,"PushButton_OK",DEFAULT,"OK",1,D
EFAULT,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Timer002=`067,083,034,014,PUSHBUTTON,"PushButton_Cancel",DEFAULT,"Can
cel",0,DEFAULT,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Timer003=`023,015,070,052,VARYTEXT,"VaryText_1",clock,"10",DEFAULT,DE
FAULT,DEFAULT,"Tahoma|49152|70|34","128|0|0",DEFAULT`
ButtonPushed=Dialog("Timer")
See Also:
DialogControlState, DialogControlGet, DialogControlSet
DirAttrGet
Gets directory attributes.
Syntax:
DirAttrGet([d:]path)
Parameters:
(s) [d:]path
directory pathname whose attributes you want to determine.
Returns:
(s)
the attributes of the specified directory pathname.
Returns attributes for the specified directory, in a string of the form "RASH". This
string is composed of four individual attribute characters, as follows:
Symbol
R
A
286
Meaning
Read-only ON
Archive ON
DirAttrGetEx
S
H
System ON
Hidden ON
A hyphen in any of these positions indicates that the specified attribute is OFF. For
example, the string "-A-H" indicates a directory which has the Archive and Hidden
attributes set.
Example:
dir = "c:\temp"
attr = DirAttrGet(dir)
Message("Attributes of Directory, %dir%", attr)
See Also:
DirAttrGetEx, DirInfoToArray, DirAttrSet, FileAttrGet, FileAttrSet, FileTimeGet,
FileTimeGetEx
DirAttrGetEx
Gets directory attributes (extended).
Syntax:
DirAttrGetEx(directory path)
Parameters:
(s) directory path
Returns:
(i)
directory pathname whose attributes you want to
determine.
extended attribute settings.
The return value is a bitmask comprised of one or more of the following integer
values, combined using the bitwise OR ('|') operator:
Value
Name
Meaning
1
READONLY
The file or directory is read-only. Applications
can read the file but cannot write to it or delete it.
In the case of a directory, applications cannot
delete it.
2
HIDDEN
The file or directory is hidden. It is not included
in an ordinary directory listing.
4
SYSTEM
The file or directory is part of, or is used
exclusively by, the operating system.
DIRECTORY
Identifies a directory.
ARCHIVE
The file or directory is an archive file or
directory. Applications use this attribute to mark
16 *
32
287
DirAttrGetEx
files for backup or removal.
128
NORMAL
The file or directory has no other attributes set.
This attribute is valid only if used alone.
256
TEMPORARY
The file is being used for temporary storage. File
systems avoid writing data back to mass storage
if sufficient cache memory is available, because
often the application deletes the temporary file
shortly after the handle is closed. In that case,
the system can entirely avoid writing the data.
Otherwise, the data will be written after the
handle is closed.
512*
SPARSE_FILE
The file is a sparse file.
1024*
REPARSE_POINT
The file or directory has an associated reparse
point.
2048*
COMPRESSED
The file or directory is compressed. For a file,
this means that all of the data in the file is
compressed. For a directory, this means that
compression is the default for newly created files
and subdirectories.
4096
OFFLINE
The data of the file is not immediately available.
This attribute indicates that the file data has been
physically moved to offline storage. This
attribute is used by Remote Storage, the
hierarchical storage management software.
Applications should not arbitrarily change this
attribute.
8192
NOT_CONTENT_
INDEXED
The file will not be indexed by the content
indexing service.
The file or directory is encrypted. For a file, this
means that all data streams in the file are
encrypted. For a directory, this means that
encryption is the default for newly created files
and subdirectories.
* The values with an asterisk next to them cannot be set using DirAttrSetEx.
16384
*
ENCRYPTED
Example:
READONLY
HIDDEN
SYSTEM
DIRECTORY
ARCHIVE
NORMAL
TEMPORARY
COMPRESSED
OFFLINE
288
=
=
=
=
=
=
=
=
=
1
2
4
16
32
128
256
2048
4096
DirAttrSet
NOT_CONTENT_INDEXED = 8192
ENCRYPTED
= 16384
tmpdir = "c:\Temp\DirAttrGetEx"
; Create a HIDDEN directory
DirAttrSetEx(tmpdir, HIDDEN, 1)
attr = DirAttrGetEx(tmpdir)
if attr & READONLY
Message(tmpdir, "READONLY")
endif
if attr & HIDDEN
Message(tmpdir, "HIDDEN")
endif
if attr & SYSTEM
Message(tmpdir, "SYSTEM")
endif
if attr & DIRECTORY
Message(tmpdir, "DIRECTORY")
endif
if attr & ARCHIVE
Message(tmpdir, "ARCHIVE")
endif
if attr & NORMAL
Message(tmpdir, "NORMAL")
endif
if attr & TEMPORARY
Message(tmpdir, "TEMPORARY")
endif
if attr & COMPRESSED
Message(tmpdir, "COMPRESSED")
endif
if attr & OFFLINE
Message(tmpdir, "OFFLINE")
Endif
if attr & NOT_CONTENT_INDEXED
Message(tmpdir, "NOT_CONTENT_INDEXED")
Endif
if attr & ENCRYPTED
Message(tmpdir, "ENCRYPTED")
Endif
See Also:
DirAttrSetEx, DirInfoToArray. DirAttrSet, FileAttrGet, FileAttrSet, FileTimeGet
DirAttrSet
Sets directory attributes.
Syntax:
DirAttrSet(dir-list,settings)
289
DirAttrSetEx
Parameters:
(s) dir-list
a tab or vertical bar delimited list of one or more subdirectory names.
new attribute settings for the directories.
(s) settings
Returns:
(s)
@FALSE.
The attribute string consists of one or more of the following characters (an upper
case letter turns the specified attribute ON, a lower case letter turns it OFF):
Symbol
Meaning
Symbol
Meaning
R
A
S
H
read only ON
archive ON
system ON
hidden ON
r
a
s
h
read only OFF
archive OFF
system OFF
hidden OFF
Note: DirAttrSet does not accept wildcards.
Example:
DirAttrSet("c:\windows\temp", "rASh")
Message("DirAttrSet","Directory attributes set.")
See Also:
DirAttrSetEx, DirAttrGet, FileAttrGet, FileAttrSet, FileTimeTouch
DirAttrSetEx
Sets directory attributes (extended).
Syntax:
DirAttrSetEx(dir-list,attributes,mode)
Parameters:
(s) dir-list
(i) attributes
(i) mode
Returns:
(i)
290
a tab or vertical bar delimited list of one or more subdirectory names.
new attribute settings for the directories.
specifies the method by which "attributes" are applied to
the specified directory(s), and can be one of the
following:
0 "attributes" replaces the existing file attributes
1 "attributes" are added to the existing file attributes
-1 "attributes" are removed from the existing file attributes
@TRUE on success, or @FALSE if unable to change the
attributes on any of the specified directory(s).
DirAttrSetEx
Note: DirAttrSetEx does not accept wildcards.
Value
1
Name
READONLY
2
HIDDEN
4
SYSTEM
16*
32
DIRECTORY
ARCHIVE
128
NORMAL
256
TEMPORARY
512*
1024*
SPARSE_FILE
REPARSE_POINT
2048*
COMPRESSED
4096
OFFLINE
8192
NOT_CONTENT_
INDEXED
ENCRYPTED
16384*
Meaning
The file or directory is read-only. Applications
can read the file but cannot write to it or delete it.
In the case of a directory, applications cannot
delete it.
The file or directory is hidden. It is not included
in an ordinary directory listing.
The file or directory is part of, or is used
exclusively by, the operating system.
Identifies a directory.
The file or directory is an archive file or
directory. Applications use this attribute to mark
files for backup or removal.
The file or directory has no other attributes set.
This attribute is valid only if used alone.
The file is being used for temporary storage. File
systems avoid writing data back to mass storage
if sufficient cache memory is available, because
often the application deletes the temporary file
shortly after the handle is closed. In that case,
the system can entirely avoid writing the data.
Otherwise, the data will be written after the
handle is closed.
The file is a sparse file.
The file or directory has an associated reparse
point.
The file or directory is compressed. For a file,
this means that all of the data in the file is
compressed. For a directory, this means that
compression is the default for newly created files
and subdirectories.
The data of the file is not immediately available.
This attribute indicates that the file data has been
physically moved to offline storage. This
attribute is used by Remote Storage, the
hierarchical storage management software.
Applications should not arbitrarily change this
attribute.
The file will not be indexed by the content
indexing service.
The file or directory is encrypted. For a file, this
means that all data streams in the file are
291
DirAttrSetEx
encrypted. For a directory, this means that
encryption is the default for newly created files
and subdirectories.
* The values with an asterisk next to them cannot be set using DirAttrSetEx.
Example:
READONLY
HIDDEN
SYSTEM
DIRECTORY
ARCHIVE
NORMAL
TEMPORARY
COMPRESSED
OFFLINE
NOT_CONTENT_INDEXED
ENCRYPTED
=
=
=
=
=
=
=
=
=
=
=
1
2
4
16
32
128
256
2048
4096
8192
16384
tmpdir = "c:\Temp\DirAttrSetEx"
; Create a HIDDEN directory
DirAttrSetEx(tmpdir, HIDDEN, 1)
attr = DirAttrGetEx(tmpdir)
if attr & READONLY
Message(tmpdir, "READONLY")
endif
if attr & HIDDEN
Message(tmpdir, "HIDDEN")
endif
if attr & SYSTEM
Message(tmpdir, "SYSTEM")
endif
if attr & DIRECTORY
Message(tmpdir, "DIRECTORY")
endif
if attr & ARCHIVE
Message(tmpdir, "ARCHIVE")
endif
if attr & NORMAL
Message(tmpdir, "NORMAL")
endif
if attr & TEMPORARY
Message(tmpdir, "TEMPORARY")
endif
if attr & COMPRESSED
Message(tmpdir, "COMPRESSED")
endif
if attr & OFFLINE
Message(tmpdir, "OFFLINE")
Endif
if attr & NOT_CONTENT_INDEXED
Message(tmpdir, "NOT_CONTENT_INDEXED")
Endif
292
DirExist
if attr & ENCRYPTED
Message(tmpdir, "ENCRYPTED")
Endif
See Also:
DirAttrSet, DirAttrGetEx, FileAttrGetEx, FileAttrSetEx, FileTimeGet,
FileTimeTouch
DirChange
Changes the current directory. Can also log a new drive.
Syntax:
DirChange([d:]path)
Parameters:
(s) [d:] path
Returns:
(i)
the desired directory name with optional drive.
@TRUE if directory was changed; @FALSE if the path
could not be found.
Use this function to change the current working directory to another directory, either
on the same or a different disk drive.
Example:
DirChange("c:\")
a = AskFileText("Your CONFIG.SYS", "config.sys", @unsorted, @single,
@false)
Message("Contents of selected line, if any", a)
See Also:
DirExist, DirGet, DirHome, LogDisk
DirExist
Tests for the existence of a directory.
Syntax:
DirExist(pathname)
Parameters:
(s) pathname
Returns:
(i)
complete drive and path.
@TRUE if the directory exists; @FALSE if it doesn't exist
or if the pathname is invalid.
You can use this function to determine whether a specified drive is valid by checking
for the existence of the root directory on that drive. A @TRUE response indicates
293
DirGet
that it is a valid drive on the system. But it does not indicate that there is a usable
disk in the drive (e.g. in a floppy drive).
This function will accept a UNC path.
Examples:
; This example checks to see if a directory c:\wp exists.
;doesn’t one is created.
wpdir = "c:\wp"
If !DirExist(wpdir) Then DirMake(wpdir)
DirChange(wpdir)
If it
; This section asks the user to input a drive, and then checks its
; existence.
while @TRUE
; Loop forever, until break or exit
drive = AskLine("Run Excel", "Enter a drive letter", "", 0)
If drive == "" Then Exit
drive = StrSub(drive, 1, 1)
If DirExist("%drive%:\") then Break
endwhile
Message("Selected Drive", drive)
See Also:
DirChange, DirMake, DirRemove, DirRename, AppExist, FileExist, DiskExist
DirGet
Gets the current working directory.
Syntax:
DirGet()
Parameters:
(none)
Returns:
(s)
current working directory.
Use this function to determine which directory we are currently in. It's especially
useful when changing drives or directories temporarily.
Example:
; Get, then restore current working directory
origdir = DirGet( )
DirChange("c:\")
FileCopy("config.sys", "%origdir%xxxtemp.xyz", @FALSE)
DirChange(origdir)
Message("DirGet","Current working directory retrieved and restored.")
See Also:
CurrentFile, CurrentPath, DirHome, DirScript, DirWindows
294
DirInfoToArray
DirHome
Returns directory containing the WIL Interpreter's executable files.
Syntax:
DirHome()
Parameters:
(none)
Returns:
(s)
pathname of the home directory.
Use this function to determine the directory where the current WIL Interpreter's
executable files are stored.
Note: For compiled scripts DirHome() returns the path to the EXE file.
Example:
a = DirHome( )
Message("WIL Executable is in ", a)
See Also:
DirGet, DirScript, DirWindows
DirInfoToArray
Returns information on a set of directories, as an array.
Syntax:
DirInfoToArray(dir-list[,flags])
Parameters:
(s) dir-list
(i) flags
Returns:
(a)
specifies a set of sub-directory names, which may be
wildcarded.
[optional] see below.
2-dimension array.
Flags can be set to 0, or can specify one or more of the following values combined
with the bitwise OR ('|') operator:
Flags
0
1
2
Value
default.
return directory sizes as huge numbers. This is a long decimal
number string, which may represent a number too large to be
converted to an integer.
return directory names with full paths
295
DirInfoToArray
This function creates and returns a 2-dimension array. There are [n + 1] rows in the
array, where 'n' is the number of directories that were returned. Each row has 7
columns. The first row (row 0) is a header containing summary information. Each
subsequent row contains information about one returned directory. The columns are
as follows:
Header row:
Column
0
1
2-6
Value
number of directories returned
total directory size. Note: Set to 0
(unused, set to 0)
Other rows:
Column
0
1
2
3
4
5
6
Value
directory name
directory size. Note: all sizes for directories will be 0.
directory last modified time, in YmdHms format
directory last accessed time, in YmdHms format
directory created time, in YmdHms format
directory attribute string in the form "RASH" (see DirAttrGet)
directory attribute bitmask (see DirAttrGetEx)
Example:
dirlist = ShortCutDir("Personal",0,@TRUE):"*.*"
infoarray = DirInfoToArray(dirlist, 1|2)
infostr = "Number of directories: ":infoarray[0,0]:@Crlf:@Crlf
For xx = 1 to infoarray[0,0]
infostr = infostr:"Directory Name: ":infoarray[xx,0]:@Crlf
;Note that all sizes (column 1) for directories will be 0.
infostr = infostr:"Directory Size: ":infoarray[xx,1]:@Crlf
infostr = infostr:"Last Modified: ":infoarray[xx,2]:@Crlf
infostr = infostr:"Last Accessed: ":infoarray[xx,3]:@Crlf
infostr = infostr:"Created: ":infoarray[xx,4]:@Crlf
infostr = infostr:"Attribute: ":infoarray[xx,5]:@Crlf
infostr = infostr:"Attribute Bitmask: ":infoarray[xx,6]:@Crlf
infostr = infostr:@Crlf
Next
tmpfile = FileCreateTemp("TMP")
FilePut(tmpfile,infostr)
AskFileText("Directory Data",tmpfile,@unsorted,@single,@false)
FileDelete(tmpfile)
See Also:
DirItemize, DirAttrGet, DirAttrGetEx, DirTimeGet, DirSize
296
DirMake
DirItemize
Returns a delimited list of directories.
Syntax:
DirItemize(dir-list)
Parameters:
(s) dir-list
Returns:
(s)
a string containing a set of sub-directory names, which may
be wildcarded.
list of directories.
This function compiles a list of sub-directories and separates the names with a TAB.
For more information on delimiters see File Delimiters, (pg. 67).
This is especially useful in conjunction with the AskItemList function, which
enables the user to choose an item from such a space-delimited list.
DirItemize("*.*") returns all sub-directories under the current directory.
Note: Some shell or file manager applications using the WIL Interpreter allow an
empty string ("") to be used as the "dir-list" parameter, in which case all subdirectories highlighted in the file display are returned. However, if there are any
directory names or wildcards in the string, all sub-directories matching the
pathnames are returned, regardless of which ones are highlighted.
By default hidden and system directories are ignored. IntControl 5 can be used to
control whether or not hidden directories are processed by the DirItemize function.
Example:
DirChange(DirWindows(0))
a = DirItemize("*.*")
AskItemList("Directories", a, @TAB, @unsorted, @single, @false)
See Also:
AskFileText, AskItemList, CurrentFile, DirInfoToArray, FileItemize,
IntControl 5, WinItemize
DirMake
Creates a new directory.
Syntax:
DirMake([d:]path)
Parameters:
(s) [d:] path
the desired directory name with optional drive.
297
DirRename
Returns:
(i)
@TRUE if the directory was successfully created, or
already exists.
Use this function to create a new directory.
Example:
DirMake("c:\xstuff")
Message("DirMake","Directory Made")
See Also:
DirExist, DirRemove, DirRename
DirRemove
Removes an empty directory.
Syntax:
DirRemove(dir-list)
Parameters:
(s) dir-list
Returns:
(i)
a delimited list of directory pathnames.
@TRUE if the directory was successfully removed;
@FALSE if it wasn't.
Use this function to delete empty directories. You can delete one or more at a time
by separating directory names with delimiters. You cannot, however, use wildcards.
Examples:
DirRemove("c:\xstuff")
Message("DirRemove","Directory removed")
;or
;DirRemove("tempdir1 tempdir2 tempdir3")
See Also:
DirExist, DirMake, DirRename
DirRename
Renames a directory.
Syntax:
DirRename([d:]oldpath,[d:]newpath)
Parameters:
(s) oldpath
(s) newpath
298
existing directory name, with optional drive.
new name for directory.
DirSize
Returns:
(i)
@TRUE if the directory was successfully renamed;
@FALSE if it wasn't.
Example:
;Do a dirmake so the example runs smoothly.
DirMake("c:\wwwtemp")
;Once 'old' directory is created execute the example
;This is the real example.
old="c:\wwwtemp"
new="c:\wwwwork"
DirRename("c:\wwwtemp", "c:\wwwwork")
Message("DirRenname","%old% Directory renamed to %new%")
See Also:
DirExist, DirMake, DirRemove
DirScript
Returns the full directory path (without the filename) of the current WinBatch
program.
Syntax:
DirScript()
Parameters:
None
Returns:
(s)
full path of the current WinBatch program.
If the current WinBatch script is a child program that was called with the Call()
function, this function will return the full directory path (without the filename) of the
main (calling) program.
Example:
wbtdir = DirScript()
;or
;exedir = DirScript()
Message("Script Directory",wbtdir)
See Also:
DirHome, DirGet, IntControl 1004
DirSize
Finds the total size of a directory.
299
DirSize
Syntax:
DirSize(dir-name,flags[,format])
Parameters:
(s) dir-name
(i) flags
(i) format
Returns:
(i/f)
specify a single directory name (no wildcards).
specifies the format of the returned value. (see below)
[optional] controls the format in which the size is returned.
size in bytes. The return value will be a floating point
number if it is larger than 2 gigabytes.
This function returns the total size of a directory, including all files in the directory,
and all files in all subdirectories under the directory.
Flags
0
1
Meaning
actual size of the files.
Instead of returning the actual size of the files, return the amount of
disk space they occupy. This is based upon the disk's cluster size.
This flag is valid only if the specified directory is on a local drive or a
network drive mapped to a drive letter; it does not support UNC's.
Format is an optional parameter that controls the format in which the size is returned.
If the result is too large to be returned as an integer (larger than 2 gigabytes).
Format
Meaning
0
(Default) Floating Point
1
Huge number. This is a long decimal number string, which may
represent a number too large to be converted to an integer.'Huge
number' is a special data type. It is a long decimal number string,
which may represent a number too large to be converted to an integer.
This value cannot be modfied with standard arithmetic operations, it
requires the use of the Huge Math extender.
Example:
a=Dirsize("C:\Windows",0)
Message("DirSize : Actual size",a)
b=Dirsize("C:\Windows",1)
Message("DirSize :The amount of disk space occupied",b)
c=Dirsize("C:\Windows",1,0)
Message("DirSize :Actual size: in floating point if over 2 GB",b)
See Also:
DirExist, DirInfoToArray, DirItemize
300
DiskExist
DirWindows
Returns the name of the Windows or Windows System directory.
Syntax:
DirWindows(request#)
Parameters:
(i) request#
see below.
Returns:
(s)
directory name.
This function returns the name of either the Windows directory or the Windows
System directory, depending on the request# specified.
Req#
0
1
2
Return value
Windows directory
Windows System directory
shared Windows directory on a multi-user system (Windows 2000 and
newer). On other versions of Windows, this will return the same value as
request 0
Example:
DirChange(DirWindows(0))
files=FileItemize("*.ini")
ini = AskItemList("Select file", files, @TAB, @unsorted, @single,
@false)
Run("notepad.exe", ini)
See Also:
DirGet, DirHome
DiskExist
Tests for the existence of a drive.
Syntax:
DiskExist(driveletter)
Parameters:
(s) driveletter
Returns:
(i)
drive being tested.
@TRUE if the drive was found; @FALSE if the drive was
not found.
Use this function to test for the existence of a specific disk drive.
301
DiskFree
Example:
b="A:"
a=DiskExist(b)
if a
Message("Disk Exists", b)
else
Message("Disk Does Not Exist", b)
endif
See Also:
AppExist, FileExist, DirExist, DiskScan, DiskFree, LogDisk
DiskFree
Finds the total available (unused) disk space on a group of drives.
Syntax:
DiskFree(drive-list[,format])
Parameters:
(s) drive-list
(i) format
Returns:
(i/f)
one or more drive letters or "UNC Shares" in the format
"\\UNC\sharename",separated by"|", or the current file
delimiter (usually a tab).
controls the format in which the size is returned.
the number of bytes available on all the specified drives.
Results larger than 2 gigabytes will be returned as a floating
point number.
This function takes a string consisting of drive letters or "UNC Shares". When
specifying drive letters, only the first character of each non-blank group of characters
is used to determine the drives, so you can use just the drive letters, or add a colon
(:), or add a backslash (\), and still get a perfectly valid result. When specifying,
UNC shares you must specify the root of the UNC share in the format
"\\UNC\sharename".
By default, results larger than 2 gigabytes will be returned as a floating point
number. However, it should be noted that in Windows 95 prior to OSR 2 incorrect
values may be returned for volumes larger than 2 gigabytes.
Format is an optional parameter that controls the format in which the size is returned.
If the result is too large to be returned as an integer (larger than 2 gigabytes).
Format
302
Meaning
0
(Default) Floating Point
1
Huge number. This is a long decimal number string, which may
represent a number too large to be converted to an integer.'Huge
DiskScan
number' is a special data type. It is a long decimal number string,
which may represent a number too large to be converted to an
integer. This value cannot be modfied with standard arithmetic
operations, it requires the use of the Huge Math extender.
Example:
size = DiskFree("c|d",0)
Message("Space Available on C: and D:", size)
See Also:
DiskScan, FileSize
DiskInfo
Returns information on the specified disk drive.
Syntax:
DiskInfo(drive-letter,request#)
Parameters:
(s) drive-letter
(i) request#
a drive letter
see below.
Returns:
(i)
depends on request specified.
Req#
1
2
3
4
Return value
sectors per cluster
bytes per sector
number of free clusters
total number of clusters
Example:
spc = DiskInfo("c", 1)
bps = DiskInfo("c", 2)
bpc = spc * bps
Message("Cluster size on drive C:", bpc)
See Also:
DiskVolInfo, DiskSize, DiskScan, FileSize
DiskScan
Returns list of drives.
Syntax:
DiskScan(request#)
303
DiskSize
Parameters:
(i) request#
see below.
Returns:
(s)
drive list.
Req#
0
1
2
4
8
16
32
64
Return value
List of unused disk IDs
List of removable drives (floppies, zip, Jaz drives etc.)
List of local fixed (hard) drives
List of remote (network) drives
CD-ROM (32 bit)
RamDisk (32 bit)
List of persistent non-connected drives
List of USB bus disk drives. (Windows 2000 and later only)
Scans disk drives on the system, and returns a tab delimited list of drives of the type
specified by request#. For more information on delimiters see File Delimiters, (pg.
67).
The request# is a bitmask, so adding the values together (except for 0) returns all
drive types specified; e.g., a request# of 3 returns removable (floppies, zip, Jaz, etc.)
drives plus local hard drives.
Example:
hd = DiskScan(2)
Message("Hard drives on system", hd)
See Also:
DiskFree, LogDisk
DiskSize
Finds the total size of the specified drive(s).
Syntax:
DiskSize(drive-list[,format])
Parameters:
(s) drive-list
(i) format
Returns:
(i/f)
304
one or more drive letters or "UNC Shares" in the format
"\\UNC\sharename", separated by"|", or the current file
delimiter (usually a tab).
This controls the format in which the size is returned.
the total size of a selected disk.
DiskVolInfo
This function takes a string consisting of drive letters or "UNC Shares". When
specifying drive letters, only the first character of each non-blank group of characters
is used to determine the drives, so you can use just the drive letters, or add a colon
(:), or add a backslash (\), and still get a perfectly valid result. When specifying UNC
shares you must specify the root of the UNC share in the format "\\UNC\sharename".
By default, results larger than 2 gigabytes will be returned as a floating point
number. However, it should be noted that in Windows 95 prior to OSR 2 incorrect
values may be returned for volumes larger than 2 gigabytes.
Format is an optional parameter that controls the format in which the size is returned.
If the result is too large to be returned as an integer (larger than 2 gigabytes).
Format
Meaning
0
(Default) Floating Point
1
Huge number. This is a long decimal number string, which may
represent a number too large to be converted to an integer.'Huge
number' is a special data type. It is a long decimal number string,
which may represent a number too large to be converted to an
integer. This value cannot be modfied with standard arithmetic
operations, it requires the use of the Huge Math extender.
Example:
size = DiskSize("c", 0)
Message("Size of C:", size)
See Also:
DiskScan, FileSize, DiskInfo
DiskVolInfo
Returns information on a file system volume.
Syntax:
DiskVolInfo(root-path,request)
Parameters:
(s) root-path
(i) request
Returns:
(i/s/t)
Request
1
specifies the root directory of a file system volume (i.e.
"C:\" or "\\SERVER\PUBLIC\")
the request number for desired information. See below.
depends on the request number specified. (see below).
Return value
(s) volume name
305
Display
2
3
4
5
6
7
8
9
10
11
(s) file system name (e.g., "FAT" or "NTFS")
(s) volume serial number (hex string; e.g., "1234-ABCD")
(i) volume serial number (decimal)
(i) max length of filename component (portion between backslashes)
(b) volume preserves the case of filenames when storing files
(b) volume supports case-sensitive filenames
(b) volume supports Unicode in filenames
(b) volume preserves and enforces ACL's
(b) volume supports file-based compression
(b) volume is a compressed volume (e.g., a DoubleSpace volume)
Note: Request numbers which indicate a return type of "(b)" return a Boolean value
of 1 (@TRUE) or 0 (@FALSE).
Example:
vol = DiskVolInfo("c:\", 1)
Message("Volume name of drive C:", vol)
See Also:
DiskInfo
Display
Displays a message to the user for a specified period of time.
Syntax:
Display(seconds,title,text)
Parameters:
(i) seconds
(s) title
(s) text
seconds to display the message (max 3600).
title of the window to be displayed.
text of the window to be displayed.
Returns:
(i)
@TRUE if terminated by user; @FALSE otherwise.
Use this function to display a message for a few seconds, and then continue
processing without user input.
Seconds must be an integer no greater than 3600.
The user can make the displayed message disappear before the designated time has
elapsed by clicking a mouse button on the client area of the display window, or by
pressing the Space or Enter key. If the user terminates the function in this manner, it
will return a value of @TRUE; otherwise, it will return @FALSE.
306
DllCall
Note: you can specify a negative number for "seconds", in which case the negative
number will be treated as a positive number (eg, -5 will be treated as 5), and the
display dialog will be invisible.
Example:
Display(3, "Current window is", WinGetActive( ))
which produces something like this:
See Also:
Message, Pause
DllCall
Calls an external DLL.
Syntax:
DllCall(dllname,returntype:epname[,paramtype:parameter ...])
Parameters:
(s) dllname
(t) returntype:
(s) epname
(t) paramtype
(t) parameters
Returns:
(i/s)
the name of the Dll to be called, or a handle returned by the
DllLoad function.
type of value the Dll entry point will return (see below).
entry point name/ordinal number into the Dll.
type of parameter (see below).
parameters as required by the entry point.
either a integer or a string. See discussion below.
The DllCall function is unlike all other WIL functions. It is designed to allow
sophisticated users to either write their own extensions to the WIL language (using
the Windows SDK), to call third party Dll’s, or to access Windows API’s directly.
In order to use this function properly, a little background is necessary. There exists a
number of very specific reasons one would want to call an external DLL to process
some code. Examples may include calling Dll’s to interface with certain hardware
devices, to perform special compute-intensive algorithms, or to perform a series of
functions not possible using the WIL language. In many cases, the user has no
control over the DLL’s to be called, so that the WIL DllCall statement must be able
to call a wide variety of Dll’s, to be able to pass an assortment of different parameter
types, and to be able to process a number of different return values.
307
DllCall
For this reason, the DllCall syntax is complicated and initially confusing. Use of the
DllCall requires detailed understanding of Windows programming and complete
documentation for the Dll and the Dll entry point being called. If you need tech
support help with the DllCall statement, you must provide the pertinent
documentation before calling for help.
To call an external Dll, the user must first determine the following information:
1)
2)
3)
4)
5)
Name of the DLL.
Entry point name of the desired function within the Dll.
Type of the return value from the Dll.
Number of passed parameters the Entry point requires.
Type of each of the passed parameters.
WIL supports the following types of return types from a Dll:
1)
2)
3)
4)
5)
6)
word
long
lpstr
lpwstr
void
double
16 bit integer
32 bit integer
32 bit pointer to an ANSI string
32 bit pointer to a Unicode string
no return value
64-bit floating point value
WIL supports the following parameter types to pass data to a Dll:
1)
2)
3)
4)
5)
6)
word
long
lpstr
lpwstr
lpnull
lpbinary
7)
8)
9)
lpstruct
double
callback
16 bit integer
32 bit integer
32 bit pointer to an ANSI string
32 bit pointer to a Unicode string
32 bit NULL pointer
32 bit pointer to a memory block allocated with the
BinaryAlloc function. The lpbinary datatype can
also be used to pass data from a Dll back to the WIL
script. See note below, and see section on Binary
Operations (pg. 137).
Dll structure handle returned by DllStructAlloc.
64-bit floating point value
32-bit integer created using DllCallbackCreate
Note: If lpbinary is used to pass information from a Dll back to a WIL script via a
DllCall, then be sure to use BinaryEodSet to manually set the end of data point so
that the other binary functions can reference the returned data.
The DllCall parameters are as follows:
First: The first parameter defined the Dll to be used. It can either be a
dllname or a dllhandle. A dllname may be used for "oneshot" types of calls where a
single call to the Dll is all that is required, or when each call to the Dll is independent
308
DllCall
of all other calls. A dllhandle is used for multiple calls to a Dll, where the calls are
interrelated -- perhaps the first call to initialize the Dll, other calls use it, and a final
call to terminate processing. In such cases the Dll must first be loaded with the
DllLoad function, and freed with the DllFree function.The first parameter must be
one of the following:
dllname: Simply the filename of the Dll that contains the desired entry point
name. A single Dll may contain one or many separate entry points. Each entry point
may have its own unique return type and parameter list.
dllhandle: A handle to a Dll obtained from the DllLoad function.
Second: The second parameter consists of two parts, the first part is the return type
of the entry point desired, followed by a colon (:), and the second part is the entry
point name itself.
Note: Only use the lpstr or lpwstr return type for entry points that returns actual text
strings. In some cases other documentation might suggest using a lpstr or lpwstr as a
return type for its structures, don’t. Use long instead.
For each parameter the entry point requires, an additional parameter is added to the
DllCall parameter list. DllCall is limited to passing up to 20 parameters total. If the
entry point has no parameters, then the DllCall function uses only the first and
second parameters as described above.
Additional:
For each parameter that the entry point in the Dll requires,
additional DllCall parameters are added. Each additional parameter consists of two
parts, the first part is the parameter type of the required parameter, followed by a
colon (:), and the second part is the parameter itself.
Example:
; DllCall example.
; This example calls the CharUpperA API in the Windows User module.
; The CharUpperA function requires a 32 bit pointer to
; a string (lpstr).
; It converts the string to uppercase and passes back a 32 bit
; pointer (also lpstr) to the uppercased string.
; The CharUpperA function is found in the Windows USER32.Dll.
; Note: Dll Name, being a normal string is in quotes.
;
Entry point name, also being a string, is also in quotes
;
Parameter a0, being a normal variable is not in quotes.
a0="Hello Dolly"
dllname=strcat(dirwindows(1),"USER32.DLL")
a1=DllCall(dllname, lpstr:"CharUpperA", lpstr:a0)
Message(a0,a1)
See Also:
DllCall Additional Information, DllCallbackCreate, DllCallCdecl, Binary
Operations, DllLoad, DllFree, DllHwnd, DllHinst
309
DllCallbackCreate
DllCallbackCreate
Associates a user defined function or subroutine with a callback handle.
Syntax:
DllCallbackCreate(UDF-name,return-type,parameter-types)
Parameters:
(s) UDF-name
(s) return-type
(s) parameter-types
Returns:
(i)
name of previously defined user defined function or
subroutine.
expected return data type. May be one of WORD,
LONG, VOID, or DOUBLE.
space delimited list of the expected types of each
parameter for the WORD, LPSTR, LPWSTR, LPNULL,
LONG or DOUBLE.
callback handle.
The returned handle can be used with DllCall or DllCallCdecl when calling external
DLL functions that require a pointer to an application-defined callback function as a
parameter. The UDF/UDS associated with the handle is executed when the external
DLL function calls the application-defined function.
The associated UDF/UDS must have the same number of parameters that the
external DLL function expects for the application-defined callback. The parameter
types and return type specified in the second and third parameters must be
compatible with the documented types for the application-defined callback function.
Use the callback handle with DllCall or DllCallCdecl by passing the handle to the
external function with the new 'callback' parameter type specifier. A maximum of
512 callback handles can be active at one time.
Example:
; DllCall with Callback example.
#DefineFunction udfEnumWindowsProc(hwnd, lparam)
; This callback will run until:
;
Callback returns FALSE
;
There are no more top level windows to enumerate
maxsize = 256
lptitle = BinaryAlloc(maxsize)
BinaryEodSet(lptitle, 0)
Dll = DirWindows(1):'user32.dll'
length=DllCall(dll,long:'GetWindowTextA',long:hwnd,lpbinary:lptitle,l
ong:maxsize)
If length>1
BinaryEodSet(lptitle, length)
title = BinaryPeekStr(lptitle, 0, length)
If StrIndex( title, lparam, 1, @FWDSCAN )
ret=AskYesNo(lparam:' window exists!','Close this window?
[':title:']')
310
DllCallbackDestroy
If ret == @YES Then WinClose(title) ;Close Window
EndIf
EndIf
BinaryFree(lptitle)
Return @TRUE
#EndFunction
; Locates window and closes it
title = 'Notepad'
ShellExecute('Notepad.exe', '', '', @NORMAL, '')
TimeDelay(1)
Dll = DirWindows(1):'user32.dll'
cbhandle=DllCallbackCreate('udfEnumWindowsProc','LONG','LONG LPSTR')
ret=DllCall( dll,long:'EnumWindows',callback:cbhandle,lpstr:title)
DllCallbackDestroy(cbhandle)
See Also:
DllCall Additional Information, DllCall, DllCallBackDestroy, DllCallCdecl, Binary
Operations, DllLoad, DllFree, DllHwnd, DllHinst, IntControl 96
DllCallbackDestroy
Releases all resources associated with callback handle created by the
DllCallbackCreate function.
Syntax:
DllCallbackDestroy(handle)
Parameters:
(i) handle
handle created using DllCallbackCreate.
Returns:
(i)
@TRUE.
After destroying the handle, it cannot be used as a parameter to the DllCall or
DllCallCdecl functions.
This function cannot be called from a UDF or UDS while it is executing as an
application-defined callback for an external function.
Example:
; See DllCallbackCreate
See Also:
DllCall Additional Information, DllCall, DllCallbackCreate, DllCallCdecl, Binary
Operations, DllLoad, DllFree, DllHwnd, DllHinst
311
DllCall Additional Information
DllCall Additional Information
Functions that are called using DllCall must use the __stdcall calling convention
(declared as WINAPI). Otherwise, DllCall will return a "Bad Entrypoint" or "Bad
Parameter List" error message, even though you have specified the correct function
name and parameter types; this would likely indicate that the function is using an
unsupported calling convention.
Problem:
Using DllCall to call a function in a custom DLL that you've developed produces the
error message:
"NT DllCall: Bad Parameter List"
followed by the error message:
"1379: DllCall: Bad type list caused stack problems.
Check types carefully."
First check the number of parameters and the parameter types carefully to make sure
that they are indeed correct. If they are, it is likely that the problem is due to your
function using the __cdecl calling convention, instead of the required __stdcall. To
change this, follow these steps:
1. Add the keyword "WINAPI" to your function prototype and declaration:
LONG WINAPI MyFunction(LPSTR);
LONG WINAPI MyFunction(LPSTR lpString)
This ensures that the function will use the __stdcall calling convention, instead of the
default __cdecl convention. DllCall requires __stdcall, in which the called function
is responsible for removing the parameters from the stack (similar to _pascal in 16
bit versions of Windows). The WIL program checks the stack pointer before and
after the DllCall; if they are not the same, this indicates that either (1) you did not
specify the correct parameters to DllCall, or (2) the called function did not clean up
the stack properly (probably because it wasn't using __stdcall).
Alternatively, in Visual C++ you can use the "/Gz" compiler option (or set Calling
Convention to "__stdcall" under "Project | Settings | C/C++ | Category: Code
Generation" in the IDE) to make all your functions use __stdcall, but it's wise to
specify WINAPI in the declarations as well.
2. Add the option "/EXPORT:MyFunction" to the (VC++) LINK command line.
Or, if you have more than one exported function, it may be easier to create a module
definition (.DEF) file with an EXPORTS section (or add an EXPORTS section to
your existing .DEF file):
312
DllCallCdecl
EXPORTS
MyFunctionA
MyFunctionB
If you use the .DEF file method, you will also need to add the option
"/DEF:filename" to the (VC++) LINK command line, where "filename" is the name
of your module definition file (by default, VC++ 2.x does not create or use .DEF
files).
This is necessary, even if you have specified "__declspec(dllexport)" in the function
declaration, because __stdcall "decorates" (mangles) the function name when it is
exported, so that in the DLL it becomes:
[email protected]
where the number following the '@' symbol is the stack space used by the function
(the parameter count * 4). This prevents DllCall from accessing the function.
Exporting the function using the /EXPORT option (or via the EXPORTS section)
causes the real, un-decorated name to be exported.
After you've done this, it's no longer necessary to declare the function as
"__declspec(dllexport)", although it certainly wouldn't hurt to do so.
DllCallCdecl
Calls an external DLL using the Cdecl calling convention.
Syntax:
DllCallCdecl(dllname,returntype:epname[,paramtype:parameter ...])
Parameters:
(s) dllname
(t) returntype:
(s) epname
(t) paramtype
(t) parameters
Returns:
(i/s)
the name of the Dll to be called, or a handle
returned by the DllLoad function.
type of value the Dll entry point will return (see below).
entry point name/ordinal number into the Dll.
type of parameter (see below).
parameters as required by the entry point.
value returned by the DllCallCdecl depends on the external
Dll. It may be either a integer or a string. See discussion
below.
This function is the same as DllCall, except it calls DLL functions using the Cdecl
calling convention, rather than the StdCall calling convention which most Win32
DLL's use.
313
DllCallCdecl
DllCallCdecl is designed to allow sophisticated users to either write their own
extensions to the WIL language (using the Windows SDK), to call third party Dll’s,
or to access Windows API’s directly.
In order to use this function properly, a little background is necessary. There exists a
number of very specific reasons one would want to call an external DLL to process
some code. Examples may include calling Dll’s to interface with certain hardware
devices, to perform special compute-intensive algorithms, or to perform a series of
functions not possible using the WIL language. In many cases, the user has no
control over the DLL’s to be called, so that the WIL DllCallCdecl statement must be
able to call a wide variety of Dll’s, to be able to pass an assortment of different
parameter types, and to be able to process a number of different return values.
For this reason, the DllCallCdecl syntax is complicated and initially confusing. Use
of the DllCallCdecl requires detailed understanding of Windows programming and
complete documentation for the Dll and the Dll entry point being called. If you
need tech support help with the DllCallCdecl statement, you must provide (email,
fax, etc.) pertinent documentation before calling for help.
To call an external Dll, the user must first determine the following information:
1)
Name of the DLL.
2)
Entry point name of the desired function within the Dll.
3)
Type of the return value from the Dll.
4)
Number of passed parameters the Entry point requires.
5)
Type of each of the passed parameters.
WIL supports the following types of return types from a Dll:
1)
2)
3)
4)
5)
6)
word
long
lpstr
lpwstr
void
double
16 bit integer
32 bit integer
32 bit pointer to an ANSI string
32 bit pointer to a Unicode string
no return value
64-bit floating point value
WIL supports the following parameter types to pass data to a Dll:
314
1)
2)
3)
4)
5)
6)
word
long
lpstr
lpwstr
lpnull
lpbinary
7)
lpstruct
16 bit integer
32 bit integer
32 bit pointer to an ANSI string
32 bit pointer to a Unicode string
32 bit NULL pointer
32 bit pointer to a memory block allocated with
the BinaryAlloc function. See section on
Binary Operations (pg. 137).
Dll structure handle returned by DllStructAlloc.
DllCallCdecl
8)
9)
double
callback
64-bit floating point value
32-bit integer created using DllCallbackCreate
Note: If lpbinary is used to pass information from a Dll back to a WIL script via a
DllCallCdecl, then be sure to use BinaryEodSet to manually set the end of data
point so that the other binary functions can reference the returned data.
The DllCallCdecl parameters are as follows:
First: The first parameter defined the Dll to be used. It can either be a dllname or
a dllhandle. A dllname may be used for "oneshot" types of calls where a single call
to the Dll is all that is required, or when each call to the Dll is independent of all
other calls. A dllhandle is used for multiple calls to a Dll, where the calls are
interrelated -- perhaps the first call to initialize the Dll, other calls use it, and a final
call to terminate processing. In such cases the Dll must first be loaded with the
DllLoad function, and freed with the DllFree function. The first parameter must be
one of the following:
dllname: Simply the filename of the Dll that contains the desired entry point name.
A single Dll may contain one to many separate entry points. Each entry point may
have its own unique return type and parameter list.
dllhandle: A handle to a Dll obtained from the DllLoad function.
Second: The second parameter consists of two parts, the first part is the return type
of the entry point desired, followed by a colon (:), and the second part is the entry
point name itself.
Note: Only use the lpstr or lpwstr return type for entry points that returns actual text
strings. In some cases other documentation might suggest using a lpstr or lpwstr as a
return type for its structures, don’t. Use long instead.
For each parameter the entry point requires, an additional parameter is added to the
DllCallCdecl parameter list. DllCallCdecl is limited to passing up to 20 parameters
total. If the entry point has no parameters, then the DllCallCdecl function uses only
the first and second parameters as described above.
Additional:
For each parameter that the entry point in the Dll requires,
additional DllCallCdecl parameters are added. Each additional parameter consists of
two parts, the first part is the parameter type of the required parameter, followed by a
colon (:), and the second part is the parameter itself.
Example:
format = "Hello %%s"
username = "Dolly"
buffer = BinaryAlloc(512)
dllname = StrCat(DirWindows(1), "USER32.DLL")
len = DllCallCdecl(dllname, long:"wsprintfA", lpbinary:buffer,
lpstr:format, lpstr:username)
BinaryEodSet(buffer, len)
315
DllHinst
string = BinaryPeekStr(buffer, 0, len)
BinaryFree(buffer)
Message("", string)
For an example on how to use binary buffers to receive data returned through a
passed pointer, see the DllHwnd example.
See Also:
DllCall Additional Information, Binary Operations, DllCall, DllCallbackCreate,
DllCallbackDestroy, DllLoad, DllFree, DllHwnd, DllHinst
DllFree
This function frees a Dll that was loaded via the DllLoad function.
Syntax:
DllFree(dllhandle)
Parameters:
(s) dllhandle
handle of the Dll to be freed.
Returns:
(i)
@FALSE.
Use this function to free Dll’s that were loaded with the DllLoad function. Failure to
free such Dlls will use up system resources.
Example:
a0="Hello Dolly"
dllhandle=DllLoad(strcat(dirwindows(1),"USER32.DLL"))
a1=DllCall(dllhandle, lpstr:"CharUpperA", lpstr:a0)
DllFree(dllhandle)
Message(a0,a1)
See Also:
DllCall Additional Information, Binary Operations, DllCall, DllCallbackCreate,
DllCallbackDestroy, DllLoad
DllHinst
Obtains an application instance handle for use in DllCall’s when required.
Syntax:
DllHinst(partial-winname)
Parameters:
(s) partial-winname
the initial part of, or an entire, window name.
Returns:
(i)
an application instance handle.
316
DllHwnd
Use this function to return a valid application instance handle (hInst) of the
application owning the specified window.
Note: "Partial-winname" is the initial part of a window name, and may be a
complete window name. It is case-sensitive. You should specify enough characters
so that "partial-windowname" matches only one existing window. If it matches more
than one window, the most recently accessed window which it matches will be used.
The windowname "" may be used as a shorthand way of referring to the WIL parent
application window.
Example:
binbuf=BinaryAlloc(100)
hInst=DllHinst("")
dllname=strcat(dirwindows(1),"KERNEL32.DLL")
DllCall(dllname,word:"GetModuleFileNameA",long:hInst,
lpbinary:binbuf, long:100)
; Note DllCalls do not set EOD point in buffer.
; EOD Point MUST be set manually with BinaryEODSet
BinaryEodSet(binbuf, 100)
a=BinaryPeekStr(binbuf, 0, 100)
BinaryFree(binbuf)
Message("Window module filename is", a)
See Also:
DllCall Additional Information, Binary Operations, DllCall, DllCallbackCreate,
DllCallbackDestroy, DllHwnd
DllHwnd
Obtains a window handle for use in DllCall’s when required.
Syntax:
DllHwnd(partial-winname)
Parameters:
(s) partial-winname
the initial part of, or an entire, window name.
Returns:
(i)
window handle on success or zero on failure.
Use this function to return a valid window handle (hWnd) of specified window.
Some Dll’s require a window handle. This function will provide - in most cases - a
usable window handle.
Note: "Partial-winname" is the initial part of a window name, and may be a complete
window name. It is case-sensitive. You should specify enough characters so that
"partial-windowname" matches only one existing window. If it matches more than
one window, the most recently accessed window which it matches will be used. The
317
DllLoad
windowname "" may be used as a shorthand way of referring to the WIL parent
application window.
Example:
binbuf=BinaryAlloc(100)
hWnd=DllHWnd("")
DllCall("USER32.DLL",word:"GetClassNameA",word:hWnd,lpbinary:binbuf,
word:100)
; Note DllCalls do not set EOD point in buffer.
BinaryEodSet(binbuf, 100)
a=BinaryPeekStr(binbuf, 0, 100)
BinaryFree(binbuf)
Message("Window class name is", a)
See Also:
Binary Operations, DllCall, DllCallbackCreate, DllCallbackDestroy, DllHinst
DllLastError
Returns the most recent error returned by a DllCall to a Win32 API.
Syntax:
DllLastError()
Parameters:
(none)
Returns:
(i)
most recent error returned by a DllCall.
If you call this function after using DllCall to call a Win32 API function which set a
"last-error code" value (or another function which used the "SetLastError" API to set
a last-error code), this function will return that value.
Example:
a0="Hello Dolly"
dllhandle=DllLoad(strcat(dirwindows(1),"USER32.DLL"))
a1=DllCall(dllhandle, lpstr:"CharUpperA", lpstr:a0)
Message("Most recent DllCall error",DllLastError())
DllFree(dllhandle)
Message(a0, a1)
See Also:
DllCall Additional Information, DllCall
DllLoad
This function loads a Dll for later use via the DllCall function
318
DllStructAlloc
Syntax:
DllLoad(dllname)
Parameters:
(s) dllname
The name of the Dll to be called.
Returns:
(s)
a handle to a Dll for use in DllCalls.
When multiple calls are to be made to a Dll, and the calls are interdependent, the Dll
should be first loaded via the DllLoad command, and the return value - a dllhandle should be passed to the DllCall function instead of a filename.
Example:
a0="Hello Dolly"
dllhandle=DllLoad(strcat(dirwindows(1),"USER32.DLL"))
a1=DllCall(dllhandle, lpstr:"CharUpperA", lpstr:a0)
DllFree(dllhandle)
Message(a0, a1)
See Also:
DllCall Additional Information, Binary Operations, DllCall, DllCallbackCreate,
DllCallbackDestroy, DllFree
DllStructAlloc
Create a Dll Structure handle to an entry in the WIL Structure descriptor table.
Syntax:
DllStructAlloc( member-descriptor [, memory-address ] )
Parameters:
(s) member-descriptor tab or space character delimited list of data type*:name
pairs of structure members Data type and name must be
separated by a colon (:) character.
(i) memory-address [optional] DLL entry point supplied memory address to a
DLL structure.
Returns:
(i)
Dll structure handle.
The returned handle can be used with DllCall or DllCallCdecl when calling an
external DLL entry point that requires the memory address of a C/C++ language
style structure as a parameter. The handle can be used to both pass information to or
retrieve information from the DLL entry point depending on the entry point's
implementation.
319
DllStructAlloc
Member-descriptor
The member descriptor string parameter must contain the string representation of the
C/C++ language structure to create. Each member of the structure must have both a
supported data type specifier and a name. The data type specifier can be any data
type from the list below.
*Supported data type strings include: atom, byte, bool, boolean, char, colorref,
dword, dwordlong, dword_ptr, double, float, handle, hbitmap, hbrush, hmenu,
hcursor, hdesk, hfile, hfont, hglobal, hicon, hiinstance, hkey, hmodule, hmonitor,
hpen, hrgn, hwnd, hresult, int, int_ptr, int64, long, lptr, long_ptr, lparam, long64,
lpstr, lpwstr, short, uchar, unsigend char, ushort, uint, ulong, unsigned long, unsigned
int, word, wchar, wparam, wndproc.
The member name can be any text excluding tab (@tab), space (" "), colons (:), or
semicolons (;). Each data type/member pair can be separated by white space or
semicolons.
The member data types must be compatible with the documented data types for the
DLL structure. Each structure member descriptor must be listed in the order
indicated by the external DLL's documentation or 'header' file.
Use the '[elements]' qualifier to indicate that a member is an array. The opening
square bracket ([) must immediately follow the name with no intervening white
space and 'elements' must be an integer indicating the number elements in the array.
Memory-address
The optional second parameter is a structure memory address returned by an external
DLL entry point. The function copies the contents of the supplied memory location
into memory allocated for the structure described by the first parameter. This
parameter is only necessary when an entry point returns a memory address to a
structure or has an out parameter that is a pointer to a pointer to a structure.
Use the returned Dll structure handle with DllCall or DllCallCdecl by passing the
handle to the external function with the new 'lpstruct' parameter type specifier. The
structure descriptor table shares resources with binary buffers so a combined
maximum of 128 binary buffer and DLL structure handles can be active at one time.
Note: the function assumes standard Windows 8 byte structure alignment.
Example:
descriptor = "int:var1 byte:var2 uint:var3 char:var4[128] float:var5"
structhandle = DllStructAlloc( descriptor )
;
Set data in the struct
DllStructPoke( structhandle, "var1", -1 )
DllStructPoke( structhandle, "var2", 255 )
DllStructPoke( structhandle, "var3", -1 )
DllStructPoke( structhandle, "var4", ArrayFromStr( "Hello World" ) )
DllStructPoke( structhandle, "var5", 99.0 )
;
Get data from the struct
320
DllStructPeek
Pause("var1", DllStructPeek( structhandle, "var1" ) )
Pause("var2", DllStructPeek( structhandle, "var2" ) )
Pause("var3", DllStructPeek( structhandle, "var3" ) )
Pause("var4", ArrayToStr( DllStructPeek( structhandle, "var4" ) ) )
Pause("var5", DllStructPeek( structhandle, "var5" ) )
; Free all resources associated with a DLL structure handle.
DllStructFree( structhandle )
See Also:
DataCast, DllCall, DllCallbackDestroy, DllCallCdecl, DllCall Additional
information, Binary Operations, DllLoad, DllFree, DllHwnd, DllHinst,
DllStructFree, DllStructPeek, DllStructPoke, IntControl 96, IntControl 97,
IntControl 98
DllStructFree
Frees all resources associated with a DLL structure handle.
Syntax:
DllStructFree( structure-handle )
Parameters:
(i) structure-handle
dll Structure handle returned by the DllStructAlloc function.
Returns:
(i)
@TRUE on success.
Structure-handle
Dll Structure handle returned by the DllStructAlloc function.
The function frees all resources associated with a DLL structure handle. The handle
is no longer valid after being passed to this function.
Example:
See DllStructAlloc example.
See Also:
DataCast, DllCall, DllCallbackDestroy, DllCallCdecl, DllCall Additional
information, Binary Operations, DllLoad, DllFree, DllHwnd, DllHinst,
DllStructAlloc, DllStructPeek, DllStructPoke, IntControl 96, IntControl 97,
IntControl 98
DllStructPeek
Retrieves the value of a member of a DLL structure represented by a structure
handle.
321
DllStructPoke
Syntax:
DllStructPeek( structure-handle, member-name )
Parameters:
(i) structure-handle
(s) member-name
Returns:
(i/s/a)
dll Structure handle returned by the DllStructAlloc function.
structure member name from the structure descriptor string
used to create the structure-handle.
value of a member of a DLL structure represented by a
structure-handle and member-name.
Usually, call the function after the structure handle has been passed as a parameter
during a DLL entry point call to retrieve data suppled by the DLL entry point. The
structure-handle parameter must be a value returned by the DllStructAlloc function
and the member-name parameter must be one of the structure member names
supplied in the member descriptor string used to create the handle.
The function returns a string when the member data type is 'lpstr' or 'lpwstr' and an
array when array syntax is used on the member name in the descriptor string. A
string of decimal digits (a huge number) is returned for most 8 byte integer data
types and a floating point number is returned for the 'double' and 'float' data types.
Most other data types are represented by an integer return value.
Structure-handle
Dll Structure handle returned by the DllStructAlloc function.
Member-name
Structure member name from the structure descriptor string used to create the
'structure-handle' parameter.
Example:
See DllStructAlloc example.
See Also:
DataCast, DllCall, DllCallbackDestroy, DllCallCdecl, DllCall Additional
information, Binary Operations, DllLoad, DllFree, DllHwnd, DllHinst,
DllStructAlloc, DllStructFree, DllStructPoke, IntControl 96, IntControl 97,
IntControl 98
DllStructPoke
Set the value of a member of a Dll structure represented by a structure handle.
Syntax:
DllStructPoke( structure-handle, member-name, member-value )
322
DOSVersion
Parameters:
(i) structure-handle
(s) member-name
dll Structure handle returned by the DllStructAlloc function.
structure member name from the structure descriptor string
used to create the structure-handle.
(i/s/a) member-value new value of the structure member. Must be an array for
member with an array data type qualifier.
Returns:
(i)
@TRUE on success.
Structure-handle
Dll Structure handle returned by the DllStructAlloc function.
Member-name
Structure member name from the structure descriptor string used to create the
'structure-handle' parameter.
Call the function before passing a DLL structure to a DLL entry point when the entry
point is using a structure to obtain information from the caller.
Member-value
New value of the structure member. Must be an array for member with an array data
type qualifier.
The function attempts to convert the member-value parameter to the data type of the
member indicated in the structure descriptor string. However, the value must be an
array for array structure members.
Example:
See DllStructAlloc example.
See Also:
DataCast, DllCall, DllCallbackDestroy, DllCallCdecl, DllCall Additional
information, Binary Operations, DllLoad, DllFree, DllHwnd, DllHinst,
DllStructAlloc, DllStructFree, DllStructPeek, IntControl 96, IntControl 97,
IntControl 98
DOSVersion
Returns the version numbers of the current version of DOS.
Syntax:
DOSVersion(level)
Parameters:
(i) level
@MAJOR or @MINOR.
323
Drop
Returns:
(i)
integer or decimal part of DOS version number.
@MAJOR returns the integer part (to the left of the decimal).
@MINOR returns the decimal part (to the right of the decimal).
If the version of DOS in use is 5.0, then:
DOSVersion(@MAJOR) ==
DOSVersion(@MINOR) ==
5
0
Example:
i = DOSVersion(@MAJOR)
d = DOSVersion(@MINOR)
If StrLen(d) == 1 Then d = StrCat("0", d)
Message("DOS Version", "%i%.%d%")
See Also:
Environment, FileVerInfo, Version, VersionDLL, WinVersion
Drop
Removes variables from memory.
Syntax:
Drop(var[,var...])
Parameters:
(s / a) var
Returns:
(i)
one or more variable names to remove, delimited with a
comma.
@TRUE.
This function removes variables from the WIL Interpreter's variable list, and
recovers the memory associated with the variable (and possibly related string
storage).
A variable is defined the first time it appears to the left of an equal sign in a
statement. It stays defined until it is explicitly dropped with the Drop function, or
until the current invocation of the WIL Interpreter gets closed.
Generally speaking: in batch file-based implementations of WIL, all variables are
dropped automatically at the end of every batch file; and in menu-based
implementations of WIL, variables stay defined until explicitly dropped.
Drop can accept a single array element as a parameter. This permits setting an
element of an array to the undefined state while keeping the array and other elements
defined. The function does not support undefining COM Automation safe array
elements.
324
DropWild
Drop and DropWild can accept array names as parameters.
Note: A WIL script is limited to 2000 variables.
Example:
a = "A variable"
b = "Another one"
Drop(a, b)
; This removes A and B from memory
Message("Drop","Dropped from memory.")
See Also:
IsDefined, DropWild
DropWild
Removes variables from memory.
Syntax:
DropWild(variable/wildcard)
Parameters:
(s/a) variable
variable or wildcarded variable.
Returns:
(i)
number of items dropped.
Note: a wildcarded variable does not recognize a wildcard at the beginning of the
variable name. DropWild only accepts a wildcard on the end of the variable name,
i.e. “var*”.
This function removes variables from the WIL Interpreter's variable list, and
recovers the memory associated with the variable (and possibly related string
storage).
A variable is defined the first time it appears to the left of an equal sign in a
statement. It stays defined until it is explicitly dropped with the DropWild function,
or until the current invocation of the WIL Interpreter gets closed.
Generally speaking: in batch file-based implementations of WIL, all variables are
dropped automatically at the end of every batch file; and in menu-based
implementations of WIL, variables stay defined until explicitly dropped.
Drop and DropWild can accept array names as parameters.
Note: A WIL script is limited to 2000 variables.
Warning: Do not attempt to use the wildcard "*". This causes unpredictable
results.
Example:
a1= "A variable"
325
Environment
a2= "Another variable"
DropWild("a*") ; This removes A1 and A2 from memory
Message("DropWild","Dropped from memory.")
See Also:
IsDefined, Drop
EndSession
Ends the Windows session.
Syntax:
EndSession()
Parameters:
(none)
Returns:
(i)
@FALSE.
Use this command to end the current Windows session, just like selecting Close
from Program Manager's control menu. If any active applications pop up dialog
boxes in response to this command (such as prompting to save data files which have
changed), the user will need to respond to them before Windows will close.
Note: For additional methods of rebooting or restarting Windows, see IntControl
66, 67 and 68.
Example:
if AskYesNo ("End Session", "You want to exit Windows?")
EndSession( )
endif
exit
:cancel
Message("", "Exit Windows canceled")
See Also:
Exit, WinClose, IntControl 66, IntControl 67, IntControl 68
Environment
Gets a DOS environment variable.
Syntax:
Environment(env-variable)
Parameters:
(s) env-variable
326
any defined environment variable.
EnvironSet
Returns:
(s)
environment variable contents.
Use this function to get the value of a DOS environment variable.
Note: It is not possible to change a DOS environment variable from within
Windows.
In 32 bit Windows, you no longer need to update the environment. Basically the
registry database commands can do the job for you.
For Windows, use the RegApp function to tell the system what path to use for
various exe files. You can update this just before launching the app. If WinBatch is
going to launch the program, you can also try the EnvironSet function along with
the RunEnviron function. After you have changed the PATH with the EnvironSet
function, you can take a look at the new settings by displaying in a message box the
path:
; Display the PATH for this session
currpath = Environment("PATH")
Message("Current System Path", currpath)
; Display the Environment for this session
allenv=EnvItemize()
Message("Environment Settings", allenv)
Note that the EnvItemize function displays alot more stuff than does the
Environment("PATH").
Example:
; Display the PATH for this DOS session
currpath = Environment("PATH")
Message("Current DOS Path", currpath)
See Also:
IniRead, RegApp, EnvItemize, EnvironSet
EnvironSet
Changes LOCAL Environment variables.
Syntax:
EnvironSet(name,value)
Parameters:
(s) name
(s) value
Returns:
(i)
name of environment variable. (See Note 1).
desired value.
@TRUE Environment variable was modified; @FALSE
Unable to modify environment.
327
EnvItemize
Use this function to change the LOCAL environment variables.
32 bit versions of WIL will always pass the local environment to any programs they
launch. In the 32 bit versions, the RunEnviron command is identical to the
RunShell Command.
Note 1: DOS expects UPPERCASE environment variable names. Windows allows
mixed upper and lowercase names. If you are using WIL with DOS, be sure to use
uppercase names.
Note 2: To alter the path for DOS programs, all that is required is a simple batch file,
and the usual WIL Run command. Assuming the case where one wished to run
"cmd.exe" with the path "c:\special", a generic batch file as shown below will
suffice, along with passing all the information required as parameters in the WIL
Run command.
DoPath.bat file listing
SET PATH=%1
ECHO %PATH%
PAUSE
%2 %3 %4 %5 %6 %7 %8 %9
WIL Run Command
Run("dopath.bat", "c:\special cmd.exe")
Example:
;Note: Permanent changes may be made by using the
;registry functions to update the registry.
;
;This function will not affect the environment for
;DOS or Console applications
;
;Modifying the path does not allow or assist WIL in
;locating the EXE file. The path WIL uses has already
;been pre-determined. However the child process (excel)
;will inhieret the PATH environment variable in this case.
EnvironSet("PATH","c:\Program Files\Tmp\")
RunEnviron("c:\Program Files\Tmp\abc.exe","",@NORMAL,@WAIT)
See Also:
Environment, EnvItemize, RunEnviron
EnvItemize
Returns a delimited list of the current environment.
Syntax:
EnvItemize()
328
ErrorEvent
Parameters:
(none)
Returns:
(s)
a list containing all variables in the current environment
(See Note).
Use this function to return a list of the variables in the current environment.
Note: This list is delimited by the newline character (ASCII 10), which can be
generated with the Num2Char function or by using the @LF constant. The returned
list is suitable for a message box display. Tabs are not used as a delimiter as they
seem to be legal characters within the environment. The StrReplace function may be
used to change the delimiter to any other character.
Example:
env=EnvItemize( )
Message("The Environment is", EnvItemize( ))
env=StrReplace(env, @LF, @TAB)
a=AskItemList("Select a Variable", env, @TAB, @SORTED, @SINGLE,
@FALSE)
b=Environment(a)
Message(a, b)
See Also:
Environment, EnvironSet
ErrorEvent
Causes a user-defined error.
Syntax:
ErrorEvent(severity,error-code,error-message)
Parameters:
(i) severity
(i) error-code
(s) error-message
Returns:
(i)
severity, which can be one of the following:
-1 minor error
-2 moderate error
-3 severe error
error code, which must be a number between 7000 and
7999.
error message, which is a string describing the error
returns @TRUE.
Example:
ErrorEvent ( -1, 7001, "Testing User Defined Error");minor error
ErrorEvent ( -2, 7002, "Testing User Defined Error");moderate error
ErrorEvent ( -3, 7003, "Testing User Defined Error");fatal error
329
ErrorMode
See Also:
ErrorMode, User-Defined-Functions
ErrorMode
Specifies how to handle errors.
Syntax:
ErrorMode(mode)
Parameters:
(i) mode
@CANCEL or @NOTIFY or @OFF.
Returns:
(i)
previous error setting.
Use this function to control the effects of runtime errors. The default is @CANCEL,
meaning the execution of the WIL program will be canceled upon any error.
@CANCEL: All runtime errors will cause execution to be canceled. The user
will be notified which error occurred.
@NOTIFY: All runtime errors will be reported to the user, and the user can
choose to continue if it isn't fatal.
@OFF: Minor runtime errors will be suppressed. Moderate and fatal errors will
be reported to the user. User has the option of continuing if the error is not fatal.
In general, we suggest the normal state of the program should be
ErrorMode(@CANCEL), especially if you are writing a WIL program for others to
use. You can always suppress errors you expect will occur and then re-enable
ErrorMode(@CANCEL).
ONLY put ErrorMode(@OFF) around SINGLE statements where you are handling
the errors yourself. If it is obvious that there is no way a statement could fail it
should be run with ErrorMode(@CANCEL).
Note: Pay close attention when suppressing errors with the ErrorMode function.
When an error occurs, the processing of the ENTIRE line is canceled. Setting the
ErrorMode( ) to @OFF or @NOTIFY allows execution to resume at the next line.
Various parts of the original line may have not been executed. Never turn
ErrorMode( ) to @OFF during debugging.
e.g.
ErrorMode(@off)
; The FileCopy will cause a file not found error,
; canceling the execution of the whole line.
; The variable A is set to @FALSE by default
A = FileCopy( "xxxxxxxxx", "*.*", @FALSE)
; Now there is a NOT symbol in front of the FileCopy.
330
Exclusive
;
;
;
;
None the less, if an error occurs A is still set to @FALSE
not @TRUE as might be assumed. When an error is suppressed
with ErrorMode the line is canceled, and any assignment is
simply set to the default @FALSE value.
A = !FileCopy("yyyyyyyyy", "*.*", @FALSE)
Message("ErrorMode","ErrorMode executed.")
For this reason, ErrorMode( ) must be used with a great deal of care. The function
for which the errors are being suppressed should be isolated from other functions and
operators as much as possible.
; INCORRECT USAGE of ErrorMode()
; In this instance, when the copy has an error, the entire if
; statement is canceled.
; Execution begins (erroneously) at the next line, and states
; that the copy succeeded. Next a fatal error occurs as the
; "else" is found, since it does not have a matching if
ErrorMode(@OFF)
if FileCopy(file1,file2,@FALSE) == @TRUE
Message("Info", "Copy worked")
else
Message("Error", "Copy failed")
endif
;
;
;
;
;
;
;
CORRECT USAGE
In this case, the FileCopy is isolated from other statements
and flow control logic. When the statement fails, execution
can safely begin at the next line. The variable "a" will
contain the default value of zero that a failed assignment
returns.
Results are not confused by the presence of other operators.
ErrorMode(@OFF)
a = FileCopy(file1,file2,@FALSE)
ErrorMode(@CANCEL)
if
a == @TRUE
Message("Info", "Copy worked")
else
Message("Error", "Copy failed")
endif
See Also:
Debug, ErrorEvent, Execute, IntControl 73, LastError
Exclusive
Controls whether or not other Windows programs will get any time to execute.
Syntax:
Exclusive(mode)
331
Execute
Parameters:
(i) mode
@ON or @OFF.
Returns:
(i)
previous Exclusive mode.
Exclusive(@OFF) is the default mode. In this mode, the WIL Interpreter is wellbehaved toward other Windows applications.
Exclusive(@ON) allows WIL programs to run somewhat faster, but causes the WIL
Interpreter to be "greedier" about sharing processing time with other active Windows
applications. For the most part, this mode is useful only when you have a series of
WIL statements which must be executed in quick succession.
Example:
Exclusive(@ON)
x = 0
start = TimeDate( )
:add
x = x + 1
If x < 1000 Then Goto add
stop = TimeDate( )
Message("Times", "Start: ":start:@crlf:"Stop:
Exclusive(@OFF)
":stop)
See Also:
Yield, TimeDelay
Execute
Executes a statement in a protected environment. Any errors encountered are
recoverable.
Syntax:
Execute statement
Parameters:
(s) statement
any executable WIL statement.
Returns:
(not applicable)
Use this command to execute computed or user-entered statements. Due to the builtin error recovery associated with Execute, it is ideal for interactive execution of
user-entered commands.
Note: The Execute command doesn't operate on a string, per se, but rather on a
direct statement. If you want to put a code segment into a string variable, you must
use the substitution feature of the language, as in the example below.
332
ExeTypeInfo
Example:
cmd = ""
cmd = AskLine("WIL Interactive", "Command:", cmd, 0)
Execute %cmd%
See Also:
ErrorMode, IntControl 87
ExeTypeInfo
Returns an integer describing the type of EXE file specified.
Syntax:
ExeTypeInfo(exename)
Parameters:
(s) exename
Returns:
(i)
the name of the desired .EXE file or data file.
0 = not an EXE file.
1 = Old style DOS EXE.
2 = New Style DOS EXE.
3 = Windows EXE.
10 = Windows NT EXE
Use this function to return an integer describing and identifying the type of EXE file
specified.
Example:
a=ExeTypeInfo(FileLocate("notepad.exe"))
switch a
case 0
b="Not an EXE file"
break
case 1
b="Old DOS EXE"
break
case 2
b="New DOS EXE"
break
case 3
b="Windows EXE"
break
case 10
b="Windows NT EXE"
break
case a
b="Unknown file type, value = %a%"
break
endswitch
Message("File Type", b)
333
Exp
See Also:
AskFileName, FileFullName, FileMapName
Exit
Unconditionally ends a WIL program.
Syntax:
Exit
Parameters:
(none)
Returns:
(not applicable)
Use this command to immediately terminate a WIL program. An Exit is implied at
the end of each top-level WIL program, and so is not necessary there.
Example:
a = 100
Message("The value of a is", a)
Exit
See Also:
Pause, Return, Terminate
Exp
Calculates the exponential.
Syntax:
Exp(x)
Parameters:
(f) x
floating point number.
Returns:
(f)
the value of the exponential ( e ** x).
The exp function returns the exponential function of the floating point argument (x).
Example:
real=AskLine("Exponential", "Enter a number", "1.23", 0)
answer=Exp(real)
Message("Exponential of %real% is",answer)
See Also:
LogE
334
FileAppend
Fabs
Calculates the absolute value of a floating-point argument.
Syntax:
Fabs(x)
Parameters:
(f) x
floating point number.
Returns:
(f)
the absolute value of the argument.
Use this function to calculate the absolute value of a floating point argument. There
is no error return.
Example:
a = -1.23
Message("Fabs(%a%) is", Fabs(a))
See Also:
Abs
FileAppend
Appends one or more files to another file.
Syntax:
FileAppend(source-list,destination)
Parameters:
(s) source-list
(s) destination
Returns:
(i)
a string containing one or more filenames, which may be
wildcarded.
target file name.
@TRUE if all files were appended successfully; @FALSE
if at least one file wasn't appended.
Use this function to append an individual file or a group of files to the end of an
existing file. If "destination" does not exist, it will be created.
The file(s) specified in "source-list" will not be modified by this function.
"Source-list" may contain * and ? wildcards. "Destination" may not contain
wildcards of any type; it must be a single file name.
The FileAppend function glues two files together assuming they are binary files.
Therefore, if the files that are being appended contain end-of-file markers, those will
be retained.
335
FileAttrGet
Example:
testfile1=FileLocate("win.ini")
testfile2=FileLocate("system.ini")
testfile3="c:\winini.bak"
FileAppend(testfile1,testfile3)
FileAppend(testfile2,testfile3)
Message("FileAppend",strcat(testfile3,@crlf,"now contains",
@crlf,testfile1,@crlf,"and",@crlf,testfile2))
See Also:
FileCopy, FileDelete, FileExist
FileAttrGet
Returns file attributes.
Syntax:
FileAttrGet(filename)
Parameters:
(s) filename
file whose attributes you want to determine.
Returns:
(s)
attribute settings.
Returns attributes for the specified file, in a string of the form "RASH". This string is
composed of four individual attribute characters, as follows:
Symbol
Meaning
Symbol
Meaning
R
read only ON
read only OFF
A
archive ON
archive OFF
S
system ON
system OFF
H
hidden ON
hidden OFF
A hyphen in any of these positions indicates that the specified attribute is OFF. For
example, the string "-A-H" indicates a file which has the Archive and Hidden
attributes set.
Example:
editfile = strcat(DirWindows(0),"win.ini")
attr = FileAttrGet(editfile)
If StrSub(attr, 1, 1) == "R"
Message("File is read-only", "Cannot edit %editfile%")
else
Run("notepad.exe", editfile)
endif
See Also:
FileInfoToArray, FileAttrSet, FileTimeGet, FileTimeGetEx
336
FileAttrGetEx
FileAttrGetEx
Returns file attributes (extended).
Syntax:
FileAttrGetEx(filename)
Parameters:
(s) filename
file whose attributes you want to determine.
Returns:
(i)
extended attribute settings.
The return value is a bitmask comprised of one or more of the following integer
values, combined using the bitwise OR ('|') operator:
Value
1
Name
READONLY
2
HIDDEN
4
SYSTEM
16*
32
DIRECTORY
ARCHIVE
128
NORMAL
256
TEMPORARY
512*
1024*
SPARSE_FILE
REPARSE_POINT
Meaning
The file or directory is read-only.
Applications can read the file but cannot
write to it or delete it. In the case of a
directory, applications cannot delete it.
The file or directory is hidden. It is not
included in an ordinary directory listing.
The file or directory is part of, or is used
exclusively by, the operating system.
Identifies a directory.
The file or directory is an archive file or
directory. Applications use this attribute
to mark files for backup or removal.
The file or directory has no other
attributes set. This attribute is valid only
if used alone.
The file is being used for temporary
storage. File systems avoid writing data
back to mass storage if sufficient cache
memory is available, because often the
application deletes the temporary file
shortly after the handle is closed. In
that case, the system can entirely avoid
writing the data. Otherwise, the data
will be written after the handle is
closed.
The file is a sparse file.
The file or directory has an associated
reparse point.
337
FileAttrGetEx
The file or directory is compressed. For
a file, this means that all of the data in
the file is compressed. For a directory,
this means that compression is the
default for newly created files and
subdirectories.
OFFLINE
The data of the file is not immediately
4096
available. This attribute indicates that
the file data has been physically moved
to offline storage. This attribute is used
by Remote Storage, the hierarchical
storage management software.
Applications should not arbitrarily
change this attribute.
NOT_CONTENT_INDEXED The file will not be indexed by the
8192
content indexing service.
The file or directory is encrypted. For a
16384* ENCRYPTED
file, this means that all data streams in
the file are encrypted. For a directory,
this means that encryption is the default
for newly created files and
subdirectories.
* The values with an asterisk next to them cannot be set using FileAttrSetEx.
2048*
COMPRESSED
Example:
READONLY
HIDDEN
SYSTEM
DIRECTORY
ARCHIVE
NORMAL
TEMPORARY
COMPRESSED
OFFLINE
NOT_CONTENT_INDEXED
ENCRYPTED
=
=
=
=
=
=
=
=
=
=
=
1
2
4
16
32
128
256
2048
4096
8192
16384
file = strcat(DirWindows(0),"win.ini")
attr = FileAttrGetEx(file)
if attr & READONLY
Message(file, "READONLY")
endif
if attr & HIDDEN
Message(file, "HIDDEN")
endif
if attr & SYSTEM
Message(file, "SYSTEM")
endif
338
FileAttrSet
if attr & DIRECTORY
Message(file, "DIRECTORY")
endif
if attr & ARCHIVE
Message(file, "ARCHIVE")
endif
if attr & NORMAL
Message(file, "NORMAL")
endif
if attr & TEMPORARY
Message(file, "TEMPORARY")
endif
if attr & COMPRESSED
Message(file, "COMPRESSED")
endif
if attr & OFFLINE
Message(file, "OFFLINE")
endif
if attr & NOT_CONTENT_INDEXED
Message(file, "NOT_CONTENT_INDEXED ")
endif
if attr & ENCRYPTED
Message(file, "ENCRYPTED")
endif
See Also:
FileAttrSetEx, FileInfoToArray, FileAttrSet, FileTimeGet
FileAttrSet
Sets file attributes.
Syntax:
FileAttrSet(file-list,settings)
Parameters:
(s) file-list
(s) settings
a delimited list of files.
new attribute settings for those file(s).
Returns:
(i)
@FALSE.
The attribute string consists of one or more of the following characters (an upper
case letter turns the specified attribute ON, a lower case letter turns it OFF):
Symbol
R
A
S
H
Meaning
read only ON
archive ON
system ON
hidden ON
Symbol
r
a
s
h
Meaning
read only OFF
archive OFF
system OFF
hidden OFF
339
FileAttrSetEx
File list may contain * and ? wildcards.
Example:
testfile1=strcat(DirWindows(0),"win.ini")
FileAttrSet(testfile1, "rAsh")
Message("FileAttrSet","File Attributes Set")
See Also:
FileAttrGet, FileAttrGetEx, FileAttrSetEx, FileTimeTouch
FileAttrSetEx
Sets file attributes (extended).
Syntax:
FileAttrSetEx(file-list,attributes,mode)
Parameters:
(s) file-list
(i) attributes
(i) mode
Returns:
(i)
Value
1
@TRUE on success; @FALSE if unable to change the
attributes on any of the specified files.
Name
READONLY
2
HIDDEN
4
SYSTEM
16*
32
340
a delimited list of files. May contain wildcards.
specifies the attributes to apply to the specified file(s). see
below.
specifies the method by which "attributes" are applied to
the specified file(s), and can be one of the following:
0 "attributes" replaces the existing file attributes
1 "attributes" are added to the existing file attributes
-1"attributes" are removed from the existing file attributes
DIRECTORY
ARCHIVE
Meaning
The file or directory is read-only.
Applications can read the file but
cannot write to it or delete it. In the case
of a directory, applications cannot
delete it.
The file or directory is hidden. It is not
included in an ordinary directory
listing.
The file or directory is part of, or is
used exclusively by, the operating
system.
Identifies a directory.
The file or directory is an archive file or
directory. Applications use this attribute
FileAttrSetEx
to mark files for backup or removal.
NORMAL
The file or directory has no other
128
attributes set. This attribute is valid
only if used alone.
TEMPORARY
The file is being used for temporary
256
storage. File systems avoid writing
data back to mass storage if sufficient
cache memory is available, because
often the application deletes the
temporary file shortly after the handle is
closed. In that case, the system can
entirely avoid writing the data.
Otherwise, the data will be written after
the handle is closed.
SPARSE_FILE
The file is a sparse file.
512*
The file or directory has an associated
1024* REPARSE_POINT
reparse point.
The file or directory is compressed. For
2048* COMPRESSED
a file, this means that all of the data in
the file is compressed. For a directory,
this means that compression is the
default for newly created files and
subdirectories.
OFFLINE
The data of the file is not immediately
4096
available. This attribute indicates that
the file data has been physically moved
to offline storage. This attribute is used
by Remote Storage, the hierarchical
storage management software.
Applications should not arbitrarily
change this attribute.
NOT_CONTENT_INDEXED The file will not be indexed by the
8192
content indexing service.
The file or directory is encrypted. For a
16384* ENCRYPTED
file, this means that all data streams in
the file are encrypted. For a directory,
this means that encryption is the default
for newly created files and
subdirectories.
* The values with an asterisk next to them cannot be set using FileAttrSetEx.
Examples:
ADD = 1
TEMPORARY = 256
curdir = DirGet()
341
FileClose
tempfile = FileCreateTemp(StrCat(curdir,"TMP"))
FileAttrSetEx(tempfile, TEMPORARY, ADD)
Message("FileAttrSet","TEMPORARY file created:":@crlf: tempfile)
See Also:
FileAttrGetEx, FileAttrGet, FileTimeTouch
FileBaseName
Extracts the base filename from a full file path.
Syntax:
FileBaseName(filename[,flag])
Parameters:
(s) filename
(i) flag
fully qualified file name.
[optional] 0, or 1. See below.
Returns:
(i)
base filename.
The optional 'flag' can be one of the following values:
Value
0
1
Meaning
(default) do not include a dot '.' on the end of a filename with no
extension.
include a dot '.' on the end of a filename with no extension.
Example:
allfiles = FileItemPath("*.*")
file = AskItemList("Get base filename of…", allfiles, @tab,
@unsorted, @single, @false)
basename = FileBaseName(file,0)
Message("Base Filename",basename)
See Also:
FileRoot, FileExtension, FileFullname
FileClose
Closes a file.
Syntax:
FileClose(filehandle)
Parameters:
(i) filehandle
342
same integer that was returned by FileOpen.
FileCompare
Returns:
(i)
@FALSE.
Example:
; the hard way to copy an ASCII file
testfile1=FileLocate("win.ini")
testfile2=strcat(FilePath(testfile1),"winini.bak")
old = FileOpen(testfile1, "READ")
new = FileOpen(testfile2, "WRITE")
while @TRUE
; Loop till break do us end
x = FileRead(old)
If x == "*EOF*" Then Break
FileWrite(new, x)
endwhile
FileClose(new)
FileClose(old)
Message("FileClose",strcat(testfile1,@crlf,"backed up
to",@crlf,testfile2))
See Also:
FileOpen, FileRead, FileWrite
FileCompare
Compares two files and reports on the result.
Syntax:
FileCompare(filename1,filename2)
Parameters:
(s) filename1
(s) filename2
name of first file to compare
name of second file to compare
Returns:
(i)
compare result (see below).
Possible return values are:
Return
0
1
-1
2
-2
3
-3
4
Meaning
Files contents are identical.
Files are same size but different - first file is newer.
Files are same size but different - second file is newer.
Files are different - first file is newer.
Files are different - second file is newer.
Second file missing - only first file exists.
First file missing - only second file exists.
Neither file exists.
343
FileCopy
Use this function to compare two files to determine if they are identical or not. If the
return value is zero, the file contents are identical. If the return value is not zero, the
actual value provides additional information on why they didn’t compare.
An actual byte by byte compare is performed only if the file sizes are identical,
otherwise it is obvious that the files must be different.
IMPORTANT: If the byte by byte compare is identical, then FileCompare will
return 0 (identical) regardless of the file dates.
Example:
;Assuming a copy of win.ini has been previously made to win.sav
a=FileCompare("WIN.INI", "WIN.SAV")
if a==0
Message("Info", "WIN.INI not modified")
else
Message("Alert!", "WIN.INI has been modified")
endif
See Also:
ExeTypeInfo, FileCopy, FileMove, FileDelete
FileCopy
Copies files.
Syntax:
FileCopy(source-list,destination,warning)
Parameters:
(s) source-list
(s) destination
(i) warning
Returns:
(i)
a string containing one or more filenames, which may be
wildcarded.
target path and/or file name/wildcard.
@TRUE if you want a warning before overwriting
existing files; @FALSE if no warning desired.
@TRUE if all files were copied successfully (see note);
@FALSE if at least one file wasn't copied.
Source-list and destination may contain * and ? wildcards.
Note: If warning parameter is set to @TRUE , then the return value will be
@TRUE, even if it was modified by the user dialog.
If a FileCopy fails, it is often for the following reason:
The target file is in-use and cannot be overwritten. In this case, check the status of
the file with the FileExist function. If FileExist returns a 2, the file is in-use.
344
FileCopy
Use this function to copy an individual file, a group of files using wildcards, or
several groups of files by separating the names with a delimiter.
You can also copy files to any COM or LPT device, but do not place a colon after
the name of the device. If "destination" is a file name of the form "USB###" where
"#" is a digit between 0 and 9, it will now be treated as a port number.
Examples:
;;;Example 1
temp=Environment("TEMP")
DirChange(DirWindows(0))
FileCopy("*.ini", temp, @TRUE)
Message("FileCopy","Windows ini files backed up to %temp%")
Exit
;;;Example 2
;Copies all files in "MyDir" to a "Temp" directory
;and checks that the source files are
;NOT open in read deny mode
filelist=FileItemize("C:\MyDir\*.*")
count=ItemCount(filelist,@TAB)
Dirchange("C:\MyDir\")
For xx = 1 to count
file=ItemExtract(xx,filelist,@TAB)
If FileExist(file)==2
Message("Copy failed","%file% is in read-deny mode.")
Else
FileCopy(file, "C:\Temp\*.*", @FALSE)
Endif
Next
Message("Files copied","Sucessful")
Exit
;;;Example 3
;Print file to LPT1 example
;This example is designed to force a file
;to print on most laser printers
;file name to print
myfile="C:\WINDOWS\desktop\myfile.txt"
;Create a file with a formfeed to send to printer
;(Used to actually force file to print)
home_dir=DirHome()
formfeed_file="%home_dir%print.txt"
file_handle=FileOpen(formfeed_file,"WRITE")
;inserts a form feed into the file
FileWrite(file_handle, Num2Char(12))
FileClose(file_handle)
;execute file copys to LPT1
FileCopy(myfile,"LPT1",@FALSE)
FileCopy(formfeed_file,"LPT1",@FALSE)
;cleanup
FileDelete(formfeed_file)
345
FileCopyAttr
message("Print Job", "Complete")
Exit
See Also:
FileDelete, FileExist, FileLocate, FileMove, FileRename, IntControl 39
FileCopyAttr
Copies files, and sets file attributes.
Syntax:
FileCopyAttr(source-list,destination,warning,attributes)
Parameters:
(s) source-list
(s) destination
(i) warning
(s) attributes
Returns:
(i)
a string containing one or more filenames, which
may be wildcarded.
target path and/or file name/wildcard.
@TRUE if you want a warning before overwriting
existing files; @FALSE if no warning desired.
attributes to be modified.
@TRUE if all files were copied successfully (see note);
@FALSE if at least one file wasn't copied.
Note: If warning parameter is set to @TRUE , then the return value will be
@TRUE, even if it was modified by the user dialog.
Use this function to copy an individual file, a group of files using wildcards, or
several groups of files by separating the names with a delimiter.
You can also copy files to any COM or LPT device, but do not place a colon after
the name of the device.
Source-list and destination may contain * and ? wildcards.
This function is like FileCopy, but takes an additional parameter which lets you
specify the file attributes for the destination files. It is equivalent to doing a
FileCopy, followed by a FileAttrSet.
If "attributes" is a blank string (""), the destination file(s) will inherit the same
attributes as the corresponding source file(s). You only need to specify those
attributes which you want to be changed.
The "attribute" string consists of one or more of the following characters (an upper
case letter turns the specified attribute ON, a lower case letter turns it OFF):
Symbol
R
A
346
Meaning
read only ON
archive ON
Symbol
r
a
Meaning
read only OFF
archive OFF
FileCreateTemp
S
H
system ON
hidden ON
s
h
system OFF
hidden OFF
Note: The default file delimiter used to delimit lists of files and directories is a TAB.
IntControl 29 allows the file delimiter to be changed to a character of your own
choosing.
Example:
temp=Environment("TEMP")
DirChange(DirWindows(0))
FileCopyAttr("*.ini", temp, @TRUE,"R")
Message("FileCopy","files backed up with Read-Only attribute set")
See Also:
FileDelete, FileExist, FileLocate, FileMove, FileRename, IntControl 39
FileCreateTemp
Creates a temporary file.
Syntax:
FileCreateTemp(prefix)
Parameters:
(s) prefix
Returns:
(s)
specifies a prefix for the file name, up to 3 characters long
(the string may be longer than that, but only the first 3
characters are used).
full path name of the temporary file created.
This function creates a 0-byte file with a unique name, in the directory designated for
temporary files (as specified by the "TMP" or "TEMP" environment variable).
The temporary file name will have the form:
preXXXX.tmp
Where "pre" is the prefix specified by the user, and "XXXX" is a 4-character
hexadecimal string generated to guarantee a unique file name. The file name will
have an extension of ".tmp".
Note: This file will not be automatically deleted by the system. See the function
FileDelete to delete this file.
Example:
tempfile = FileCreateTemp("TMP")
filehandle = FileOpen(tempfile,"WRITE")
FileWrite(filehandle,"Temporary stuff")
347
FileDigest
FileClose(filehandle)
Message(tempfile,"Temp file created")
FileDelete(tempfile)
Message(tempfile,"Temp file deleted")
See Also:
FileDelete, FileOpen
FileDelete
Deletes files.
Syntax:
FileDelete(file-list)
Parameters:
(s) file-list
Returns:
(i)
a string containing one or more filenames, which may be
wildcarded.
@TRUE if all the files were deleted; @FALSE if a file
cannot be deleted (i.e., marked with the READ-ONLY
attribute).
"File-list" may contain * and ? wildcards.
Use this function to delete an individual file, a group of files using wildcards, or
several groups of files by separating the names with a delimiter.
Example:
temp=Environment("TEMP")
DirChange(temp)
testfile1="test1.bak"
testfile2="temp.fil"
handle = fileopen(testfile1, "write")
filewrite(handle, "dummy data one")
fileclose(handle)
handle = fileopen(testfile2, "write")
filewrite(handle, "dummy data two")
fileclose(handle)
Pause("FileDelete","OK to delete *.bak & temp.fil files from %temp%")
FileDelete("*.bak|temp.fil")
See Also:
FileExist, FileLocate, FileMove, FileRename
FileDigest
Computes a message digest (hash) for a file.
348
FileExist
Syntax:
FileDigest(filename,algorithm,format)
Parameters:
(s) filename
(s) algorithm
(i) format
Returns:
(s)
either a fully qualified filename with drive and path, or just
a filename and extension.
specifies the hash algorithm to use, and can be one of the
following: MD2, MD5, SHA, SHA1 (Note that "SHA" and
"SHA1" are the same).
specifies the format of the returned string.
a message digest (hash) for a file.
"format" specifies the format of the returned string. If "format" is 0, the message
digest is returned as an unformatted sequence of hex characters, with each byte in the
digest represented by two hex characters in the returned string. For example:
00112233445566778899AABBCCDDEEFF
00112233445566778899AABBCCDDEEFF00112233
(MD2/MD5 = 16 bytes)
(SHA/SHA1 = 20 bytes)
If "format" is 1, then hyphens (for MD2 and MD5) or spaces (for SHA and SHA1)
are inserted after every 8 characters in the returned string. For example:
00112233-44556677-8899AABB-CCDDEEFF
00112233 44556677 8899AABB CCDDEEFF 00112233
(MD2/MD5 = 16 bytes)
(SHA/SHA1 = 20 bytes)
See Also:
FileExist, FileLocate
FileExist
Tests for the existence of files.
Syntax:
FileExist(filename)
Parameters:
(s) filename
Returns:
(i)
either a fully qualified filename with drive and path, or just
a filename and extension.
1 if the file exists;
0 if it doesn't exist or if the pathname is invalid;
2 if the specified file exists but is currently open by another
application in read deny mode.
If a fully-qualified file name is used, only the specified drive and directory will be
checked for the desired file. If only the root and extension are specified, then first the
349
FileExtension
current directory is checked for the file, and then, if the file is not found in the
current directory, all directories in the DOS path are searched.
FileExist returns "2" if the specified file exists but is currently open by another
application in read deny mode. If you try to access this file using (most of) the other
"File..." functions, it will cause a sharing violation.
FileExist does not support wild-carded file names. Here is a workaround.
if FileItemize("c:\somedir\*.*")==""
message("","No files were found")
else
message("","Files were found")
endif
Examples:
; check for file in current directory
fex = FileExist(StrCat(DirGet( ), "myfile.txt"))
if fex
Message("MyFile.Txt","Is in the current directory")
else
Message("MyFile.Txt","Is NOT in the current directory")
endif
See Also:
DirExist, FileLocate
FileExtension
Returns the extension of a file.
Syntax:
FileExtension(filename)
Parameters:
(s) filename
[optional path]full file name, including extension.
Returns:
(s)
file extension.
This function parses the passed filename and returns the extension part of the
filename.
Example:
; prevent the user from editing a COM or EXE file
allfiles = FileItemize("*.*")
editfile = AskItemList("Select file to edit", allfiles, @TAB,
@unsorted, @single, @false)
ext = FileExtension(editfile)
If (ext == "COM") || (ext == "EXE")
Message ("Sorry", "You may not edit a program file")
else
350
FileGet
Run("notepad.exe", editfile)
endif
See Also:
Dialog, FileBaseName, FilePath, FileRoot
FileFullName
Fleshes out a file name with drive and path information.
Syntax:
FileFullName(partial filename)
Parameters:
(s) partial filename
Returns:
(s)
possibly incomplete filename - missing drive
and/or path.
a complete file name.
Use this function to return the complete file name from a partial file name. Drive and
path information will be added to the file name to create a full file name. If both
drive and path are missing, the currently logged drive and path will be used. If only
drive is missing, the currently logged drive will be used. If drive is specified without
a path, then the currently logged directory on that drive will be used.
Example:
DirChange("C:\TEMP")
a="Test.abc"
b=FileFullName(a)
Message(a,b)
; b will equal C:\TEMP\TEST.ABC
See Also:
AskFileName, ExeTypeInfo, FileBaseName, FileMapName, FileLocate
FileGet
Converts a file to a string variable.
Syntax:
FileGet(filename[,null-char])
Parameters:
(s) filename
(s) null-char
name of the file to read.
[optional] specifies the character which NULL characters
in the file will be replaced with in the string. If omitted or a
blank string (""), then NULL characters will be removed.
351
FileInfoToArray
Returns:
(s)
a string containing the file contents.
Example:
filename = "c:\temp\readme.txt"
data = FileGet(filename , "")
Message(StrCat("Contents of ",filename),data)
See Also:
FilePut, FileRead, IntControl 39
FileGetW
Converts a file to a Unicode string variable.
Syntax:
FileGetW(filename[,null-char])
Parameters:
(s) filename
(s) null-char
Returns:
(s)
name of the file to read.
[optional] specifies the character which NULL characters
in the file will be replaced with in the string. If omitted or a
blank string (""), then NULL characters will be removed.
a Unicode string containing the file contents.
This function is like FileGet, except that the return value is a Unicode string, and
"null-char" specifies a Unicode character.
Example:
filename = "c:\temp\unicode.txt"
data = FileGetW(filename , "")
bytecount = StrByteCount(data)
bb = BinaryAlloc(bytecount)
BinaryPokeStr(bb,0,data)
Message("Unicode data is in the binary buffer.")
BinaryFree(bb)
See Also:
FileGet, FilePutW, IntControl 39
FileInfoToArray
Returns information on a set of files, as an array.
Syntax:
FileInfoToArray(file-list[,flags])
352
FileInfoToArray
Parameters:
(s) file-list
(i) flags
specifies a list of filenames, which may be wildcarded.
[optional] see below.
Returns:
(a)
2-dimension array.
Flags can be set to 0, or can specify one or more of the following values combined
with the bitwise OR ('|') operator:
Flags
0
1
2
Meaning
default
return file sizes as huge numbers. This is a long decimal number string,
which may represent a number too large to be converted to an integer.
Return file names with full paths.
This function creates and returns a 2-dimension array. There are [n + 1] rows in the
array, where 'n' is the number of files that were returned. Each row has 7 columns.
The first row (row 0) is a header containing summary information. Each subsequent
row contains information about one returned file.
The columns are as follows:
Header row:
Column
0
1
2-6
Value
number of files returned
total size of files returned
(unused, set to 0)
Other rows:
Column
0
1
2
3
4
5
6
Value
file name
file size
file last modified time, in YmdHms format
file last accessed time, in YmdHms format
file created time, in YmdHms format
file attribute string in the form "RASH" (see FileAttrGet)
file attribute bitmask (see FileAttrGetEx)
Example:
filelist = StrCat(ShortCutDir("Personal",0,@TRUE),"*.*")
infoarray = FileInfoToArray(filelist, 1|2)
infostr = StrCat("Number of files: ",infoarray[0,0],@Crlf)
353
FileItemize
infostr = StrCat(infostr,"Total size of files: ", infoarray[0,1],
@Crlf, @Crlf)
For xx = 1 to infoarray[0,0]
infostr = StrCat(infostr,"File Name: ",infoarray[xx,0],@Crlf)
infostr = StrCat(infostr,"File Size: ",infoarray[xx,1],@Crlf)
infostr = StrCat(infostr,"Last Modified: ",infoarray[xx,2],@Crlf)
infostr = StrCat(infostr,"Last Accessed: ",infoarray[xx,3],@Crlf)
infostr = StrCat(infostr,"Created: ",infoarray[xx,4],@Crlf)
infostr = StrCat(infostr,"Attribute: ",infoarray[xx,5],@Crlf)
infostr = StrCat(infostr,"Attribute Bitmask: ", infoarray[xx,6],
@Crlf)
infostr = StrCat(infostr,@Crlf)
Next
tmpfile = FileCreateTemp("TMP")
FilePut(tmpfile, infostr)
AskFileText("File Data",tmpfile,@unsorted,@single, @false)
FileDelete(tmpfile)
See Also:
FileItemize, FileAttrGet, FileAttrGetEx, FileTimeGet, FileTimeGetEx, FileSize,
FileSizeEx
FileItemize
Returns a delimited list of files.
Syntax:
FileItemize(file-list)
Parameters:
(s) file-list
Returns:
(s)
a string containing a list of filenames, which may be
wildcarded.
a tab delimited list of files.
This function compiles a list of filenames and separates the names with delimiters.
This is especially useful in conjunction with the AskItemList function, which lets
the user choose an item from such a delimited list.
Note: Some shell or file manager applications using the WIL Interpreter allow an
empty string ("") to be used as the "file-list" parameter, in which case all files
highlighted in the file display are returned. However, if there are any file names or
wildcards in the string, all files matching the file names are returned, regardless of
which ones are highlighted.
By default hidden and system files are ignored. IntControl 5 can be used to control
whether or not hidden files are processed by this function.
354
FileItemPath
Example:
a = FileItemize("*.bak")
;all BAK files
b = FileItemize("*.arc|*.zip|*.lzh")
;compressed files
; Get which .INI file to edit
ifiles = FileItemize("c:\windows\*.ini")
ifile = AskItemList(".INI Files", ifiles, @TAB, @unsorted, @single,
@false)
RunZoom("notepad", ifile)
Drop(ifiles, ifile)
See Also:
FileInfoToArray, FileItemPath, CurrentFile, DirItemize, AskItemList, AskFileText,
IntControl 5, IntControl 29, IntControl 91
FileItemPath
Returns a delimited list of file paths.
Syntax:
FileItemPath(file-list)
Parameters:
(s) file-list
Returns:
(s)
a string containing a list of filenames, which may be
wildcarded.
a delimited list of file paths.
This function compiles a list of filepaths and separates the names with delimiters.
This function is like FileItemize, but the list of file names it returns contains full
path information.
This is especially useful in conjunction with the AskItemList function, which lets
the user choose an item from such a delimited list.
Note: Some shell or file manager applications using the WIL Interpreter allow an
empty string ("") to be used as the "file-list" parameter, in which case all files
highlighted in the file display are returned. However, if there are any file names or
wildcards in the string, all files matching the file names are returned, regardless of
which ones are highlighted.
By default hidden and system files are ignored. IntControl 5 can be used to control
whether or not hidden files are processed by this function.
Examples:
a = FileItemPath("*.bak")
;all BAK files
b = FileItemPath("*.arc|*.zip|*.lzh")
;compressed files
; Get which .INI file to edit
355
FileMapName
DirChange("c:\windows")
ifiles = FileItemPath("*.ini")
ifile = AskItemList(".INI Files", ifiles, @TAB, @unsorted, @single,
@false)
RunZoom("notepad", ifile)
See Also:
FileItemize, CurrentFile, DirItemize, AskItemList, IntControl 5, WinItemize
FileLocate
Finds file in current directory or along the DOS path.
Syntax:
FileLocate(filename)
Parameters:
(s) filename
full file name, including extension.
Returns:
(s)
fully-qualified path name.
This function is used to obtain the fully qualified path name of a file. The current
directory is checked first, and if the file is not found, the DOS path is searched. The
first occurrence of the file is returned.
Example:
; Edit WIN.INI
winini = FileLocate("win.ini")
If winini == ""
Message("???", "WIN.INI not found")
else
Run("notepad.exe", winini)
endif
See Also:
FileExist
FileMapName
Transforms a filename with a file wildcard mask and returns a new filename.
Syntax:
FileMapName(filename,mapping-data).
Parameters:
(s) filename
(s) mapping-data
356
full or partial file name.
mapping and wildcard definition string (see below).
FileMapName
Returns:
(s)
transformed file name.
Use this function to generate a new filename based on an old filename. It can be used
to generate *.bak filenames easily, or to perform assorted wildcard transformations
on a filename.
The mapping-data consists of the normal [optional] drive, path, legal filename
characters, the period, and two special wildcard characters, the asterisk (*) and the
question mark (?). The following algorithm is used to transform the file name:
1)
drive.
If drive is specified in the mapping-data use specified drive, else use current
2)
If path is specified in the mapping-data use specified path, else use current
path on the drive selected above.
3)
Examine root of the filename and root position of mapping-data, sequencing
through the root characters together, one character at a time.
map-char
root transformation rule
.
If the mapping data position character is a period, stop
processing the root filename, add a period to the end of the
new filename string and proceed to process the extension as
outlined below.
*
If mapping data position is a asterisk, copy remainder of root
file name to new filename string and proceed to process the
extension as outlined below.
?
If mapping data position is a question mark, copy the current
character from the root filename to the new filename string.
other
If the mapping data character is not one of the above, copy the
map character to the new filename string and ignore the
corresponding character in the root filename.
<none>
If there are no more characters in the mapping-data string,
filename generation is complete. Return with the new string.
4)
Examine extension of the filename and extension position of mapping-data,
sequencing through the extension characters together, one character at a time.
map-char
extension transformation rule
*
If mapping data position is a asterisk, copy remainder of
extension file name to new filename string and return.
?
If mapping data position is a question mark, copy the current
character from the extension filename to the new filename
string.
357
FileMove
other
If the mapping data character is not one of the above, copy the
map character to the new filename string and ignore the
corresponding character in the extension filename.
<none>
If there are no more characters in the mapping-data string,
filename generation is complete. Return with the new string.
Example:
DirChange("C:\TEMP")
a=FileMapName("d:\sample\xxx.txt", "*.bak")
Message("New filename", a)
; This will return C:\TEMP\XXX.BAK
a=FileMapName("d:\sample\xxx.txt", "c:\demo\??Q.bak")
Message("New filename", a)
; This will return C:\DEMO\XXQ.BAK
See Also:
AskFileName, FileFullName, FileCopy, FileMove
FileMove
Moves files.
Syntax:
FileMove(source-list,destination,warning)
Parameters:
(s) source-list
(s) destination
(i) warning
Returns:
(i)
one or more filenames separated by a delimiter.
target filename.
@TRUE for a warning before overwriting existing files;
@FALSE if no warning desired.
@TRUE if the file was moved; @FALSE if the source file
was not found, or the target filename is invalid.
Use this function to move an individual file, a group of files using wildcards, or
several groups of files by separating the names with a delimiter.
You can move files to another drive. You can also move a file to a COM or LPT
port, which would cause the file to be copied to the port and then deleted (do not put
a colon after the name of the port).
"Source-list" and "destination" may contain * and ? wildcards.
Examples:
;Example one
temp=Environment("TEMP")
DirChange(temp)
testfile="test.txt"
destination="C:\Backup"
358
FileMoveAttr
If DirExist(destination)
FileMove(testfile, destination, @FALSE)
Message("FileMove","File Moved")
Endif
;Example two
temp=Environment("TEMP")
DirChange(temp)
testfile1="test1.txt"
testfile2="test2.txt"
handle = fileopen(testfile1, "write")
filewrite(handle, "dummy data one")
fileclose(handle)
FileMove(testfile1, testfile2, @FALSE)
Message("FileMove","File Moved")
See Also:
FileMoveAttr, FileCopy, FileDelete, FileExist, FileLocate, FileRename, IntControl
29
FileMoveAttr
Moves files, and sets file attributes.
Syntax:
FileMoveAttr(source-list,destination,warning,attributes)
Parameters:
(s) source-list
(s) destination
(i) warning
(s) attributes
Returns:
(i)
one or more filenames separated by a delimiter.
target filename.
@TRUE for a warning before overwriting existing files;
@FALSE if no warning desired.
attributes to be modified.
@TRUE if the file was moved; @FALSE if the source file
was not found, or the target filename is invalid.
Use this function to move an individual file, a group of files using wildcards, or
several groups of files by separating the names with a delimiter.
You can move files to another drive. You can also move a file to a COM or LPT
port, which would cause the file to be copied to the port and then deleted (do not put
a colon after the name of the port).
"Source-list" and "destination" may contain * and ? wildcards.
The "attribute" string consists of one or more of the following characters (an upper
case letter turns the specified attribute ON, a lower case letter turns it OFF):
359
FileNameShort
Symbol
R
A
S
H
Meaning
read only ON
archive ON
system ON
hidden ON
Symbol
r
a
s
h
Meaning
read only OFF
archive OFF
system OFF
hidden OFF
Example:
temp=Environment("TEMP")
DirChange(temp)
testfile1="test1.txt"
testfile2="test2.txt"
handle = fileopen(testfile1, "write")
filewrite(handle, "dummy data one")
fileclose(handle)
FileMoveAttr(testfile1, testfile2, @FALSE,"R")
Message("FileMove","File Moved with Read Only attribute set")
See Also:
FileMove, FileCopy, FileDelete, FileExist, FileLocate, FileRename, IntControl 29
FileNameLong
Returns the long version of a filename.
Syntax:
FileNameLong(filename)
Parameters:
(s) filename
fully qualified file name, path optional.
Returns:
(s)
the long version of a filename.
FileNameLong searches the path for the filename specified, returning the long
filename if found.
Example:
DirChange("C:\windows")
a=FileNameLong("carved~1.bmp")
message("Long Filename", a)
See Also:
FileFullName, FileNameShort
FileNameShort
Returns the short (i.e., 8.3) version of a filename.
360
FileOpen
Syntax:
FileNameShort(filename)
Parameters:
(s) filename
fully qualified file name, path optional.
Returns:
(s)
the short version of a filename.
FileNameShort searches the path for the filename specified, returning the short
filename if found.
Example:
DirChange("C:\windows")
a=FileNameShort("carved stone.bmp")
message("Short Filename", a)
See Also:
FileFullName, FileNameLong
FileOpen
Opens a file for reading, writing or appending.
Syntax:
FileOpen(filename,mode[,Unicode[,timeout]])
Parameters:
(s) filename
(s) mode
(i) Unicode
(i) timeout
Returns:
(i)
name of the file to open.
"READ", "WRITE", or "APPEND"
If "Unicode" is @TRUE, the file will be treated as
containing Unicode data, otherwise it will be treated
as containing ANSI data.
number of seconds to spend retrying the file open operation
if it fails due to a sharing violation.
filehandle, or 0 on error.
The "filehandle" returned by the FileOpen function may be subsequently used by the
FileRead, FileWrite, and FileClose functions. If the file cannot be opened as
requested, and errors are suppressed with Errormode then FileOpen returns a
filehandle of 0.
You may have a maximum of 128 files open at one time.
FileOpen on an existing file in "WRITE" mode, will overwrite (zero out) the file. If
you specify a non-existing file in "WRITE" or "APPEND" mode, it will create the
file.
361
FileOpen
FileOpen by default expects each line to be terminated with a line feed character.
The file must be some type of standard text file. The binary operations may be used
for non-text files.
The "Unicode" option will affect how FileRead and FileWrite process the file data.
If the file is opened in "APPEND" mode, subsequent calls to FileWrite always write
the data in the format of the existing text in the file. If you open the file in
"WRITE" mode, then FileWrite will write the text lines according to the unicode
parameter:
Mode
APPEND
APPEND
WRITE
WRITE
Unicode
ignored
ignored
@FALSE(default)
@TRUE
Text in file
ANSI
Unicode
ignored
ignored
FileWrite output format
ANSI
Unicode
ANSI
Unicode
By default, if the file is opened in "READ" mode then subsequent calls to FileRead
will read the text lines as they exist in the file. But if Unicode is @TRUE, then
FileRead will always return the string as Unicode:
Mode
READ
READ
READ
Unicode
@FALSE(default)
@FALSE(default)
@TRUE
Text in file
ANSI
Unicode
ignored
FileRead return format
ANSI
Unicode
Unicode
The "timeout" option specifies the number of seconds to spend retrying the file open
operation if it fails due to a sharing violation. The default is 0, for no retry. If
"timeout" is 1 to 20, the operation will be retried 20 times, evenly-spaced over the
specified time period. If "timeout" is greater than 20, the operation will be retried
once every second for the specified time period. If "timeout" is -1, the operation will
be retried once every second with no timeout. If the file can be opened before the
specified time period has elapsed, FileOpen will return successfully, otherwise it
will fail.
Examples:
; To open for reading:
handle = FileOpen("stuff.txt", "READ")
; To open for writing:
handle = FileOpen("stuff.txt", "WRITE")
; To open for appending:
handle = FileOpen("stuff.txt", "APPEND")
Temp = environment("temp")
if strsub(temp,strlen(temp),1)!="\" then temp=strcat(temp,"\")
testfile1=strcat(temp,"test1.txt")
handle=fileopen(testfile1, "write")
362
FilePut
filewrite(handle, "dummy data one")
fileclose(handle)
Message("FileOpen","File %testfile1% created")
See Also:
Binary Operations, BinaryRead, BinaryReadEx, BinaryWrite,BinaryWriteEx,
IntControl 40, IntControl 39, IntControl 94, FileClose, FileRead, FileWrite
FilePath
Returns the path of a file.
Syntax:
FilePath(filename)
Parameters:
(s) filename
fully qualified file name, including path.
Returns:
(s)
fully qualified path name.
FilePath parses the passed filename and returns the drive and path of the file
specification, if any.
Example:
coms = Environment("COMSPEC")
compath = FilePath(coms)
Message("Your command processor is located in", compath)
See Also:
CurrentPath, FileExtension, FileRoot
FilePut
Writes a string to a file.
Syntax:
FilePut(filename,string)
Parameters:
(s) filename
(s) string
name of the file to write to.
string to write to the file.
Returns:
(i)
number of bytes written to the file.
If "filename" exists, it will be overwritten.
Example:
filename = "c:\temp\readme.txt"
363
FileRead
str = "Hello World"
data = FilePut(filename , str)
Message("Done", "Writing string to file")
See Also:
FileGet, FilePutW, FileWrite, IntControl 40
FilePutW
Writes a Unicode string to a file.
Syntax:
FilePutW(filename,Unicode string)
Parameters:
(s) filename
(s) Unicode string
Returns:
(i)
name of the file to write to.
Unicode string to write to the file.
the number of bytes (not characters) written to the file.
This will include a 2-byte Unicode header written to the
beginning of the file.
If "filename" exists, it will be overwritten.
This function is like FilePut, except that "string" specifies a Unicode string.
Example:
Filename = StrCat(DirScript(),"Unicode.txt")
Unicodestr = AskLine("First Name", "Please Enter your first name",
"Bob", 1)
data = FilePutW(filename, unicodestr)
Message("Done", "Writing Unicode string to file")
See Also:
FileGetW, FilePut, IntControl 40
FileRead
Reads data from a file.
Syntax:
FileRead(filehandle)
Parameters:
(i) filehandle
same integer that was returned by FileOpen.
Returns:
(s)
line of data read from file.
364
FileRename
When the end of the file is reached, the string *EOF* will be returned.
Note: This function expects standard DOS CR-LF terminated lines in the file. It will
read the next unread line from the file and return that line without the CR-LF on the
end. FileRead strips out any NULL's from the file being read.
Also, the default maximum length of a line, which can be read using the FileRead
function is 4096 bytes. If you need to increase the length of line that FileRead can
read see IntControl 65.
FileRead can be used to read files containing Unicode data, and will automatically
determine the correct file type (ANSI or Unicode), regardless of the "Unicode"
parameter in FileOpen, and will convert the return string if necessary.
Example:
;Read through file line by line
testfile = FileLocate("win.ini")
handle = FileOpen(testfile, "READ")
count = 0
while @TRUE
; Loop till break do us end
line = FileRead(handle)
If line == "*EOF*" Then Break
count = count + 1
Message(StrCat("Line # ",count), line)
endwhile
FileClose(handle)
See Also:
FileClose, FileGet, FileOpen, FileWrite, IntControl 65
FileRename
Renames files.
Syntax:
FileRename(source-list,destination)
Parameters:
(s) source-list
(s) destination
one or more filenames, separated by a tab delimiter.
target filename.
Returns:
(i)
@TRUE if the file was renamed.
Use this function to rename an individual file, a group of files using wildcards, or
several groups of files by separating the names with a delimiter.
Note: Unlike FileMove, you cannot make a file change its resident disk drive with
FileRename.
"Source-list" and "destination" may contain * and ? wildcards.
365
FileSize
Examples:
;Sample 1
FileRename("c:\config.sys", "config.old")
;Sample 2
FileRename("c:\*.txt", "*.bak")
See Also:
FileCopy, FileExist, FileLocate, FileMove, IntControl 29
FileRoot
Returns root of file.
Syntax:
FileRoot(filename)
Parameters:
(s) filename
[optional path] full file name, including extension.
Returns:
(s)
file root.
FileRoot parses the passed filename and returns the root part of the filename.
Example:
allfiles = FileItemize("*.*")
editfile = AskItemList("Select file to edit", allfiles,@TAB,
@unsorted, single, @false)
root = FileRoot(editfile)
ext = FileExtension(editfile)
lowerext = StrLower(ext)
nicefile = StrCat(root, ".", lowerext)
Message("", "You are about to edit %nicefile%.")
Run("notepad.exe", editfile)
See Also:
FileBaseName, FileExtension, FilePath
FileSize
Finds the total size of a group of files.
Syntax:
FileSize(file-list[,format])
Parameters:
(s) file-list
(i) format
366
zero or more filenames, separated by a delimiter and may
contain wildcards.
[optional] controls the format in which the size is returned.
FileSizeEx
Returns:
(i)
total bytes taken up by the specified file(s).
This function returns the total size of the specified files. "File-list" may contain * and
? wildcards.
Format is an optional parameter that controls the format in which the size is returned.
If the result is too large to be returned as an integer (larger than 2 gigabytes).
Format
Meaning
0
(Default) Floating Point
1
Huge number. This is a long decimal number string, which may
represent a number too large to be converted to an integer.'Huge
number' is a special data type. It is a long decimal number string,
which may represent a number too large to be converted to an
integer. This value cannot be modfied with standard arithmetic
operations, it requires the use of the Huge Math extender.
FileSizeEx can be used to get the size of files that are open in 'read deny' by other
applications.
Example:
size = FileSize("*.*")
Message("Size of All Files in Directory", size)
See Also:
FileSizeEx, FileInfoToArray, DiskFree
FileSizeEx
Finds the total size of a group of files(including open files).
Syntax:
FileSizeEx(file-list[,format])
Parameters:
(s) file-list
(i) format
zero or more filenames which may contain * and ?
wildcards., separated by a delimiter.
[optional] controls the format in which the size is returned,
if it is too large to be returned as an integer.
0 - (default) The return value will be a floating point
number if it is larger than 2 gigabytes.
1 - the size will be returned as a huge number. This is a
long decimal number string, which may represent a number
too large to be converted to an integer.
367
FileTimeCode
Returns:
(i)
total bytes taken up by the specified file(s).
This function returns the total size of the specified files.
"File-list" may contain * and ? wildcards.
This function is like FileSize, but can be used to get the size of files that are open by
other applications (which FileSize cannot).
Format is an optional parameter that controls the format in which the size is returned.
If the result is too large to be returned as an integer (larger than 2 gigabytes).
Format
Meaning
0
(Default) Floating Point
1
Huge number. This is a long decimal number string, which may
represent a number too large to be converted to an integer.'Huge
number' is a special data type. It is a long decimal number string,
which may represent a number too large to be converted to an
integer. This value cannot be modfied with standard arithmetic
operations, it requires the use of the Huge Math extender.
Example:
size = FileSizeEx("*.*")
Message("Size of all (including open) Files in Directory", size)
See Also:
FileSize, FileInfoToArray, DiskFree
FileTimeCode
Returns a machine readable/computable code for a file time.
Syntax:
FileTimeCode(filename)
Parameters:
(s) filename
file name to get the time code from.
Returns:
(i)
file time code.
Use this function to return an 32 bit integer representing the current file time stamp.
This number may be compared to other file times to compare ages of files. It is
basically the DOS 16 bit date and the DOS 16 bit time in a 32 bit integer. This
function returns a valid, comparable time through the year 2044.
368
FileTimeGet
Example:
a=FileTimeCode("C:\AUTOEXEC.BAT")
b=FileTimeCode("C:\CONFIG.SYS")
if a == b
ans="Same Time"
else
if a > b
ans = "AutoExec newer than Config"
else
ans = "AutoExec older than Config"
endif
endif
Message("Comparing file times", ans)
See Also:
FileTimeGet, FileTimeGetEx, FileYmdHms
FileTimeGet
Returns file date and time in a human readable format.
Syntax:
FileTimeGet(filename)
Parameters:
(s) filename
Returns:
(s)
name of file for which you want the date and time.
file time in YmdHms format:
(YYYY:MM:DD:HH:MM:SS.).
This function will return the date and time of a file, in a pre-formatted string. The
format of the string depends on the current settings in the [Intl] section of the registry
key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows
NT\CurrentVersion\IniFileMapping\win.ini[Intl]
The registry value will be examined to determine which format to use. You can
adjust the registry value via the Regional and Language Options icon in Control
Panel if the format isn't what you prefer.
Note: If you must parse the time data returned by this function, use the ParseData
function to break the day, date, and time into separate components. However you
should check the FileYmdHms and FileTimeCode functions first.
Example:
oldtime = FileTimeGet("C:\windows\win.ini")
RunWait("notepad.exe", "win.ini")
newtime = FileTimeGet("C:\windows\win.ini")
If StrCmp(oldtime, newtime) == 0
Message("WIN.INI not changed", "Last change was %oldtime%")
else
369
FileTimeSet
Message("WIN.INI modified", "New time stamp is %newtime%")
endif
See Also:
FileTimeGetEx, FileTimeCode, TimeDate, FileAttrGet, FileTimeTouch,
FileTimeSet, FileTimeSetEx, FileYmdHms, FileInfoToArray
FileTimeGetEx
Gets extended time information for a file or directory.
Syntax:
FileTimeGetEx(filename,time-field)
Parameters:
(s) filename
(i) time-field
Returns:
(s)
specifies a file or directory name.
see below.
file time in YmdHms format:
(YYYY:MM:DD:HH:MM:SS).
This function is like FileYmdHms, but works with directories as well as files, and
lets you specify which time field you want to get. "Filename" can specify a file or
directory name.
"Time-field" can be one of the following:
1
file created
2
file last modified
3
file last accessed
Example:
oldtime = FileTimeGetEx("C:\windows\win.ini",2)
RunWait("notepad.exe", "win.ini")
newtime = FileTimeGetEx("C:\windows\win.ini",2)
If StrCmp(oldtime, newtime) == 0
Message("WIN.INI not changed", "Last change was %oldtime%")
else
Message("WIN.INI modified", "New time stamp is %newtime%")
endif
See Also:
FileTimeGet, FileTimeCode, TimeDate, FileAttrGet, FileTimeTouch, FileTimeSet,
FileTimeSetEx, FileYmdHms
FileTimeSet
Sets the date and time of one or more files.
370
FileTimeSetEx
Syntax:
FileTimeSet(file-list,datetime)
Parameters:
(s) file-list
(s) datetime
Returns:
(i)
filename, list of files, or list of wildcards of files to set.
datetime in the YmdHms format
@TRUE all files specified were time stamped;
@FALSE one or more files were not time stamped.
Use this function to reset the date and time of a specific file or list of files.
Example:
; Alter time of the WIN.INI file
winini= FileLocate("Win.ini")
b=FileYmdhms(winini)
Message("File Time for %winini% is", b)
a="1999:02:14:09:38:26"
FileTimeSet(winini, a)
b=FileYmdhms(winini)
Message("File Time for %winini% is now", b)
See Also:
FileTimeSetEx, GetExactTime, FileYmdHms, IntControl 29, TimeDiffDays,
TimeDiffSecs, TimeYmdHms
FileTimeSetEx
Sets extended time information for one or more files.
Syntax:
FileTimeSetEx(file-list,datetime,time-field)
Parameters:
(s) file-list
(s) datetime
(i) time-field
Returns:
(i)
filename, list of files, or list of wildcards of files to set.
datetime in the YmdHms format
see below.
@TRUE on success; @FALSE if any of the specified files
could not be changed.
"Time-field" can be one of the following:
1
file created
2
file last modified
3
file last accessed
371
FileTimeTouch
This function is like FileTimeSet, but lets you specify which time field you want to
set.
Example:
; Alter time of the WIN.INI file
winini= FileLocate("Win.ini")
b=FileYmdhms(winini)
Message("File Time for %winini% is", b)
a="1999:02:14:09:38:26"
FileTimeSetEx(winini, a, 2)
b=FileYmdhms(winini)
Message("File Time for %winini% is now", b)
;Alter the time of all files in the temp directory
a=TimeYmdHms( )
Temp = environment("temp")
if strsub(temp,strlen(temp),1)!="\" then temp=strcat(temp,"\")
FileTimeSetEx("%temp%*.*", a, 2)
See Also:
FileTimeSet, GetExactTime, FileYmdHms, TimeDiffDays, TimeDiffSecs,
TimeYmdHms
FileTimeTouch
Sets file(s) to current date and time.
Syntax:
FileTimeTouch(file-list)
Parameters:
(s) file-list
a delimited list of files
Returns:
(i)
@FALSE.
"File-list" is a delimited list of files, which may contain wildcards. The path is
searched if the file is not found in current directory and if the directory is not
specified in "file-list".
Example:
;Alter the time of all files in the temp directory
Temp = environment("temp")
if strsub(temp,strlen(temp),1)!="\" then temp=strcat(temp,"\")
FileTimeTouch("%temp%*.*")
a=TimeYmdHms( )
Message("FileTimeTouch","All files in %temp% set to %a%")
See Also:
FileAttrSet, FileTimeGet, IntControl 29
372
FileVerInfo
FileVerInfo
Returns a version resource string from a binary file.
Syntax:
FileVerInfo(filename,language-key,resource-string)
Parameters:
(s) filename
(s) language-key
(s) resource-string
Returns:
(s)
name of the EXE, DLL, or other binary file containing
version resource information.
a hexadecimal string identifying the desired language and
character-set block within the file's resource table.
specifies the item to return. (see below.)
version resource string from binary file or a blank string ("")
if the specified item was not found.
Note: if you specify blank strings for both "language-key" and "resource-string", it
will now return a tab-delimited list of language keys for which version information is
available in the specified file.
"Language-key" is a hexadecimal string identifying the desired language and
character-set block within the file's resource table. U.S. English (w/ Windows
Multilingual character set) is "040904E4".
You can specify a blank string ("") to indicate U.S. English, which will almost
always be appropriate. if you specify a blank string for "language-key", it will try to
look up the item under the following language keys, in the specified order:
language-key
040904E4
040904B0
000004E4
04090000
00000000
000004B0
language
U.S. English
U.S. English
Neutral
U.S. English
Neutral
Neutral
character set
Windows Multilingual
Unicode
Windows Multilingual
Neutral
Neutral
Unicode
For a list of all the possible language keys see the WIL help file.
"Resource-string" specifies the item to return. The following are standard item names
(although some of these are optional and will not necessarily be present in any
particular file):
"Comments"
"CompanyName"
"FileDescription"
"FileVersion"
"InternalName"
"LegalCopyright"
"LegalTrademarks"
"OriginalFilename"
"ProductName"
"ProductVersion"
373
FileVerInfo
Note: FileVerInfo can return numeric version fields, by preceding the resource
string name with a '#'.
The following are available:
"#FileVersion"
"#ProductVersion"
"#FileFlagsMask"
"#FileFlags"
"#FileOS"
"#FileType"
"#FileSubtype"
"#FileVersion" and "#ProductVersion" are 64-bit numbers, and are returned as
comma-separated strings in the form "n1,n2,n3,n4", where n1 is the most significant
word and n4 is the least significant word. The other fields each return a single 32-bit
number.
Example:
; Version Information Example WinBatch Script
FileN = FileLocate("explorer.exe")
ErrorMode(@OFF)
FComments = FileVerInfo(FileN, "", "Comments")
FCompany = FileVerInfo(FileN, "", "CompanyName")
FDescription = FileVerInfo(FileN, "", "FileDescription")
FVersion = FileVerInfo(FileN, "", "FileVersion")
FInternalName = FileVerInfo(FileN, "", "InternalName")
FLegalCopyright = FileVerInfo(FileN, "", "LegalCopyright")
FOriginalFilename = FileVerInfo(FileN, "", "OriginalFilename")
FProductName = FileVerInfo(FileN, "", "ProductName")
FProductVersion = FileVerInfo(FileN, "", "ProductVersion")
ErrorMode(@Cancel)
DlgFormat=`WWWDLGED,6.2`
DlgCaption=`FileVerInfo`
DlgX=004
DlgY=021
DlgWidth=240
DlgHeight=147
DlgNumControls=019
DlgProcedure=`DEFAULT`
DlgFont=`DEFAULT`
DlgTextColor=`DEFAULT`
DlgBackground=`DEFAULT,DEFAULT`
DlgConfig=0
Dlg001=`067,003,168,014,VARYTEXT,"VaryText_1",FComments,DEFAULT,DEFAU
LT,1,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Dlg002=`003,003,066,014,STATICTEXT,"StaticText_Comments:",DEFAULT,"Co
mments:",DEFAULT,2,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Dlg003=`003,017,064,014,STATICTEXT,"StaticText_Company:",DEFAULT,"Com
pany:",DEFAULT,3,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
374
FileWrite
Dlg004=`067,017,168,014,VARYTEXT,"VaryText_2",FCompany,DEFAULT,DEFAUL
T,4,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Dlg005=`003,031,064,014,STATICTEXT,"StaticText_Description:",DEFAULT,
"Description:",DEFAULT,5,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Dlg006=`067,031,168,014,VARYTEXT,"VaryText_3",FDescription,DEFAULT,DE
FAULT,6,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Dlg007=`003,045,064,014,STATICTEXT,"StaticText_Version:",DEFAULT,"Ver
sion:",DEFAULT,7,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Dlg008=`067,045,168,014,VARYTEXT,"VaryText_4",FVersion,DEFAULT,DEFAUL
T,8,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Dlg009=`003,059,064,014,STATICTEXT,"StaticText_5",DEFAULT,"Internal
Name:",DEFAULT,9,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Dlg010=`067,059,168,014,VARYTEXT,"VaryText_5",FInternalName,DEFAULT,D
EFAULT,10,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Dlg011=`003,073,064,014,STATICTEXT,"StaticText_6",DEFAULT,"Legal
Copyright:",DEFAULT,11,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Dlg012=`067,073,168,014,VARYTEXT,"VaryText_6",FLegalCopyright,DEFAULT
,DEFAULT,12,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Dlg013=`003,087,064,014,STATICTEXT,"StaticText_7",DEFAULT,"Original
Filename:",DEFAULT,13,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Dlg014=`067,087,168,014,VARYTEXT,"VaryText_7",FOriginalFilename,DEFAU
LT,DEFAULT,14,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Dlg015=`003,101,064,014,STATICTEXT,"StaticText_8",DEFAULT,"Product
Name:",DEFAULT,15,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Dlg016=`067,101,168,014,VARYTEXT,"VaryText_8",FProductName,DEFAULT,DE
FAULT,16,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Dlg017=`003,115,064,014,STATICTEXT,"StaticText_9",DEFAULT,"Product
Version:",DEFAULT,17,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Dlg018=`067,115,168,014,VARYTEXT,"VaryText_9",FProductVersion,DEFAULT
,DEFAULT,18,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
Dlg019=`087,129,064,014,PUSHBUTTON,"PushButton_Ok",DEFAULT,"Ok",1,19,
DEFAULT,DEFAULT,DEFAULT,DEFAULT`
ButtonPushed=Dialog("Dlg")
See Also:
DOSVersion, Environment, Version, VersionDLL, WinVersion
FileWrite
Writes data to a file.
Syntax:
FileWrite(filehandle,output-data)
Parameters:
(i) filehandle
(s) output-data
same integer that was returned by FileOpen.
data to write to file.
Returns:
(i)
@FALSE.
375
FileYmdHms
Note: This function will append a CR-LF line terminator to the end of each line
written to the file, or as directed by IntControl 53.
If the file is opened in "APPEND" mode, subsequent calls to FileWrite always write
the data in the format of the existing text in the file.
If you open the file in "WRITE" mode, then FileWrite will write the text lines
according to the unicode parameter:
Mode
APPEND
APPEND
WRITE
WRITE
Unicode
ignored
ignored
@FALSE(default)
@TRUE
Text in file
ANSI
Unicode
ignored
ignored
FileWrite output format
ANSI
Unicode
ANSI
Unicode
Example:
handle = FileOpen("stuff.txt", "WRITE")
FileWrite(handle, "Gobbledygook")
FileClose(handle)
Message("FileWrite","File Written.")
See Also:
FileClose, FileOpen, FilePut, FileRead, IntControl 53
FileYmdHms
Returns a file time in the YmdHms date time format.
Syntax:
FileYmdHms(filename)
Parameters:
(s) filename
filename.
Returns:
(s)
file time in YmdHms format.
Use this function to retrieve a file time in the YmdHms datetime format.
Example:
b=FileYMDHMS("C:\CONFIG.SYS")
Message("File Time is", b)
See Also:
FileTimeGet, FileTimeGetEx, TimeDate, TimeAdd, TimeDiffDays, TimeYmdHms,
TimeDelay, TimeWait
376
Floor
FindWindow
Returns a window title matching a specified class name.
Syntax:
FindWindow(class name)
Parameters:
(s) class name
the full unique window class name.
Returns:
(s)
a window title.
FindWindow returns the window title of the first window whose class name
matches the specified "class-name". It can be used to manipulate windows when the
title is either unknown or there are several windows with the same title. A blank
string ("") is returned if no matching window is found.
Note: "Class-name" is not case sensitive but must be the full class name (i.e., not a
partial name).
Example:
run("explorer.exe",strcat("/n,/e,",DirGet( )))
while FindWindow("ExploreWClass")==""
;wait for it to come up
Timedelay(1)
endwhile
See Also:
IntControl 44
Floor
Calculates the floor of a value.
Syntax:
Floor(x)
Parameters:
(f) x
Returns:
(f)
value Floor is calculated from.
a floating point number whose value represents the largest
integer that is less than or equal to x.
Use this function to calculate the floor of a value.
Example:
; This example accepts a value from the user to calculate
; the ceiling and floor.
a=AskLine("Ceiling and Floor", "Please enter a number", "1.23", 0)
c=Ceiling(a)
377
For
f=Floor(a)
Message("Ceiling and Floor of %a%", "Ceiling: %c%
A=
25.2
25.7
24.9
-14.3
Ceiling=
26.0
26.0
25.0
-14.0
Floor: %f%")
Floor=
25.0
25.0
24.0
-15.0
See Also:
Abs, Ceiling, Fabs, Min, Max
For
Controls the looping of a block of code based on an incrementing index.
Syntax:
For var-name = initial-value to last-value [ by increment]
Parameters:
(s) var-name
(f) initial-value
(f) last-value
(f) increment
a variable name to be used for the loop index.
an expression used to set the initial value of the loop index.
an expression that defines last value to be used in the loop.
When the initial value is incremented past the last value, the
loop terminates.
an expression that defines the amount to increment the loop
index on each pass through the loop. The default is one. The
increment may be negative.
Use the For statement to execute a block of code a fixed number of times. When the
For statement is executed, it initializes the specified variable "var-name" to the
"initial-value" This variable is called the "loop index". It then tests the "loop index"
with the "last value". If the "increment" is positive and the "loop index" is greater
than the last value, or if the "increment" is negative and the "loop index" is less than
the last value, then the loop terminates and control is passed to the statement after the
Next statement.
Otherwise the statements below the For are executed until the Next statement is
reached. When the Next statement is reached, control returns to the For statement so
that the "loop index" may be incremented and the test for "last value" repeated.
Example:
; Compute sum of numbers between 1 and selected number
a=AskLine("Sums", "Please enter a number", 5, 0)
f=0
For j = 1 to a
f = f + j
378
ForEach
Next
Message("Sum [ 1 to %a% ] is", f)
;Compute factorials
a=AskLine("Factorials", "Please enter a number", 5, 0)
f=1
For j = a to 2 by -1
f=f*j
Next
Message("%a% Factorial is", f)
See Also:
Break, Continue, If, Select, Switch, While
ForEach
The ForEach loop is similar to the For loop, but it executes the statement block for
each element in a collection, instead of a specified number of times.
Syntax:
ForEach Elementvariable In Collection
…
Next
Parameters:
(*) Elementvariable
(r) Collection
A variable name.
A COM/OLE collection object reference, or object property
or method holding a collection.
For each iteration of the loop, WinBatch sets the variable Elementvariable to one of
the elements in Collection and executes the statement block between the ForEach
and Next. When all the elements in Collection have been assigned to
Elementvariable, the ForEach loop terminates and control passes to the statement
following the Next statement.
If Elementvariable is not used before the loop, it will be created for you. If it is used
before the loop, the previously existing value of the variable is lost when the
ForEach statement executes for the first time.
The elements of Collection can be of any data type, so the data assigned to
elementvariable can be of any supported type including object references.
After the loop terminates, Elementvariable contains the last element of the
collection. If the elements of the collection are object references, you are responsible
for releasing the last references with an assignment statement or the ObjectClose
function.
To terminate a loop before the last element of the Collection is assigned to
ElementVarible use a break statement. Goto statments are not permitted inside of
ForEach...Next loops and will cause WinBatch to generate an error message.
379
ForEach
It recommended that you not modify the Elementvariables in a ForEach...Next loop.
Any modification you make may affect only the local copy of the element and may
not be reflected back into the collection. Attempts to modify an element may also
generate an error message
It is also recommended that you not alter the collection by adding, deleting,
replacing, or reordering any elements. If you alter the collection after you have
initiated a ForEach...Next loop, the Collection object becomes invalid, and the next
attempt to access an element may result in an error message or other unexpected
behavior.
You can iterate through single dimension arrays returned by object properties and
methods with a ForEach...Next loop. However, you should not attempt to change
array elements from within the loop.
Example:
This example uses a ForEach … Next loop and WMI to collect information on all
installed printers on the local machine.
objWMIService =
ObjectGet("winmgmts:{impersonationLevel=impersonate}!\
\.\root\cimv2")
colInstalledPrinters =
objWMIService.ExecQuery("Select * from Win32_Printer")
sPrinterInfo = ""
; Iterate through each printer and collect
ForEach objPrinter in colInstalledPrinters
sPrinterInfo = strcat(sPrinterInfo, "Name: ",
objPrinter.Name, @crlf)
sPrinterInfo = strcat(sPrinterInfo, "Location: ",
objPrinter.Location, @crlf)
if objPrinter.Default
sYesNo = "Yes"
else
sYesNo = "No"
endif
sPrinterInfo = strcat(sPrinterInfo, "Default: ",
sYesNo, @crlf, @crlf)
Next
Message("Installed Printers", sPrinterInfo)
; Clean up
objPrinter
= ""
colInstalledPrinters = ""
objWMIService
= ""
See Also
For, ObjectCreate, ObjectGet
380
GetTickCount
GetExactTime
Returns current time in hundredths of a second.
Syntax:
GetExactTime()
Parameters:
(none)
Returns:
(s)
the current time in hundredths of a second.
Use this function to obtain the current time in hundredths of seconds.
Example:
a=GetExactTime( )
Message("Time is", a)
See Also:
TimeDate, TimeYmdHms, GetTickCount
GetObject
Pseudonym for ObjectGet. Returns a reference to an object provided by a
COM/OLE component.
See ObjectGet for details.
See Also:
ObjectGet, ObjectCreate
GetTickCount
Returns number of clock ticks used by Windows since Windows started.
Syntax:
GetTickCount()
Parameters:
(none)
Returns:
(i)
the number of clock ticks.
Use this function to obtain the number of clock ticks since Windows started.
Example:
a=GetTickCount( )
Message("Clock Ticks", a)
381
GoSub
See Also:
TimeDate, GetExactTime, TimeYmdHms
GoSub
Transfers control to another point in a WIL program and saves the location of the
next statement.
Syntax:
GoSub label
Parameters:
(s) label
user-defined identifier
GoSub label causes an unconditional transfer of control to the line in the program
marked :label where the identifier is preceded by a colon (:). The location of the next
statement after the GoSub statement is retained, and control may be transferred back
to that statement with a Return statement.
Note: If you call GoSub from within a User-Defined-Function, the 'label' must be
defined within the User-Defined-Function.
Labels for Goto and Gosub can be up to 249 characters.
Example:
a=1
b=2
c=3
x=21
GoSub Poly
Message("Polynomial evaluates to", y)
a=3
b=4
c=6
x=45
GoSub Poly
Message("Polynomial evaluates to", y)
exit
; Polynomial Computation Subroutine here
:Poly
y = a*(x**2) + b*x + c
return
See Also:
For, Goto, Return, Switch, Select, While
382
IconExtract
Goto
Changes the flow of control in a WIL program.
Syntax:
Goto label
Parameters:
(s) label
user-defined identifier.
Goto label causes an unconditional branch to the line in the program marked :label,
where the identifier is preceded by a colon (:).
Note: Program flow control structures, such as For/Next, ForEach/Next,
While/EndWhile, Switch/EndSwitch, If/EndIf must not be "jumped" by a Goto
statement. If a Goto is used inside of one of these structures to send the flow of
control outside of the structure, or if a Goto is used to send the flow of control inside
a structure, errors will result.
Labels for Goto and Gosub can be up to 249 characters.
Example:
If WinExist("Solitaire") == @FALSE Then Goto open
WinActivate("Solitaire")
Goto loaded
:open
Run("C:\Program Files\Microsoft Games\Solitaire\Solitaire.exe", "")
:loaded
exit
See Also:
For, If, Switch, While
IconExtract
Extracts an icon group from an EXE/DLL.
Syntax:
IconExtract(filename,icon filename,index)
Parameters:
(s) filename
(s) icon filename
(i) index
Returns:
(i)
specifies a fully qualified filename of the EXE or DLL
from which the icon group will be extracted.
specifies the name of the ICO file to which the icon group
will be written. If the file exists, it will be overwritten.
specifies the ordinal position in "filename" of the icon
group to be extracted, where the first icon group is 1.
the number of images in the icon group that was extracted.
383
IconInfo
Example:
num = IconExtract(DirWindows(0):"notepad.exe","ICONFILE.ICO",1)
Message("Number of images in icon group extracted ",num)
See Also:
IconInfo, IconReplace
IconInfo
Returns information about the icons in an EXE/DLL or ICO file.
Syntax:
IconInfo(filename,filetype)
Parameters:
(s) filename
(i) filetype
Returns:
(a)
specifies a fully qualified filename of the file from which
the icon information will be returned.
specifies the type of file:
0 = EXE or DLL (Win32)
1 = ICO file
an array of icon information.
For filetype 0, the array is a three-dimension array in the following format:
arr[0,0,0] = number of icon groups in the file
arr[1,*,*] = icon group 1
arr[2,*,*] = icon group 2 (if any)
etc.
For each icon group 'x':
arr[x,0,0] = number of icon images in the group
arr[x,0,1] = the string "WIDTH"
arr[x,0,2] = the string "HEIGHT"
arr[x,0,3] = the string "COLOR DEPTH"
Then, for each icon image 'y' in the group:
arr[x,y,0] = image index, where the first image in the group is 1
arr[x,y,1] = image width, in pixels
arr[x,y,2] = image height, in pixels
arr[x,y,3] = image color depth, in bits
For filetype 1, the array is a two-dimension array in the following format:
arr[0,0] = number of icon images in the file
arr[0,1] = the string "WIDTH"
arr[0,2] = the string "HEIGHT"
arr[0,3] = the string "COLOR DEPTH"
384
IconReplace
arr[1,*] = icon image 1
arr[2,*] = icon image 2 (if any)
etc.
For each icon image 'x':
arr[x,0] = image index, where the first image in the file is 1
arr[x,1] = image width, in pixels
arr[x,2] = image height, in pixels
arr[x,3] = image color depth, in bits
The "color depth" value is the number of bits per pixel. This corresponds to the
number of colors as follows:
Depth
1
2
4
8
16
24
32
Colors
2
4
16
256
65536
16 million
4 billion
Example:
arr = IconInfo(StrCat(DirWindows(0),"notepad.exe"), 0)
groups = arr[0,0,0]
info = ""
For i = 1 to groups
info = StrCat(info, "Group #", i, @crlf, "--------",@crlf)
icons = arr[i,0,0]
For j = 1 to icons
info = StrCat(info, "Icon #", j, @crlf, "--------", @crlf)
For k = 1 to 3
info = StrCat(info, @tab, arr[i,0,k], " = ",
arr[i,j,k],@crlf)
Next
Next
Next
Message("Icon Info",info)
See Also:
IconExtract, IconReplace
IconReplace
Replaces an existing icon group with a new icon group.
Syntax:
IconReplace(filename,icon filename[,index[,flags]])
385
IconReplace
Parameters:
(s) filename
(s) icon filename
(i) index
(i) flags
Returns:
(i)
either a fully qualified filename with drive and path,
or just a filename and extension.
the filename of the icon.
[optional] specifies the ordinal position of the icon
group to modify, where the first icon group is 1.
[optional] see below.
number of icons replaced.
"flags" can be set to 0, or can specify one or more of the following values combined
with the bitwise OR ('|') operator:
Value
0
1
Meaning
Default
Delete un-replaced icon images in the target icon group (32-bit
EXE's only) (Windows NT and newer) For example, if the target
icon group in the EXE has 6 icon images, and the specified .ICO
file has only one icon image, if you specify this flag then the one
matching icon image in the EXE will be replaced and the other 5
will be deleted.
It is suggested that caution be used when using this command, keeping the following
points in mind:
1)
The EXE file might become damaged and be unable to run. This is
especially true of some programs that checksum themselves to verify the
EXE. KEEP BACKUPS.
2)
System anti-virus tools might detect the alteration of an EXE file and
complain. If this is true, then either the anti-virus program must be
disabled, or another work around must be used. Some anti-virus
programs allow the specification of a "trusted" program - the trusted
feature may be used with due caution.
3)
The application whose icon is being modified must not be running while
its EXE file is being modified.
Note: An icon group is a set of one or more associated icon images, of different
dimensions and color depths. An EXE file can contain multiple icon groups; an icon
(.ICO) file contains a single icon group.
Each icon image in the targeted icon group in the EXE file is compared with each
icon image in the specified .ICO file, and if the .ICO file contains an icon image
whose size (and dimensions and color depth) is the same as the targeted icon image
in the EXE, then the targeted icon image in the EXE is replaced with the
386
If … Endif
corresponding icon image from the .ICO file. If no suitable replacement icon is
found in the .ICO file, then that particular icon image in the EXE is left unchanged.
Requirements for Icons
The .ICO file must have all the following image formats to successfully replace all
the icons in the icon group.
Dimensions
16x16
16x16
16x16
32x32
32x32
32x32
48x48
48x48
48x48
Color Depth
4 bit color
8 bit color
32 bit color
4 bit color
8 bit color
32 bit color
4 bit color
8 bit color
32 bit color
Example:
IconReplace("FILENAME.EXE", "ICONFILE.ICO",1)
See Also:
IconExtract, IconInfo
If … Endif
Conditionally performs a function or series of statements.
Syntax:
Note: There are several forms of the if statement:
if ... endif (structured):
if expression
series
of
statements
endif
if ... else ... endif (structured):
if expression
series
of
statements
else
series
387
If … Endif
of
statements
endif
if ... elseif … else ... endif (structured):
if expression
series
of
statements
elseif expression
series
of
statements
else
series
of
statements
endif
if ... then (single statement):
if expression then statement
if ... then ... else ... (single statement):
if expression
then statement
else statement
Parameters:
(s) expression
a condition to be evaluated.
(s) statement
any valid WIL function or command.
(s) series of statements multiple lines of valid WIL statements.
The if statement evaluates the expression following it. The expression must evaluate
to an integer. In the structured forms of the if syntax, if the expression evaluates to a
non-zero value (@TRUE) the series of statements after the if statement up to the
first matching else or endif are executed, otherwise they are skipped. In the if ... else
... endif syntax, the series of statements after the else are executed if the result of
evaluating the expression is zero (@FALSE).
In the single statement forms of the if syntax, if the expression evaluates to a nonzero value (@TRUE) the statement following the then keyword is executed,
otherwise it is skipped. In the if ... then ... else ... syntax, the statement following the
else is executed if the result of evaluating the expression is zero (@FALSE).
The elseif conditional statement can be used in conjunction with the structured if ...
else ... endif syntax. Like the if the elseif evaluates the expression following it and
the expression must evaluate to an integer. But unlike the if statement the elseif
statement is only evaluated if a preceding if or elseif statement has evaluated to zero
(@FALSE). When an elseif statement evaluates to a non zero value (@TRUE), the
388
IgnoreInput
series of statements after the elseif statement up to the next matching elseif, else or
endif are executed. Once an if or elseif statement in a if...elseif...else...endif syntax
group evaluates to a non zero value (@TRUE), no other elseif statements in the
group are evaluated. The elseif statement cannot be used with standalone if and else
statements.
Example:
; This example guesses a # between 1 and 1023.
Message("Think of a number", "Any number between 0 and 1023")
start = 0
stop = 1023
for i = 1 to 10
guess = (start+stop+1) /2
if AskYesNo("Hmmmm", "Is your number smaller than %guess%")
stop = guess - 1
else
start = guess
endif
next
guess = (start+stop+1) /2
if guess==0 || guess==1023
Message("Hmmm", "%guess% eh? Testing the limits again I assume")
else
if guess==13
Message("Hmmm", "%guess% seems rather unlucky to me")
else
a = guess mod 2
if a==0 then Message("Hmmm", "Even I can figure %guess%")
else Message("Hmmm", "It must be %guess%",oddly enough")
endif
endif
See Also:
For, Select, Switch, While
IgnoreInput
Turns off hardware input to Windows.
Syntax:
IgnoreInput(mode)
Parameters:
(i) mode
@TRUE or @FALSE. Specify -1 to retrieve the current
state.
389
IniDelete
Returns:
(i)
previous IgnoreInput mode, or -1 if this function is not
supported.
Note: If you explicity request input, using any WIL function that displays a
dialog/window, while in IgnoreInput(@TRUE) mode, input will be enabled as the
program awaits user input, and the re-disabled afterwards.
Examples:
Message("IgnoreInput","Turns off Keyboard/Mouse input for 10
seconds")
IgnoreInput(@TRUE)
Run("notepad.exe", "")
TimeDelay(10)
IgnoreInput(@FALSE)
Message("IgnoreInput","Keyboard/Mouse input restored")
See Also:
Sendkey
IniDelete
Removes a line or section from WIN.INI.
Syntax:
IniDelete(section,keyname)
Parameters:
(s) section
(s) keyname
the major heading under which the item is located.
the keyword name of the item to delete.
Returns:
(i)
@FALSE.
This function will remove the specified line from the specified section in WIN.INI.
You can remove an entire section, instead of just a single line, by specifying a
"keyname" of @WHOLESECTION. Case is not significant in "section" or
"keyname".
Note: INI files are mapped to registry
Example:
IniDelete("Desktop", "Wallpaper")
IniDelete("Quicken", @WHOLESECTION)
Message("IniDelete","Ini Deleted.")
See Also:
IniDeletePvt, IniItemize, IniRead, IniWrite
390
IniItemize
IniDeletePvt
Removes a line or section from a private INI file.
Syntax:
IniDeletePvt(section,keyname,filename)
Parameters:
(s) section
(s) keyname
(s) filename
the major heading under which the item is located.
the keyword name of the item to delete.
path and file name of the INI file.
Returns:
(i)
@FALSE.
This function will remove the specified line from the specified section in a private
INI file. You can remove an entire section, instead of just a single line, by specifying
a "keyname" of @WHOLESECTION. Case is not significant in "section" or
"keyname".
Note: Path information must be specified if the INI file is not in the Windows
directory. If there is no path information provided, then the INI file is assumed to be
in the Windows directory (as shown by DirWindows(0) ).
Example:
IniDeletePvt("Current Users", "Excel", "meter.ini")
Message("IniDeletePvt"," Pvt Ini Deleted.")
See Also:
IniDelete, IniItemizePvt, IniReadPvt, IniWritePvt
IniItemize
Lists keywords or sections in WIN.INI.
Syntax:
IniItemize(section)
Parameters:
(s) section
the major heading to itemize.
Returns:
(s)
list of keywords or sections.
IniItemize will scan the specified section in WIN.INI, and return a tab-delimited list
of all keyword names contained within that section.
Note: The WIN.INI is mapped to registry.
391
IniItemizePvt
IniItemize cannot accept a blank string "" to get all the section names. The INI files
are mapped to the registry, and null section names are not valid for mapped INI files.
Use the following instead:
allsections=IniItemizePvt("","WIN.INI")
message("All Sections", allsections)
IniItemize returns the string "(NONE)" if the specified section does not exist. Case
is not significant in section names.
Example:
; Returns all keywords in the [Extensions] section
keywords = IniItemize("Extensions")
AskItemList("Keywords in [Extension] of in.INI",keywords,
@tab, @sorted, @single, @false)
See Also:
IniDelete, IniItemizePvt, IniRead, IniWrite
IniItemizePvt
Lists keywords or sections in a private INI file.
Syntax:
IniItemizePvt(section,filename)
Parameters:
(s) section
(s) filename
the major heading to itemize.
path and file name of the INI file.
Returns:
(s)
list of keywords or sections.
IniItemizePvt will scan the specified section in a private INI file, and return a tabdelimited list of all keyword names contained within that section.
If a null string ("") is given as the section name, IniItemizePvt will return a list of all
section names contained within the file. It returns the string "(NONE)" if the
specified section does not exist. Case is not significant in section names.
Note: Path information must be specified if the INI file is not in the Windows
directory. If there is no path information provided, then the INI file is assumed to be
in the Windows directory (as shown by DirWindows(0) )
There is no distinction between an empty section and a section that doesn't exist.
Example:
; Returns all keywords in the [Boot] section of SYSTEM.INI
keywords = IniItemizePvt("Boot", "system.ini")
Message("IniItemizePvt","Pvt Ini Itemized.")
392
IniReadPvt
See Also:
IniDeletePvt, IniItemize, IniReadPvt, IniWritePvt
IniRead
Reads data from the WIN.INI file.
Syntax:
IniRead(section,keyname,default)
Parameters:
(s) section
(s) keyname
(s) default
the major heading to read the data from.
the name of the item to read.
string to return if the desired item is not found.
Returns:
(s)
data from WIN.INI file.
This function allows a program to read data from the WIN.INI file.
The WIN.INI file has the form:
[section]
keyname=settings
Most of the entries in WIN.INI are set from the Windows Control Panel program,
but individual applications can also use it to store option settings in their own
sections.
Notes: INI files are mapped to registry.
IniRead and IniReadPvt support strings up to 65,535 characters, if supported by the
operating system.
Example:
; Find the default output device
a = IniRead("windows", "device", "No Default")
Message("Default Output Device", a)
See Also:
Environment, IniDelete, IniItemize, IniReadPvt, IniWrite
IniReadPvt
Reads data from a private INI file.
Syntax:
IniReadPvt(section,keyname,default,filename)
393
IniWrite
Parameters:
(s) section
(s) keyname
(s) default
(s) filename
the major heading to read the data from.
the name of the item to read.
string to return if the desired item is not found.
path and file name of the INI file.
Returns:
(s)
data from the INI file.
Looks up a value in the "filename" .INI file. If the value is not found, the "default"
will be returned.
Note: Path information must be specified if the INI file is not in the Windows
directory. If there is no path information provided, then the INI file is assumed to be
in the Windows directory (as shown by DirWindows(0) ).
IniRead and IniReadPvt support strings up to 65,535 characters, if supported by the
operating system.
Example:
;IMPORTANT Path information must be specified if the
;INI file is not in the Windows directory.
a=IniReadPvt("Main", "Lang", "English", "WB.INI")
Message("IniReadPvt",a)
Given the following segment from WB.INI:
[Main]
Lang=French
The previous statement would return: French
See Also:
Environment, IniDeletePvt, IniItemizePvt, IniRead, IniWritePvt
IniWrite
Writes data to the WIN.INI file.
Syntax:
IniWrite(section,keyname,data)
Parameters:
(s) section
(s) keyname
(s) data
major heading to write the data to.
name of the data item to write.
string to write to the WIN.INI file.
Returns:
(i)
@TRUE.
394
IniWritePvt
This command allows a program to write data to the WIN.INI file. The "section" is
added to the file if it doesn't already exist.
INI files may be mapped to to the registry.
INI files are limited to 64K in size, on Windows 95/98 and ME. No real limit on
other windows platforms.
To force the INI updates to disk, add an additional IniWrite statement as follows:
IniWrite("","","")
Example:
; Change the list of pgms to load upon Windows
loadprogs = IniRead("windows", "load", ""); startup
newprogs = AskLine("Add Pgm To LOAD= Line", "Add:", loadprogs, 0)
IniWrite("windows", "load", newprogs)
See Also:
IniDelete, IniItemize, IniRead, IniWritePvt
IniWritePvt
Writes data to a private INI file.
Syntax:
IniWritePvt(section,keyname,data,filename)
Parameters:
(s) section
(s) keyname
(s) data
(s) filename
major heading to write the data to.
name of the data item to write.
string to write to the INI file.
path and file name of the INI file.
Returns:
(i)
@TRUE.
Writes a value in the "filename" .INI file.
Notes: You cannot use this function to add or update any of the "Device=" entries in
the [386Enh] section of SYSTEM.INI, because that section contains multiple entries
with the same keyword. See BinaryPokeStr for an example on how to modify the
device= lines of the SYSTEM.INI file.
INI files are limited to 64K in size, on Windows 95/98 and ME. No real limit on
other windows platforms.
Path information must be specified if the INI file is not in the Windows directory. If
there is no path information provided, then the INI file is assumed to be in the
Windows directory (as shown by DirWindows(0) )
395
InstallFile
To force the INI updates to disk, add an additional IniWritePvt statement as
follows:
IniWritePvt("","","",filename)
Example:
IniWritePvt("Main", "Lang", "French", "MYFILE.INI")
This would create the following entry in MYFILE.INI:
[Main]
Lang=French
See Also:
Binary Operations, BinaryPokeStr, IniDeletePvt, IniItemizePvt, IniReadPvt, IniWrite
InstallFile
Installs and uncompresses a file.
Syntax:
InstallFile(filename,targname,default-targdir,delete-old,flags)
Parameters:
(s) filename
(s) targname
(s) default-targdir
(i) delete-old
(i) flags
Returns:
(s)
source file to be installed. (path optional, short , 8.3 version
required)
the name of the target file to be created. (without path)
directory where the file is to be installed.
@TRUE - to delete existing same name files.
@FALSE - to ignore existing same name files.
1 - shared file
2 - force install
"result|tempname", or "result|".
When installing 32-bit image files (EXE's, DLL's, etc.), this function uses the version
information embedded in the files to determine whether a file being installed is
newer than an existing file with the same name. When installing any other type of
file, which does not contain appropriate version information, this function uses the
time stamps of the respective files instead.
The return value is in the form:
"result|tempname", or "result|"
where "result" is the value returned by the "VerInstallFile" Windows API function;
and "tempname" is the name of the temporary file that was created if the file could
not be installed, or blank otherwise.
396
Int
"Default-targdir" is the directory where you want the file to be installed. The file will
be installed to this directory, unless it is a shared file or a file with the same name
already exists elsewhere.
If "Delete-old" is @TRUE (or non-zero), and a file with the same name as the file
being installed already exists, it will be deleted, even if it is located in a directory (on
the path) other than the target directory. If "delete-old" is @FALSE, such a file will
not be deleted.
"Flags" specifies other optional flags that affect the operation of this function,
combined with the OR ('|') operator. They are:
1 - shared file (file should be installed to a shared directory)
2 - force install (install file even if older than existing file)
Note: InstallFile can uncompress files compressed by the Microsoft setup compress
utility. The image version can only be interpreted by a corresponding platform
version, i.e. 32-bit images by a 32-bit platform.
Example:
InstallFile("a:\ctl3d.dl_", "ctl3d.dll", DirWindows(1), @TRUE, 1)
;or in the case of a long filename:
InstallFile(FileNameShort("a:\carved stone.bm_"), "carved~1.bmp",
DirWindows(0), @TRUE, 0)
DirChange(DirWindows(0))
FileRename("carved~1.bmp", "carved stone.bmp")
See Also:
FileCopy, RegApp
Int
Converts a floating point number or a string to an integer.
Syntax:
Int(x)
Parameters:
(s) x
value to be converted.
Returns:
(i)
an integer.
Use this function to convert a floating point number or a string to an integer. If the
argument is a string, it is first converted to a number- if possible. If the argument is a
floating point number within integer range, it will be converted to the closest integer.
397
IntControl
Example:
a=int(5.1) + int("123")
Message("Result is", a)
; a= 5+123 = 128
See Also:
IsInt, IsFloat, IsNumber
IntControl
Internal control functions.
Syntax:
IntControl(request#,p1,p2,p3,p4)
Parameters:
(i) request#
(s) p1 - p4
specifies which sub-function is to be performed (see below).
parameters which may be required by the function (see
below).
Returns:
(s)
varies (see below).
Short for Internal Control, a special function that permits numerous internal
operations in the various products. The first parameter of IntControl defines exactly
what the function does, while the other parameters are possible arguments to the
function.
Refer to your product documentation for any further information on this function.
Warning: Many of these operations are useful only under special circumstances,
and/or by technically knowledgeable users. Some could lead to adverse side effects.
If it isn't clear to you what a particular function does, don't use it.
IntControl(1,p1,p2,p3,p4)
Just a test IntControl. It echoes back p1 & p2 and p3 & p4 in a pair of message
boxes.
IntControl(4,p1,0,0,0)
Controls whether or not the Dialog box with a file-list box.must have an item
selected or not.
398
p1
Meaning
0
Allows no item to be selected. Returns
"NOFILESSELECTED"
1
An item must be selected. Returns a file name (default)
IntControl
IntControl(5,p1,0,0,0)
Controls whether system & hidden files or directories are seen and processed.
p1
Meaning
0
System & Hidden files or directories not used (default)
1
System & Hidden files or directories seen and used
Returns previous setting.
IntControl(12,p1,p2,0,0)
IntControl 12 is used to direct WIL and its parent application (if the parent
application supports this function) as to how to handle users either terminating
WinBatch via the "Ctrl-Break" keystroke sequence or perhaps a menu item, or by
simply exiting windows.
p1 includes one value from BOTH the Exit Windows value and the Terminate WIL
value.
1) Exit Windows: Used to direct how and if Windows will exit. (choose one)
p1
0
1
2
3
Meaning
Pop up message box giving user a chance to either cancel
bat file or continue.
Allow Windows to be exited with no warning.
Refuse any attempt to exit Windows and give optional
warning. When p2 is not "" or "0", a message box will
display p2.
e.g. IntControl(12,2,"Attention! Close all apps first",0,0)
Reserved
2) Terminate WIL: Used to direct WIL to allow itself to be terminated without
warning or to simply refuse any termination request (such as Ctrl-Break).
p1
Meaning (choose one)
Provide notification message when program terminated by
user.
Allow quiet termination.
4
Refuse to terminate.
8
p2 Codes: When the “Exit Windows” group code "2" is included in p1, p2
provides the message to display to the user. Use "" or "0" to clear any
previously-set exit message.
0
Returns previous setting.
Example:
; We want to refuse any attempt to exit Windows until the WIL
399
IntControl
; script is complete and also refuse any attempts to close the
; WIL script.
IntControl(12,2|8,"Close Net apps before exiting Windows", 0, 0 )
Message("IntControl"," Done.")
IntControl(20,0,0,0,0)
Returns window handle of current parent window. (Similar to DllHwnd)
IntControl(21,p1,0,0,0)
Returns window handle of window matching the partial window-name in p1.
IntControl(22,p1,p2,p3,p4)
Issues a Windows "SendMessage".
IntControl 22 has been superceded with the functions SendMessageA and
SendMessageW.
IntControl(23,p1,p2,p3,p4)
Issues a Windows "PostMessage"
p1
p2
p3
p4
Window handle
Message ID number (in decimal)
wParam
lParam - assumed to be numeric
Returns @TRUE on success and @FALSE on failure
IntControl(26,0,0,0,0)
Re-assesses the language currently being used and makes any necessary changes to
the language strings used by the WIL Interpreter. Normally, this is done at program
startup.
IntControl(28,p1,0,0,0)
Selects system font used in list boxes.
Note: this function only works for AskItemList,AskLine,AskPassword, and
AskFileText type dialogs. It will not affect fonts in Dialog Editor created dialogs.
p1
0
1
2
Meaning
proportional font (default)
fixed pitch font
GUI font
Note: that this option applies to AskLine, AskPassword,
AskFileText and AskItemList
Returns the current font type (0 or 1, as above)
400
IntControl
Note: If you use IntControl 28 to specify a fixed pitch font for list boxes, a fixed
pitch font will now also be used for ITEMBOX controls in WIL dialogs.
IntControl(29,p1,0,0,0)
Changes the default file delimiter.
p1
New delimiter
We have added the ability to change the file delimiter to a character of your own
choosing, using the new IntControl 29.
IntControl(29, " ", 0, 0, 0) ;makes file delimiter a SPACE
Conversely, if you want to restore the TAB delimiter, you can use:
IntControl(29, @TAB, 0, 0, 0) ;restores default TAB delimiter
The first parameter for IntControl 29 is the new file delimiter you want to use, and
must be a single character. The return value of the function is the previous file
delimiter character. If you specify an empty string ("") as the first parameter, the
function will return the current file delimiter character but the file delimiter will not
be changed.
IntControl(30,p1,p2,0,0){*NT}
Performs a delayed file move.
p1
p2
source file
destination
The file is not actually moved until the operating system is restarted. This can be
useful for replacing system files. "Sourcefile" must be a single file name, with no
wildcards. "Destination" may be a file name (which may contain wildcards) or a
directory name. The destination file MUST be on the same drive as the source file. If
the destination file exists, it will be replaced without warning. "Destination" can also
be a NULL string (""), in which case the source file will be deleted when the
operating system is restarted.
This function returns "1" on success, "2" if it performed a regular FileMove instead,
and "0" on failure.
IntControl(31,p1,0,0,0)
Returns "Window ID's" for all Explorer windows.
p1
0
1
Meaning
Enumerate Explorer windows of class ExploreWClass.
32-bit Windows: Enumerates 32 bit Explorer windows id's
of class CabinetWClass
401
IntControl
64-bit Windows: Enumerates 64-bit Explorer window id's.
This function returns a tab-delimited list of Window ID's for all open Explorer
windows.
IntControl(32,address,data-type,operation,new-value)
Returns or sets the contents of the memory location specified by "address".
Parameters:
(i) address
(s) data type
(i) operation
(s/i) new-value
address of a memory location.
specifies the type of data to be retrieved:
"BYTE" - returns a byte
"WORD" - returns a word
"LONG" - returns a long integer
can be one of the following:
value
meaning
0
Read from memory
1
Write to memory
specifies the value to be written to the memory location (if
"operation" == 1). It must be a single character or integer,
corresponding to "data-type".
IntControl(33,p1,0,0,0)
Controls whether a listbox control in a dialog box allows multiple items to be
selected.
p1
Meaning
0
Single selection
1
Multiple selection (default)
Note: This function must be called before the dialog box is displayed. It cannot be
used to modify an existing dialog. For example, you cannot call this function from a
dialog callback procedure.
Returns previous setting.
IntControl(34,p1,p2,0,0)
Returns the error message string which corresponds to the specified error.
p1
{error number}
-1
Meaning
returns the error message string which corresponds to the
specified error
returns the error message string corresponding to the last
extender error or user-defined error.
Type of error passed.
p2
402
Meaning
IntControl
0
WIL error code
1
Windows error code
Explanation of various parameters:
p1 value
p2 value
Result
{error number}
0
Returns WIL error string
{error number}
1
Returns Windows error string
-1
0
Returns WIL Extender error string
-1
1
Returns the last Windows error string
Note: Windows Error codes are returned with a trailing carriage return line feed.
IntControl(35,p1,p2,0,0)
Slows down SendKey and/or mouse clicks.
p1
amount of time to delay between each keypress (SendKey,
SendKeyChild, SendKeysto), in milliseconds. Default delay is 0
milliseconds. Set to zero to return to default.
p2
amount of time to delay in MouseClick and MousePlay between
pressing and releasing the mouse button for a single click (not a
double-click), in milliseconds. Default is 0 (no delay).
1000 milliseconds = 1 second
Specify a larger number to slow down, or a smaller number to speed up.
Returns previous delay setting.
IntControl(36,p1,p2,0,0)
Waits until an application is waiting for user input.
IntControl 36 has been superceded with the function WinWaitReady
IntControl(38,p1,p2,0,0)
Sets quiet mode.
p1
-1
0
1
Meaning
Don't change (just return current setting)
Disable quiet mode (default).
Enable quiet mode.
p2 = error log filename, or a blank string ("") for no error log.
In "quiet mode":
403
IntControl
1. No error messages are displayed. If an error log filename is specified, then error
messages will be written to that file.
2. You MUST set the "warning" parameter in any FileCopy or FileMove commands
to @FALSE, or else a fatal error will occur.
3. Sounds that would normally be controlled by the Sounds function are suppressed.
Returns previous setting.
IntControl(39,p1,0,0,0)
Sets the file sharing mode for file reads.
p1 = share mode for file reads (default = 1)
Valid share modes are:
p1
-1
0
1
2
3
Meaning
don't change (keep current setting)
prevent the file from being shared
allow other open operations for read access
allow other open operations for write access
allow other open operations for read and write access
IntControl 39 will affect the following functions:
ArrayFileGet
ArrayFileGetCsv
BinaryRead
BinaryReadEx
FileCopy where the destination parameter is a port.
FileCopyAttr where the destination parameter is a port.
FileGet
FileGetW
FileOpen in "READ" mode.
Returns previous setting.
IntControl(40,p1,0,0,0)
Sets the file sharing mode for file writes.
p1
share mode for file writes (default = 0)
See IntControl 39 for a list of valid share modes.
IntControl 40 will affect the following functions:
ArrayFilePut
ArrayFilePutCsv
404
IntControl
BinaryWrite
BinaryWriteEx
FileOpen in "WRITE" / "APPEND" modes.
FilePut
FilePutW
Returns previous setting.
IntControl(41,p1,0,0,0)
Controls YmdHms format returned by time functions.
p1
0
1
-1
Meaning
2-digit year (YY:MM:DD:HH:MM:SS)
4-digit year (YYYY:MM:DD:HH:MM:SS) (default)
Don't change (just return current setting)
Note: The YY’s in the range 50 to 99 are assumed to be in the range 1950 to 1999.
YY’s in the range 00 to 49 are assumed to be in the range of 2000 to 2049.
This affects the following functions which return a YmdHms string: FileYmdHms,
TimeAdd, TimeJulToYmd, TimeSubtract, TimeYmdHms. Returns previous setting.
IntControl(42,p1,0,0,0)
Get the pointer to a binary buffer.
p1
specifies the binary buffer (see BinaryAlloc).
This returns the address of a pointer to a binary buffer. The address will be within the
memory space of the WIL Interpreter.
IntControl(43,p1,0,0,0)
Enable/disable "WaitForInputIdle".
p1
0
1
-1
Meaning
Don't wait for application to be ready.
Wait for application to be ready (default).
Don't change (just return current setting)
This controls whether SendKey, SendKeysTo and SendKeysChild attempts to wait
until the active application is ready to accept input before sending each keystroke.
Returns the previous setting.
IntControl(44,p1,0,0,0)
Returns class name for specified window handle.
p1
window handle.
405
IntControl
The window handle can be obtained with the DllHwnd function. Returns a blank
string ("") if the window doesn't exist.
IntControl(45,p1,0,0,0)
Enable/disable "SendKey speedup" in DOS programs in Windows NT.
p1
-1
0
1
Meaning
Don't change (returns current setting)
Don't speed up SendKey in DOS programs in Windows NT.
Speed up SendKey in DOS programs in Windows NT (default).
Normally, SendKey, SendKeysTo and SendKeysChild yield processor time between
keystrokes, allowing other Windows programs to multitask. However, when sending
keystrokes to a DOS program in Windows NT, this yielding can result in excessive
delays between keystrokes. When this occurs, SendKey goes into "speedup" mode
and dominates the processors time.
SendKey speed is also affected by the delay inserted between keystrokes. By default,
the delay between keystrokes is 25 milliseconds. This length can be adjusted with
IntControl 35. However, when "SendKey speedup" mode is in effect, no such delay
is inserted.
IntControl 45 allows you to disable the "SendKey speedup" behavior in the case that
it causes problems or is not desired.
Returns previous setting.
IntControl(46,p1,0,0,0)
Sets window retry timeout.
p1
-1
0
secs
Meaning
Don't change (returns current setting)
No retries
The number of seconds to wait (default = 9)
WIL functions which take a window title as a parameter (except for WinExist) and
will wait up to 9 seconds for the specified window to appear. IntControl 46 allows
the timeout setting to be changed.
Returns previous setting.
IntControl(47,p1,0,0,0)
Closes another WinBatch program.
IntControl 47 has been superceded with the function TerminateApp.
406
IntControl
IntControl(49,p1,p2,0,0)
Adds system menus to WIL popup windows.
p1 specifies which popup windows will have system menus:
p1
-1
0
1
Meaning
Don't change (return current setting)
No system menus (default).
Dialog boxes (created with Dialog or the WIL Dialog Editor).
Note: If using dialog callback procedure use DialogProcOption
code 1002 instead.
Item listboxes (e.g., created with "AskItemList", "AskFileText"
or related functions).
Both Dialog boxes (1) and Item list boxes (2).
2
3
p2 Specifies the value that a dialog box (created using the Dialog function) will
return if the user closes the dialog without pressing one of the pushbuttons in the
dialog (e.g., by pressing <Alt-F4>, or by clicking on the "Close" icon in the title bar)
. If a dialog returns 0, processing will be transferred to the label in the script marked
":Cancel" (if any).
IntControl 49 allows certain types of WIL popup windows to have system menus
(the drop down menu of minimize/maximize options accessed via the small icon or
box to the left side of a windows title bar).
Returns previous setting of p1.
IntControl(50,p1,p2,0,0)
Controls whether "Go to web page" button is added to WIL error boxes.
p1
-1
0
1
Meaning
Don't change (return current setting)
Remove "Go to web page" button from error boxes.
Add "Go to web page" button to error boxes (default).
When an error occurs in a WIL program an error message box is displayed. Prior to
display, WIL checks the system to see if a Web browser has been configured; if so, a
"Go to Tech Support Web Page" push-button is added to the error message box.
When pressed, the button launches the Web browser and opens to the Wilson
WindowWare Tech Support Web Page.
IntControl 50 prevents the "Go to Tech Support Web Page" button from being added.
Returns previous setting.
p2
URL
407
IntControl
default
user defined
"http://www.winbatch.com/"
"http://www.domain.com"
p2 can specify the URL of the web page to be launched when the user clicks on
the "Go to Tech Support Web Page" button. If p2 is "" or 0, no change is made
to URL that is currently set. The default is:
IntControl(50, 1, "http://techsupt.winbatch.com/", 0, 0)
IntControl(51,p1,0,0,0)
Specifies flags for CreateProcess.
p1
one or more of the following flags, combined using the binary "OR" ("|")
operator. The default setting is 32.
In the 32-bit version, all the Run[..] commands call the Windows API
"CreateProcess" function to launch the application. This IntControl lets you specify
certain flags that control the priority class and the creation of the process, and affects
all subsequent Run[..] commands. Under normal circumstances, you should not need
to use this IntControl at all. It should be used only by knowledgeable users, and
completely at your own risk. Some of these flags can have unexpected or undesirable
results. We cannot provide any support for their use.
Returns previous setting
Value
1
2
4
8
408
Flag Name/ Meaning
DEBUG_PROCESS
If this flag is set, the calling process is treated as a debugger, and
the new process is a process being debugged. The system notifies
the debugger of all debug events that occur in the process being
debugged. If you create a process with this flag set, only the
calling thread (the thread that called CreateProcess) can call the
WaitForDebugEvent function.
DEBUG_ONLY_THIS_PROCESS
If not set and the calling process is being debugged, the new
process becomes another process being debugged by the calling
process’s debugger. If the calling process is not a process being
debugged, no debugging-related actions occur.
CREATE_SUSPENDED
The primary thread of the new process is created in a suspended
state, and does not run until the ResumeThread function is called.
DETACHED_PROCESS
For console processes, the new process does not have access to
the console of the parent process. The new process can call the
AllocConsole function at a later time to create a new console.
This flag cannot be used with the CREATE_NEW_CONSOLE
IntControl
16
512
1024
2048
4096
67108864
flag.
CREATE_NEW_CONSOLE
The new process has a new console, instead of inheriting the
parent’s console. This flag cannot be used with the
DETACHED_PROCESS flag.
CREATE_NEW_PROCESS_GROUP
The new process is the root process of a new process group. The
process group includes all processes that are descendants of this
root process. The process identifier of the new process group is
the same as the process identifier, which is returned in the
lpProcessInformation parameter. Process groups are used by the
GenerateConsoleCtrlEvent function to enable sending a CTRL+C
or CTRL+BREAK signal to a group of console processes.
CREATE_UNICODE_ENVIRONMENT
If set, the environment block pointed to by lpEnvironment uses
Unicode characters. If clear, the environment block uses ANSI
characters.
CREATE_SEPARATE_WOW_VDM
Windows NT only: This flag is valid only when starting a 16-bit
Windows-based application. If set, the new process is run in a
private Virtual DOS Machine (VDM). By default, all 16-bit
Windows-based applications are run as threads in a single, shared
VDM. The advantage of running separately is that a crash only
kills the single VDM; any other programs running in distinct
VDMs continue to function normally. Also, 16-bit Windowsbased applications that are run in separate VDMs have separate
input queues. That means that if one application hangs
momentarily, applications in separate VDMs continue to receive
input.
CREATE_SHARED_WOW_VDM
Windows NT only: The flag is valid only when starting a 16-bit
Windows-based application. If the DefaultSeparateVDM switch
in the Windows section of WIN.INI is TRUE, this flag causes the
CreateProcess function to override the switch and run the new
process in the shared Virtual DOS Machine.
CREATE_DEFAULT_ERROR_MODE
The new process does not inherit the error mode of the calling
process. Instead, CreateProcess gives the new process the current
default error mode. An application sets the current default error
mode by calling SetErrorMode. This flag is particularly useful for
multi-threaded shell applications that run with hard errors
disabled. The default behavior for CreateProcess is for the new
process to inherit the error mode of the caller. Setting this flag
changes that default behavior.
409
IntControl
These flags control the new process’s priority class, which is used in determining the
scheduling priorities of the process’s threads. If none of the following priority class
flags are specified, the priority class defaults to NORMAL_PRIORITY_CLASS
unless the priority class of the creating process is IDLE_PRIORITY_CLASS. In this
case, the default priority class of the child process is IDLE_PRIORITY_CLASS.
One of the following flags can be specified:
Value
32
64
128
256
Flag Name/Meaning
NORMAL_PRIORITY_CLASS
Indicates a normal process with no special scheduling
needs.
IDLE_PRIORITY_CLASS
Indicates a process whose threads run only when the system
is idle and are preempted by the threads of any process
running in a higher priority class. An example is a screen
saver. The idle priority class is inherited by child processes.
HIGH_PRIORITY_CLASS
Indicates a process that performs time-critical tasks that
must be executed immediately for it to run correctly. The
threads of a high-priority class process preempt the threads
of normal-priority or idle-priority class processes.
An example is Windows Task List, which must respond
quickly when called by the user, regardless of the load on
the operating system. Use extreme care when using the
high-priority class, because a high-priority class CPUbound application can use nearly all available cycles.
REALTIME_PRIORITY_CLASS
Indicates a process that has the highest possible priority. The
threads of a real-time priority class process preempt the threads
of all other processes, including operating system processes
performing important tasks. For example, a real-time process that
executes for more than a very brief interval can cause disk caches
not to flush or cause the mouse to be unresponsive.
IntControl(53,p1,0,0,0)
Set line terminator type for FileWrite.
p1
410
-1
Terminator
Don't change (just return current setting)
0
No line terminator
1
CR/LF (DOS) (default)
IntControl
2
LF (UNIX)
3
CR (Macintosh)
4
Tab
Normally, FileWrite adds a carriage return and line feed (CR/LF) after writing each
line to the file. This IntControl lets you select a different line terminator, or none at
all, as specified by "p1".
Returns previous setting.
IntControl(54,p1,p2,0,0)
Keep window on top.
IntControl 54 has been superceded with the function WindowOnTop.
IntControl(56,p1,p2,p3,0)
Terminate an application.
IntControl 56 has been superceded with the function TerminateApp.
IntControl(58,p1,0,0,0)
Set system time.
p1
new system time, in YmdHms format.
This IntControl changes the time of the computer's system clock.
Returns @TRUE on success, @FALSE on failure.
IntControl(59,p1,p2,0,0)
Sends a WM_SETTINGCHANGE message.
This IntControl sends a message to one or all application windows, informing them
that a change has been made to the registry.
p1
handle
p2
key
Meaning
window handle of the window to send the message to, or -1 for all
top-level windows.
Meaning
name of the registry key that has been changed. Specify only the
leaf node in the registry, not the whole path, but this will be
application-dependent. You can specify a blank string ("") to
request that the application re-read all sections or keys that affect
it.
411
IntControl
Returns @TRUE on success; @FALSE on error.
IntControl(60,p1,p2,0,0)
Sends a WM_DEVMODECHANGE message.
This IntControl sends a message to one or all application windows, informing them
that a change has been made to device mode settings.
p1
handle
Meaning
window handle of the window to send the message to, or minus one
(-1) for all top-level windows.
p2
device
Meaning
name of the device (as specified in the
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows
NT\CurrentVersion\IniFileMapping\win.ini[Devices]) whose
settings have been changed.
Returns @TRUE on success; @FALSE on error.
IntControl(61,p1,0,0,0)
Sets WinActivate() method.
p1
Method to use
-1
Don't change (just return current setting).
0
Standard method (SetForegroundWindow API call).
1
Switch to the window, then click on it.
2
Iconize the window, then switch to it.
3
Change foreground lock timeout.
4
Attach to the input thread of the foreground window.
5
Display invisible window, then attach to the input thread of the
foreground window
This IntControl lets you change the current method being used. Some methods may
work with some particular windows and not others, so you may need to experiment.
Note: The default WinActivate method used:
5
Windows 2000 and newer.
0
Previous versions of Windows
Returns previous setting.
412
IntControl
IntControl(62,p1,0,0,0)
Sets dialog activation method.
This IntControl lets you change the method used to activate dialog windows that are
displayed by the WIL Interpreter. See IntControl 61 for more information.
p1
Method to use
-2
Don't activate dialogs.
-1
Don't change (just return current setting).
0
Standard method (SetForegroundWindow API call).
1
Switch to the window, then click on it.
2
Iconize the window, then switch to it.
3
Change foreground lock timeout.
4
Attach to the input thread of the foreground window.
5
Display invisible window, then attach to the input thread of the
foreground window.
Note: The default methods used:
5
Windows 2000 and newer.
0
Previous versions of Windows
Returns previous setting.
IntControl(63,p1,p2,p3,p4)
Sets coordinates for AskFileText, AskItemList and AskTextBox windows.
This function sets the window coordinates for the dialog displayed by the next
AskFileText, AskItemList, AskTextBox function call. The coordinates will be reset
to default values after the Ask[..] function is called. Note: This function is designed
to enlarge dialogs. Reducing the size could produce unwanted output. Coordinates
are based on a virtual 1000 x 1000 screen:
p1
p2
p3
p4
=
=
=
=
left (upper-x)
top (upper-y)
right (lower-x)
bottom (lower-y)
To explicitly indicate the default values that should be used, use:
IntControl(63, 0, 0, 0, 0)
IntControl(64,0,0,0,0)
Gets the exit code returned by the last program run.
413
IntControl
This function gets the exit code (also known as the "errorlevel") that was
returned by the program that was most-recently run using RunWait, RunShell
or RunWithLogon with the @WAIT flag specified. If no program has been
run, or if the last-run program was not run in @WAIT mode, this function will
return 99999.
IntControl(65,p1,0,0,0)
Sets maximum line length for FileRead.
p1 specifies the maximum length of a line which can be read using the FileRead
function, in bytes. This is also the number of bytes which are buffered internally
with each file read operation.
The default is 4096. You can specify a value of 0, in which case file reads are not
buffered internally, and the maximum line length is 1280 bytes (although this
number is subject to change).
p1
-1
-2
Meaning
Don't change (just return current setting)
(default) Smart size. By default, the allocated buffer size will be
between 4K and 32K according to a "smart size" method, based on the
file size
0
Don't buffer file reads - max line length limited by generic buffer
(currently 1280 bytes)
##
Any other positive value specifies the actual buffer size
This IntControl affects subsequent FileOpen commands, and has no effect on
files which are already open.
Returns previous setting.
IntControl(66,0,p2,0,0)
Logs the user out of the current session.
p2
0
1
Meaning
default. Normal shutdown. User is prompted for open files.
Force. Forces the restart of Windows by not giving notice to any
running applications about the restart. This doesn't allow the
applications to save information or to display shut down messages.
Be very careful using IntControl(66,0,1,0,0) . This can cause the loss of data.
Note: This function is not supported when run as a service.
IntControl(67,0,p2,0,0)
Reboot system.
p2
414
Meaning
IntControl
0
1
default. Normal shutdown. User is prompted for open files.
Force. Forces the reboot of the system by not giving notice to
any running applications about the reboot. This doesn't allow
the applications to save information or to display shut down
messages.
Be very careful using IntControl(67,0,1,0,0). This can cause the loss of data.
Note: This function is not supported when run as a service.
IntControl(68,0,p2,p3,0)
This will cause a shutdown of the machine, awaiting power off.
p2
0
1
Meaning
default. Normal shutdown. User is prompted for open files.
Force. Forces the reboot of the system by not giving notice to any
running applications about the reboot. This doesn't allow the
applications to save information or to display shut down messages.
p3
0
1
2
Meaning
Power-off if supported by the computer (*see note below*)
Don't attempt to power-off
Attempt to power-off in any case
Note: We don't currently have a reliable method of determining if a computer
supports the power-off feature, so 0 will attempt to do a power-off in any case.
Be very careful using IntControl(68,0,1,0,0). This can cause the loss of data.
Note: This function is not supported when run as a service.
IntControl(69,p1,p2,0,0)
Suspends machine by shutting power down.
p1
Meaning (NT or newer only)
0
hibernate mode
1
suspend mode
p2
Meaning
0
Don't force apps to suspend. The function broadcasts a
PBT_APMQUERYSUSPEND event to each application to
request permission to suspend operation.
415
IntControl
1
Force apps to suspend. The function broadcasts a
PBT_APMSUSPEND event to each application and driver, then
immediately suspends operation
This IntControl puts the system into standby mode, if supported by the hardware and
device drivers.
Note: This function is not supported when run as a service.
IntControl(70,p1,p2,0,0)
Set delay after WinWait[..] functions or PostMessage's.
p1 - specifies the delay, in milliseconds, after the type of operation specified by "p2".
p2 specifies the type of operation that the delay applies to:
0
"p1" specifies the delay after a successful WinWaitExist, WinWaitChild, or
WinWaitClose. The default is 500 (ie, 1/2 second). Specify 0 for no delay.
1
"p1" specifies the delay after successful calls to the Windows PostMessage
API (except when performing mouse clicks). The default is 100 (ie, 1/10 second).
Specify 0 for no delay.
Returns previous setting.
IntControl(72,p1,p2,p3,0)
Sets Cancel handler.
This IntControl lets you specify what should happen when the next Cancel event
occurs in the script.
p1
Meaning
-1
Don't change (just return current setting)
0
Exit on cancel processing (i.e., the script exits)
1
Goto the label :CANCEL
2
Gosub the label :CANCEL
3
Call the UDF specified by p3
p2 @TRUE or @ FALSE. Specifies whether any existing "wberroradditionalinfo"
data should be cleared first. This is a one-time flag, which gets reset to 0 after the
next error occurs.
p3 Name of the cancel handling UDF. The cancel handler UDF must be defined to
accept exactly one parameter. The parameter it receives will be the "wberrorarray"
array. None of the other WIL variables will be automatically set.
416
IntControl
The return value of the cancel handling UDF has special meaning.
Value
Meaning
0
(default) UDF handling is canceled.
1
Continue handling cancel events with this UDF.
2
Treat this cancel event as unhandled, and do normal cancel
processing
3
Treat this cancel event as unhandled, but continue handling cancel
events with this UDF.
If the cancel handler UDF is invoked during a variable assignment statement (eg,
"variable = function()"), and you set wberrorarray[11] to a specific value inside the
handler UDF, that value will be assigned to the variable (x). Note that this does not
work for a property assignment. By default, the value assigned when a cancel occurs
is 0.
By default, if you don't use this IntControl at all, then every time a Cancel event
occurs, WIL does a "Goto Cancel".
The first time you use this IntControl, the behavior changes to being a one-time flag,
which gets reset to 0 after the next Cancel event occurs.
When processing goes to :CANCEL, the following WIL variables are automatically
set:
Variable
Meaning
wberrorhandlerline
(s) Cancel line (i.e., line in script that caused
Cancel)
wberrorhandleroffset
(i) offset into script of Cancel line, in bytes
wberrorhandlerassignment
(s) variable being assigned on Cancel line, or ""
if none
wberrorhandlerfile
wberrortextstring
wberroradditionalinfo
(s) name of the currently-executing script
(s) description of the WIL error
(s) delimited string of additional error
information, if any. ASCII 160 is delimiter
character between each error incident.
(s) name of the currently-executing UDF, or a
blank string ("") if not in a UDF.
(i) line number in the currently executing script
or 0 if the cancel cannot be matched to a
particular line.
wberrorinsegment
wberrorhandlerlinenumber
417
IntControl
wberrorarray
(a) WIL array with the following elements:
wberrorarray[0]= LastError()
wberrorarray[1]= wberrorhandlerline
wberrorarray[2]= wberrorhandleroffset
wberrorarray[3]= wberrorhandlerassignment
wberrorarray[4]= wberrorhandlerfile
wberrorarray[5]= wberrortextstring
wberrorarray[6]= wberroradditionalinfo
wberrorarray[7]= wberrorinsegment
wberrorarray[8]= wberrorhandlerlinenumber
wberrorarray[9]= line number in the UDF
where the cancel occurred or 0.
wberrorarray[10]= a positive number if
reported line numbers are accurate, zero (0) if
possibly inaccurate or -1 if run from WinBatch
Studio, in which case both wberrorarray[8] and
wberrorarray[9] will contain the line number of
the cancel in the UDF.
wberrorarray[11]= Used only with cancel
handler UDF method to set return value of the
function the cancel occurred on.
Note: The :CANCEL label must be in the same script where the Cancel event
occurred. If a Cancel event occurs in a called script, it will go to the label in the
called script, not the calling script.
If you want to have cancel handling in a User-Defined-Function/UserDefined
Subroutine, then IntControl 72 must either:
Be defined within the User-Defined-Function/User-Defined-Subroutine. The
:CANCEL label must also be contained within the User-Defined-Function/UserDefined-Subroutine.
Or p1 must be the value of 3 and p3 must specify the name of the cancel handler
UDF.
Returns previous setting, or -1 if the setting had not previously been changed from
the default behavior.
IntControl(73,p1,p2,p3,0)
Sets Error handler.
This IntControl lets you specify what should happen when the next error occurs in
the script.
418
p1
Meaning
-1
Don't change (just return current setting)
IntControl
0
Normal error processing (default)
1
Goto the label :WBERRORHANDLER
2
Gosub the label :WBERRORHANDLER
3
Call the UDF specified by p3
p2 @TRUE or @ FALSE. Specifies whether any existing "wberroradditionalinfo"
data should be cleared first. This is a one-time flag, which gets reset to 0 after the
next error occurs.
p3 Name of the error handling UDF. The error handler UDF must be defined to
accept exactly one parameter. The parameter it receives will be the "wberrorarray"
array. None of the other WIL variables will be automatically set.
The return value of the error handling UDF has special meaning.
Value
Meaning
0
(Default) UDF error handling is canceled.
1
Continue handling error events with this UDF.
2
Treat this error event as unhandled, and do normal error processing
3
Treat this error event as unhandled, but continue handling errors with
this UDF.
If the error handler UDF is invoked during a variable assignment statement (eg,
"variable = function()"), and you set wberrorarray[11] to a specific value inside the
handler UDF, that value will be assigned to the variable (x). Note that this does not
work for a property assignment. By default, the value assigned when an error occurs
is 0.
When processing goes to :WBERRORHANDLER, the following WIL variables are
automatically set:
Variable
Meaning
wberrorhandlerline
(s) Error line (i.e., line in script that caused Error)
wberrorhandleroffset
(i) offset into script of error line, in bytes
wberrorhandlerassignment
(s) variable being assigned on error line, or "" if
none
wberrorhandlerfile
wberrortextstring
wberroradditionalinfo
(s) name of the currently-executing script
(s) description of the WIL error
(s) delimited string of additional error
419
IntControl
wberrorinsegment
wberrorhandlerlinenumber
wberrorarray
information, if any. ASCII 160 is delimiter
character between each error incident.
(s) name of the currently-executing UDF, or a
blank string ("") if not in a UDF.
(i) line number in the currently executing script or
0 if the error cannot be matched to a particular
line.
(a) WIL array with the following elements:
wberrorarray[0]= LastError()
wberrorarray[1]= wberrorhandlerline
wberrorarray[2]= wberrorhandleroffset
wberrorarray[3]= wberrorhandlerassignment
wberrorarray[4]= wberrorhandlerfile
wberrorarray[5]= wberrortextstring
wberrorarray[6]= wberroradditionalinfo
wberrorarray[7]= wberrorinsegment
wberrorarray[8]= wberrorhandlerlinenumber
wberrorarray[9]= line number in the UDF where
the error occurred or 0.
wberrorarray[10]= a positive number if reported
line numbers are accurate, zero (0) if possibly
inaccurate or -1 if run from WinBatch Studio, in
which case both wberrorarray[8] and
wberrorarray[9] will contain the line number of
the error in the UDF.
wberrorarray[11]= Used only with error handler
UDF method to set return value of the function
the error occurred on.
Returns previous setting.
Notes:
The :WBERRORHANDLER label or User Defined Function/User Defined
Subroutine must be in the same script where the error occurred. If an error
occurs in a called script, it will go to the label in the called script, not the calling
script.
If you want to have error handling occur with in a User Defined Function /
User Defined Subroutine, then IntControl 73 must be defined with in the User
Defined Function/User Defined Subroutine.
If you want the script to continue to handle errors, make sure to re-arm the error
handler by calling IntControl 73 at the end of your error handling routine.
Getting Extended Error Information:
420
IntControl
Most WIL errors are accompanied by 'extended error information'. Extended
error information is written to the wwwbatch.ini file:
On XP:
C:\Documents and Settings\{username}\Application
Data\WinBatch\Settings\wwwbatch.ini
On Vista or newer:
C:\Users\{username}\AppData\Roaming\WinBatch\Settings\wwwbatch.ini
There is a section that contains additional diagnostic information that may give
some clue as to what it is that failed.
IntControl 73 returns this same information in the 'wberroradditionalinfo'
variable.
Extended error information is most commonly in the form of a Windows system
error.
Example:
IntControl(73,2,0,0,0)
a=5
b=c+7
Message(a,b)
exit
:WBERRORHANDLER
Error=LastError()
Message("LastError Value is",Error)
Message("wberrorhandlerline",wberrorhandlerline)
Message("wberrorhandleroffset",wberrorhandleroffset)
Message("wberrorhandlerassignment",wberrorhandlerassignment)
Message("wberrorhandlerfile", wberrorhandlerfile)
Message("wberrortextstring", wberrortextstring)
Message("wberroradditionalinfo", wberroradditionalinfo)
Message("wberrorinsegment", wberrorinsegment)
Message("wberrorhandlerlinenumber", wberrorhandlerlinenumber)
%wberrorhandlerassignment%="eeek"
return
See Also:
IntControl 34
IntControl(74,p1,0,0,0)
Set idle wait after Run commands. (32-bit only)
p1 specifies the amount of time, in milliseconds, that the WIL Interpreter will wait,
after launching an application with the Run (and similar) commands, for the
application to become "idle" (i.e., ready for user input). The default is 10000 (i.e., 10
seconds). Specify 0 for no idle wait.
421
IntControl
Returns previous setting.
See Also:
IntControl 43
IntControl(75,p1,0,0,0)
Gets last dialog coordinates.
p1
Meaning
1
Returns last X coordinate
2
Returns last Y coordinate
This IntControl returns the X or Y coordinate of the most recently displayed dialog
(created with the Dialog function), at the time the previous dialog was closed.
Coordinates are in dialog units.
Returns -1 if there was no previous dialog.
IntControl(76,p1,0,0,0)
Sets the computer name.
IntControl 76 has been superceded by the function ComputerNameSet.
IntControl(77,p1,0,0,0)
Gets internal operating parameters.
This IntControl returns internal values which may be useful in script debugging. p1
specifies one of the following request codes:
422
Request
Meaning
0
total memory allocated for strings, in bytes
10
number of variables assigned
11
number of variable slots available
12
tab-delimited list of variables assigned
20
number of files open
21
number of file slots available
30
Combination of the number of binary buffers and structure
handles open. (see BinaryAlloc and DllStructAlloc.)
31
Combination of the number of binary buffer slots and structure
handles available. (see BinaryAlloc and DllStructAlloc.)
IntControl
40
number of extenders loaded
41
number of extender slots available
42
tab-delimited list of extenders loaded
50
number of extender functions loaded
51
number of extender function slots available
60
number of COM/OLE objects open
62
tab-delimited list of COM/OLE objects
70
current structure depth
71
current structure slots remaining
72
line feed-delimited list of tab-delimited structure stack
information
80
current Call level depth
90
number of UDF's defined
91
number of UDF slots available
100
tab-delimited list of WIL function table entries
101
tab-delimited list of parent application function table entries
102
tab-delimited list of loaded extender function table entries
103
tab-delimited list of UDF's
110
number of DDE conversations open
111
number of DDE conversations available
Requests 100, 101 and 102 return a tab-delimited list of table entries. Each entry
consists of a list of fields delimited with an ASCII 255 character, as follows:
Item
1
2
Value
Index
Entry Type
Type
Value
0
BINARYOP
1
UNARYOP
2
FUNCTION
3
CONSTANT
4
COMMAND
423
IntControl
3
4
5
6
5
COMPOP
6
FUNCTBYNAME
7
UNDEFINED
8
STRUCTOP
Parameter type mask
Parameter count OR constant value
Name length
Name
Returns the indicated integer or string.
IntControl(78,0,0,0,0)
Frees all UDF's.
This IntControl frees (undefines) all User-Defined-Functions. It cannot be used
while a User-Defined-Function is currently executing.
Returns the number of User-Defined-Function's that were freed.
IntControl(79,p1,p2,p3,0)
Causes a user-defined error.
IntControl 79 has been superceded with the function ErrorEvent
IntControl(80,0,0,0,0)
Waits until no keys on the keyboard are pressed.
Always @TRUE.
IntControl(81,p1,0,0,0)
Sets seed for the Random function.
This IntControl sets the seed value used in subsequent calls to Random.
p1 - seed value or control value
424
p1
Meaning
-1
(Control Value)
Reseed the random number generator with a WIL
generated seed value. The WIL generated seed
value has various time based components and will
change many times in one second.
1
(Control Value)
Allow the run time library to select a seed. This
may allow a predictable pattern to the generated
numbers
IntControl
Other positive numbers
(Seed Value)
Use provided value for the seed. This will allow a
predictable pattern to the generated numbers
Other negative numbers
(Seed Value)
Undefined results
Note: Providing a fixed seed value in a program will result in a predictable pattern
to the generated numbers. This is often used for program debugging.
For normal programs, it is recommended that either the default WIL-generated seed
value be used or that a provided seed value have a truly random or time-based
component so that the pseudo-random numbers generated are more difficult to
predict.
Always @TRUE
IntControl(84,p1,0,0,0)
Itemize desktops, or windows on specified desktop. (Windows NT or newer only)
If p1 is a blank string (""), this returns a tab-delimited list of desktops, or a blank
string ("") if the function fails.
If p1 specifies a desktop name, this returns a tab-delimited list of "Window ID's" of
all top-level windows on that desktop, or a blank string ("") if the function fails.
IntControl(87,p1,0,0,0)
Sets Execute recovery mode.
This specifies what should happen if the Execute command causes an error.
p1
Meaning
-1
Don't change (just return current setting)
0
Display a dialog with an option to continue or cancel.
1
Display a notification dialog then continue.
2
Continue automatically without displaying a dialog.
Returns the previous setting.
See Also: Execute
IntControl(91,p1,0,0,0)
Sets file mask matching mode.
p1
Meaning
425
IntControl
0
Only match long version of file names (default).
1
Match long and short versions of file names.
2
Only match long version of file names, using alternate method
(PathMatchSpec API).
This controls the behavior of functions which take file masks. By default, masks
only match the long version of the file name. For example, if you do
FileItemize("*.htm"), it will not match a file "home.html" whose short name is
"home~1.htm". If you want it to match the short version of the file name as well, set
"p1" to 1.
Returns the previous setting.
IntControl(92,operation,value,0, 0)
Disables or reverts file system redirection when running in WOW64 (32-bit
emulation under 64-bit Windows).
IntControl 92 has no effect when a script is run by native 64-bit WinBatch or as a
compiled native 64-bit executable."operation" may be either "Disable" or "Revert".
If "operation" is "Disable", file system redirection is disabled, and the function
returns a value that should be specified on a subsequent "Revert" operation. "Value"
should be set to 0.
If "operation" is "Revert", file system redirection is reverted to the state specified by
"value", which should be the result of a previous "Disable" operation. Returns a
non-zero value on success.
Returns a value as specified above, or -1 on error.
Example:
oldvalue = IntControl( 92, "disable", 0, 0, 0 )
ret = FileExist( "C:\Windows\System32\cmd.exe" )
IntControl( 92, "revert", oldvalue, 0, 0 )
IntControl(93,p1,p2,p3,0)
Performs certificate operations.
p1
0
426
Meaning
Sign a file (Windows XP/Vista only)
p2 specifies a tab-delimited string with the following five
parameters:
п‚· file to sign
п‚· certificate friendly name
п‚· description of file being signed (can be "" if not needed)
IntControl
п‚· location (URL) of information about file (can be "" if not
needed)
п‚· URL of timestamp server (can be "" if not needed)
Get the thumbprint of a certificate in a file
p2 specifies a .CER or .SPC file
1
Set the friendly name of a certificate
p2 specifies the thumbprint of a certificate
p3 specifies the friendly name to set
2
IntControl(94,p1,0,0,0)
Returns the real file handle corresponding to a WIL file handle.
p1
WIL file handle
Meaning
A file handle returned by one of the WIL functions.
(i.e., FileOpen)
Returns a Windows file handle, or 0 if the "WIL file handle" is invalid.
IntControl(96,0,0,0,0)
Frees all resource associated with all callback handles create by the
'DllCallbackCreate' function.
No previously defined callback handles can be used after a call to this IntControl. It
cannot be used by a user defined function or subroutine while the function or
subroutine is executing an application-defined callback for an external function.
Returns the number of callback handles destroyed.
IntControl(97,0,0,0,0)
This IntControl frees all resource associated with all Dll Structure handles created by
one or more calls to the DllStructAlloc function. All Dll Structure handles are
invalid after using this IntControl.
Returns the number of Dll Structure handles destroyed.
IntControl(98,p1,p2,0,0)
Use this IntControl obtain information about a DLL structure handle.
p1
valid DLL structure handle returned by a call to the
DllStructAlloc function.
427
IntControl
p2
type of information returned by the IntControl.
1 = size in bytes of a structure represented by the DLL
structure handle.
2 = memory address of the buffer holding the C-language
structure represented by the DLL structure handle.
IntControl(1000,p1,0,0,0)
Sets the exit code returned by WinBatch.
p1
exit code
This specifies the value returned by WinBatch's "WinMain" (entry point) function.
Returns the previous setting.
IntControl(1001,p1,0,0,0)
Set service process status.
p1
0
1
Meaning
Run as a normal application (default).
Run as a service.
If WinBatch is running as a service, it will not be closed when the user logs out.
Windows NT and newer: It is not necessary to use IntControl 1001 in order to run a
WinBatch service, but doing so will not hurt. To create a compiled WinBatch
program that will run as a native service under Windows NT or newer: compile the
WinBatch script as usual using the WinBatch Compiler, but specify an output file
with an extension of ".EXS" instead of ".EXE". Alternatively, you can simply
rename an existing WinBatch program by changing its extension from ".EXE" to
".EXS". You can install a WinBatch service (or any service) using the Win32
Network Extender function wntSvcCreate. See the WinBatch help file for further
details on running a WinBatch script as a NT native service.
Returns @TRUE on success, @FALSE on failure.
IntControl(1002,p1,0,0,0)
Sets WinBatch icon display state.
p1
-1
0
1
Meaning
Don't change (returns current setting)
Hide WinBatch icon.
Show WinBatch icon (default).
This function sets the display state of the WinBatch icon for the duration of the
script. The default display state is minimized.
428
IntControl
This IntControl is equivalent to using WinShow or WinHide on the current
WinBatch window. However, WinShow and WinHide do not have the capability of
hiding the icon permanently. If any Box[..] functions are used to display information,
the WinBatch icon will return to its previous display state.
Returns previous setting.
IntControl(1003,p1,0,0,0)
Prevents the WinBatch icon from being opened.
This function sets the "open-able" flag for the WinBatch icon. If the flag is on
(default), then the WinBatch icon can be opened (restored) to a normal window by
clicking on the icon. If the flag is off, then it is not possible to open the WinBatch
icon by any method, including WinShow or BoxOpen.
p1
-1
0
1
Meaning
Don't change (returns current setting)
WinBatch icon cannot be opened.
WinBatch icon can be opened (default).
Returns previous setting.
IntControl(1004,0,0,0,0)
Returns the path and file name of the current WinBatch program.
If the current WinBatch script is a child program that was called with the Call
function, this IntControl will return the name of the main (calling) program.
IntControl(1006,0,0,0,0)
Returns the un-parsed WinBatch command line.
This returns the actual command line string that WinBatch was launched with.
Example:
; get un-parsed WinBatch command line
rc = IntControl(1006, 0, 0, 0, 0)
Message("Un-parsed Command Line String =", rc)
IntControl(1007,p1,p2,p3,p4)
Add/remove/check tray icon.
p1
Parameters
Meaning
Notes
0
p2, p3, p4
ignored
Check whether tray
icon has been clicked
(and reset "clicked"
state)
This function will return one of the
following values:
Val
Meaning
0
Not clicked
429
IntControl
1
Left click
2
Right click
Note: Each time you call this
function the "click state" will be
reset to 0 (not clicked).
1
p2 = 1 or 2
p3 = tool tip
p4 = icon file
Add currentlyrunning script to the
system tray
2
p2, p3, p4
ignored
Remove currentlyrunning script from
the system tray
3
p2 = timeout
value in
milliseconds
after which the
script will
automatically
continue. If 0,
there is no
timeout.
p3, p4 ignored
Suspend script until
user clicks on the
tray icon
This can be used at any point after a
WinBatch script has already been
placed in the tray. When the user
clicks on the tray icon, it will return
one of the click values as listed for
p1 == 0.
4
p2 = 1 or 2
p3 = tool tip
p4 = icon
resource
Modify currentlyrunning script in the
system tray
p2 can be one or more of the
following flags, combined with the
bitwise OR ("|") operator:
Val Meaning
1 Modify tool tip (p3 specifies
430
p2 can be one or more of the
following flags, combined with the
binary OR ("|") operator:
Val Meaning
1 Hide regular WinBatch icon
while the icon is in the system
tray
2 Suspend script until user clicks
on the tray icon. The WinBatch
script will be suspended until
the user clicks on the tray icon,
at which point the script will
continue, and this function will
return one of the click values.
Otherwise, the WinBatch script
will continue running, and you
can periodically check to see
whether the user has clicked on
the tray icon by calling this
function with p1 == 0.
IntControl
the new tool tip)
2 Modify icon (p4 specifies the
new icon file)
p3 can be the tool tip (i.e., string
that is displayed when the mouse
passes over the tray icon), or "" for
none.
p4 can be icon file, or "" for the
default icon. If a file name is
specified, it can be a .ICL file (icon
library), or an .EXE or .DLL (or
similar resource file) containing
icons. If it is a resource containing
multiple icons, by default the first
icon in the file is used.
You can specify a different icon
using the following format:
"filename|#"
where "filename" is the name of the
file, followed by a vertical bar and
then the index of the desired icon in
the file ("#"). The first icon in a file
has an index of 0. If an invalid icon
file is specified, the default icon
will be used.
Note: The icon resource must
contain multiple images if you want
to specify an index greater than
zero.
Returns @TRUE (success) or @FALSE (failure), or a click value.
Example:
;This intcontrol puts script in systray and hides icon on taskbar
IntControl(1007, 1, 1, "YooHoo", "")
while 1
;This intcontrol Suspends the script
;until user clicks on the tray icon
IntControl(1007, 3, 1, "", "")
Pause("BEEEP","Icon was clicked")
;do stuff here
endwhile
IntControl(1008,p1,0,0,0)
Enables/disables Close command.
This function sets the "allow close" flag for the WinBatch icon/window.
431
IsDefined
By default, the "Close" item on the control menu and the "Close" icon to the right of
the window title are grayed out, and WinBatch does not respond to WM_CLOSE
messages sent by applications. Using this IntControl, you can enable all these, in
which case the Close command behaves the same as the existing Terminate/CtrlBreak command.
p1
Meaning
-1
Don't change (just return current setting)
0
Close command is disabled (default).
1
Close command is enabled.
Returns previous setting.
Example:
IntControl(12, 1+4, 0, 0, 0) ;Close Quietly
IntControl(1008, p1, 0, 0, 0) ;Enable Close button
IntControl(1009,p1,0,0,0)
Gets name of current service.
If the current script is running as a service, this function returns the name of the
service. Otherwise it returns a blank string ("").
"p1" specifies which name to return:
p1
Meaning
0
Returns the service name (the actual registry key name)
1
Returns the display name (the name shown in Control Panel)
Example:
svcname = IntControl(1009, 0, 0, 0, 0)
Message("Service name",svcname)
IsDefined
Determines if a variable name is currently defined.
Syntax:
IsDefined(var)
Parameters:
(s / a) var
432
a variable name.
IsFloat
Returns:
(i)
@YES if the variable is currently defined;
@NO if it was never defined or has been dropped;
-1 if the specified name is a function name or other reserved
word.
A variable is defined the first time it appears to the left of an equal sign in a
statement. It stays defined until it is explicitly dropped with the Drop function, or
until the current invocation of the WIL Interpreter gets closed.
Generally speaking: in batch file-based implementations of WIL, all variables are
dropped automatically at the end of every batch file; and in menu-based
implementations of WIL, variables stay defined until explicitly dropped.
IsDefined can accept an array name as a parameter.
Example:
if IsDefined(thisvar)
Message("Value of thisvar is", thisvar)
else
Message("ERROR!", "Variable not defined")
endif
See Also:
Drop, DropWild, VarType
IsFloat
Tests whether a variable can be converted to a floating point number.
Syntax:
IsFloat(x)
Parameters:
(s) x
value to be tested.
Returns:
(i)
@TRUE if the data can be converted to a floating point
number; @FALSE if the data cannot be converted to a
floating point number.
Use this function to test whether a variable can be converted into a floating point
number.
Example:
A=IsFloat(4)
Message("Is 4 a floating point number", A)
B=IsFloat("Hamburger")
Message(�Is "Hamburger" a floating point number’, B)
C=IsFloat(4.5)
Message("Is 4.5 a floating point number", C)
433
IsKeyDown
See Also:
IsInt, IsNumber
IsInt
Tests whether a variable is or can be converted into a valid integer.
Syntax:
IsInt(x)
Parameters:
(s) x
Returns:
(i)
value to be tested.
@TRUE if the data is or can be converted to a valid integer;
@FALSE if the data is not or cannot be converted to a valid
integer.
Use this function to test whether a variable can be converted into a valid integer.
Example:
A=IsInt(4)
Message("Is 4 an integer", A)
B=IsInt("Hamburger")
Message('Is "Hamburger" an integer', B)
C=IsInt(4.5)
Message("Is 4.5 an integer", C)
See Also:
IsFloat, IsNumber
IsKeyDown
Tells about keys/mouse.
Syntax:
IsKeyDown(keycodes)
Parameters:
(i) keycodes
@SHIFT and/or @CTRL.
Returns:
(i)
@YES if the key is down; @NO if the key is not down.
Determines if the Shift key or the Ctrl key is currently down.
Note: The right mouse button is the same as Shift, and the middle mouse button is
the same as Ctrl.
434
IsNumber
Examples:
IsKeyDown(@SHIFT)
IsKeyDown(@CTRL)
IsKeyDown(@CTRL | @SHIFT)
IsKeyDown(@CTRL & @SHIFT)
Message("IsKeyDown","Key Is Down.")
See Also:
WaitForKey
IsLicensed
Tells if the calling application is licensed.
Syntax:
IsLicensed()
Parameters:
(none)
Returns:
(i)
@YES if it is licensed; @NO if it is not licensed.
Returns information on whether or not the currently-running version of the calling
application is a licensed copy.
Example:
a=IsLicensed( )
If a == @TRUE
Message("IsLicensed","It's Licensed.")
else
Message("IsLicensed","No, it's not licensed.")
endif
See Also:
Version, VersionDLL
IsNumber
Tests whether a variable is or can be converted into a valid number.
Syntax:
IsNumber(x)
Parameters:
(s) x
value to be tested
435
ItemCountCsv
Returns:
(i)
@TRUE if the data is or can be converted to a valid
number; @FALSE if the data is not or cannot be converted
to a valid number.
Use this function to test whether a variable can be converted into a valid number,
either an integer or a floating point number.
Example:
A=IsNumber(4)
Message("Is 4 a number", A)
B=IsNumber("Hamburger")
Message('Is "Hamburger" a number', B)
C=IsNumber(4.5)
Message("Is 4.5 a number", C)
See Also:
IsFloat, IsInt
ItemCount
Returns the number of items in a list.
Syntax:
ItemCount(list,delimiter)
Parameters:
(s) list
(s) delimiter
a string containing a list of items.
a character to act as a delimiter between items in the list.
Returns:
(i)
the number of items in the list.
Note: leading and trailing delimiters are significant. This means that the commadelimited list "a,b,c," has 4 items in it.
A single item null list ("") is not a valid list.
Example:
a = FileItemize("*.*")
n = ItemCount(a, @TAB)
Message("Note", "There are %n% files")
See Also:
ItemCountCsv, ItemExtract, ItemExtractCsv, ItemInsert, ItemLocate,
ItemLocateWild, ItemRemove, ItemReplace, ItemSort, Lists Explained (pg. 82)
ItemCountCsv
Returns the number of items in a comma separated values line.
436
ItemCountCsv
Syntax:
ItemCountCsv(line,flags[,delimiter])
Parameters:
(s) line
(i) flags
(s)delimiter
Returns:
(i)
specifies a comma separated values line (see below).
can be set to 0, or can specify one or more of the following
values combined with the bitwise OR ('|') operator:
Value
Meaning
1
treat leading and trailing whitespace as
significant
[optional] specifies the character used to separate
values in the line. It can be any single
character except a space, null, carriage return, line
feed or quotation mark (double quote). If omitted,
a comma will be used as the delimiter.
the number of items in the Comma Separated Value line.
This function is like ItemCount, but instead of a list, it counts items in a CSV line.
A CSV ("comma separated values") line consists of comma-delimited items. Items
may optionally be enclosed in quotation marks (aka, "double quotes").
There are two cases where an item *must* be enclosed in quotation marks:
(1) If the item contains a comma
(2) If the item contains a quotation mark
Here are some examples:
1,2,3,4,5
"January","February","March"
"Doe, John",20
In order to embed a quotation mark in an item, you must replace it with two
quotation marks (i.e., add an extra quotation mark). For example, you would specify
the item "My Fair Lady" (with quotes) as:
"""My Fair Lady"""
Each quotation mark is doubled, and the entire item is enclosed in a set of quotation
marks.
Normally, whitespace outside of quoted strings is ignored. The following two lines
would be considered identical:
A,B,C
A, B, C
437
ItemExtract
But if you specify a "flags" value of 1, then the whitespace will be considered part of
the items. Whitespace *inside* a quoted string is always preserved, regardless of the
"flags" value:
"
This line has spaces around it
"
Similarly, whitespace outside of a quoted string is always ignored. i.e., the following
two lines are considered identical, regardless of the "flags" value
"String 1","String 2","String 3"
"String 1", "String 2", "String 3"
Example:
line = '"January","February","March"'
n = ItemCountCsv(line, 0, ",")
Message("Note", "There are %n% items in this CSV line")
See Also:
ItemCount, ItemExtract, ItemExtractCsv, ItemInsert, ItemLocate, ItemLocateWild,
ItemRemove, ItemReplace, ItemSort, Lists Explained (pg. 82)
ItemExtract
Returns the selected item from a list.
Syntax:
ItemExtract(index,list,delimiter)
Parameters:
(i) index
(s) list
(s) delimiter
the position in list of the item to be selected.
a string containing a list of items.
a character to act as a delimiter between items in the list.
Returns:
(s)
the selected item.
Note: Using -1 as the index will return the last item in the list.
A single item null list ("") is not a valid list.
Example:
DirChange(DirWindows(0))
bmpfiles = FileItemize("*.bmp")
bmpcount = ItemCount(bmpfiles, @TAB)
pos = (Random(bmpcount - 1)) + 1
paper = ItemExtract(pos, bmpfiles, @TAB)
Wallpaper(paper, @FALSE)
Message("ItemExtract","Wallpaper changed to %paper% - not tiled")
See Also:
ItemCount, ItemCountCsv, ItemExtractCsv, ItemInsert, ItemLocate,
ItemLocateWild, ItemRemove, ItemReplace, ItemSort, Lists Explained (pg. 82)
438
ItemExtractCsv
ItemExtractCsv
Returns the selected item from a CSV line.
Syntax:
ItemExtractCsv(index,line,flags[,delimiter])
Parameters:
(i) index
(s) line
(i) flags
(s) delimiter
Returns:
(s)
the ordinal position of the item to be returned.
a CSV line (see below).
can be set to 0, or can specify one or more of the following
values combined with the bitwise OR ('|') operator:
Value
Meaning
1
treat leading and trailing whitespace as
significant
[optional] specifies the character used to separate
values in the line. It can be any single
character except a space, null, carriage return, line
feed or quotation mark (double quote). If omitted,
a comma will be used as the delimiter.
the selected item.
This function is like ItemExtract, but instead of a list, it extracts items from a CSV
line. A CSV ("comma separated values") line consists of comma-delimited items.
Items may optionally be enclosed in quotation marks (aka, "double quotes").
There are two cases where an item *must* be enclosed in quotation marks:
(1) If the item contains a comma
(2) If the item contains a quotation mark
Here are some examples:
1,2,3,4,5
"January","February","March"
"Doe, John",20
In order to embed a quotation mark in an item, you must replace it with two
quotation marks (i.e., add an extra quotation mark). For example, you would specify
the item "My Fair Lady" (with quotes) as:
"""My Fair Lady"""
Each quotation mark is doubled, and the entire item is enclosed in a set of quotation
marks.
Normally, whitespace outside of quoted strings is ignored. The following two lines
would be considered identical:
439
ItemInsert
A,B,C
A, B, C
But if you specify a "flags" value of 1, then the whitespace will be considered part of
the items. Whitespace *inside* a quoted string is always preserved, regardless of the
"flags" value:
"
This line has spaces around it
"
Similarly, whitespace outside of a quoted string is always ignored. i.e., the following
two lines are considered identical, regardless of the "flags" value
"String 1","String 2","String 3"
"String 1", "String 2", "String 3"
The function returns the selected item, with any enclosing quotes removed, and any
doubled quotation marks converted to normal quotation marks. Leading and trailing
whitespace may be stripped out, as described above.
Example:
line = '"January","February","March"'
count = ItemCountCsv(line, 0, ",")
For x = 1 to count
item = ItemExtractCsv(x,line,0, ",")
Message(StrCat("Item number ",x),item)
Next
See Also:
ItemCount, ItemCountCsv, ItemExtract, ItemInsert, ItemLocate, ItemLocateWild,
ItemRemove, ItemReplace, ItemSort, Lists Explained (pg. 82)
ItemInsert
Adds an item to a list.
Syntax:
ItemInsert(item,index,list,delimiter)
Parameters:
(s) item
(i) index
(s) list
(s) delimiter
a new item to add to list.
the position in list after which the item will be inserted.
a string containing a list of items.
a character to act as a delimiter between items in the list.
Returns:
(s)
new list, with item inserted.
This function inserts a new item into an existing list, at the position following index.
It returns a new list, with the specified item inserted; the original list (list) is
440
ItemLocate
unchanged. For example, specifying an index of 1 causes the new item to be inserted
after the first item in the list; i.e., the new item becomes the second item in the list.
You can specify an index of 0 to add the item to the beginning of the list, and an
index of -1 to append the item to the end of the list.
Note: trailing delimiters are significant. This means that if you specify a blank item
("") and an offset of -1, a blank item will be added to the end of the list, even if the
list already has a trailing delimiter.
Example:
item="apricots"
list="apples pears oranges grapes"
newlist = ItemInsert(item, -1, list, " ")
message("List after ItemInsert", newlist)
See Also:
ItemCount, ItemCountCsv, ItemExtract, ItemExtractCsv, ItemLocate,
ItemLocateWild, ItemRemove, ItemReplace, ItemSort, Lists Explained (pg. 82)
ItemLocate
Returns the position of an item in a list.
Syntax:
ItemLocate(item,list,delimiter)
Parameters:
(s) item
(s) list
(s) delimiter
item to search for in list. (this is case sensitive)
a string containing a list of items.
a character to act as a delimiter between items in the list.
Returns:
(i)
position in list of item, or 0 if no match found.
This function finds the first occurrence of item in the specified list, and returns the
position of the item (the first item in a list has a position of 1). If the item is not
found, the function will return a 0.
A single item null list ("") is not a valid list.
Example:
list="apples pears oranges grapes"
index=ItemLocate("oranges", list, " ")
message("The item is located at index #", index)
See Also:
ItemCount, ItemCountCsv, ItemExtract, ItemExtractCsv, ItemInsert,
ItemLocateWild, ItemRemove, ItemReplace, ItemSort, Lists Explained (pg. 82)
441
ItemRemove
ItemLocateWild
Searches for an item in that list that fully matches a 'pattern'.
Syntax:
ItemLocateWild (pattern, list, delimiter, start)
Parameters:
(s) pattern
(s) list
(s) delimiter
(i) start
pattern to search for. may contain wild cards.
a string containing a list of items.
a character to act as a delimiter between items in the list.
position of first item to search.
Returns:
(i)
position in list of item, or 0 if no match found.
Searches 'list' for first item that fully matches 'pattern' and returns the position of the
matching item or 0 if no item fully matches. The search starts with the item indicated
by the 'start' parameter. When an item satisfies the pattern, checking of that item is
halted. If the pattern is satisfied without consuming the entire item, it is not
considered a match and checking continues with the next item.
In the wild-card pattern, "*" matches zero or more characters, and "?" matches any
one character.
ItemLocateWild searches are case insensitive.
A single item null list ("") is not a valid list.
Example:
list="apples pears oranges grapes"
index = ItemLocateWild("o*s", list, " ", 1)
message("The item is located at index #", index)
See Also:
ItemCount, ItemCountCsv, ItemExtract, ItemExtractCsv, ItemInsert, ItemLocate,
ItemRemove, ItemReplace, ItemSort, Lists Explained (pg. 82)
ItemRemove
Removes an item from a list.
Syntax:
ItemRemove(index,list,delimiter)
Parameters:
(i) index
(s) list
(s) delimiter
442
the position in list of the item to be removed.
a string containing a list of items.
a character to act as a delimiter between items in the list.
ItemReplace
Returns:
(s)
new list, with item removed.
This function removes the item at the position specified by index from a list. The
delimiter following the item is removed as well. It returns a new list, with the
specified item removed; the original list (list) is unchanged.
Note: Using -1 as the index will remove the last item in the list.
A single item null list ("") is not a valid list.
Example:
Exlist="apples pears oranges grapes"
index=ItemLocate("oranges", list, " ")
newlist = ItemRemove(index, list, " ")
message("List after item is removed", newlist)
See Also:
ItemCount, ItemCountCsv, ItemExtract, ItemExtractCsv, ItemInsert, ItemLocate,
ItemLocateWild, ItemReplace, ItemSort, Lists Explained (pg. 82)
ItemReplace
Replaces an item in a list.
Syntax:
ItemReplace(item,index,list,delimiter)
Parameters:
(s) item
(i) index
(s) list
(s) delimiter
replacement item.
the position in list of the item to be replaced.
a string containing a list of items.
a character to act as a delimiter between items in the list.
Returns:
(s)
new list, with item replaced.
This function replaces an item in a list with a new item. It returns a new list, with the
specified replacement made; the original list ("list") is unchanged. For example,
specifying an index of 1 causes the first item in the list to be replaced with the new
item ("item").
Note: Using -1 as the index will replace the last item in the list.
A single item null list ("") is not a valid list.
Example:
list="apples pears oranges grapes"
index=ItemLocate("oranges", list, " ")
newlist = ItemReplace("tangerine", index, list, " ")
message("List after item is replaced", newlist)
443
KeyToggleGet
See Also:
ItemCount, ItemCountCsv, ItemExtract, ItemExtractCsv, ItemInsert, ItemLocate,
ItemLocateWild, ItemRemove, ItemSort, Lists Explained (pg. 82)
ItemSort
Sorts a list.
Syntax:
ItemSort(list,delimiter)
Parameters:
(s) list
(s) delimiter
a string containing a list of items.
a character to act as a delimiter between items in the list.
Returns:
(s)
new, sorted list.
This function sorts a list, using an "ANSI Collating Sequence" sort, also known as a
"dictionary sort". It returns a new, sorted list; the original list is unchanged.
A single item null list ("") is not a valid list.
Example:
list=" one two three four "
newlist = ItemSort(list, " ")
message("List generated by ItemSort", newlist)
See Also:
ItemCount, ItemCountCsv, ItemExtract, ItemExtractCsv, ItemInsert, ItemLocate,
ItemLocateWild, ItemRemove, ItemReplace, Lists Explained (pg. 82)
KeyToggleGet
Returns the status of a toggle key.
Syntax:
KeyToggleGet(@key)
Parameters:
(i) @key
Returns:
(i)
444
the toggle key in question. Values may be one of:
@CAPSLOCK
for the CapsLock key
@NUMLOCK
for the NumLock key
@SCROLLLOCK for the ScrollLock key
@ON key was set; @OFF key was unset.
LastError
Use this function to obtain the state of one of the toggle keys - the CapsLock,
NumLock, and ScrollLock keys.
Example:
a1=KeyToggleGet(@NUMLOCK)
a2=KeyToggleGet(@CAPSLOCK)
a3=KeyToggleGet(@SCROLLLOCK)
b= strcat(a1,"
",a2,"
",a3)
Message("NumLock
CapsLock
ScrollLock", b)
See Also:
KeyToggleSet, SendKey
KeyToggleSet
Sets the state of a toggle key and returns the previous value.
Syntax:
KeyToggleSet(@key,value)
Parameters:
(i) @key
(i) value
Returns:
(i)
the toggle key in question. Values may be one of:
@CAPSLOCK
for the CapsLock key
@NUMLOCK
for the NumLock key
@SCROLLLOCK for the ScrollLock key
The new value of the toggle key.
@OFF
for the unset state
@ON
for the set state
Previous toggle state of the key:
@ON key was set; @OFF key was not set
Use this function to alter the state of one of the toggle keys - the CapsLock,
NumLock, and ScrollLock keys.
Example:
KeyToggleSet(@NUMLOCK, @ON)
KeyToggleSet(@CAPSLOCK, @ON)
KeyToggleSet(@SCROLLLOCK, @ON)
See Also:
KeyToggleGet, SendKey
LastError
Returns the most-recent error encountered during the current WIL program.
445
Log10
Syntax:
LastError()
Parameters:
(none)
Returns:
(i)
most-recent WIL error code encountered.
WIL errors are numbered according to their severity. "Minor" errors go from 1000
through 1999. Moderate errors are 2000 through 2999. Fatal errors are numbered
3000 to 3999.
Depending on which error mode is active when an error occurs, you may not get a
chance to check the error code. See ErrorMode for a discussion of default error
handling.
Every time the LastError function is called, the "last error" indicator is reset to zero.
A full listing of possible errors you can encounter in processing a WIL program is in
the WIL help file. Of course, if you use the LastError function to trap errors, then
extensive script testing -- including all error conditions -- is highly recommended.
Example:
ErrorMode(@OFF)
LastError( )
FileCopy("data.dat", "c:\backups\*.*", @FALSE)
ErrorMode(@CANCEL)
If LastError( ) == 1006
Message("Error", "Please call Tech Support at 555-9999.")
endif
Message("LastError"," Done.")
See Also:
Debug, ErrorMode, Handling Errors, IntControl 73
Log10
Calculates the base-10 logarithm.
Syntax:
Log10(x)
Parameters:
(f) x
floating point number.
Returns:
(f)
the logarithm of the argument .
446
LogE
The Log10 function calculates the base-10 logarithm of the argument. If the
argument is negative or zero, an error will occur.
Example:
a = Log10(123.45)
Message("Base-10 log of 123.45 is", a)
See Also:
Loge, Exp, operator **
LogDisk
Logs (activates) a disk drive.
Syntax:
LogDisk(drive-letter)
Parameters:
(s) drive-letter
Returns:
(i)
the disk drive to log into.
@TRUE if the current drive was changed;
@FALSE if the drive doesn't exist.
Use this function to change to a different disk drive.
Example:
LogDisk("C:")
Message("LogDisk","Disk Logged.")
See Also:
DirChange, DiskScan
LogE
Calculates the natural logarithm.
Syntax:
LogE(x)
Parameters:
(f) x
floating point number.
Returns:
(f)
the logarithm of the argument x.
The LogE function calculates the natural logarithm of the argument. If the argument
is negative or zero, an error will occur.
447
Message
Example:
a = LogE(123.45)
Message("Natural log of 123.45 is", a)
See Also:
Log10, Exp, operator **
Max
Returns largest number in a list of numbers.
Syntax:
Max(number[,number...])
Parameters:
(f) number
floating point number(s).
Returns:
(f)
largest number.
Use this function to determine the largest of a set of comma-delimited numbers.
Example:
a = Max(5, -3.57, 125, 34E3, 2345.12, -32767)
Message("Largest number is", a)
See Also:
Abs, Average, Min, Random
Message
Displays a message to the user.
Syntax:
Message(title,text)
Parameters:
(s) title
(s) text
title of the message box.
text to display in the message box.
Returns:
(i)
@TRUE.
Use this function to display a message to the user. The user must respond by
selecting a button before processing will continue.
Example:
Message("Current directory is", DirGet( ))
which produces:
448
Mod
See Also:
Display, Pause
Min
Returns lowest number in a list of numbers.
Syntax:
Min(number[,number...])
Parameters:
(f) number
floating point number(s).
Returns:
(f)
lowest number.
Use this function to determine the lowest of a set of comma-delimited numbers.
Example:
a = Min( 5, -37.5, 125, 34.26, 2345E4, -32767)
Message("Smallest number is", a)
See Also:
Abs, Average, Max, Random
Mod
An operator used to divide two numbers and return only the remainder.
Syntax:
result = number1 Mod number2
The modulus, or remainder, operator divides number1 by number2 (rounding
floating-point numbers to integers) and returns only the remainder as result. For
example, in the following expression, ret (which is result) equals 1.
449
MouseClick
ret = 10 Mod 3
Message("Result = ", ret)
Example:
;This example grabs the Time/Day of the Week.
a=TimeYmdHms( )
b=TimeJulianDay(a)
c=(b+5) mod 7
day=ItemExtract(c+1, "Sun Mon Tue Wed Thu Fri Sat", " ")
line=StrCat("Julian Date-> ", b,@CRLF,"Day of week-> ",day)
Message(TimeDate( ), line)
See Also:
Operators
MouseClick
Clicks mouse button(s).
Syntax:
MouseClick(click-type,modifiers)
Parameters:
(i) click-type
(i) modifiers
a mouse button press.
click variations for mouse button presses.
Returns:
(i)
@TRUE on success; @FALSE on error.
This function performs a mouse click at the current cursor position.
"Modifiers" can be set to 0 if none are needed.
Click-types:
@LCLICK
@RCLICK
@MCLICK
@LDBLCLICK
@RDBLCLICK
@MDBLCLICK
left click
right click
middle click
left double-click
right double-click
middle double-click
Modifiers (multiple modifiers can be linked together with a logical OR, "|"):
@SHIFT
@CTRL
@LBUTTON
@RBUTTON
@MBUTTON
450
hold down shift key
hold down control key
hold down left mouse button
hold down right mouse button
hold down middle mouse button
MouseClickBtn
NOTE: The modifers are in effect until the click type is executed. [ For example, a
Shift key plus a right mouse click would be: MouseClick(@RCLICK, @SHIFT) ]
Example:
Run("notepad.exe","")
Message("Notepad Running","We will now close it via a mouseclick on
the close button")
winpos = WinPlaceGet(@NORMAL, "~Notepad")
; get coordinates for upper right corner of window
x = ItemExtract(3, winpos, " ") - 10
y = ItemExtract(2, winpos, " ") + 10
WinActivate("~Notepad")
MouseMove(x - 10, y + 10, "", "")
MouseClick(@LCLICK, 0)
See Also:
IntControl 35, MouseInfo, MouseClickBtn, MouseMove, SendKey
MouseClickBtn
Clicks on the specified button control.
Syntax:
MouseClickBtn(parent-winname,child-winname,button-text)
Parameters:
(s) parent-winname
(s) child-winname
(s) button-text
the initial part of, or an entire parent window name.
the initial part or, or an entire child window name.
text specifying a button control.
Returns:
(i)
@TRUE on success; @FALSE on error.
This function clicks on the pushbutton, radio button, or checkbox whose text is
specified by "button-text".
If the button is located within a top-level window, specify the window name in
"parent-winname" and specify a blank string ("") for "child-winname".
If the button is located within a child window, specify the top-level window name in
"parent-winname" and the child window name in "child-winname".
Example:
SendMenusTo("Exploring", "Tools | Map Network Drive")
TimeDelay(1)
;Click Reconnect at logon button
MouseClickBtn("Map Network Drive", "", "Reconnect at logon")
Message("MouseClickBtn","Reconnect at logon button clicked")
451
MouseInfo
See Also:
MouseClick, MouseClickBtn, MouseMove, SendKey
MouseCoords
Returns coordinates of the mouse within a window.
Syntax:
MouseCoords(parent-winname,child-winname)
Parameters:
(s) parent-winname
(s) child-winname
Returns:
(s) coordinates
the initial part of, or an entire parent window name.
the initial part or, or an entire child window name.
the x and y coordinates of the mouse cursor, relative to the
window specified by "win-name" and "child-win".
If "parent-winname" specifies a top-level window and "child-winname" is a blank
string, the specified X-Y coordinates are relative to "parent-winname".
If "parent-winname" specifies a top-level window and "child-winname" specifies a
child window of "parent-winname", the specified X-Y coordinates are relative to
"child-winname".
If "parent-winname" and "child-winname" are both blank strings, the specified X-Y
coordinates are relative to the Windows desktop.
All coordinates are based on a virtual 1000 x 1000 screen.
Note: The size and shape of displayed windows are usually based on a combination
of screen resolution and the system font size. Thus the x and y coordinates may be
different on each individual machine.
Example:
coords=MouseCoords("", "")
message("Coordinates are relative to the Windows desktop.",coords)
See Also:
MouseClick, MouseClickBtn,MouseInfo, SendKey
MouseInfo
Returns assorted mouse information.
Syntax:
MouseInfo(request#)
452
MouseInfo
Parameters:
(i) request#
see below.
Returns:
(s)
see below.
The information returned by MouseInfo depends on the value of request#.
Req#
0
1
2
3
4
5
6
7
8
9
10
Return value
Window name under mouse
Top level parent window name under mouse
Mouse coordinates, assuming a 1000x1000 virtual screen
Mouse coordinates in absolute numbers
Status of mouse buttons, as a bitmask:
Binary
Decimal
Meaning
000
0
No buttons down
001
1
Right button down
010
2
Middle button down
011
3
Right and Middle buttons down
100
4
Left button down
101
5
Left and Right buttons down
110
6
Left and Middle buttons down
111
7
Left, Middle, and Right buttons down
returns mouse coordinates relative to the client area of the window
under the cursor, in virtual (1000x1000) screen units.
returns mouse coordinates relative to the client area of the window
under the cursor, in virtual (1000x1000) client units.
returns mouse coordinates relative to the bounding rectangle of the
window under the cursor, in virtual (1000x1000) screen units.
returns asynchronous status of mouse buttons, as a bitmask. This is like
request #4, except #8 returns the asynchronous (current) state of the
buttons, whereas #4 returns the state at the time the function was called.
Window ID of top level parent window under mouse.
Similar to request 0 except that the request can also return the window
name of static, hidden and disabled child windows that have a caption.
Examples of static windows include WIL Dialog VARYTEXT,
STATICTEXT and PICTURE controls.
For example, if mouse is at the center of a 640x480 screen and above the "Clock"
window, and the left button is down, the following values would be returned:
Req#
0
1
Return value
"Clock"
"Clock"
453
MouseMove
2
3
4
"500 500"
"320 240"
"4"
Note: The size and shape of displayed windows are usually based on a combination
of screen resolution and the system font size. Thus the x and y coordinates may be
different on each individual machine.
Example:
Display(1, "", "Press a mouse button to continue")
buttons = 0
while buttons == 0
buttons = MouseInfo(4)
endwhile
If buttons & 4
Display(1, "", "Left button was pressed")
endif
If buttons & 1
Display(1, "", "Right button was pressed")
endif
See Also:
SysParamInfo, WinMetrics, MouseClick, MouseClickBtn, MouseMove
MouseMove
Moves the mouse to the specified X-Y coordinates.
Syntax:
MouseMove(X,Y,parent-winname,child-winname)
Parameters:
(i) X
(i) Y
(s) parent-winname
(s) child-winname
integer specifying the coordinate X.
integer specifying the coordinate Y.
the initial part of, or an entire parent window name.
the initial part or, or an entire child window name.
Returns:
(i)
@TRUE on success; @FALSE on error.
This function accepts partial window names.
If "parent-winname" specifies a top-level window and "child-winname" is a blank
string, the specified X-Y coordinates are relative to "parent-winname".
If "parent-winname" specifies a top-level window and "child-winname" specifies a
child window of "parent-winname", the specified X-Y coordinates are relative to
"child-winname".
454
MousePlay
If "parent-winname" and "child-winname" are both blank strings, the specified X-Y
coordinates are relative to the Windows desktop.
All coordinates are based on a virtual 1000 x 1000 screen.
Note: The size and shape of displayed windows are usually based on a combination
of screen resolution and the system font size. Thus the x and y coordinates may be
different on each individual machine.
Example:
MouseMove(335, 110, "", "")
See Also:
MouseClick, MouseClickBtn, MouseInfo, SendKey
MousePlay
Performs full range of mouse associated activities.
Syntax:
MousePlay(X-Y-coordinates,parent-winname,child-winname,buttons,delay)
Parameters:
(s) X-Y-coordinates space-delimited string with the final mouse x and y position,
in virtual 1000x1000 units.
(s) parent-winname name of parent window to move mouse relative to, or "" to
specify the desktop.
(s) child-winname
name of child window (i.e., child of "parent-window") to
move mouse relative to, or "" if the movement will be
relative to "parent".
(i) buttons
combination of one or more mouse buttons and keys to click
and/or hold down (see below for list).
(f) delay
amount of time to take for performing the mouse activity, in
seconds. Can be a decimal number to indicate a fraction of
a second.
Returns:
(i)
returns @TRUE.
MousePlay allows you to perform the full range of mouse associated activities with
a single function.
You can simulate drag-and-drop operations by specifying the drop location in the
"X-Y-coordinates" parameter and adding the @MPLAYLBUTTON constant to the
"buttons" parameter. This tells MousePlay to move the mouse to the position x,y
with the left mouse button down.
You can perform a mouse button click at a specific location by using one of the
button click values in the "buttons" parameter.
455
MousePlay
MousePlay can move the mouse cursor relative to the upper left-hand corner of a
window. To do this simply place a window name in the "parent window" parameter
and optionally in the "child window" parameter. If you give MousePlay a child
window name you must give it a parent name as well. When window names are
present, MousePlay considers the upper left-hand corner of the parent or child
window to be 0,0. It is, therefore, possible to give it a negative x or y value to move
the mouse cursor to the left or above the window. If the window you specify is
minimized, MousePlay will use its last un-minimized size for calculating mouse
position.
MousePlay also accepts the WIL constants @SHIFT and @CTRL in the "buttons"
parameter. You can combine these constants with a mouse button constant using the
bitwise OR ('|') operator to duplicate holding down the Shift or Control key while
performing a mouse drag-and-drop or button click.
You can use the "delay" parameter to control the amount of time MousePlay takes to
perform an action. Sometimes it is necessary to slow down the mouse so that
Windows will properly recognize the action. You may also want to slow things
down to better track events or to just give your mouse activity a natural appearance.
This parameter expects values in seconds, and only recognizes the first three digits to
the right of the decimal point.
IntControl 35 can also be used to slow down mouse clicks. If the MousePlay delay
is less than the IntControl specified time, MousePlay will take the amount of time
indicated by the IntControl setting.
Values for the "buttons" parameter:( combine using the bitwise | (OR) operator.)
Constant
@MPLAYLCLK
@MPLAYRCLK
@MPLAYMCLK
@MPLAYLDBLCK
@MPLAYRDBLCK
@MPLAYMDBLCK
@MPLAYLBUTTON
@MPLAYRBUTTON
@MPLAYMBUTTON
@SHIFT
@CTRL
Meaning
Click left mouse button.
Click right mouse button.
Click middle mouse button.
Double click left mouse button.
Double click right mouse button.
Double click middle mouse button.
Hold down the left mouse button.
Hold down the right mouse button.
Hold down the middle mouse button.
Hold down the shift key.
Hold down the control key.
Note: The size and shape of displayed windows are usually based on a combination
of screen resolution and the system font size. Thus the x and y coordinates may be
different on each individual machine.
456
MsgTextGet
Example:
Note: These examples may not run on your system due to various configuration
options.
; Example 1
; Run Explorer as a maximized window
RunZoom("explorer.exe", "")
WinWaitExist("~Exploring",5)
WinActivate("~Exploring")
; now click on the minimize button in the upper-right corner
MousePlay("956 16", "~Exploring", "", @MPLAYLCLK, 5)
exit
; Example 2
; Moves mouse cursor from lower left hand corner of the screen
; to the upper right hand corner of the screen
MousePlay("0 1000", "", "", 0, 0.2)
MousePlay("70 973", "", "", 0, 0.2)
MousePlay("589 533", "", "", 0, 0.2)
MousePlay("880 238", "", "", 0, 0.2)
MousePlay("997 107", "", "", 0, 0.2)
MousePlay("1000 0", "", "", 0, 0.2)
See Also:
IntControl 35, MouseClick, MouseClickBtn, MouseInfo, SendKey, SendKeysTo
MsgTextGet
Returns the contents of a Windows message box.
Syntax:
MsgTextGet(window-name)
Parameters:
(s) window-name
full title of the message box window.
Returns:
(s)
contents of the message box.
This function returns the text contents of a standard Windows message box.
"Window-name" must be the full title of the message box window, and is casesensitive.
Note1: This function may not work with the types of message boxes created by the
application you wish to control if it is not a standard Windows Message box.
However, if this function does work, it is the easiest way to keep tabs on an
application.
Note2: This function will not work with the types of message boxes created by most
WIL functions, since they are not standard Windows message boxes.
457
NetInfo
Example:
msg = MsgTextGet("Microsoft Word")
If msg == "Search text not found"
SendKey("~")
endif
Message("MsgTextGet"," Message Text Gotten.")
See Also:
WinGetActive
Net101
All network functionality for WIL is performed via "WIL Extenders", add-on Dlls
for WIL, which contain Network commands for assorted networks.
NetInfo is the only WIL network function. It returns the types of the networks
currently active on the local machine, and can be used to help determine which
network extenders should be loaded in multi-network environments.
Documentation for the various network extenders are found in associated help files.
See Also:
AddExtender, DllCall, NetInfo
NetInfo
Determines network(s) installed.
Syntax:
NetInfo(requestcode)
Parameters:
(i) requestcode
Returns:
(s)
0 for primary network name
1 for secondary subnet list
Primary network name for request code 0, or
Secondary network list for request code 1.
Use this function to determine the network type(s) running on a workstation. When
running in a mixed network environment, it may be important to be able to determine
the types of networks running on a workstation so as to be able to load the
appropriate network extender Dlls and issue the corresponding commands.
NetInfo(0) will return the string "WINNT" for 32 bit Windows platforms.
Under Windows NT and newer, NetInfo(1) will return a list of installed network
provider ID's, delimited with the standard file delimiter (by default, a tab).
Possible providers, with their corresponding descriptions, are:
458
ObjectClose
Provider ID
LanmanWorkstation
NetWareWorkstation
NWCWorkstation
Description
Microsoft Windows Network
NetWare Services
NetWare or Compatible Network
Example:
a = NetInfo(0)
b = NetInfo(1)
;NT or newer
c = "Network Provider ID's: "
d = StrReplace(b, @tab, ",")
rslt = StrCat("Primary Network Name: ", a, @CRLF, c, d)
Message("NetInfo Results", rslt)
See Also:
AddExtender, DllCall, Net101
Num2Char
Converts a number to its character equivalent.
Syntax:
Num2Char(number)
Parameters:
(i) number
Returns:
(s)
any number from 0 to 255.
one-byte string containing the character which the number
represents.
Use this function to convert a number to its ASCII equivalent.
Example:
; Build a variable containing a CRLF combo
crlf = StrCat(Num2Char(13), Num2Char(10))
Message("NUM2CHAR", StrCat("line1", crlf, "line2"))
See Also:
Char2Num, IsNumber
ObjectClose
Closes an COM/OLE Automation object
Syntax:
ObjectClose(objecthandle)
Parameters:
(r) objecthandle
handle of object to close.
459
ObjectClrNew
Returns:
(i)
@TRUE.
ObjectClose is now obsolete. When WIL processing for an object is complete,
set the object variable to a null string to free WIL processor memory.
objVar = ""
The ObjectClose function closes an object and frees WIL processor memory. The
parameter passed to ObjectClose must be the same variable that the return value
from the corresponding ObjectOpen was placed into. Otherwise the function will
fail.
Example:
objFSO = ObjectOpen("Scripting.FilesystemObject")
objDrives = objFSO.Drives
ForEach objDrive in objDrives
Message("", objDrive.Path)
Next
ObjectClose(objFSO)
See Also:
COM, ObjectOpen
ObjectClrNew
Creates a class, structure or enumeration implemented by a managed assembly. The
function returns a Framework based type as a COM Automation reference that can
be used to access the members of the underlying Framework based type.
Syntax:
ObjectClrNew( typename [, ctorparm,...] )
Parameters:
(s) typename
(s/i/f/v) ctorparm
The name of a Framework based class, structure or
enumeration. The name must be fully qualified by including
the dot (.) separated namespace prefixed to the type's
immediate name. The namespace name and immediate
name must also be separated by a dot character.
0 to 15 constructor parameters to be used when creating a
type. Since type constructors can be overloaded, the type
and number of these parameters control which constructor
will be used to create the type.
Returns:
(r) object reference.
The assembly implementing the type specified by 'typename' must be loaded into the
WinBatch process before this function can be called to create the type. The
460
ObjectClrNew
exceptions to this requirement are types implemented by the "mscorlib" assembly.
This assembly is automatically loaded by WinBatch when the CLR is loaded. All
other assemblies must be loaded into the WinBatch process using the
ObjectClrOption function's Use option.
Members of the returned object reference are called using the same variablename+dot+member-name syntax used by standard COM Automation object
references. However, there are some important differences between regular COM
calls and CLR type member calls. The most significant difference is that CLR
constructors and type member names can be overloaded. This means that more than
one member can have the same name. When more than one member has the same
name, WinBatch and the CLR determine which member to call based on the number
and type of the parameters passed in the call statement. The combination of member
name, parameter types and parameter count is called the member's signature. This
means that using the correct type for each parameter is crucial to calling the correct
member.
Both member overloading and the fact that WinBatch cannot query the object for
type information before making a member call, as it does with regular COM
Automation references, means that the colon (:) type qualifier needs to be used more
frequently on CLR object member parameters. Fortunately, WinBatch will take
standard variant type names like BSTR, UI8, BOOLEAN, R8, e.g., and convert them
to equivalent Framework types automatically. It will also automatically deduce the
correct Framework type for variant variables passed as parameters to a member
without needing to specify a type with the colon qualifier. When a Framework based
type does not have equivalent variant type, the fully qualified Framework based type
name can be used with colon type qualifier on a parameter. This is most often
necessary when the object member is expecting an up-cast or down-cast of
Framework based class, when it is expecting a value from a Framework based
enumeration, or when it is expecting an array with elements of a specific Framework
based type. In the case of arrays, the type qualifier should be the Framework based
type of the elements prefixed to the variable name of a variable that holds either a
WIL array or a variant safearray. No array type information ('ARRAY' or
'System.Array') should be included in the type qualifier. When using a Framework
type name qualifier with any parameter the type qualifier's assembly must be loaded
before the member with the qualified parameter is called.
Another significant difference between standard COM Automation object and
Framework based wrapped objects is that unlike standard COM Automation objects,
Framework based object member names are case sensitive.
The function allows access to most Framework based types and their members but
there are a few limitations and restrictions. The following is a partial list of those
limitations and restrictions:
461
ObjectClrOption
п‚·
WinBatch relies on the CLR hosting's reflection functionality to instantiate
classes. There are a few classes attributed to block instantiation via
reflection.
п‚·
WinBatch does not support 'out' parameters. Method without parameters
can still be called but 'out' parameter values are not modified on the
method's return.
п‚·
Class member overloads that rely solely on the return type and name for
their signature cannot be used.
п‚·
Value types (structures) that only provide a multiple parameter
constructor(s) cannot be used.
п‚·
A small number of type member names conflict with WinBatch identifier
naming rules and cannot be called directly.
п‚·
Parameterize properties are not supported.
Example:
objDirectory = ObjectClrNew( 'System.IO.Directory' )
path = 'C:\temp\'
ret = objDirectory.Exists( path )
If ret
Pause( 'Directory Exist?', 'Yes' )
Else
Pause( 'Directory Exist?', 'No' )
EndIf
Exit
See Also:
ObjectClrOption, ObjectClrType, ObjectType, ObjectTypeGet
ObjectClrOption
Sets CLR configuration options before the CLR is loaded and loads an assembly into
the current WinBatch process.
Syntax:
ObjectClrOption (option-name, option-value )
Parameters
(s) option-name
(s) option-value
available options are "version", "appbase", or "use". See
below for details.
CLR version string, file system path, or assembly name
depending on the option-name.
Returns:
(i) @TRUE on success.
462
ObjectClrOption
Option-Name
Option-Value
version
Use this option to instruct WinBatch to load a specific version
of the CLR. The option-value parameter string must start with
the character "v" followed by the first three parts of the version
number. Currently, Microsoft provides the following CLR
versions "v1.0.3705","v1.1.4322","v2.0.50727" and
"v4.0.30319". The option must be set before the first call to this
function with the "use" option or before the first call to the
ObjectClrNew function. If the "version" option is not used
before the CLR is loaded, WinBatch will attempt to load the
current system's latest installed version of the CLR.
appbase
The option-value parameter for this option is used to indicate
the full file system path that presents the location of assemblies
you plan on using in your script that are not installed into the
global assembly cache (GAC) of the system running the script.
This option must be set before the first call to this function
setting a "use" option or before the first call to the
ObjectClrNew function.
You DO NOT use the name of the file containing the
assemblies with the 'appbase' option. You DO specify the full
(not partial) path to the location of the assemblies you are
going to use in your script that are not in the GAC. Logically
this means that all non GAC assemblies need to be placed in
the same directory for a given script
version
This option is used to load assemblies into the WinBatch
process. Assemblies must be loaded before the types the
assembly implements can be used. The option-value parameter
for this option must be a string variable or literal containing an
assembly name. If an assembly is stored in the GAC, it is
generally necessary to use the fully qualified assembly name.
The fully qualified assembly name has the format "assembly's
name, version=x.x.x.x,
culture=xxxx,PublickeyToken=xxxxxxxxxxxxxxxx". For
example, the fully qualified name of the "System.Data"
assembly is "System.Data, version=1.0.3300.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089". Full
assembly names can be found by using the Mscorcfg.msc tool,
by view the Global Assembly Cache (GAC) directory directly,
or by using the Gacutil.exe tool.
Example:
process = 'C:\Windows\Notepad.exe'
friendlyname = 'Notepad'
463
ObjectClrType
; Version - Instruct WinBatch to load a specific version of the CLR
ObjectClrOption ("version","v4.0.30319")
; Use - Load assembly into the WinBatch process
ObjectClrOption ("use","System, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089")
objnetProcess = ObjectClrNew("System.Diagnostics.Process" )
; Start a process
objnetProcess.Start(process)
TimeDelay(1)
; GetProcessesByName method
; Creates an array of new Process components and associates them with
; all the process resources on the local computer that share the ;
specified process name.
arrProcesses = objnetProcess.GetProcessesByName(friendlyname)
If ArrInfo(arrProcesses, 1 ) >= 1
; Get first matching process
myProcess = arrProcesses[0]
myProcess = ObjectClrType("System.Diagnostics.Process",myProcess)
; Tests the Responding property for a @True return value.
action = 'No Op '
If myProcess.Responding
myProcess.CloseMainWindow()
action = 'Closed '
Else
;Forces the process to close if the Responding value is @False.
myProcess.Kill()
action = 'Killed '
EndIf
EndIf
Pause(friendlyname, action : friendlyname )
Exit
See Also:
ObjectClrNew, ObjectClrType, ObjectType, ObjectTypeGet
ObjectClrType
Associate a Framework based type name with a value, or to up-cast or down-cast
Framework based object references.
Syntax:
ObjectClrType (typename, value-ref)
Parameters
(s) typename
464
name of a Framework based class, structure or enumeration.
The name must be fully qualified by including the dot (.)
separated namespace prefixed to the type's immediate
name. The namespace name and immediate name must also
be separated by a dot character.
ObjectClrType
(s/i/f/v) value- ref
simple string, integer, float, variant or a reference to a
Framework based object.
Returns:
(r) special WIL variant containing a reference to an Unknown interface.
Use this function to either associate a Framework based type name with a value, or
to up-cast or down-cast Framework based object references.
If the second parameter is a simple string, integer, float, or variant that is NOT a
reference to a Framework based object, the returned reference can ONLY be used as
a parameter to a Framework based object method call, as the right-hand side of a
Framework based object property assignment or a constructor argument in a call to
ObjectClrNew. In other words, the returned reference does not have user callable
methods, properties or fields.
On the other hand, if the second parameter is a reference to a Framework based
object and the first parameter is the typename of a base or derived type of that object
then the returned reference can be used to access the members of either the base or
derived type of the input object.
If the second parameter does NOT contain a Framework based object reference, the
assembly implementing typename must be loaded BEFORE the return reference is
used as a method parameter, property value or constructor argument. If the second
parameter contains a Framework based object reference, the assembly implementing
typename must be loaded BEFORE this function is called.
Example:
See ObjectClrNew Example.
See Also:
ObjectClrNew, ObjectClrOption, ObjectType, ObjectTypeGet
ObjectConstantsGet
Creates a Constants object.
Syntax:
ObjectConstantsGet(object)
Parameters
(r) object reference
COM object reference.
Returns:
(r)
constants object reference.
Use this function to create a constants object for a COM Automation object:
adoApp = ObjectCreate("ADODB.Connection")
adoConst = ObjectConstantsGet(adoApp)
465
ObjectClrType
The function will produce an error, if the supplied parameter is not a COM object or
is a COM object that does not have any associated constants.
A constants object is a special WIL language construct that allow you to access the
constant values associated with a COM object by name. You access values by using
the constants.name syntax where constants is the name of the variable holding this
function’s return and name is the name of constant whose value you wish to use. For
instance, if the constants object from the example above is used, then
conVal = adoConst.adBSTR
assigns the value of the constant adBSTR to the variable conVal. In this case, the
constant adBSTR has the value eight(8), so after the assignment the variable conVal
will hold the number 8.
You can use the constants.name syntax anywhere you would use a literal. This
includes using it as an object method parameter, as the right-hand-side of an object
property assignment, and in relational and arithmetic expressions. You cannot,
however, assign a new value to an individual constant name. They are in effect readonly.
NOTE: This function may have an impact on the performance of your scripts. Some
COM objects have thousands of constants and you may experience a small delay
while the function collects the constants’ names and values.
Example:
This example uses the ObjectConstantsGet function to obtain the constants
associated with the ADODB.RecordSet object. The constants are then used to set the
CursorLocation property and to specify the data types for each record field.
; Get a recordset object reference.
objRs = ObjectCreate("ADODB.RecordSet")
; Get the constants object for RecordSet
conRs = ObjectConstantsGet(objRs)
; Set cursor source using constant.
objRs.CursorLocation = conRs.adUseClient
; Create record fields using constants
; for Append’s data types parameter.
objRs.Fields.Append("MyText",conRs.adVarwchar,30)
objRs.Fields.Append("MyDecimal",conRs.adDecimal)
objRs.Fields("MyDecimal").DefinedSize = 19
objRs.Fields("MyDecimal").Precision = 18
objRs.Fields("MyDecimal").NumericScale = 6
objRs.Fields.Append("MyBoolean",conRs.adBoolean)
objRs.Fields.Append("MyDate",conRs.adDate)
; Commit the record metadata
466
ObjectConstToArray
objRs.Open()
objRs.Addnew()
; ... Add data to the record set here...
; ... save records to disk here...
; Clean up.
objRs.Close()
conRs = 0
objRs = 0
See Also:
ObjectConstToArray, ObjectCreate, ObjectGet
ObjectConstToArray
Creates an array of Constants object names and values.
Syntax:
ObjectConstToArray(constants-object)
Parameters
(r) constants-object
constants object reference.
Returns:
(a)
two dimensional array of constants names and values.
ObjectConstToArray creates an array that contains the textual names and numeric
values of a constants object:
adoApp = ObjectCreate("ADODB.Connection")
adoConst = ObjectConstantsGet(adoApp)
aConstants = ObjectConstToArray(adoConst)
This function can be used during the script writing process to examine the contents
of a constants object obtained using the ObjectConstantsGetfunction.
Note: Refer to the ObjectConstantsGet documentation for details about constants
object.
The returned array has two dimensions. There is one row for each constant and two
columns for each row. The first column contains the string name of a constant and
the second column contains the value of the constant. The name is the same one
used following the dot (.) in the constants.name syntax and the value is the same one
returned by constants.name.
In addition, row zero column zero of the array contains the number of constants
stored in the array. Using the example above, the number of constants is obtained
with:
nNumberOfConstants = aConstants[0,0]
467
ObjectCreate
The name of the first constant stored in the array is accessed with:
sName = aConstants[1,0]
And the first value is accessed with:
nValue = aConstants[1,1]
Example:
This example uses the ObjectConstToArray function to create an array of the
constants associated with the “Excel.Application” object. The contents of the array
are then displayed in a message box, one row at a time.
; Get the Excel application object.
objXL = ObjectCreate("Excel.Application")
; Get the constants object.
constXL = ObjectConstantsGet(objXL)
; Create an array of constants.
aXL = ObjectConstToArray(constXL )
; Display each name and value.
; (There are over 1500 of them.)
for i = 1 to aXL[0,0]
sTittle = Strcat(" Constant No. ", i)
sText = Strcat( aXL[i,0], " = ",aXL[i,1] )
message( sTittle, sText)
next
; Clean up
constXL = 0
objXL = 0
See Also:
ObjectConstantsGet, ObjectCreate, ObjectGet
ObjectCreate
Creates and returns a reference to a COM object.
Syntax:
ObjectCreate(progid[,location])
Parameters
(s) progid
468
The programmatic identifier of the object to create, usually
in the form servername.classname.
ObjectCreate
(s) location
[optional] The name of the network server where the object
will be created. If Location is an empty string ("") or
omitted, the local machine is used.
Returns:
(r)
COM object reference.
To create an instance of a COM object, assign the return value of ObjectCreate to a
variable:
adoApp = ObjectCreate("ADODB.Connection")
As shown in the examples that follow, you can access properties and methods of the
object using the object variable and dot (.) notation.
You can create an object on a remote networked computer by passing the name of
the computer to the Location argument of the ObjectCreate function. That name is
the same as the Machine Name portion of a share name. i.e.: for a share named
"\\MyServer\Public", the Location is "MyServer".
The following code returns the version number of an instance of Excel running on a
remote computer named MyServer:
; Replace string "\\MyServer" with name of the remote computer.
xlObj = ObjectCreate("Excel.Application", "\\MyServer")
message("Remote Excel version", xlObj.Version)
xlObj = ""
Note: Refer to Microsoft documentation for additional information on making an
application accessible on a remote networked computer.
Use ObjectCreate when there is no current instance of the object. If, however, an
instance of the object is already running, ObjectCreate starts a new instance, and an
object reference of the specified type is returned. To use the current instance or to
start the application and have it load a file, or to access an object using a moniker,
use the ObjectGet function. If an object has registered itself as a single-instance
object, only one instance of the object is created, no matter how many times
ObjectCreate is executed.
Each COM object reference consumes system resources so it is best to hold a
reference only as long as necessary. You can release a reference to an object by
simply assigning a new value to the object variable. Some object servers require that
a termination method be called before an object’s last reference is released. Check
your COM server documentation for details.
Note: The legacy function ObjectClose can still be used to release an object
reference. However, continued use of the function is discouraged.
ObjectCreate vs. ObjectGet: What's the Difference?
469
ObjectCreate
Besides minor differences in the syntax, the ObjectCreate and ObjectGet functions
are used in different contexts. The differences can be summarized as follows:
п‚·
ObjectCreate is used to create an interface to a new instance of an application.
Use ObjectCreate when it's not certain whether the application to integrate is
running. For example:
xl = ObjectCreate ("Excel.Application")
starts Microsoft Excel. The object returned in xl is a reference to the
Excel.Application object just created.
п‚·
ObjectGet is used with an application that's already running, or to start an
application with a file already loaded. For example:
xlBook = ObjectGet ("C:\TEST.XLS")
would start Microsoft Excel with the file Test.xls already loaded. The object
returned would be a reference to the Workbook object representing the just
opened Test.xls file.
Example:
This example uses the ObjectCreate function to create a Microsoft Internet Explorer
window and display a Web page. To use this example, Internet Explorer must be
installed on the computer where this program will run.
objExplorer = ObjectCreate("InternetExplorer.Application")
objExplorer.addressbar = @FALSE
objExplorer.statusbar = @FALSE
objExplorer.menubar = @FALSE
objExplorer.toolbar = @FALSE
objExplorer.visible = @TRUE
objExplorer.Width
= 800
objExplorer.Height = 550
objExplorer.Left
= 0
objExplorer.Top
= 0
objExplorer.navigate("http://www.winbatch.com/")
;
Wait until page loads...
While objExplorer.busy || objExplorer.readystate<> 4
TimeDelay(0.5)
EndWhile
; Do something.
objExplorer.quit
objExplorer = ""
See Also:
ObjectGet, CreateObject, ObjectConstantsGet, ObjectConstToArray
470
ObjectEventAdd
ObjectEventAdd
Associates a User-Defined-Function or subroutine with a COM object event.
Syntax:
ObjectEventAdd(object-reference,event-name,UDF-name)
Parameters:
(r) object-reference
(s) event-name
(s) UDF-name
variable containing an object reference
name of event to be handled
name of UDF/UDS event handler
Returns:
(i)
@TRUE on success; @FALSE on failure
ObjectEventAdd binds a User-Defined-Function or subroutine to a COM object
event. COM object events are notifications sent to a script in response to some
action or object state change. Events can even be fired in response to an action taken
by your script. Once your event handling User-Defined-Function or subroutine is
bound to an event, the COM object calls your UDF/UDS when ever the event occurs.
For many events, your script must pause execution long enough to receive the event.
You can pause your script by placing the TimeDelay function in a While or For
loop. You can also use a WIL dialog, one of the built-in dialogs or one of the "wait"
functions to pause script execution. If you do choose a TimeDelay or "wait" loop,
remember to include logic for loop termination.
Note: While you can pause your script in a User-Defined-Function or even a nested
call to a User-Defined-Function, a User-Defined-Subroutine event handler's variable
scope is always the outer most scope of the script. This means that variables created
from within the "pausing" User-Defined-Function are not available to event handling
User-Defined-Subroutine.
object-reference
The first parameter is a reference to the object whose event you wish to handle. The
parameter must be a variable containing an object reference. Object references can
be obtained by calling the ObjectCreate, ObjectGet, or DialogObject function.
event-name
This is the name associated with the event you wish to handle. Consult a COM
object's documentation to find the names of events supported by an object.
UDF-name
The third parameter is the name of the User-Defined-Function or subroutine that will
handle the event. The UDF/UDS must be defined before you call the
ObjectEventAdd function. The UDF/UDS definition must also contain the number
of parameters specified for the event handler by the object's documentation. If the
471
ObjectEventAdd
event supports "out" parameters, you can assign values to these parameter variables
inside your handler and the values will be passed back to the COM object. Consult
the object's documentation to determine if any of the parameters can return values to
the object.
Example:
;This example uses the ObjectEventAdd function and a WMI event to
;monitor the Run registry key. The script uses the WaitForKeyEx
;function in a loop to pause while waiting for a registry change.
;Script processing completes when the key change event fires or the
;user presses the Esc key.
bNoEvent = @True
; Initialize loop control variable
; WMI event OnObjectReady subroutine handler
#DefineSubroutine OnObjectReady(objWbemObject, objWbemAsyncContext)
Message("Registry Key Change", objWbemObject.GetObjectText_())
bNoEvent = @False
; Causes loop to exit
return
#EndSubroutine
; Need the WMI service and sink objects
objWmiServices = ObjectGet("winmgmts:root/default")
objWmiSink
= ObjectCreate("WbemScripting.SWbemSink")
; Bind the event handler to the WMI event
ObjectEventAdd(objWmiSink, "OnObjectReady", "OnObjectReady")
; Create the WMI query to check for modifications to the Run key
sHive = "Hive='HKEY_LOCAL_MACHINE'"
sKey
=
"KeyPath='SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run'"
sQuery = "SELECT * FROM RegistryKeyChangeEvent"
sQuery = StrCat(sQuery, " WHERE ", sHive, " AND ", sKey)
; Start the registry monitor
objWmiServices.ExecNotificationQueryAsync( objWmiSink , sQuery)
; Loop until the registry changes
BoxOpen("Waiting for a registry key to change.", "Press ESC key to
quit")
while bNoEvent
if WaitForKeyEx("{ESC}", 1) == 1
break ; Esc key pressed
endif
endwhile
BoxShut()
; Remove the event.
ObjectEventRemove(objWmiSink, "OnObjectReady")
; To be safe shut down the WMI event sink
472
ObjectEventRemove
objWmiSink.Cancel()
objWbemObject
objWbemAsyncContext
objWmiSink
objWmiServices
=
=
=
=
0
0
0
0
See Also:
ObjectEventRemove, ObjectCreate, ObjectGet,
ObjectEventRemove
Cancels the association between a User-Defined-Function or subroutine and a COM
object event.
Syntax:
ObjectEventRemove(object-reference,event-name)
Parameters:
(r) object-reference
(s) event-name
variable containing an object reference
name of event being handled as a string
Returns:
(i)
@TRUE on success; @FALSE on failure.
ObjectEventRemove breaks the previously established link between a UserDefined-Function or subroutine and a COM object event. Once the link is broken,
your User-Defined-Function or subroutine will no longer execute when the COM
object fires the indicated event.
You can also break the link between an event and your event handling function or
subroutine by releasing all references to the COM object associated with the event.
This is usually done by assigning a zero (0) to all variables holding a reference to the
COM object. This function is provided for the occasion where you wish to stop
handling an event but wish to continue using the COM object in your script.
object-reference
The first parameter is a reference to the object whose event you wish to stop
handling. The parameter must be a variable containing an object reference and the
reference must have been previously used in a successful call to ObjectEventAdd.
event-name
The second parameter is the name of the event you wish to stop handling. The event
name must have been previously used in a successful call to ObjectEventAdd.
Example:
;This example illustrates a script wrapper for Excel which uses the
;ObjectEventRemove function to remove events when the initial Excel
;workbook is closed. The script also demonstrates that is possible
;to remove events from within event handlers.
473
ObjectEventRemove
#DefineSubRoutine WorkbookBeforeClose(objWorkbook, bCancel)
; This is called when you choose to close the workbook in Excel.
; The event handlers are removed, and then the workbook is closed
; without saving changes.
ObjectEventRemove(objXlApp, "SheetChange")
ObjectEventRemove(objXlApp, "WorkbookBeforeClose")
objWorkbook.Saved = @True ; Set the dirty flag to true so there
; is no prompt to save.
bDone
= @True ; End event loop
#EndSubRoutine
#DefineSubRoutine SheetChange(objSheet, objTarget)
;This is called when a cell or cells on a worksheet are changed.
sWhere = StrCat(objTarget.Address, " on ",
objTarget.Worksheet.Name())
Message("You Changed Cells", sWhere)
#EndSubroutine
;Start Excel and create a new workbook.
bDone
= @False ; Event loop control variable
objXlApp = ObjectCreate("Excel.Application")
objXlBook = objXlApp.Workbooks.Add()
objXlBook.Windows(1).Caption = "Event Handler Example"
objXlBook.Worksheets.Item(1).Activate()
;Add an event handler for the WorkbookBeforeClose Event of the
;Application object.
ObjectEventAdd(objXlApp,"WorkbookBeforeClose","WorkbookBeforeClose")
; Add an event handler for the SheetChange event of all Worksheet
; objects.
ObjectEventAdd(objXlApp,"SheetChange","SheetChange")
;Make Excel visible and give the user control.
objXlApp.Visible
= @True
objXlApp.UserControl = @True
; Event processing loop
while !bDone
TimeDelay(1)
endwhile
; Add a fresh workbook before exiting in case
; the user closed the workbook but not Excel
objXlBook = objXlApp.Workbooks.Add()
objXlBook.Windows(1).Caption = "Event Handler Example (No Events)"
objWorkbook
objTarget
objSheet
objXlBook
474
=
=
=
=
0
0
0
0
ObjectGet
objXlApp
= 0
See Also:
ObjectEventAdd, ObjectCreate, ObjectGet
ObjectGet
Returns a reference to an object provided by a COM/OLE component.
Syntax:
ObjectGet([moniker[,progId]])
Parameters:
(s) moniker
(s) progId
Returns:
(r)
[optional] A name for a namespace or class, or the full path
and name of a file associated with an object. If moniker is
omitted,progId is required.
[optional] The programmatic identifier of the object to
create, usually in the form servername.classname.
COM/OLE object reference.
Use the ObjectGet function to load an instance of a COM/OLE object from a file.
For example:
xlObject = ObjectGet("c:\Projects\Test\exceltest.xls")
When this code is executed, the application associated with the specified file path
and name is started and the associated object is activated.
If moniker is a zero-length string (""), ObjectGet returns a new object instance as
specified by ProgId . If the moniker argument is omitted, ObjectGet returns the
currently active progId object. If no object of type progId is running, an error occurs.
For example:
xlObject = ObjectGet(, "Excel.Application")
If Excel is not running, the above line will cause an error.
If you do not specify the object's progId with a file and path, the system determines
the application to start and the object to activate, based on the file name you provide.
Some files, however, may support more than one class of object. To specify which
object in a file you want to activate, use the optional progId argument.
Once an object is activated, you reference it in your script using the object variable
you defined. In the preceding example, you access properties and methods of the
new object using the object variable xlObject. For example:
; Set the value of the first cell of worksheet 1.
xlObject.Worksheets(1).Range("A1").Value = "2.5"
475
ObjectGet
The Moniker parameter accepts strings other than file paths and names. Many
monikers consist of a namespace, and an object path with a class name. These
monikers are often used to report on or manage operating system services. Some
namespace examples include “winmgmts:” which is used to access WMI service and
“LDAP:” which is used to access Directory Services.
Sometimes monikers can contain multiple namespaces. For example, the following
WMI namespace moniker identifies the Win32_LogicalDisk class in the root\cimv2
namespace on the 'myServer' server:
WinMgmts:{impersonationLevel=impersonate}!//myServer/root/cimv2:Win32
_LogicalDisk
Here is an example of an LDAP namespace moniker that identifies an Active
Directory user object using the toons server:
LDAP://toons/CN=Daf Duckus,CN=users,DC=acme,DC=com
Note: Refer to Microsoft documentation for additional information on WMI and
Active Directory Services Interfaces classes, properties and methods.
Each COM/OLE object reference consumes system resources so it is best to hold a
reference only as long as necessary. You can release a reference to an object by
simply assigning a new value to the object variable. Some object servers require that
a termination method be called before an object’s last reference is released. Check
your COM/OLE server documentation for details.
Note: The legacy function ObjectClose can still be used to release an object
reference. However, continued use of the function is discouraged.
ObjectCreate vs. ObjectGet: What's the Difference?
Besides minor differences in the syntax, the ObjectCreate and ObjectGet functions
are used in different contexts. The differences can be summarized as follows:
п‚·
ObjectCreate is used to create an interface to a new instance of an application.
Use ObjectCreate when it's not certain whether the application to integrate is
running. For example:
xl = ObjectCreate ("Excel.Application")
starts Microsoft Excel. The object returned in xl is a reference to the
Excel.Application object just created.
п‚·
ObjectGet is used with an application that's already running, or to start an
application with a file already loaded. For example:
xlBook = ObjectGet ("C:\TEST.XLS")
476
ObjectType
would start Microsoft Excel with the file Test.xls already loaded. The object
returned would be a reference to the Workbook object representing the just
opened Test.xls file.
Example:
This example uses the ObjectGet function to get a reference to a WMI service
object. It then uses the object's ExecQuery method to obtain a collection of operating
systems installed on the local computer. The collection is then enumerated for the
version of the last service pack installed on the machine.
objWMIService =
ObjectGet("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
colOS = objWMIService.ExecQuery ("Select * from
Win32_OperatingSystem")
; Use a ForEach In loop to iterate the Operating System collection.
ForEach objOS in colOS
sVersion =
StrCat(objOS.ServicePackMajorVersion,".",objOS.ServicePackMinorVersio
n)
Message ( "Service Pack Version" , sVersion)
Next
See Also:
GetObject, ObjectCreate, ObjectConstantsGet, ObjectConstToArray
ObjectOpen
Opens or creates an COM/OLE Automation object
ObjectOpen has been superceded with the function ObjectCreate.
ObjectType
Creates a WIL variable with a specific COM/OLE variant type.
Syntax:
ObjectType(variant-type,value)
Parameters:
(s) variant-type
(s/i) value
see below.
value of the variable.
Returns:
(i)
a WIL variable with a specific COM/OLE variant type.
"variant-type" can be one of the following:
Variant-type
Value to specify
477
ObjectType
A string
A 1-byte character value
A 2-byte integer value
A 4-byte integer value.
A 8-byte integer value.
An unsigned 1-byte character.
An unsigned 2-byte character.
An unsigned 2-byte character.
A Boolean (True/False) value.
A currency value, specified as a string in the form
"#CURRENCY:value".
A date/time value, specified as a string in Ymd or
DATE
YmdHms format
A decimal value, specified as a string in the form
DECIMAL
"#DECIMAL:value".
A blank string ("").
NULL
A safe array.
ARRAY
A pointer to an object was specified. This object is
DISPATCH
known only to implement IDispatch.
A pointer to an object that implements the IUnknown
UNKNOWN
interface. You can only specify the value 0 to create a
NULL VT_UNKNOWN variant.
The "variant-type" may be preceded by the prefix "VT_", so for example you could
specify either "BOOL" or "VT_BOOL".
BSTR
I1
I2
I4
I8
UI1
UI2
UI4
BOOL
CY
ObjectType can convert WIL arrays and binary buffers to variant safearrays of a
specific type. Request conversion by prepending "ARRAY|" to the variant element
type in the first parameter. The function's second parameter should contain a WIL
array, a Variant safearray or a binary buffer when using the "ARRAY|" specification.
The special type specification "ARRAY|VARIANT" can be used to convert WIL
arrays already containing multiple variant types into a safearrays of type VARIANT.
When an COM/OLE method or property returns a value that is one of these
supported variant types, WinBatch now retains the variant type for the returned
variable, without having to use the ObjectType function. However, if you
subsequently assign a new value to that variable using a regular WIL assignment
operator, the variant type information will be lost. For example:
visible = ExcelApp.Visible
ExcelApp.Visible = visible
The variable "visible" is returned as a VT_BOOL, and is still a VT_BOOL when it is
passed back to the COM/OLE object. But here:
visible = ExcelApp.Visible
478
ObjectType
visible = 0
ExcelApp.Visible = visible
The assignment "visible = 0" causes "visible" to become an ordinary WIL integer,
without a variant type. In that case, if you wanted it to be a VT_BOOL you would
need to use ObjectType:
visible = ObjectType("BOOL", 0)
ExcelApp.Visible = visible
Or simply:
ExcelApp.Visible = ObjectType("BOOL", 0)
Example:
#DefineFunction PrintGraphic(File)
; This can be used to Print: HTML files or
; Graphics files (i.e., BMP TIFF JPG JPEG GIF)
; Requires Windows 2000 or later.
if WinVersion(1) != 5
Message("Error","This function is not supported on this
Windows platform")
return(0)
endif
objBrowser = ObjectOpen("InternetExplorer.Application")
objBrowser.addressbar = @false
objBrowser.statusbar = @false
objBrowser.menubar = @false
objBrowser.toolbar = @false
objBrowser.visible = @false
objBrowser.navigate(file)
While @TRUE
If objBrowser.ReadyState == 4 then Break
TimeDelay(1)
EndWhile
objBrowserDoc = objBrowser.Document
objAll = objBrowserdoc.all
OLECMDID_PRINT = 6
OLECMDEXECOPT_DONTPROMPTUSER = 2
PRINT_DONTBOTHERUSER = 1
PRINT_WAITFORCOMPLETION = 2
pvaIn =
ObjectType("I2",PRINT_WAITFORCOMPLETION|PRINT_DONTBOTHERUSER)
pvaOut = ObjectType("NULL","")
objBrowser.ExecWB(OLECMDID_PRINT,OLECMDEXECOPT_DONTPROMPTUSER,pva
In, pvaOut)
;Give the browser enough time to print before closing the object
TimeDelay(1)
objBrowserDoc = ""
objAll = ""
objBrowser = ""
Return(1)
479
ObjectTypeGet
#EndFunction
file = "c:\temp\test.jpg"
If FileExist(file)then PrintGraphic(File)
else Message("Error","Unable to locate file. Check file path.")
See Also:
COM, ObjectOpen, ObjectClose, ObjectTypeGet, BinaryAllocArray
ObjectTypeGet
Gets the COM/OLE variant type of a WIL variable.
Syntax:
ObjectTypeGet(object-reference)
Parameters:
(r) object-reference
Returns:
(s)
variable containing an object reference.
COM/OLE variant-type or a blank string (""). This function
will return a blank string ("") if the variable passed is a non
variant type.
"variant-type" can be one of the following:
Variant Type
EMPTY
NULL
I1
UI1
I2
UI2
I4
INT
UI4
UINT
I8
UI8
R4
R8
DECIMAL
480
Meaning
No data, the size of the value is zero.
This is like a pointer to NULL.
1-byte signed integer.
1-byte unsigned integer.
Two bytes representing a 2-byte signed integer
value.
2-byte unsigned integer.
4-byte signed integer value.
4-byte signed integer value (equivalent to VT_I4).
4-byte unsigned integer.
4-byte unsigned integer (equivalent to VT_UI4).
8-byte signed integer.
8-byte unsigned integer.
32-bit IEEE floating point value.
64-bit IEEE floating point value.
A decimal value, specified as a string in the form
"#DECIMAL:value".
ObjectTypeGet
CY
DATE
BSTR
BOOL
ERROR
FILETIME
LPSTR
LPWSTR
CLSID
CF
BLOB
BSTR_BLOB
BLOBOBJECT
STREAM
STREAMED_OBJECT
A currency value, specified as a string in the form
"#CURRENCY:value".
A date/time value, specified as a string in Ymd or
YmdHms format.
A string.
A Boolean (True/False) value.
A DWORD containing a status code.
64-bit FILETIME structure as defined by Win32.
It is recommended that all times be stored in
Universal Coordinate Time (UTC).
Pointer to a null-terminated ANSI string in the
system default code page.
Pointer to a null-terminated Unicode string in the
user's default locale.
Pointer to a class identifier (CLSID) (or other
globally unique identifier (GUID)).
Pointer to a CLIPDATA structure.
DWORD count of bytes, followed by that many
bytes of data. The byte count does not include the
four bytes for the length of the count itself; an
empty blob member would have a count of zero,
followed by zero bytes. This is similar to the value
VT_BSTR but does not guarantee a null byte at
the end of the data.
Reserved for system use.
A blob member containing a serialized object in
the same representation that would appear in
VT_STREAMED_OBJECT. That is, a DWORD
byte count (where the byte count does not include
the size of itself) which is in the format of a class
identifier followed by initialization data for that
class.
The only significant difference between
VT_BLOB_OBJECT and
VT_STREAMED_OBJECT is that the former
does not have the system-level storage overhead
that the latter would have, and is therefore more
suitable for scenarios involving numbers of small
objects.
Pointer to an IStream interface, representing a
stream which is a sibling to the "Contents" stream.
As in VT_STREAM, but indicates that the stream
contains a serialized object, which is a CLSID
481
ObjectTypeGet
STORAGE
STORED_OBJECT
VECTOR
ARRAY
BYREF
VARIANT
482
followed by initialization data for the class. The
stream is a sibling to the "Contents" stream that
contains the property set.
Pointer to an IStorageinterface, representing a
storage object that is a sibling to the "Contents"
stream.
As in VT_STORAGE, but indicates that the
designated IStoragecontains a loadable object.
If the type indicator is combined with
VT_VECTOR by using an OR operator, the value
is one of the counted array values. This creates a
DWORD count of elements, followed by a pointer
to the specified repetitions of the value.
For example, a type indicator of
VT_LPSTR|VT_VECTOR has a DWORD
element count, followed by a pointer to an array
of LPSTR elements.
VT_VECTOR can be combined by an OR
operator with the following types: VT_I1,
VT_UI1, VT_I2, VT_UI2, VT_BOOL, VT_I4,
VT_UI4, VT_R4, VT_R8, VT_ERROR, VT_I8,
VT_UI8, VT_CY, VT_DATE, VT_FILETIME,
VT_CLSID, VT_CF, VT_BSTR, VT_LPSTR,
VT_LPWSTR, and VT_VARIANT.
If the type indicator is combined with
VT_ARRAY by an OR operator, the value is a
pointer to a SAFEARRAY. VT_ARRAY can use
the OR with the following data types: VT_I1,
VT_UI1, VT_I2, VT_UI2, VT_I4, VT_UI4,
VT_INT, VT_UINT, VT_R4, VT_R8,
VT_BOOL, VT_DECIMAL, VT_ERROR,
VT_CY, VT_DATE, and VT_BSTR.
VT_ARRAY cannot use OR with VT_VECTOR.
If the type indicator is combined with
VT_BYREF by an OR operator, the value is a
reference. Reference types are interpreted as a
reference to data.
VT_BYREF can use OR with the following types:
VT_I1, VT_UI1, VT_I2, VT_UI2, VT_I4,
VT_UI4, VT_INT, VT_UINT, VT_R4, VT_R8,
VT_BOOL, VT_DECIMAL, VT_ERROR,
VT_CY, VT_DATE, VT_BSTR, VT_ARRAY,
and VT_VARIANT.
A DWORD type indicator followed by the
corresponding value. VT_VARIANT can be used
ObjectTypeGet
DISPATCH
UNKNOWN
VOID
HRESULT
SAFEARRAY
CARRAY
USERDEFINED
RECORD
RESERVED
only with VT_VECTOR or VT_BYREF.
A pointer to an object was specified. This object is
known only to implement IDispatch.
A pointer to an object that implements the
IUnknown interface.
VOID.
Standard return type.
VT_ARRAY in VARIANT.
C-style array.
User-defined type.
User-defined type.
This function returns the "variant-type" string for the specified variable name, or "" if
it does not have a variant type.
Important: Note that some of these types do not work for Automation (IDispatch)
method parameters and property values. They are included for completeness.
Theoretically, WinBatch will support any variant data type as long as you don't try to
pass it to WinBatch functions or use it in non-COM expressions. Of course we
support all the variant types that can be converted to standard WIL types in any
WinBatch expression or sub expression or function call.
Example:
objLocator = ObjectCreate("WbemScripting.SWbemLocator")
objService = objLocator.ConnectServer(".","root/cimv2","","")
objSecurity = objService.Security_
objSecurity.ImpersonationLevel = 3
class = "Win32_BIOS"
; query instances
query = "SELECT * FROM Win32_BIOS WHERE Name = 'Default System BIOS'
AND SoftwareElementID = 'Default System BIOS' AND
SoftwareElementState = '3' AND TargetOperatingSystem = '0' AND
Version = 'DELL
- 6'"
colInstances = objService.ExecQuery(query)
; loop once for each instance
ForEach objInstance in colInstances
;Check if Object is EMPTY
type = ObjectTypeGet(objInstance)
if type=="EMPTY" then break
; obtain properti
Message("Manufacturer",objInstance.Manufacturer)
Next
; close object handles
colInstances = ""
objSecurity = ""
objService = ""
objLocator = ""
483
Pause
See Also:
COM, ObjectOpen, ObjectClose, ObjectType, BinaryAllocArray
ParseData
Parses the passed string.
Syntax:
ParseData(string)
Parameters:
(s) string
string to be parsed.
Returns:
(i)
number of parameters in string.
This function breaks a string constant or string variable into new sub-string variables
named param1, param2, etc. Blank spaces in the original string are used as
delimiters to create the new variables.
Param0 is the count of how many sub-strings are found in "string".
Example:
data = "Alpha Bravo Charlie Delta"
ParseData(data)
reverse = StrCat(param4," ",param3," ",param2," ",param1)
Message(data,reverse)
See Also:
ItemExtract, StrSub
Pause
Provides a message to user. User may cancel processing.
Syntax:
Pause(title,text)
Parameters:
(s) title
(s) text
title of pause box.
text of the message to be displayed.
Returns:
(i)
@TRUE.
This function displays a message to the user with an exclamation point icon. The
user may respond by selecting the OK button, or may cancel the processing by
selecting Cancel.
484
PipeClientOpen
The Pause function is similar to the Message function, except for the addition of the
Cancel button and icon.
Example:
Pause("Change Disks", "Insert new disk into Drive F:")
which produces:
See Also:
Display, Exit, Message, Terminate
PipeClientClose
Closes a named pipe connection.
Syntax:
PipeClientClose(pipe-handle)
Parameters:
(i) pipe-handle
pipe handle returned by PipeClientOpen.
Returns:
(i)
returns @TRUE.
Example:
See PipeClientOpen Example
See Also:
PipeClientOpen, PipeClientSendRecvData, PipeInfo, PipeServerClose,
PipeServerCreate, PipeServerRead, PipeServerWrite
PipeClientOpen
Connects to a named pipe.
485
PipeClientOpen
Syntax:
PipeClientOpen(pipe-name,timeout)
Parameters:
(s) pipe-name
(i) timeout
Returns:
(i/s)
specifies the name of a pipe, in one of these forms:
\\ServerName\pipe\PipeName or \\.\pipe\PipeName
specifies the timeout period in seconds, or -1 for no timeout.
returns a pipe handle on success, or "*TIMER*".
Example:
;-----------; CLIENT.WBT
;-----------server = "myserver" ; Or "." for the local machine
pipename = "fluggle"
pipepath = StrCat("\\",server,"\pipe\",pipename)
querydata = "GET_TIME"
timeout = -1
IntControl(12,5,0,0,0);terminate quietly
notice = StrCat(@CRLF,@CRLF,"[ Press CTRL+BREAK to exit script ]")
BoxOpen("Time Client","Initializing connection to server...")
While @TRUE
pipehandle = PipeClientOpen(pipepath,timeout)
if pipehandle=="*ERROR*" || pipehandle=="*TIMER*" then continue ;
try again
data=PipeClientSendRecvData(pipehandle, querydata,timeout)
BoxText(StrCat("Data sent from server = ", data, notice))
PipeClientClose(pipehandle)
Endwhile
Message("Client","Exited")
Exit
;-----------; SERVER.WBT
;-----------pipename="\\.\pipe\fluggle"
timeout = -1
IntControl(12,5,0,0,0);terminate quietly
notice = StrCat(@CRLF,@CRLF,"[ Press CTRL+BREAK to exit script ]")
BoxOpen("Time Server","Initializing - Awaiting connect from Client")
While @TRUE ; General Server loop
pipehandle = PipeServerCreate(pipename,timeout)
if pipehandle=="*ERROR*" || pipehandle=="*TIMER*" then continue
readinfo = PipeServerRead(pipehandle, timeout)
if readinfo=="*ERROR*" || readinfo=="*TIMER*"
PipeServerClose(pipehandle,0)
continue
; try again
endif
if readinfo == "GET_TIME"
486
PipeInfo
response= TimeYmdHms()
else
response = "ERROR: UNKNOWN REQUEST"
endif
rslt=PipeServerWrite(pipehandle,response)
BoxText(StrCat("Data sent to client = ",response, notice))
PipeServerClose(pipehandle,timeout)
Endwhile
Message("Server","Exited")
Exit
See Also:
PipeClientClose, PipeClientSendRecvData, PipeInfo, PipeServerClose,
PipeServerCreate, PipeServerRead, PipeServerWrite
PipeClientSendRecvData
Writes a message to a named pipe and then reads a message back.
Syntax:
PipeClientSendRecvData(pipe-handle,data,read-timeout)
Parameters:
(i) pipe-handle
(s) data
(i) read-timeout
Returns:
(s)
pipe handle returned by PipeClientOpen.
message/data to send to named pipe.
specifies the timeout period in seconds, or -1 for no timeout.
Returns a message string on success; "*ERROR*" on error;
"*TIMER*" on timeout.
Example:
See PipeClientOpen Example
See Also:
PipeClientClose, PipeClientOpen, PipeInfo, PipeServerClose, PipeServerCreate,
PipeServerRead, PipeServerWrite
PipeInfo
Returns information about a pipe or pipe operation.
Syntax:
PipeInfo(request,pipe-handle)
Parameters:
(i) request
(i) pipe-handle
see below.
pipe handle returned by PipeClientOpen.
487
PipeServerCreate
Returns:
(i)
depends on request.
Request
Returns
0
Error code for last unsuccessful pipe function ("pipe-handle" is ignored)
Example:
See PipeClientOpen Example
See Also:
PipeClientClose, PipeClientOpen, PipeClientSendRecvData, PipeServerClose,
PipeServerCreate, PipeServerRead, PipeServerWrite
PipeServerClose
Closes a named pipe instance.
Syntax:
PipeServerClose(pipe-handle,timeout)
Parameters:
(i) pipe-handle
(i) timeout
pipe handle returned by PipeServerCreate.
specifies the timeout period in seconds, or -1 for no timeout.
Returns:
(i/s)
returns @TRUE on success, or "*TIMER*" on timeout.
If there is a client connected to the pipe, the function will wait "timeout" seconds for
the client to close its end of the pipe.
Example:
See PipeClientOpen Example
See Also:
PipeClientClose, PipeClientOpen, PipeClientSendRecvData, PipeInfo,
PipeServerCreate, PipeServerRead, PipeServerWrite
PipeServerCreate
Creates an instance of a named pipe and waits for a client to connect. (Windows NT
family only)
Syntax:
PipeServerCreate(pipe-name,timeout)
488
PipeServerWrite
Parameters:
(s) pipe-name
(i) timeout
Returns:
(i/s)
specifies the name of a pipe, in the form:
\\.\pipe\PipeName
specifies the timeout period in seconds that it will wait for a
client to connect., or -1 for no timeout.
a pipe handle on success; "*TIMER*" on timeout.
A maximum of 100 instances of a pipe can be created.
Example:
See PipeClientOpen Example
See Also:
PipeClientClose, PipeClientOpen8, PipeClientSendRecvData, PipeInfo,
PipeServerClose, PipeServerRead, PipeServerWrite
PipeServerRead
Reads a message from a named pipe.
Syntax:
PipeServerRead(pipe-handle,timeout)
Parameters:
(i) pipe-handle
(i) timeout
Returns:
(s)
pipe handle returned by PipeServerCreate.
specifies the timeout period in seconds, or -1 for no timeout.
a message string on success; "*ERROR*" upon error;
"*TIMER*" on timeout.
Example:
See PipeClientOpen Example
See Also:
PipeClientClose, PipeClientOpen, PipeClientSendRecvData, PipeInfo,
PipeServerClose, PipeServerCreate, PipeServerWrite
PipeServerWrite
Writes a message to a named pipe.
Syntax:
PipeServerWrite(pipe-handle,data)
Parameters:
(i) pipe-handle
pipe handle returned by PipeServerCreate.
489
PlayMedia
(s) data
Returns:
(i/s)
message/data to send to named pipe.
returns @TRUE on success; "*ERROR*" upon error.
Example:
See PipeClientOpen Example
See Also:
PipeClientClose, PipeClientOpen, PipeClientSendRecvData, PipeInfo,
PipeServerClose, PipeServerCreate, PipeServerRead
PlayMedia
Controls multimedia devices.
Syntax:
PlayMedia(mci-string)
Parameters:
(s) mci-string
string to be sent to the multimedia device.
Returns:
(s)
response from the device.
If the appropriate Windows multimedia extensions are present, this function can
control multimedia devices. Valid command strings depend on the multimedia
devices and drivers installed. The basic Windows multimedia package has a
waveform device to play and record waveforms, and a sequencer device to play
MIDI files. Refer to the appropriate documentation for information on command
strings.
Many multimedia devices accept the WAIT or NOTIFY parameters as part of the
command string:
WAIT
Causes the system to stop processing input until the
requested operation is complete. You cannot switch tasks
when WAIT is specified.
WAIT NOTIFY Same as WAIT
NOTIFY
Causes the WIL program to suspend execution until the
requested operation completes. You can perform other
tasks and switch between tasks when NOTIFY is
specified.
If neither WAIT nor NOTIFY is specified, the multimedia operation is started and
control returns immediately to the WIL program.
490
PlayMidi
In general, if you simply want the WIL program to wait until the multimedia
operation is complete, use the NOTIFY keyword. If you want the system to hang
until the operation is complete, use WAIT. If you just want to start a multimedia
operation and have the program continue processing, don't use either keyword.
The return value from PlayMedia is whatever string the driver returns. This will
depend on the particular driver, as well as on the type of operation performed.
Example:
; Plays a music CD on a CDAudio drive, from start to finish
stat = PlayMedia("status cdaudio mode")
answer = 1
If stat == "playing"
answer = AskYesNo("CD Audio", "CD is Playing. Stop?")
If answer == 0 Then Exit
endif
PlayMedia("open cdaudio shareable alias donna notify")
PlayMedia("set donna time format tmsf")
PlayMedia("play donna from 1")
PlayMedia("close donna")
Exit
:cancel
PlayMedia("set cdaudio door open")
See Also:
Beep, PlayMidi, PlayWaveForm, Sounds
PlayMidi
Plays a MID or RMI sound file.
Syntax:
PlayMidi(filename,mode)
Parameters:
(s) filename
(i) mode
name of the MID or RMI sound file.
play mode (see below).
Returns:
(i)
@TRUE if successful; @FALSE if unsuccessful.
If Windows multimedia sound extensions are present, and MIDI-compatible
hardware is installed, this function will play a MID or RMI sound file. If "filename"
is not in the current directory and a directory is not specified, the path will be
searched to find the file.
491
PlayWaveForm
If "mode" is set to 0, the WIL program will wait for the sound file to complete before
continuing. If "mode" is set to 1, it will start playing the sound file and continue
immediately.
Example:
PlayMidi("C:\windows\media\canyon.mid", 1)
Message("PlayMidi","Midi Played")
See Also:
Beep, PlayMedia, PlayWaveForm, Sounds
PlayWaveForm
Plays a WAV sound file.
Syntax:
PlayWaveForm(filename,mode)
Parameters:
(s) filename
(i) mode
name of the WAV sound file.
play mode (see below).
Returns:
(i)
@TRUE if successful; @FALSE if unsuccessful.
If Windows multimedia sound extensions are present, and waveform-compatible
hardware is installed, this function will play a WAV sound file. If "filename" is not
in the current directory and a directory is not specified, the path will be searched to
find the file. If "filename" is not found, the WAV file associated with the
"SystemDefault" keyword is played, (unless the "NoDefault" setting is on).
Instead of specifying an actual filename, you may specify a keyword name from the
[Sound] section of the WIN.INI file (e.g., "SystemStart"), or equivalent Registry key,
in which case the WAV file associated with that keyword name will be played.
"Mode" is a bitmask, composed of the following bits, combine using the binary OR
operator.
Mode
0
1
Meaning
Wait for the sound to end before continuing.
Don't wait for the sound to end. Start the sound and immediately
process more statements.
2
If sound file not found, do not play a default sound
9
Continue playing the sound forever, or until a PlayWaveForm(" ", 0)
statement is executed
16
If another sound is already playing, do not interrupt it. Just ignore this
PlayWaveForm request.
The command PlayWaveForm(" ", 0) can be used at any time to stop sound.
492
PtrGlobal
Examples:
PlayWaveForm("tada.wav", 0)
PlayWaveForm("SystemDefault", 1 | 16)
Message("PlayWaveForm"," Done.")
See Also:
Beep, PlayMedia, PlayMidi, Sounds
Print
Instructs the application responsible for a file to print the file on the default printer.
Syntax:
Print(data file,directory,display mode,reserved)
Parameters:
(s) data file
(s) directory
(i) display mode
(i) reserved
Returns:
(i)
the name of the file to print.
current working directory (if applicable).
@NORMAL, @ICON, @ZOOMED, @HIDDEN.
reserved.
@TRUE if the function completed; @FALSE if an error
occurred.
Instructs the application responsible for a file to print the file on the default printer.
The Windows ShellExecute API is used. It examines the extension of the data file,
looks the extension up in the Windows registry to determine the owning application,
starts the owning application, and instructs it, also according to data specified in the
registry, to print the data file. Most applications will send the printout to the default
printer, however the exact action taken by the application is under the application’s
own control.
Applications that support this command or their setup programs will generally make
the necessary modifications to the Windows registry to allow this function to
perform successfully.
Example:
FileCopy("C:\config.sys", "xxx.txt", 0)
a=Print("xxx.txt", DirGet( ), @NORMAL, 0)
exit
See Also:
RunShell
PtrGlobal
Retrieves a "pointer" to a global variable.
493
PtrGlobalDefine
Syntax:
PtrGlobal(variable-name)
Parameters:
(s) variable-name
specifies a variable name.
Returns:
(s) pointer
a pointer string.
"variable-name" must have been previously been marked as global using
PtrGlobalDefine.
Example:
#DefineFunction CheckGlobalValue()
Ptr_Global_A=PtrGlobal(Global_A)
Ptr_Global_B=PtrGlobal(Global_B)
if *Ptr_Global_A != "Potatoes"
Message("Error","Global_A is not the expected value")
endif
*Ptr_Global_B = 1234
#EndFunction
PtrGlobalDefine( Global_A)
PtrGlobalDefine( Global_B)
Global_A = "Potatoes"
retvalue=CheckGlobalValue()
If Global_B != 1234
Message("Error","Global_B is not the expected value")
endif
See Also:
PtrGlobalDefine, PtrPersistent
PtrGlobalDefine
Creates a "pointer" to a global variable.
Syntax:
PtrGlobalDefine(variable-name)
Parameters:
(s) variable-name
specifies a variable name.
Returns:
(s)
a pointer string.
This function can only be called from the main script, not from a UDF.
If "variable-name" does not already exist, it will be created.
494
PtrGlobalTest
Example:
#DefineFunction CheckGlobalValue()
Ptr_Global_A=PtrGlobal(Global_A)
Ptr_Global_B=PtrGlobal(Global_B)
if *Ptr_Global_A != "Potatoes"
Message("Error","Global_A is not the expected value")
endif
*Ptr_Global_B = 1234
#EndFunction
PtrGlobalDefine( Global_A)
PtrGlobalDefine( Global_B)
Global_A = "Potatoes"
retvalue=CheckGlobalValue()
If Global_B != 1234
Message("Error","Global_B is not the expected value")
endif
See Also:
PtrGlobal, PtrPersistent
PtrGlobalTest
Tests whether a variable has been marked as being globally accessible.
Syntax:
PtrGlobalTest(variable-name)
Parameters:
(s) variable-name
specifies a variable name.
Returns:
(i)
@TRUE globally accessible; @FALSE if not.
Example:
#DefineFunction CheckGlobalValue()
Ptr_Global_A=PtrGlobal(Global_A)
*Ptr_Global_A = 1234
#EndFunction
PtrGlobalDefine( Global_A)
ret = PtrGlobalTest( Global_A)
If ret == @TRUE
Message("PtrGlobalTest","Global_A is globally accessible")
EndIf
See Also:
PtrGlobal, PtrGlobalDefine, PtrPersistent
495
PtrPersistent
PtrPersistent
Creates a "pointer" to a persistent variable.
Syntax:
PtrPersistent(variable-name,value)
Parameters:
(s) variable-name
(s/i) value
Returns:
(s)
specifies a variable name which CANNOT be longer than
25 characters.
specifies a value which will be assigned to "variable-name"
if the variable does not already exist.
a pointer string.
This function marks a variable as persistent. If called from a UDF, the variable will
retain its value after the UDF returns. If variable does not already exist, it will be
created. If it already exists, its value will not be changed.
A "persistent" variable is defined and used in a single UDF. But unlike other UDF
variables, it "stays around". Kind of like a private global variable that no other UDF's
can see. For example, if a UDF wants to save away some information that it needs, it
can use a persistent variable. The next time the UDF is called, its persistnt variable is
still there, with what ever value was left over from the previous call to it.'
Example:
#DefineFunction IncMyCounter(flag)
; flag = 0 will report on current value of counter
; flag = 1 will increment counter first
Ptr_MyCounter = PtrPersistent(MyCounter,0)
if flag==1 ; report on number of calls
*Ptr_MyCounter = *Ptr_MyCounter + 1
endif
return *Ptr_Mycounter
#EndFunction
r=Random(100)
for xx = 1 to r
IncMyCounter(1)
next
cnt=IncMyCounter(0)
Message("Counter Value is",cnt)
See Also:
PtrGlobal, PtrGlobalDefine
496
Registration Database Operations
Random
Computes a pseudo-random number.
Syntax:
Random(max)
Parameters:
(i) max
largest desired integer number.
Returns:
(i)
difficult to predict, positive number.
This function will return a random integer between 0 and max.
Example:
a = Random(79)
Message("Random number between 0 and 79", a)
See Also:
IntControl 81, Average, Max, Min
Registration Database Operations
In the early days of Windows, there was a single INI file, WIN.INI. As Windows
advanced, the WIN.INI file became cluttered, and it was then subdivided into
SYSTEM.INI, WIN.INI and a large number of application specific INI files.
With the advent of COM/OLE, Windows NT, and other advancements in operating
system technology, the simple INI files could not hold or organize the new and vast
amounts of information required to run a modern operating system. For this reason, a
new data storage structure was developed. Sometimes called the Registry or the
Registration Database, this new file was designed to be able to hold and organize
large amounts of seemingly random information.
The Registration Database is organized in a tree structure, much like a file system.
At every level "keys" to the data exist. The keys are analogous to the sub-directories
in a file system. A set of keys to a data item look very much like a path to a filename.
In Windows, the Registration Database may be viewed and altered with the
"RegEdit" utility. It requires a "/v" parameter, as in "regedit.exe /v", to enable the
edit mode of the utility. There exists the "RegEdt32" utility in Windows NT+ that
allows access to the Registration Database.
CAUTION: The reason that these utilities are not made easily accessible is that it is
trivially easy to make a modification to the database that will completely ruin a
Windows installation, and may require a complete re-install of Windows to get the
system running again. It is best to study the database and understand what is going
497
RegApp
on, instead of perhaps using a somewhat common "trial and error" method of making
changes.
There are two ways to query and set information in the Registration Database. The
easy way is to simply base all operations on an always open root key. Using just the
RegQueryValue and RegSetValue functions you can alter all data associated with
pre-defined keys.
The other more complicated and more flexible method is to open or create a desired
key, using the RegOpenKey or RegCreateKey functions, modify the database with
other registration functions, passing it a handle to the key, and then finally close the
database with the RegCloseKey function. Most of the registration functions accept
both a handle to a key and a subkey string which further defines a lower key.
Oftentimes the subkey string is simply set to null (empty quotes), and the handle
points directly to the destination. At other times, one of the pre-defined roots of the
database is passed as the handle and the subkey string points all the way down to the
desired data item.
Pre-defined keys are provided. Windows provides several keys, as shown in the table
below:
32 Bit Windows handles to "always open" keys
@REGMACHINE Root of the machine section of the Registration Database.
HKEY_LOCAL_MACHINE
@REGCLASSES Shortcut to the classes sub-section.
HKEY_CLASSES_ROOT
@REGUSERS
Root of the user section of the Registration Database.
HKEY_USERS
@REGCURRENT Shortcut to the current user’s sub-section.
HKEY_CURRENT_USER
Note: Named data entries as found in Windows are specified by enclosing the "data
item name" in square brackets at the end of the key string. For Example:
RegSetValue(@REGMACHINE,"SOFTWARE\Wilson
WindowWare\Settings\WWWBATCH\MAIN[SOUNDS]",1)
Use [] to refer a '(Default)' data item under a specified key.
For Example:
;this example gets the DEFAULT value under a specific key
ret=RegQueryValue(@REGCLASSES,"txtfile[]")
message("Value of default key",ret)
RegApp
Creates registry entries for a program under "App Paths".
498
RegCloseKey
Syntax:
RegApp(program-name,path)
Parameters:
(s) program-name
(s) path
Returns:
(i)
the name of an executable program (EXE), optionally
containing a path.
optional desired "PATH" setting for the specified program.
@TRUE entry was created; @FALSE operation failed.
This function creates (or updates) a sub-key in the registration database for the
specified program, of the form PROGNAME.EXE, under the key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App
Paths\
If "program-name" does not contain a path, the function will search for it on the path.
The function creates a "(Default)" value for the key, containing the full path to the
specified program.
If the "path" parameter is not a blank string (""), the function also creates a "Path"
value for the key. This should contain one or more directories (separated by semicolons) which you want to be prepended to the existing "PATH" environment
variable when the program is run.
Windows Vista or newer: This function may require an Administrator level
account, because it attempts to write to the HKEY_LOCAL_MACHINE registry
key.
Example:
residence="c:\msoffice\excel.exe"
path="c:\msoffice\excel;c:\msoffice\winword"
RegApp(residence, path)
Message("Excel.EXE","Registered at %residence% and use path %path%")
See Also:
InstallFile, RegOpenKey, RegCreateKey, RegQueryValue, RegQueryKey and the
section on Registration Database Operations (pg. 497)
RegCloseKey
Closes a key to the Registration Database.
Syntax:
RegCloseKey(handle)
Parameters:
(i) handle
handle to a registration database key.
499
RegConnect
Returns:
(i)
@TRUE database was closed; @FALSE close failed.
The RegCloseKey function closes a key to the Registration Database. The key is
opened or created with the RegOpenKey or the RegCreateKey functions.
Registration Database changes made using a key are saved when the key is closed.
Example:
key=RegOpenkey(@RegClasses, "txtfile")
b=RegQueryValue(key, "shell\open\command")
RegCloseKey(key)
Message("Default textfile editor is", b)
See Also:
RegOpenKey, RegCreateKey, RegSetValue, RegQueryValue and the section on
Registration Database Operations (pg. 497)
RegConnect
Connects to a predefined registry handle on another computer.
Syntax:
RegConnect(computer-name,handle[,remoteOSflag])
Parameters:
(s) computer-name
(i) handle
(s) remoteOSflag
Returns:
(s)
the name of the computer in the form of "\\computername".
either @REGMACHINE OR @REGUSERS
[optional] indicate the processor architecture
used by the remote operating system.
a key handle to the specified handle on the remote
computer.
remoteOSflag
Optional parameter that indicates the processor architecture or 'bitness' used by the
remote operating system. Set the optional parameter to the string "RemoteOS32", if
the remote computer is running a 32-bit version of Windows and the computer
running the script is using a 64-bit version of Windows. Set the optional parameter to
"RemoteOS64", if the remote computer is running a 64-bit version of Windows and
the computer running the script is using 32-bit version of Windows. If the remote
computer and the computer running the script are using the same bitness, do not
supply a value for this parameter.
Note: When a handle returned by RegConnect is no longer needed, it should be
closed by calling RegCloseKey.
May need to call wntCancelCon, if explicitly connected to the IPC$ share (i.e., via
wntAddDrive).
500
RegCreateKey
Windows Vista or newer: This function may require an Administrator level
account.
Example:
Fred=RegConnect("\\FRED", @REGMACHINE, "")
Iver=RegQueryValue(Fred, "SOFTWARE\Microsoft\Internet
Explorer[Iver]")
RegCloseKey(Fred)
Message("Internet Explorer Version Installed on \\Fred.", Iver)
See Also:
RegCreateKey, RegCloseKey, RegDeleteKey, RegSetValue, RegQueryValue,
RegQueryKey and the section on Registration Database Operations (pg. 497)
RegCreateKey
Returns a handle to a new registration database key.
Syntax:
RegCreateKey(handle,subkey-string[,view-flag])
Parameters:
(i) handle
(s) subkey-string
(i) view-flag
Returns:
(i)
handle to a registration database key.
a path from the key provided to the desired key.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
a handle to the new key.
The RegCreateKey function will create and open a desired key into the Registration
Database. If the key already exists, RegCreateKey will open it. When using
RegCreateKey you must pass a pre-existing, open key to create a new key. A predefined key may be used.
Example:
; Associate DIZ files with the default textfile editor
key=RegCreatekey(@REGCLASSES, ".diz")
RegSetValue(key, "", "txtfile")
RegClosekey(key)
Message("RegCreatekey","*.DIZ files now associated with your text
editor")
See Also:
RegOpenKey, RegCloseKey, RegDeleteKey, RegSetValue, RegQueryValue,
RegQueryKey and the section on Registration Database Operations (pg. 497)
501
RegDelValue
RegDeleteKey
Deletes a key and data items associated with the key.
Syntax:
RegDeleteKey(handle,subkey-string[,view-flag])
Parameters:
(i) handle
(s) subkey-string
(i) view-flag
Returns:
(i)
an open registration database key (see below).
a path from the key provided to the desired key.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
@TRUE key was deleted; @FALSE key was not found.
The RegDeleteKey function will delete a pre-existing key from the Registration
Database. If the key does not exist, RegDeleteKey will fail. When using
RegDeleteKey you must pass a pre-existing, open key to access the desired key. A
pre-defined key may be used.
Example:
; Delete default operation for *.DIZ files
; from the registration database
ErrorMode(@off)
RegDeleteKey(@REGCLASSES, ".diz")
ErrorMode(@cancel)
Message("Regdeletekey","*.DIZ files no longer associated with text
editor")
See Also:
RegOpenKey, RegCreateKey, RegCloseKey, RegDelValue and the section on
Registration Database Operations (pg. 497)
RegDelValue
Deletes a named value data item for the specified subkey from the registry.
Syntax:
RegDelValue(handle,subkey-string[,view-flag])
Parameters:
(i) handle
502
handle to a registration database key.
RegEntryType
(s) subkey-string
(i) view-flag
Returns:
(i)
a path from the key provided to the desired key, including
the "data item name" in square brackets at the end of the key
string.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
@TRUE data item was deleted; @FALSE data was not
found.
The "data item name" in the Subkey-string must be enclosed in square brackets (see
RegSetValue). Use "[]" for the data item name to delete the "default" value.
Example:
;To turn Sounds ON in the case Sounds was disabled.
ErrorMode(@off)
RegDelValue(@REGMACHINE, "SOFTWARE\Wilson
WindowWare\Settings\WWWBATCH\MAIN[SOUNDS]")
ErrorMode(@cancel)
Message("Sounds", "Sound Settings - Sounds is on.")
See Also:
RegOpenKey, RegCreateKey, RegCloseKey, RegDeleteKey, RegQueryValue,
RegSetValue and the section on Registration Database Operations (pg. 497)
RegEntryType
Returns the type of data for the specified subkey.
Syntax:
RegEntryType(handle,subkey-string[,view-flag])
Parameters:
(i) handle
(s) subkey-string
(i) view-flag
Returns:
(s)
an open registration database key. (see below).
a path from the key provided to the desired key.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
data type of specified subkey. (see below).
503
RegEntryType
The return value will be one of the following:
Value
0
1
2
DataType
(REG_NONE)
(REG_SZ)
(REG_EXPAND_SZ)
3
4
5
(REG_BINARY)
(REG_DWORD)
(REG_DWORD_BIG_ENDIAN)
6
(REG_LINK)
7
(REG_MULTI_SZ)
8
(REG_RESOURCE_LIST)
9
(REG_FULL_RESOURCE_DESCRIPTOR)
10
11
(REG_RESOURCE_REQUIREMENTS_LIST)
(REG_QWORD)
Description
No value type
An ANSI string
ANSI string that
contains unexpanded
references to
environment variables
(for example,
%PATH%).
Free form binary
32-bit number
32-bit number, high
byte first
Symbolic Link
(Unicode)
A delimited list of
ANSI strings.
Resource list in the
resource map
Resource list in the
hardware description
Resource requirements
64-bit number
Example:
;This set of UDFs can clone or rename a registry key
;It is not blindingly fast, but should be ok for smaller trees.
;CopyRegValue - Copies one single value from one place to another
;CloneRegTree - copies one tree from one place to another
;RenameRegTree - Renames a tree.
;However, due to the fact that the registry API does not have
;a rename facility, the RenameRegTreeis implemented by first
;cloning the tree, then deleting the original tree.
;Keys are used by first obtaining a handle to one. One of the
;predefined handles (@REGMACHINE @REGCURRENT, etc) or a handle
;returned by one of the registry functions RegConnect, RegCreateKey
;or RegOpenKey may be used
;Each function needs a handle to a section in the registry
;database in addition to a string that consists of the subkey to
;an entry in the Registry database.
504
RegEntryType
;For current versions of Windows, there are 4 handles: @REGMACHINE,
;@REGCLASSES, @REGUSRS, and @REGCURRENT. These are WIL constants
;for HKEY_LOCAL_MACHINE, HKEY_CLASSES_ROOT, HKEY_USERS, and
;HKEY_CURRENT_USER. When you obtain a registry subkey from
Microsoft's
;registry viewer, regedit.exe (by using Copy Key Name from the right
;mouse menu in RegEdit.exe) it will look like this example:
;HKEY_LOCAL_MACHINE\SOFTWARE\myTest\Sub2\sub21\Sub211
;For use in the WIL registry functions, the above key must be
;divided into handle and subkey. The handle, @REGMACHINE, takes the
;place of the first item, 'HKEY_LOCAL_MACHINE\'. The subkey needed
;for the second parameter in the functions is,
;'SOFTWARE\myTest\Sub2\sub21\Sub211'.
;Note: it does not start with the '\' backslash character.
;
;Define the CopyRegValue UDF.
#DefineFunction CopyRegValue(fromHandle,fromSubkey,toHandle,toSubkey)
;Stop if value does not exist.
Terminate(RegExistValue(fromHandle,fromSubkey)==0,"Reg value does
not exist",fromSubkey)
;Get the entry type
type=RegEntryType(fromHandle,fromSubkey)
;Stop if type is not supported.
Terminate( ((type<1) || (type>4)) && type!=7, "Cannot handle reg
value",fromSubkey)
;Define a hopefully sufficiently obscure delimiter for the BIN
function
delim=Num2Char(255)
;Get the value.
value=RegQueryEx(fromHandle,fromSubkey,delim,type)
;Copy value to a new subkey.
RegSetEx(toHandle,toSubkey,value,delim,type)
Return ;Return nothing.
#endfunction
;Define the CloneRegTree UDF.
#DefineFunction CloneRegTree(fromHandle, fromSubkey, toHandle,
toSubkey)
;Stop if key does not exist.
Terminate(RegExistKey(fromHandle,fromSubkey)==0,"Reg key does not
exist",fromSubkey)
;copy top default key
;Check value.
if RegExistValue(fromhandle,fromsubkey)
;Get value.
defval=RegQueryValue(fromHandle,fromSubkey)
;Set value of destination subkey.
if defval!="" then RegSetValue(toHandle,toSubkey,defval)
endif
;copy all values under key, if any
505
RegEntryType
items=RegQueryItem(fromHandle,fromSubkey)
icount=ItemCount(items,@tab)
for ii=1 to icount
;Assemble source subkey with value in brackets.
thisitem=strcat(fromSubkey,'[',ItemExtract(ii,items,@tab),']')
;Assemble destination subkey with value in brackets.
thatitem=strcat(toSubkey,'[',ItemExtract(ii,items,@tab),']')
;Copy the entry.
CopyRegValue(fromHandle, thisitem, toHandle, thatitem)
next
;Get list of subkeys
;Open source key with read access rights.
tempkey=RegOpenKeyEX(fromHandle,fromSubkey,"READ",0,0)
;Get keys.
keys=RegQueryKeys(tempkey)
;Close source key.
RegCloseKey(tempkey)
;Process each subkey
kcount=ItemCount(keys,@tab)
for kk=1 to kcount
thiskey=strcat(fromSubkey,"\",ItemExtract(kk,keys,@tab))
thatkey=strcat(toSubkey,"\",ItemExtract(kk,keys,@tab))
;Use the CloneRegTree UDF to do the work.
CloneRegTree(fromHandle,thiskey,toHandle,thatkey)
next
#EndFunction
#DefineFunction RenameRegTree(fromHandle, fromSubkey, toHandle,
toSubkey)
;Set up UDF
;Use previous UDF to copy the source key to the destination key.
CloneRegTree(fromHandle, fromSubkey, toHandle, toSubkey)
;Delete the source key.
RegDeleteKey(fromHandle,fromSubkey)
#EndFunction
;Test code follows.
;Registry handle. In this case, both source and destination are the
same.
fromHandle = @REGCURRENT
toHandle = @REGCURRENT
;source subkey
fromSubkey = "Software\Wilson WindowWare"
;destination subkey
toSubkey = "Software\MyWilson WindowWare"
;copy the subkey
CloneRegTree( fromHandle , fromSubkey , toHandle , toSubkey)
Message("Progress" , "New key created.%@CRLF%%@CRLF%See this with
regedit.exe, %@CRLF%Be sure to refresh it with f5!")
506
RegExistKey
fromSubkey = "Software\MyWilson WindowWare"
toSubkey = "Software\MyOtherWilson WindowWare"
;copy the subkey to a new named key, and delete the old key.
RenameRegTree( fromHandle , fromSubkey , toHandle , toSubkey)
Message("Progress" , "New key copied and renamed.%@CRLF%Check this
with f5 in regedit.exe.")
See Also:
RegQueryEx, RegSetEx and the section on Registration Database Operations (pg.
497)
RegExistKey
Checks whether a registry key exists.
Syntax:
RegExistKey(handle,subkey-string[,view-flag])
Parameters:
(i) handle
(s) subkey-string
(i) view-flag
Returns:
(i)
handle to an open registration database key.
a path from the key provided to the desired key.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
@TRUE key exists and is accessible (i.e., can be opened
with RegOpenKey); @FALSE doesn't exist or cannot be
opened.
Example:
key=RegExistkey(@RegClasses, "txtfile")
if key == 1
who=RegQueryStr(@REGClasses,"txtfile\shell\open\command")
else
message("Sorry","The specified key does not exist!")
exit
endif
Display(3,"Default text file editor is", who)
See Also:
RegOpenKey and the section on Registration Database Operations (pg. 497)
507
RegLoadHive
RegExistValue
Checks whether a value for a registry key exists.
Syntax:
RegExistValue(handle,subkey-string[,view-flag])
Parameters:
(i) handle
(s) subkey-string
(i) view-flag
Returns:
(i)
an open registration database key.
a path from the key provided to the desired key, including
the "data item name" in square brackets at the end of the key
string.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
@TRUE value (data item) exists and is accessible
(i.e., can be read with RegQuery[..]); @FALSE doesn't
exist or cannot be read.
Example:
reg = RegExistValue(@REGMACHINE, "SOFTWARE\Wilson
WindowWare\WinBatch\CurrentVersion")
if reg == 0
Message("RegExistValue","The value doesn't exist?")
exit
endif
regkey = RegQueryValue(@REGMACHINE, "SOFTWARE\Wilson
WindowWare\WinBatch\CurrentVersion[]")
Message("WinBatch directory", regkey)
See Also:
RegQueryValue and the section on Registration Database Operations (pg. 497)
RegLoadHive
Loads a hive into a registry subkey.
Syntax:
RegLoadHive(handle,subkey,filename)
Parameters:
(i) handle
(s) subkey
(s) filename
508
either @REGUSERS or @REGMACHINE.
the name of the key to be created
specifies the name of a hive file.
RegOpenFlags
Returns:
(s)
@TRUE.
This function creates a subkey under HKEY_USERS or
HKEY_LOCAL_MACHINE and stores registration information from the specified
file into that subkey. This registration information is in the form of a hive. A hive is a
discrete body of keys, subkeys, and values that is rooted at the top of the registry
hierarchy.
Windows Vista or newer: This function may require an Administrator level
account, because it attempts to access to the HKEY_LOCAL_MACHINE registry
key.
Example:
RegLoadHive(@REGMACHINE, "WinWare", "winware")
See Also:
RegUnloadHive and the section on Registration Database Operations (pg. 497)
RegOpenFlags
Specifies the registry view of the various Reg[..] functions.
Syntax:
RegOpenFlags(flag)
Parameters:
(i) flag
Returns:
(i)
a flag which specifies which view of the registry
the various Reg[..] functions will see.
previous value.
This function lets you specify an alternate view of the registry for Reg[..] functions
which create, open, and delete registry keys, when running on (or accessing) a 64-bit
Windows platform.
Flags
0
32
64
Meaning
32-bit view under Win32, 64-bit view under WOW64 (default)
32-bit view
64-bit view
Registry Redirection
To prevent 32-bit registry settings from overwriting the 64-bit registry settings,
computers that are running an x64-based version of Windows store the settings for
32-bit programs in a new branch in the registry. The registry redirection process
enables program installations and program configuration settings to access the
'correct' registry sub key without user intervention.
509
RegOpenKey
32-bit programs and 64-bit programs that are running on an x64-based version of
Windows operate in different modes and use the following sections in the registry:
п‚·
Native mode 64-bit programs run in Native mode and access keys and values
that are stored in the following registry sub key:
HKEY_LOCAL_MACHINE\Software
п‚·
32-bit programs (like WinBatch) run in WOW64 mode and access keys and
values that are stored in the following registry sub key:
HKEY_LOCAL_MACHINE\Software\WOW6432node
2 simple rules to accessing the registry on 64-bit systems:
п‚·
NEVER directly access keys stored under WOW6432node.
п‚·
If you do want access something under WOW6432node, just set the registry
view to 32-bit using RegOpenFlags(32) and specify the key/value without using
'WOW6432node' in the registry path. (In other words use it 's regular 32-bit
key/value.)
You can launch the 32-bit version of Registry Editor on a 64-bit Windows platform
using the following commandline:
C:\Windows\syswow64\regedit.exe
Example:
;64-bit view
RegOpenFlags(64)
See Also:
RegOpenKeyEx, RegCreateKey, RegCloseKey, RegDeleteKey, RegSetValue,
RegQueryValue, RegQueryKey and the section on Registration Database Operations
(pg. 497)
RegOpenKey
Returns a handle to an existing registration database key.
Syntax:
RegOpenKey(handle,subkey-string[,view-flag])
Parameters:
(i) handle
(s) subkey-string
(i) view-flag
510
handle to a registration database key.
a path from the key provided to the desired key.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
RegOpenKeyEx
Returns:
(i)
a handle to the new key.
The RegOpenKey function will open a desired key into the Registration Database. If
the key does not exist, RegOpenKey will fail. When using RegOpenKey you must
pass a pre-existing, open key to create a new key. A pre-defined key may be used.
Note: The opened key should be closed with RegCloseKey.
Example:
key=RegOpenkey(@RegClasses, "txtfile");Find default text editor
who=RegQueryStr(key, "shell\open\command")
RegClosekey(key)
Message("Default text file editor is", who)
; The preceding is actually a hard way to do ...
who=RegQueryStr(@REGClasses, "txtfile\shell\open\command")
Message("Default text file editor is", who)
See Also:
RegCreateKey, RegCloseKey, RegDeleteKey, RegSetValue, RegQueryValue,
RegQueryKey and the section on Registration Database Operations (pg. 497)
RegOpenKeyEx
Opens a registry key with specified access rights.
Syntax:
RegOpenKeyEx(handle,subkey-string,mode[,view-flag[,reserved]])
Parameters:
(i) handle
(s) subkey-string
(s/i) mode
(i) view-flag
(s) reserved
Returns:
(i)
handle to a registration database key
a path from the key provided to the desired key
access mode (see below)
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the RegOpenFlags.
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
[optional] reserved for future use; should be set to "".
a handle to the newly-opened key.
This function is like RegOpenKey, but lets the user specify the desired access rights
(RegOpenKey opens a key with default access, so may fail if the user only has read
permission for the key).
"Mode" may be one of the following pre-defined string values:
511
RegQueryBin
Value
READ
Name
KEY_READ
WRITE
KEY_WRITE
FULL
KEY_ALL_ACCESS
Meaning
KEY_QUERY_VALUE |
KEY_ENUMERATE_SUB_KEYS |
KEY_NOTIFY |
STANDARD_RIGHTS_READ
KEY_SET_VALUE |
KEY_CREATE_SUB_KEY |
STANDARD_RIGHTS_WRITE
(KEY_QUERY_VALUE |
KEY_SET_VALUE |
KEY_CREATE_SUB_KEY |
KEY_ENUMERATE_SUB_KEYS |
KEY_NOTIFY |
KEY_CREATE_LINK |
STANDARD_RIGHTS_ALL) &
~SYNCHRONIZE
Or, "mode" may be a bitmask comprised of one or more of the following integer
values, combined using the bitwise OR ('|') operator:
Val
1
Name
KEY_QUERY_VALUE
2
4
8
KEY_SET_VALUE
KEY_CREATE_SUB_KEY
KEY_ENUMERATE_SUB_KEYS
16
KEY_NOTIFY
32
KEY_CREATE_LINK
Meaning
Permission to query subkey
data.
Permission to set subkey data.
Permission to create subkeys.
Permission to enumerate
subkeys.
Permission for change
notification.
Permission to create a
symbolic link.
See Also:
RegCloseKey, RegOpenFlags, RegOpenKey and the section on Registration
Database Operations (pg. 497)
RegQueryBin
Returns binary value at subkey position.
Syntax:
RegQueryBin(handle,subkey-string[,view-flag])
Parameters:
(i) handle
512
handle to a registration database key.
RegQueryDword
(s) subkey-string
(i) view-flag
Returns:
(s)
a path from the key provided to the desired key,
including the "data item name" in square brackets
at the end of the key string.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
contents of data item at key position desired.
The value is returned as a space-delimited string of hex bytes;
e.g.:
"AB 45 3E 01".
Example:
subkey = "Control Panel\Appearance[CustomColors]"
value = RegQueryBin(@REGCURRENT, subkey)
Message("CustomColors", value)
See Also:
RegApp, RegEntryType, RegQueryDword, RegQueryEx, RegQueryExpSz,
RegQueryItem, RegQueryMulSz, RegQueryValue and the section on Registration
Database Operations (pg. 497)
RegQueryDword
Returns DWORD value at subkey position.
Syntax:
RegQueryDword(handle,subkey-string[,flags])
Parameters:
(i) handle
(s) subkey-string
(i) flags
Returns:
(s)
handle to a registration database key.
a path from the key provided to the desired key,
including the "data item name" in square brackets
at the end of the key string.
[optional]
0 - (default) value will be returned in decimal format.
1 - value will be returned in hexadecimal format.
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
contents of data item at key position desired.
513
RegQueryEx
Example:
subkey = "Control Panel\Desktop[ScreenSaveUsePassword]"
value = RegQueryDword(@REGCURRENT,subkey,0)
Message("ScreenSaveUsePassword", value)
See Also:
RegApp, RegEntryType, RegQueryBin, RegQueryEx, RegQueryExpSz,
RegQueryItem, RegQueryMulSz, RegQueryValue and the section on Registration
Database Operations (pg. 497)
RegQueryEx
Retrieves a value from the registry.
Syntax:
RegQueryEx(handle,subkey-string,delimiter,type[,view-flag])
Parameters:
(i) handle
(s) subkey-string
(s) delimiter
(i) type
(i) view-flag
Returns:
(s)
an open registration database key (see below).
a path from the key provided to the desired key, including
the "data item name" in square brackets at the end of the key
string.
a character to act as a delimiter between items. "Delimiter"
is ignored unless "type" is 7.
see below.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
a value from the registry.
"type" can be one of the following:
Value
1
2
3
4
7
11
514
Meaning
REG_SZ - Unicode null terminated string
REG_EXPAND_SZ - Unicode null terminated string (with environment
variable references)
REG_BINARY - Free form binary
REG_DWORD - 32-bit number
REG_MULTI_SZ - Multiple Unicode strings
REG_QWORD - 64-bit number
RegQueryExpSz
Example:
See the Registry Cloning Script under RegEntryType.
See Also:
RegApp, RegEntryType, RegQueryBin, RegQueryDword, RegQueryExpSz,
RegQueryItem, RegQueryMulSz, RegQueryValue and the section on Registration
Database Operations (pg. 497)
RegQueryExpSz
Retrieves a REG_EXPAND_SZ value from the registry.
Syntax:
RegQueryExpSz(handle,subkey-string[,view-flag])
Parameters:
(i) handle
(s) subkey-string
(i) view-flag
Returns:
(i)
an open registration database key.
a path from the key provided to the desired key, including
the "data item name" in square brackets at the end of the key
string.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
contents of the data item at the key position desired.
Example:
; Note: For 32-bit Path Modifications See RegApp
; Following is location of users path in Windows NT.
userenv="Environment[path]"
sysenv="SYSTEM\CurrentControlSet\Control\Session
Manager\Environment[path]"
if WinMetrics(-4)==4 ; Win NT
lasterror( )
Errormode(@off)
oldpath=RegQueryExpSz(@RegCurrent, userenv)
ErrorMode(@cancel)
If lasterror( ) == 1233
Errormode(@off)
oldpath=RegQueryExpSz(@RegMachine, sysenv)
ErrorMode(@cancel)
if oldpath==0
Message("Environment Variable - Users Path", "No path found")
else
Message("System Environment Variable - Users Path", oldpath)
endif
515
RegQueryItem
else
Message("User Environment Variable - Users Path", oldpath)
exit
endif
if WinMetrics(-4) !=4
Message("RegQueryExpSz","Not supported in Non-NT versions of
Windows")
exit
endif
See Also:
RegApp, RegEntryType, RegQueryBin, RegQueryDword, RegQueryEx,
RegQueryItem, RegQueryMulSz, RegQueryStr, RegQueryValue and the section on
Registration Database Operations (pg. 497)
RegQueryItem
Returns a list of named data items for a subkey.
Syntax:
RegQueryItem(handle,subkey-string[,view-flag])
Parameters:
(i) handle
(s) subkey-string
(i) view-flag
Returns:
(s)
handle to a registration database key.
a path from the key provided to the desired key.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
tab-delimited list of named data items for the specified
subkey-string.
Example:
items = RegQueryItem(@REGCURRENT,
"Software\Microsoft\Windows\CurrentVersion\Extensions")
item = AskItemList("Select an item", items, @TAB,@SORTED,@SINGLE, @
FALSE)
if RegExistValue(@REGCURRENT,
"Software\Microsoft\Windows\CurrentVersion\Extensions[%item%]") ==
@FALSE
Message("Error","Item not defined.")
Exit
endif
value = RegQueryValue(@REGCURRENT,
"Software\Microsoft\Windows\CurrentVersion\Extensions[%item%]")
Message(item, value)
516
RegQueryKeyLastWriteTime
See Also:
RegApp, RegEntryType, RegQueryBin, RegQueryDword, RegQueryEx,
RegQueryExpSz, RegQueryMulSz, RegQueryValue and the section on Registration
Database Operations (pg. 497)
RegQueryKey
Returns subkeys of the specified key.
Syntax:
RegQueryKey(handle,index)
Parameters:
(i) handle
(i) index
handle to a registration database key.
zero-based index into list of subkeys.
Returns:
(s)
name of desired subkey.
Use this function to enumerate the subkeys of a desired key. The first subkey is
referenced by index number 0, the second key by 1, and so on. If the key does not
exist, a null string will be returned.
Example:
for i=0 to 999
a=RegQueryKey(@REGMACHINE, I)
if a=="" then break
Display(2, "HKEY_LOCAL_MACHINE subkey number %i%", a)
next
See Also:
RegOpenKey, RegCreateKey, RegCloseKey, RegDeleteKey, RegEntryType,
RegSetValue, RegQueryKeys, RegQueryValue and the section on Registration
Database Operations (pg. 497)
RegQueryKeyLastWriteTime
Returns the last write time for a registry key. (Windows NT or newer)
Syntax:
RegQueryKeyLastWriteTime(handle,subkey-string[,view-flag])
Parameters:
(i) handle
(s) subkey-string
handle to a registration database key.
a path from the key provided to the desired key,
including the "data item name" in square brackets
at the end of the key string.
517
RegQueryMulSz
(i) view-flag
Returns:
(s)
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
last write time for a registry key, in YmdHms format.
Example:
lastwritetime = RegQueryKeyLastWriteTime(@REGMACHINE,
"Software\Wilson WindowWare")
Message("Last write time:", lastwritetime)
exit
See Also:
RegOpenKey, RegCreateKey, RegCloseKey, RegDeleteKey, RegSetValue,
RegQueryKey, RegQueryKeys, RegQueryValue and the section on Registration
Database Operations (pg. 497)
RegQueryKeys
Returns a tab-delimited list of subkey names under a specified key.
Syntax:
RegQueryKeys(handle)
Parameters:
(i) handle
handle to a registration database key.
Returns:
(s)
tab-delimited list of subkey names.
Example:
key=RegOpenkey(@RegMachine, "SOFTWARE\Microsoft")
who=RegQueryKeys(key)
RegClosekey(key)
AskItemList("Registry Keys under SOFTWARE\Microsoft", who,
@TAB,@SORTED, @SINGLE)
See Also:
RegOpenKey, RegCreateKey, RegCloseKey, RegDeleteKey, RegSetValue,
RegQueryKey, RegQueryValue and the section on Registration Database Operations
(pg. 497)
RegQueryMulSz
Retrieves a REG_MULTI_SZ value from the registry.
518
RegQueryQword
Syntax:
RegQueryMulSz(handle,subkey-string,delimiter[,view-flag])
Parameters:
(i) handle
(s) subkey-string
(s) delimiter
(i) view-flag
Returns:
(s)
an open registration database key.
a path from the key provided to the desired key, including
the "data item name" in square brackets at the end of the key
string.
a character to act as a delimiter between items.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
a list of strings, delimited with the specified delimiter
character.
Example:
key=RegCreatekey(@REGCURRENT, "sample")
RegSetMulSz(key, "testmulz[foods]", "apple|pear|grapes|toast", "|")
RegClosekey(key)
a1=RegOpenkey(@REGCURRENT, "sample")
c=RegQueryMulSz(a1, "testmulz[foods]",@tab)
RegClosekey(a1)
Message("Foods",c)
See Also:
RegApp, RegEntryType, RegQueryBin, RegQueryDword, RegQueryEx,
RegQueryExpSz, RegQueryItem, RegQueryValue and the section on Registration
Database Operations (pg. 497)
RegQueryQword
Retrieves a QWORD value from the registry.
Syntax:
RegQueryQword(handle,subkey-string[,view-flag])
Parameters:
(i) handle
(s) subkey-string
an open registration database key.
a path from the key provided to the desired key,
including the "data item name" in square brackets
at the end of the key string.
519
RegQueryStr
(i) view-flag
Returns:
(s)
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
space-delimited string of hex bytes, beginning with the
low byte of the QWORD.
Example:
key=RegCreatekey(@REGMACHINE, "Software\Wilson WindowWare\Sample")
RegSetQword(key, "TestQword[]", "00 00 62 69 6e 61 72 79")
rslt=RegQueryQword(key, "TestQword[]")
RegClosekey(key)
RegDeleteKey(@REGMACHINE, "Software\Wilson WindowWare\Sample")
Message("Result",rslt)
exit
See Also:
RegSetQword, RegApp, RegEntryType, RegQueryBin, RegQueryEx,
RegQueryExpSz, RegQueryDword, RegQueryItem, RegQueryValue and the section
on Registration Database Operations (pg. 497)
RegQueryStr
Retrieves and expands a string value from the registry.
Syntax:
RegQueryStr(handle,subkey-string[,view-flag])
Parameters:
(i) handle
(s) subkey-string
(i) view-flag
Returns:
(i)
520
an open registration database key.
a path from the key provided to the desired key, including
the "data item name" in square brackets at the end of the key
string.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
the expanded registry value.
RegQueryValue
This function can be used to read a REG_SZ or REG_EXPAND_SZ value from the
registry. If the value is a REG_EXPAND_SZ, any environment strings will be
expanded to their defined values in the string returned by this function (the registry
entry itself is untouched).
Example:
userenv="Environment[path]"
sysenv="SYSTEM\CurrentControlSet\Control\Session
Manager\Environment[path]"
if WinVersion(4)!=4
Message("RegQueryStr","Not supported in Non-NT versions of
Windows")
exit
endif
if WinVersion(1)!=4 ; Win NT 4.0
Message("RegQueryStr","Script not designed for NT 2000 versions of
Windows")
exit
endif
lasterror( )
Errormode(@off)
oldpath=RegQueryStr(@RegCurrent, userenv)
ErrorMode(@cancel)
If lasterror( ) == 1233
Errormode(@off)
oldpath=RegQueryStr(@RegMachine, sysenv)
ErrorMode(@cancel)
if oldpath==0
Message("Environment Variable - Users Path", "No path found")
else
Message("System Environment Variable - Users Path", oldpath)
endif
else
Message("User Environment Variable - Users Path", oldpath)
exit
endif
exit
See Also:
RegApp, RegEntryType, RegQueryBin, RegQueryDword, RegQueryEx,
RegQueryExpSz, RegQueryItem, RegQueryValue, RegQueryMulSz and the section
on Registration Database Operations (pg. 497)
RegQueryValue
Returns data item string at subkey position.
521
RegSetBin
Syntax:
RegQueryValue(handle,subkey-string[,view-flag])
Parameters:
(i) handle
(s) subkey-string
(i) view-flag
Returns:
(s)
handle to a registration database key.
a path from the key provided to the desired key, including
the "data item name" in square brackets at the end of the key
string.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
contents of data item at key position desired.
Use this function to retrieve data items from the Registration Database. The function
will fail if the data item does not exist.
Note: Named data entries are specified by enclosing the data item name in square
brackets at the end of the key string. For example:
RegQueryValue(@REGMACHINE,"SOFTWARE\Wilson WindowWare\Settings
\WWWBATCH\MAIN[SOUNDS]")
Example:
b=RegQueryValue(@REGMACHINE,
"SOFTWARE\Microsoft\Windows\CurrentVersion[Version]")
Message("Windows Version", b)
See Also:
RegApp, RegEntryType, RegQueryBin, RegQueryDword, RegQueryEx,
RegQueryExpSz, RegQueryItem, RegQueryMulSz, RegQueryStr and the section on
Registration Database Operations (pg. 497)
RegSetBin
Sets a binary value in the Registration Database.
Syntax:
RegSetBin(handle,subkey-string,value[,view-flag])
Parameters:
(i) handle
(s) subkey-string
522
handle to a registration database key.
a path from the key provided to the desired key, including
the "data item name" in square brackets at the end of the key
string.
RegSetDword
(s) value
(i) view-flag
Returns:
(i)
data to be stored into the database at desired key.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
@TRUE.
The value is specified as a space-delimited string of hex bytes; e.g.:
"AB 45 3E 01".
Example:
RegSetBin(@REGCURRENT, "A Test Key[My Binary Value]", "00 01 22 AB FF
00")
Message("RegSetBin"," Done.")
See Also:
RegApp, RegEntryType, RegSetDword, RegSetEx, RegSetExpSz, RegSetMulSz,
RegSetValue and the section on Registration Database Operations (pg. 497)
RegSetDword
Sets a DWORD value in the Registration Database.
Syntax:
RegSetDword(handle,subkey-string,value[,flags])
Parameters:
(i) handle
(s) subkey-string
(i) value
(i) flags
Returns:
(i)
handle to a registration database key.
a path from the key provided to the desired key, including
the "data item name" in square brackets at the end of the key
string.
dword value to be stored into the database at desired key.
[optional]
0 - (default) value will be returned in decimal format.
1 - value will be returned in hexadecimal format.
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
@TRUE data item value was stored.
Example:
RegSetDword(@REGCURRENT, "A Test Key[My DWORD Value]", 32,0)
Message("RegSetDWord","Done.")
523
RegSetEx
See Also:
RegApp, RegEntryType, RegSetBin, RegSetEx, RegSetExpSz, RegSetMulSz,
RegSetValue and the section on Registration Database Operations (pg. 497)
RegSetEx
Sets a value in the registry.
Syntax:
RegSetEx(handle,subkey-string,value,delimiter,type[,view-flag])
Parameters:
(i) handle
(s) subkey-string
(s) value
(s) delimiter
(i) type
(i) view-flag
Returns:
(s)
Type
1
2
3
4
7
11
an open registration database key.
a path from the key provided to the desired key, including
the "data item name" in square brackets at the end of the key
string.
data to be stored in the database at desired key.
a character to act as a delimiter between items. "Delimiter"
is ignored unless "type" is 7.
see below.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
@TRUE data item value was stored.
Meaning
(REG_SZ) Unicode null terminated string
(REG_EXPAND_SZ) Unicode null terminated string with environment
variable references
(REG_BINARY) Free form binary
(REG_DWORD) 32-bit number
(REG_MULTI_SZ) Multiple Unicode strings
(REG_QWORD) 64-bit number
Example:
See the Registry Cloning Script under RegEntryType.
See Also:
RegApp, RegEntryType, RegSetBin, RegSetDword, RegSetExpSz, RegSetMulSz,
RegSetValue and the section on Registration Database Operations (pg. 497)
524
RegSetExpSz
RegSetExpSz
Sets a REG_EXPAND_SZ value in the registry.
Syntax:
RegSetExpSz(handle,subkey-string,value[,view-flag])
Parameters:
(i) handle
(s) subkey-string
(s) value
(i) view-flag
Returns:
(i)
an open registration database key.
a path from the key provided to the desired key, including
the "data item name" in square brackets at the end of the key
string.
data to be stored in the database at desired key.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
@TRUE data item value was stored.
Example:
;
;
;
;
Note: To modify path in NT 4.0+
See the RegApp function
The Following is the location of users path in Windows NT
For the User Environment Path variable use:
userenv="Environment[path]"
; For the System Environment Path variable use:
sysenv="SYSTEM\CurrentControlSet\Control\Session
Manager\Environment[path]"
; Directory to add to the path
addpath="Q:\"
if WinMetrics(-4)==4
;Check to make sure system is Windows NT.
LastError( )
;clear the errors
Errormode(@off)
;tell WB we'll handle the errors
oldpath=RegQueryExpSz(@RegCurrent, userenv)
ErrorMode(@cancel)
If LastError( ) == 1233
Message("Users Path", "No path found, replacement not made.")
else
newpath=strcat(oldpath,";",addpath)
c=RegSetExpSz(@RegCurrent, userenv, newpath)
Message("Users new path is", newpath)
WININICHG=26
DaDll=Strcat(DirWindows(1),"USER32.DLL")
525
RegSetMulSz
DllCall(DaDll,long:"SendMessageA",long:-1, long:WININICHG,
long:0, lpstr:"Environment")
endif
exit
else
Message("RegQueryExpSz","Not supported by Non-NT registry")
endif
See Also:
RegApp, RegEntryType, RegSetBin, RegSetDword, RegSetExpSz, RegSetMulSz,
RegSetValue and the section on Registration Database Operations (pg. 497)
RegSetMulSz
Sets a REG_MULTI_SZ value in the registry.
Syntax:
RegSetMulSz(handle,subkey-string,value,delimiter[,view-flag])
Parameters:
(i) handle
(s) subkey-string
(s) value
(s) delimiter
(i) view-flag
Returns:
(i)
an open registration database key.
a path from the key provided to the desired key,including
the "data item name" in square brackets at the end of the key
string.
a list of strings, delimited with the specified delimiter
character.
a character to act as a delimiter between items.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
@TRUE data item value was stored.
Example:
key=RegCreatekey(@REGCURRENT, "sample")
RegSetMulSz(key, "testmulz[foods]", "apple|pear|grapes|toast", "|")
RegClosekey(key)
a1=RegOpenkey(@REGCURRENT, "sample")
c=RegQueryMulSz(a1, "testmulz[foods]",@tab)
RegClosekey(a1)
Message("Foods",c)
exit
526
RegSetValue
See Also:
RegApp, RegEntryType, RegSetBin, RegSetDword, RegSetEx, RegSetExpSz,
RegSetValue and the section on Registration Database Operations (pg. 497)
RegSetQword
Sets a QWORD value in the registry.
Syntax:
RegSetQword(handle,subkey-string,value[,view-flag])
Parameters:
(i) handle
(s) subkey-string
(i) value
(i) view-flag
Returns:
(i)
an open registration database key.
a path from the key provided to the desired key,
including the "data item name" in square brackets
at the end of the key string.
a space-delimited string of hex bytes, beginning with the
low byte of the QWORD.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
@TRUE data item value was stored.
Example:
key=RegCreatekey(@REGMACHINE, "Software\Wilson WindowWare\Sample")
RegSetQword(key, "TestQword[]", "00 00 62 69 6e 61 72 79")
rslt=RegQueryQword(key, "TestQword[]")
RegClosekey(key)
RegDeleteKey(@REGMACHINE, "Software\Wilson WindowWare\Sample")
Message("Result",rslt)
exit
See Also:
RegQueryQword, RegApp, RegEntryType, RegSetBin, RegSetDword, RegSetEx,
RegSetExpSz, RegSetValue and the section on Registration Database Operations
(pg. 497)
RegSetValue
Sets the value of a data item in the Registration Database.
527
RegUnloadHive
Syntax:
RegSetValue(handle,subkey-string,value[,view-flag])
Parameters:
(i) handle
(s) subkey-string
(s) value
(i) view-flag
Returns:
(i)
handle to a registration database key.
a path from the key provided to the desired key, including
the "data item name" in square brackets at the end of the key
string.
data to be stored into the database at desired key.
[optional] controls which registry view the function uses
when accessing the Windows registry.
0 - view indicated by the last call to the Error! Hyperlink
reference not valid..
32 - use the 32-bit registry view.
64 - use the 64-bit registry view.
@TRUE data item was stored; @FALSE operation failed.
Use this function to store data items into the Registration Database. If the desired key
does not exist, the function will create it.
Note: Named data entries are specified by enclosing the data item name in square
brackets at the end of the key string. For example:
RegSetValue(@REGMACHINE,"SOFTWARE\Wilson WindowWare\Settings
\WWWBATCH\MAIN[SOUNDS]",1)
Example:
; Associate DIZ files with default textfile editor
key=RegCreatekey(@REGCLASSES, ".diz")
RegSetValue(key, "", "txtfile")
RegClosekey(key)
; The preceding is actually a hard way to do ...
RegSetValue(@REGCLASSES, ".diz", "txtfile")
See Also:
RegApp, RegEntryType, RegSetBin, RegSetDword, RegSetEx, RegSetExpSz,
RegSetMulSz and the section on Registration Database Operations (pg. 497)
RegUnloadHive
Unloads a hive from the registry.
Syntax:
RegUnloadHive(handle,subkey)
Parameters:
(i) handle
528
either @REGUSERS or @REGMACHINE.
Return
(s) subkey
Returns:
(i)
the name of a key which is mapped to a hive file.
@TRUE on success.
Windows Vista or newer: This function may require an Administrator level
account, because it attempts to access to the HKEY_LOCAL_MACHINE registry
key.
Example:
RegUnloadHive(@REGMACHINE, "WinWare")
See Also:
RegLoadHive and the section on Registration Database Operations (pg. 497)
Reload {*M}
Reloads menu file(s).
Syntax:
Reload()
Parameters:
(none)
Returns:
(i)
@TRUE.
This function is used to reload the WIL Interpreter's menu file(s). It is useful after
editing a menu file, to cause the changes to immediately take effect.
Note1: This command does not take effect until the WIL program has completed,
regardless of where the command may appear in the program.
Note2: This command is not part of the WIL Interpreter package, but is documented
here because it has been implemented in many of the shell or file manager-type
applications which use the WIL Interpreter.
Example:
RunZoomWait("notepad.exe", "c:\win\cmdpost.cpm")
Reload( )
Return
Used to return from a Call to the calling program or to return from a GoSub :label.
Syntax:
Return
529
RtStatus
Parameters:
(dependent)
Returns:
(dependent)
depends on use, see below.
the Return command can return a value, by specifying a
value (or an expression that evaluates to a value) after the
"Return" keyword, except when using GoSub.
The Return statement returns to the statement following the most recently executed
Call, GoSub or UDF. If there is no matching Call, GoSub or UDF, an Return is
assumed.
The Return command can return a value, by specifying a value (or an expression
that evaluates to a value) after the "Return" keyword. The value or expression may
optionally be enclosed in parentheses. This feature can be used with the Call
command, and with the User-Defined-Functions. It does not affect the Gosub
command.
Examples:
Return
Return
Return
Return
Return
(10)
"Okay"
myvariable * 10
(ItemCount(list, @TAB))
A script run with the Call command can now return a value by using a Return
command with a value (see above). If a Return command without a value is used,
or the called script does not contain a Return command, the called script will return
0.
example:
result = Call("other.wbt", "")
Example:
Display(2, "End of subroutine", "Returning to MAIN.WBT")
Return
See Also:
Call, Exit, GoSub, User-Defined-Functions
RtStatus
Returns a number indicating the current execution mode of WinBatch.
Syntax:
RtStatus()
Parameters:
(none)
530
Run
Returns:
(i)
execution mode:
0 - WinBatch Interpreter
1 - Compiled WinBatch EXE file
5 - Compiled WinBatch Service (EXS file)
10 - WinBatch Studio debug
12 = FileMenu
13 = PopMenu
14 = WebBatch
Example:
flag=rtStatus()
switch flag
case 0
type="WinBatch Interpreted Script"
break
case 1
type="Compiled WinBatch EXE file"
break
case 5
type="Compiled WinBatch Service (EXS file)"
break
case 10
type="WinBatch Studio Debug"
break
case 12
type="FileMenu"
break
case 13
type="PopMenu"
break
case 14
type="WebBatch"
break
case flag
type="Unknown"
break
end switch
Message("Code running as",type)
Run
Runs a program as a normal window.
Syntax:
Run(program-name,params)
Parameters:
(s) program-name
the name of the desired .EXE, .COM, .PIF, .BAT file, or a
data file.
531
RunEnviron
(s) params
Returns:
(i)
optional parameters as required by the application.
@TRUE if the program was found; @FALSE if it wasn't.
Use this command to run an application.
If the drive and path are not part of the program name, the current directory will be
examined first, followed by the Windows and Windows System directories, and then
the DOS path will be searched to find the desired executable file.
If the "program-name" has an extension other than .EXE, .COM, .PIF, or .BAT, it
will be run with the associated application. When this happens, any "parameters" you
specified are ignored.
Examples:
Run("notepad.exe", "abc.txt")
Run("paint.exe", "pict.msp")
See Also:
RunShell, AppExist, RunHide, RunIcon, RunWait, RunZoom, ShellExecute,
WinClose, WinExeName, WinWaitClose
RunEnviron
Launches a program and has it inherit the current environment as set with the
EnvironSet command.
Syntax:
RunEnviron(program-name,params,display mode,waitflag)
Parameters:
(s) program-name
(s) params
(i) display mode
(i) waitflag
Returns:
(i)
the name of the desired Windows EXE file.
optional parameters as required by the application.
@NORMAL, @ICON, @ZOOMED, @HIDDEN,
@NOACTIVATE.
@WAIT, @NOWAIT.
@TRUE executed normally; @FALSE failed.
Use this function to launch a program with the current environment.
Only Windows EXE’s may be executed with this command. It is possible to change
the environment for DOS programs by launching a DOS BAT file that includes DOS
SET statements to alter the environment settings before executing the DOS program.
Use the Run commands to launch DOS programs and BAT files.
This function is identical to the RunShell function.
532
RunHide
To alter the path for DOS programs, all that is required is a simple batch file, and the
usual WIL Run command. Assuming the case where one wished to run "cmd.exe"
with the path "c:\special", a generic batch file as shown below will suffice, along
with passing all the information required as parameters in the WIL Run command.
DoPath.bat file listing
SET PATH=%1
ECHO %PATH%
PAUSE
%2 %3 %4 %5 %6 %7 %8 %9
WIL Run Command
Run("dopath.bat", "c:\special cmd.exe")
If the "program-name" has an extension other than .EXE, .COM, .PIF, or .BAT, it
will be run with the associated application.
The @NOACTIVATE value causes the targeted application's window to be
displayed in its most recent size and position but without making the application's
window the active window when another top-level window is already active.
Example:
;Note: Permanent changes may be made by
;using the registry functions to update the registry.
;
;Note that this function will not affect the environment for
; DOS or Console applications
;
;Note: Modifying the path does not allow assist WIL in
;locating the EXE file. The path WIL uses has already
;been pre-determined. However the child process (excel)
;will inherit the PATH environment variable in this case.
EnvironSet("PATH","c:\Program Files\Excel\")
RunEnviron("c:\Program Files\Excel\Excel.exe","",@NORMAL,@WAIT)
See Also:
RunShell, Run, RunWait, Environment, EnvironSet, ShellExecute
RunHide
Runs a program as a hidden window.
Syntax:
RunHide(program-name,params)
Parameters:
(s) program-name
(s) params
name of the desired .EXE, .COM, .PIF, .BAT, or data file.
optional parameters as required by the application.
533
RunHideWait
Returns:
(i)
@TRUE if the program was found; @FALSE if it wasn't.
Use this command to run an application as a hidden window.
If the drive and path are not part of the program name, the current directory will be
examined first, followed by the Windows and Windows System directories, and then
the DOS path will be searched to find the desired executable file.
If the "program-name" has an extension other than .EXE, .COM, .PIF, or .BAT, it
will be run with the associated application.
Note: When this command launches an application, it merely informs it that you
want it to run as a hidden window. Whether or not the application honors your wish
is beyond RunHide's control.
Examples:
RunHide("notepad.exe", "abc.txt")
RunHide("paint.exe", "pict.msp")
See Also:
RunShell, Run, RunHideWait, RunIcon, RunZoom, ShellExecute, WinClose,
WinExeName, WinHide, WinWaitClose
RunHideWait
Runs a program as a hidden window, and waits for it to close.
Syntax:
RunHideWait(program-name,params)
Parameters:
(s) program-name
(s) params
name of the desired .EXE, .COM, .PIF, .BAT, or data file.
optional parameters as required by the application.
Returns:
(i)
@TRUE if the program was found; @FALSE if it wasn't.
Use this command to run an application as a hidden window. The WIL program will
suspend processing until the application is closed.
If the drive and path are not part of the program name, the current directory will be
examined first, followed by the Windows and Windows System directories, and then
the DOS path will be searched to find the desired executable file.
If the "program-name" has an extension other than .EXE, .COM, .PIF, or .BAT, it
will be run with the associated application.
534
RunIconWait
Note: When this command launches an application, it merely informs it that you
want it to run as a hidden window. Whether or not the application honors your wish
is beyond RunHideWait's control.
Example:
RunHideWait(Environment("COMSPEC"), "/c dir *.exe> temp.txt")
Print("temp.txt","",@NORMAL,0)
See Also:
RunShell, RunHide, RunIconWait, RunWait, RunZoomWait, ShellExecute,
WinWaitClose
RunIcon
Runs a program as an iconic (minimized) window.
Syntax:
RunIcon(program-name,params)
Parameters:
(s) program-name
(s) params
name of the desired .EXE, .COM, .PIF, .BAT, or data file.
optional parameters as required by the application.
Returns:
(i)
@TRUE if the program was found; @FALSE if it wasn't.
Use this command to run an application as an icon.
If the drive and path are not part of the program name, the current directory will be
examined first, followed by the Windows and Windows System directories, and then
the DOS path will be searched to find the desired executable file.
If the "program-name" has an extension other than .EXE, .COM, .PIF, or .BAT, it
will be run with the associated application.
Note: When this command launches an application, it merely informs it that you
want it to begin as an icon. Whether or not the application honors your wish is
beyond RunIcon's control.
Examples:
RunIcon("notepad.exe", "")
See Also:
RunShell, Run, RunHide, RunIconWait, RunZoom, ShellExecute, WinClose,
WinExeName, WinIconize, WinWaitClose
RunIconWait
Runs a program as an iconic (minimized) window, and waits for it to close.
535
RunShell
Syntax:
RunIconWait(program-name,params)
Parameters:
(s) program-name
(s) params
name of the desired .EXE, .COM, .PIF, .BAT, or data file.
optional parameters as required by the application.
Returns:
(i)
@TRUE if the program was found; @FALSE if it wasn't.
Use this command to run an application as an icon. The WIL program will suspend
processing until the application is closed.
If the drive and path are not part of the program name, the current directory will be
examined first, followed by the Windows and Windows System directories, and then
the DOS path will be searched to find the desired executable file.
If the "program-name" has an extension other than .EXE, .COM, .PIF, or .BAT, it
will be run with the associated application.
Note: When this command launches an application, it merely informs it that you
want it to begin as an icon. Whether or not the application honors your wish is
beyond RunIconWait's control.
Example:
comspec = Environment("COMSPEC")
params = "/c dir *.exe>temp.txt"
RunIconWait(comspec, params)
Message("RunIconWait","It Ran, It Iconned, It Waited.")
exit
See Also:
RunShell, RunHideWait, RunIcon, RunWait, RunZoomWait, ShellExecute,
WinWaitClose
RunShell
An advanced form of the Run function that even allows the specification of a
working directory, along with the window view mode and whether or not to wait for
completion of the run program in a single function.
Syntax:
RunShell(program-name,params,directory,displaymode,waitflag)
Parameters:
(s) program-name
(s) params
(s) directory
(i) displaymode
536
name of the desired .EXE, .COM, .PIF, .BAT, or data file.
optional parameters as required by the application.
target directory (if applicable).
@NORMAL, @ICON, @ZOOMED, @HIDDEN,
@NOACTIVATE.
RunWait
(i) waitflag
Returns:
(i)
@WAIT, @NOWAIT, @GETPROCID,
@GETEXITCODE.
@TRUE if the program was found; @FALSE if it wasn't.
If a data file is specified instead of an executable file (i.e. EXE, COM, PIF, or BAT
file), the function examines the extension of the data file, looks the extension up in
the Windows registry to determine the owning application and starts the owning
application, passing the data file name as a parameter. Applications that support this
command or their setup programs will generally make the necessary modifications to
the Windows registry to allow this function to perform successfully.
If the drive and path are not part of the program name, the current directory will be
examined first, followed by the Windows and Windows System directories, and then
the DOS path will be searched to find the desired executable file.
The @NOACTIVATE value causes the targeted application's window to be
displayed in its most recent size and position but without making the application's
window the active window when another top-level window is already active.
If the @WAIT parameter is used, the WIL program will suspend processing until
the application is closed.
If the @GETPROCID parameter is used, a process-id will be returned that can be
used with the function WinItemProcID.
If the @GETEXITCODE parameter is used, the exit code of an application that is
launched with the RunShell function will be returned. This is the same as specifying
@WAIT, except that on success the function will return the exit code of the
application that was launched.
Note: When this command launches an application, it merely informs it how you
wish it to appear on the screen. Whether or not the application honors your wish is
beyond this function's control.
Example:
RunShell("NOTEPAD.EXE", "CONFIG.SYS", "C:\", @NORMAL, @NOWAIT)
See Also:
IntControl 64, Print, Run, RunWait, ShellExecute, WinItemProcID
RunWait
Runs a program as a normal window, and waits for it to close.
Syntax:
RunWait(program-name,params)
537
RunWithLogon
Parameters:
(s) program-name
(s) params
name of the desired .EXE, .COM, .PIF, .BAT, or data file.
optional parameters as required by the application.
Returns:
(i)
@TRUE if the program was found; @FALSE if it wasn't.
Use this command to run an application. The WIL program will suspend processing
until the application is closed.
If the drive and path are not part of the program name, the current directory will be
examined first, followed by the Windows and Windows System directories, and then
the DOS path will be searched to find the desired executable file.
If the "program-name" has an extension other than .EXE, .COM, .PIF, or .BAT, it
will be run with the associated application.
Example:
RunWait(Environment("COMSPEC"), "/c dir *.exe>temp.txt")
Print("temp.txt","",@NORMAL,0)
WinWaitClose("~Notepad")
FileDelete("temp.txt")
See Also:
AppWaitClose, Run, RunShell, RunHideWait, RunIconWait, RunZoomWait,
ShellExecute, WinWaitClose, WinWaitExist
RunWithLogon
Runs a program as a specified user. (Windows 2000+)
Syntax:
RunWithLogon(program-name,params,directory,display mode,waitflag,
username,domain,password,logon-flags)
Parameters:
(s) program-name
(s) params
(s) directory
(i) display mode
(i) waitflag
(s) username
538
name of the desired .EXE, .COM, .PIF, .BAT, or data file.
optional parameters as required by the application.
target directory (if applicable).
@NORMAL, @ICON, @ZOOMED, @HIDDEN,
@NOACTIVATE.
@WAIT, @NOWAIT, @GETPROCID.
specifies the name of the user account to
log on to. Note: If you use the UPN format
([email protected]_domain_name),
"domain" must be a blank string ("").
RunWithLogon
(s) domain
(s) password
(i) logon-flags
specifies the name of the domain or server whose
account database contains the "username" account.
Note: If this parameter is a blank string, "username"
must be specified in UPN format.
specifies the password for the "username" account.
see below.
"logon-flags" can be one of the following values:
Value
0
1
2
Name
Default
LOGON_WITH_PROFILE
LOGON_NETCREDENTIALS_ONLY
Meaning
No logon-flag.
Log on, then load the user's
profile. Loading the profile can
be time-consuming, so it is best
to use this value only if you must
access the user's profile
information.
Log on, but use the specified
credentials on the network only.
This value can be used to create
a process that uses a different set
of credentials locally than it does
remotely. This is useful in interdomain scenarios where there is
no trust relationship.
If a data file is specified instead of an executable file (i.e. EXE, COM, PIF, or BAT
file), the function examines the extension of the data file, looks the extension up in
the Windows registry to determine the owning application and starts the owning
application, passing the data file name as a parameter. Applications that support this
command or their setup programs will generally make the necessary modifications to
the Windows registry to allow this function to perform successfully.
If the drive and path are not part of the program name, the current directory will be
examined first, followed by the Windows and Windows System directories, and then
the DOS path will be searched to find the desired executable file.
The @NOACTIVATE value causes the targeted application's window to be
displayed in its most recent size and position but without making the application's
window the active window when another top-level window is already active.
If the @WAIT parameter is used, the WIL program will suspend processing until
the application is closed.
If the @GETPROCID parameter is used, a process-id will be returned that can be
used with the function WinItemProcID.
539
RunWithLogon
Notes: When this command launches an application, it merely informs it how you
wish it to appear on the screen. Whether or not the application honors your wish is
beyond this function's control.
Windows Server 2003 and Windows XP:
There is a known issue on Windows XP SP1and 2003 where the RunWithLogon
function ignoring the 'display mode' parameter. There is a windows service pack
update/hotfix that addresses this problem. See Microsoft's knowledgebase article
818858, for details.
RunWithLogon accesses the 'program-name' in the security context of the target
user. If the executable you want to launch is on a network and a network drive letter
is specified in the path, the network drive letter is not available to the target user, as
network drive letters are assigned on a per logon basis, thus this function will fail. If
the executable you want to launch is on a network, use the UNC path.
Issues involved with RunWithLogon when you change the credentials under
which a program runs:
RunWithLogon changes the security context of the script. Security context is
nothing more than a 'sandbox' in which programs can all play. When you are logged
on to a NT platform system, your session consists of multiple processes, with each
process running one program. When you connect a drive letter to a network resource,
that drive letter only exists within your security context. Other sessions [e.g. other
terminal sessions on a terminal server system, services running under separate user
accounts different from your own] have separate security contexts and thus they
don't see your drive letter mappings as they exist in their own private 'sandboxes'.
When you use RunWithLogon() to make use of impersonation, you are causing that
process to run in a separate security context.
Examples:
Example 1
DirChange(DirWindows(0))
;check the platform
if WinVersion(5) >= "2-5-0"
;Win2000 or newer
;NOTE: For security reasons *always* assign the password
; to a variable and then use the variable in the RunWithLogon
; statement. NEVER hardcode the password into the
; RunWithLogon statement or else the password my be
; exposed if the RunWithLogon fails on some kind of error
; This is also a good idea with the userid and domain
; information
runas_user = "Administrator"
runas_pswd = "password"
runas_domain = ComputernameGet(0) ; local account database
; The following should be on one line
RunWithLogon("NOTEPAD.EXE", "", "C:\", @NORMAL, @NOWAIT,
runas_user, runas_domain, runas_pswd,1)
else
Message("RunWithLogon","Is not designed for this platform.")
540
RunWithLogon
endif
exit
Example 2
;This script
; :SETINFO ; :BEFORE ; :ADMIN
; :AFTER
;
;
;
;
;
;
;
supports four subroutines
code to specify Admin userid and password and domain
code that executes in user mode BEFORE running as admin
code that runs as ADMIN
code that executes in user mode AFTER running as admin
Basically this script executes the BEFORE subroutine, then does a
RUNWITHLOGON to run a copy of itself in admin mode. When the admin
mode portion exits, then this script executes the AFTER subroutine.
When the original script performs the RUNWITHLOGON it adds an
additional parameter to the script's command line (if any), which
is the string URADMIN, to let the admin script know that it is
already in admin mode so that it can do that portion of the code.
; The top section of this example can generally be used as-is. The
; intent is that all the changes required can be done in the four
; Gosub's at the bottom.
; This picks up the entire passed parameter line to see if the
; URADMIN parameter exits
moiparams=IntControl(1006,0,0,0,0)
; Check passed parameters for URADMIN string
if StrIndexNC(moiparams,"URADMIN",0,@fwdscan) == 0
; URDAMIN NOT FOUND. Not running as Admin.
; check to see if doing this is supported
if WinVersion(5) >= "2-5-0"
;Win2k or newer.
; RunWithLogon supported.
; GOSUB BEFORE code
Gosub BEFORE
; Set up to RUN a copy of this script with ADMIN privileges
Gosub SETINFO
moi=WinExename("")
;Get current script name
moiparams=strcat(moiparams, " URADMIN") ;Add URADMIN to param
; The following should be on one line
RunWithLogon(moi, moiparams, "", @NORMAL, @WAIT,runas_user,
runas_domain, runas_pswd,0)
; GOSUB the AFTER code here
GOSUB AFTER
;Quit. Script is complete
; Drop out of if/endif to exit statement
else ; RUNWITHLOGON not supported on this platform
; Provide error message and exit
541
RunWithLogon
Message("RunWithLogon","Is not designed for this platform.")
; Drop out of if/endif to exit statement
endif
else
; Already launched as admin
param0 = param0-1 ; Remove the URADMIN param
;Do the ADMIN code
GOSUB ADMIN
; Drop out of if/endif to exit statement
endif
exit
:SETINFO
; This subroutine is used to setup the account
; information required to Run as the Administrator.
; Userid, password, and domain are defined here
;NOTE: For security reasons *always* assign the password
; to a variable and then use the variable in the RunWithLogon
; statement. NEVER hardcode the password into the
; RunWithLogon statement or else the password my be
; exposed if the RunWithLogon fails on some kind of error
; This is also a good idea with the userid and domain
; information
runas_user = "Administrator"
runas_pswd = "secretpassword"
runas_domain = ComputernameGet(0); local account database
return
:BEFORE
; Running in user mode, BEFORE running the admin mode
; portion of the script
Message("Debug","Executing BEFORE section of script")
return
:ADMIN
;------------------------------; Running in ADMIN mode.
;------------------------------Message("Debug","Running ADMIN section of script")
return
:AFTER
; Running in user mode, AFTER running the admin mode
; portion of the script
Message("Debug","Executing AFTER section of script")
return
See Also:
RunShell, Run, RunHide, RunIcon, RunZoomWait, ShellExecute, WinClose,
WinExeName, WinWaitClose, WinZoom
542
RunZoomWait
RunZoom
Runs a program as a full-screen (maximized) window.
Syntax:
RunZoom(program-name,params)
Parameters:
(s) program-name
(s) params
name of the desired .EXE, .COM, .PIF, .BAT, or data file.
optional parameters as required by the application.
Returns:
(i)
@TRUE if the program was found; @FALSE if it wasn't.
Use this command to run an application as a full-screen window.
If the drive and path are not part of the program name, the current directory will be
examined first, followed by the Windows and Windows System directories, and then
the DOS path will be searched to find the desired executable file.
If the "program-name" has an extension other than .EXE, .COM, .PIF, or .BAT, it
will be run with the associated application.
Note: When this command launches an application, it merely informs it that you
want it to be maximized to full-screen. Whether or not the application honors your
wish is beyond RunZoom's control.
Examples:
RunZoom("notepad.exe", "abc.txt")
RunZoom("notepad.exe", "")
RunZoom("paint.exe", "pict.msp")
See Also:
RunShell, Run, RunHide, RunIcon, RunZoomWait, ShellExecute, WinClose,
WinExeName, WinWaitClose, WinZoom
RunZoomWait
Runs a program as a full-screen (maximized) window, and waits for it to close.
Syntax:
RunZoomWait(program-name,params)
Parameters:
(s) program-name
(s) params
name of the desired .EXE, .COM, .PIF, .BAT, or data file.
optional parameters as required by the application.
Returns:
(i)
@TRUE if the program was found; @FALSE if it wasn't.
543
Select
Use this command to run an application as a full-screen window. The WIL program
will suspend processing until the application is closed.
If the drive and path are not part of the program name, the current directory will be
examined first, followed by the Windows and Windows System directories, and then
the DOS path will be searched to find the desired executable file.
If the "program-name" has an extension other than .EXE, .COM, .PIF, or .BAT, it
will be run with the associated application.
Note: When this command launches an application, it merely informs it that you
want it to be maximized to full-screen. Whether or not the application honors your
wish is beyond RunZoomWait's control.
Example:
RunZoomWait(Environment("COMSPEC"), "/c dir *.exe>temp.txt")
Print("temp.txt","",@NORMAL,0)
See Also:
RunShell, RunHideWait, RunIconWait, RunWait, RunZoom, ShellExecute,
WinWaitClose
Select
The Select statement allows selection among multiple blocks of statements.
Syntax:
Select expression
case expression
statements
break
case expression
statements
break
EndSelect
Parameters:
(s) expression
an expression that must evaluate to an integer.
The Select statement allows selection among multiple blocks of statements,
depending on the value of an expression. The expression must evaluate to an integer.
The Select statement causes the statements in the select body to be scanned by the
parser as it attempts to find a case statement. When a case statement is found, the
expression following the case statement is evaluated, and if the expression evaluates
to the same value as the expression following the Select statement, execution of the
following statements is initiated. The EndSelect statement terminates the Select
structure.
544
SendKey
If a matching case expression was found, and execution was initiated, the following
statements will affect continued execution:
Break
Terminates the Select structure and transfers control to the
statement following the next matching EndSelect.
Continue
Stops execution and resumes scanning for a case statement.
Case
Ignored. Treated as a comment.
EndSelect
Terminates the Select structure and transfers control to the
next statement.
Note: Switch and Select may be used interchangeably. They are synonyms for the
same statement.
EndSwitch, EndSelect, "End Switch", and "End Select" may be used
interchangeably.
Example:
response=AskLine("Select", "Enter a number between 1 and 3", 1, 0)
Select response
case 1
Message("Select", "Case 1 entered")
break
case 2
Message("Select", "Case 2 entered")
break
case 3
Message("Select", "Case 3 entered")
break
case response
; default case
Message("Select", "Default case entered")
break
EndSelect
See Also:
If, For, GoSub, While
SendKey
Sends keystrokes to the currently active window.
Syntax:
SendKey(char-string)
Parameters:
(s) char-string
string of regular and/or special characters.
Returns:
(i)
@FALSE.
545
SendKey
Note: SendKey will send keystrokes to the currently active window. For many
applications, the related functions, SendKeysChild, SendKeysTo or SendMenusTo
may be better alternatives.
This function is used to send keystrokes to the active window, just as if they had
been entered from the keyboard. Any alphanumeric character, and most punctuation
marks and other symbols which appear on the keyboard, may be sent simply by
placing it in the "char-string".
In addition, the following special characters, enclosed in "curly" braces, may be
placed in "char-string" to send the corresponding special characters:
Key
SendKey equivalent
~
!
^
+
{
}
Alt
Backspace
Clear
Ctrl-Break
Delete
Down Arrow
End
Enter
Escape
F1 through F16
Help
Home
Insert
Left Arrow
Page Down
Page Up
Pause
Right Arrow
Space
Tab
Up Arrow
{~}
; This is how to send a ~
{!}
; This is how to send a !
{^}
; This is how to send a ^
{+}
; This is how to send a +
{{}
; This is how to send a {
{}}
; This is how to send a }
{ALT}
{BACKSPACE} or {BS}
{CLEAR}
{CANCEL}
{DELETE} or {DEL}
{DOWN}
{END}
{ENTER} or ~
{ESCAPE} or {ESC}
{F1} through {F16}
{HELP}
{HOME}
{INSERT} or {INS}
{LEFT}
{PGDN}
{PGUP}
{PAUSE}
{RIGHT}
{SPACE} or {SP}
{TAB}
{UP}
Additional special characters to the SendKey (and SendKeysTo and
SendKeysChild) functions:
Key
0 on numeric keypad
1 on numeric keypad
546
SendKey equivalent
{NUMPAD0}
{NUMPAD1}
SendKey
2 on numeric keypad
3 on numeric keypad
4 on numeric keypad
5 on numeric keypad
6 on numeric keypad
7 on numeric keypad
8 on numeric keypad
9 on numeric keypad
* on numeric keypad
+ on numeric keypad
- on numeric keypad
. on numeric keypad
/ on numeric keypad
Enter on numeric keypad
Print Screen
% (single percent sign)
{NUMPAD2}
{NUMPAD3}
{NUMPAD4}
{NUMPAD5}
{NUMPAD6}
{NUMPAD7}
{NUMPAD8}
{NUMPAD9}
{NUMPAD*}
{NUMPAD+}
{NUMPAD-}
{NUMPAD.}
{NUMPAD/}
{NUMPAD~}
{PRTSC}
%%
In the following, "Standalone" means the key is pressed and then released.
"Combination" means the key is held down while the following key is pressed. These
may or may not work for any particular application or situation:
Left Alt key, standalone
Right Alt key, standalone
Left Control key, standalone
Right Control key, standalone
Left Shift key, standalone
Right Shift key, standalone
Left Windows key, standalone
Right Windows key, standalone
Applications key, standalone
Left Alt key, combination
Right Alt key, combination
Left Control key, combination
Right Control key, combination
Left Shift key, combination
Right Shift key, combination
Left Windows key, combination
Right Windows key, combination
Applications key, combination
{LALT}
{RALT}
{LCONTROL}
{RCONTROL}
{LSHIFT}
{RSHIFT}
{LWIN}
{RWIN}
{APPS}
{*LALT}
{*RALT}
{*LCONTROL}
{*RCONTROL}
{*LSHIFT}
{*RSHIFT}
{*LWIN} ;see notes below
{*RWIN} ;see notes below
{*APPS}
Notes: The left and right Alt, Control, and Shift keys can only be distinguished
on Windows NT or newer. On other platforms they are treated as plain Alt,
Control, and Shift keys, respectively.
The "Windows" and Applications" keys are on the Microsoft Natural keyboard.
547
SendKey
In the specific case of "{*LWIN}L" or "{*RWIN}L" which would be the
keystrokes to swap a currently logged-in user (in Windows XP and newer), a
problem occurs where the user session that executed the SendKey misses the
key-up of the Windows key. When returning to that user session, the system
thinks the Windows key is still depressed, and thus keyboard input does not
work properly. The problem can be manually cleared by pressing the Windows
key again and hitting Escape to clear the Start Menu that pops up. Thus it is
recommended that you do not attempt to use these key combinations in a script
to swap users. As an alternative you may wish to look into the RunWithLogon
function which allows a program to be run as another user.
To enter an Alt, Control, or Shift key combination, precede the desired character
with one or more of the following symbols:
Alt
Control
Shift
!
^
+
To enter Alt-S:
SendKey("!s")
To enter Ctrl-Shift-F7:
SendKey("^+{F7}")
You may also repeat a key by enclosing it in braces, followed by a space and the
total number of repetitions desired.
To type 20 asterisks:
SendKey("{* 20}")
To move the cursor down 8 lines:
SendKey("{DOWN 8}")
To toggle a checkbox:
SendKey("{+}")
SendKey("{-}")
;always checks a checkbox
;always unchecks a checkbox
To type a single percent sign:
SendKey("%%")
;types a single percent sign
Example:
; start Notepad, and use *.* for filenames
Run("notepad.exe", "")
SendKey("!fo*.*~")
548
SendKeysChild
In those cases where you have an application which can accept text pasted in from
the clipboard, it will often be more efficient to use the ClipGet function:
Run("notepad.exe", "")
; copy some text to the clipboard
ClipPut("Dear Sirs:":@CRLF:@CRLF)
; paste the text into Notepad (using Ctrl-v)
SendKey("^v")
A WIL program cannot send keystrokes to its own WIL Interpreter window.
Notes:
You should, in general, use lower-case letters to represent Alt-key combinations
and other menu shortcut keys as that is the normal keys used when typing to
application. For example, "!fo" is interpreted as Alt-f-o, as one might expect.
However, "!FO" is interpreted as Alt-Shift-f-o, which is not a normal keystroke
sequence.
If your SendKey statement doesn't seem to be working (e.g., all you get are
beeping noises), you may need to place a WinActivate statement before the
SendKey statement to insure that you are sending the keystrokes to the correct
window, or you may try using the SendKeysTo or SendKeysChild function.
When sending keystrokes to a DOS box, the DOS box must be in a window (Not
Full Screen). Most keystrokes can be sent to a full screen DOS box, however,
SendKey can only send the ENTER key to a Windowed DOS Box.
The function IgnoreInput may be used to block user input during a sendkey
operation.
See Also:
IntControl 35, IgnoreInput, SendKeysTo, SendKeysChild, SendMenusTo, SnapShot,
WinActivate
SendKeysChild
Sends keystrokes to a child window.
Syntax:
SendKeysChild(parent-winname,child-winname,sendkey string)
Parameters:
(s) parent-winname
(s) child-winname
(s) sendkey string
the initial part of, or an entire parent window name.
the initial part of, or an entire child window name.
string of regular and/or special characters.
Returns:
(i)
@FALSE.
549
SendKeysTo
Use this function to send keystrokes to a particular child window. This function is
similar to SendKey, but the desired parent and child windows will be activated
before sending any keys in lieu of using WinActiveChild. Consequently, a previous
WinActiveChild command will be overridden by this function. See the SendKey
function for a description of the "sendkey string".
Note: "main-winname" and "child-winname" are the initial parts of their respective
window names, and may be complete window names. They are case-sensitive. You
should specify enough characters so that the window names will match only one
existing window of its type. If a winname matches more than one window, the most
recently accessed window which it matches will be used.
The function IgnoreInput may be used to block user input during a sendkey
operation.
Example:
; Start Windows File Manager - the hard way
; This code activates Program Manager, then
; activates the "Main" child window. Sending an
; "f" should (hopefully) activate the File Manager
; icon. The Enter key (abbreviated as ~ ) runs it.
SendKeysChild("Program Manager", "Main", "f~")
See Also:
IntControl 35, IgnoreInput, SendKeysTo, SendKey, SendMenusTo, KeyToggleSet,
SnapShot, WinActivate
SendKeysTo
Sends keystrokes to a "parent-windowname".
Syntax:
SendKeysTo(parent-winname,sendkey string)
Parameters:
(s) parent-winname
(s) sendkey string
the initial part of, or an entire parent window name.
string of regular and /or special characters.
Returns:
(i)
@FALSE.
Use this function to send keystrokes to a particular window. This function is similar
to SendKey, but the correct "parent-winname" will be activated before sending any
keys in lieu of using WinActivate. Consequently, a previous WinActivate
command will be overridden by this function. See the SendKey function for a
description of the "sendkey string". See SendKey for a list of keystroke equivalents.
Note: "parent-winname" is the initial part of a window name, and may be a complete
window name. It is case-sensitive. You should specify enough characters so that
550
SendMenusTo
"winname" matches only one existing window. If it matches more than one window,
the most recently accessed window which it matches will be used.
The function IgnoreInput may be used to block user input during a sendkey
operation.
Example:
run("notepad.exe","")
SendKeysTo("~Notepad", "aBcDeF")
See Also:
IntControl 35, IgnoreInput, SendKey, SendKeysChild, SendMenusTo,
KeyToggleSet, SnapShot, WinActivate
SendMenusTo
Activates a window and sends a specified menu option.
Syntax:
SendMenusTo(parent-winname,menuname)
Parameters:
(s) parent-winname
(s) menuname
the initial part of, or an entire parent window name.
menu item to be selected.
Returns:
(i)
@FALSE.
Use this function to access drop down menus on a window. The function activates
the "winname" application window, searches its menus and sends the specified
windows message for the menu operation.
To construct the "menuname" parameter simply string together all the menu options
selected to access the desired function. All punctuation and special characters are
ignored, as well as any possible "hotkeys" used to access the function via the
keyboard. For example, most Windows applications have a "File" menu and an
"Open" menu. To construct the "menu name" parameter, simply string together the
words, making "FileOpen", or for better readability use "File Open" - the spaces are
ignored.
Note 1: "winname" is the initial part of a window name, and may be a complete
window name. It is case-sensitive. You should specify enough characters so that
"winname" matches only one existing window. If it matches more than one window,
the most recently accessed window which it matches will be used.
Note 2: SendMenusTo does not work with all applications. If you get a 'windows
menu not accessible' error, SendMenusTo will not work with that application. Use
SendKeysTo instead.
551
SendMessageW
Example:
Run("notepad.exe", "c:\config.sys")
SendMenusTo("~Notepad", "Edit Select All")
SendMenusTo("~Notepad", "Edit Copy")
See Also:
SendKeysTo, SendKeysChild, SendKey, SnapShot
SendMessageA
Issues a Windows "SendMessage", with lParam as an ANSI string.
Syntax:
SendMessageA(window-id/handle,message-id,wParam,lParam)
Parameters:
(i) window-id/handle
(i) message-id
(i) wParam
(s) lParam
Returns:
(s)
window id or handle to send to.
message ID number (in decimal).
wParam value (message-specific information).
lParam value (message-specific information
assumed to be a character string).
result of the message processing; it depends on the message
sent.
The lParam string is copied to a GMEM_LOWER buffer, and a LPSTR to the copied
string is passed as lParam. The GMEM_LOWER buffer is freed immediately upon
return from the SendMessageA.
Example:
; Send WM_SETTINGCHANGE to all top-level windows
; when they make changes to system parameters
HWND_BROADCAST = -1
WM_SETTINGCHANGE = 26
SendMessageA( HWND_BROADCAST, WM_SETTINGCHANGE, 0, "")
See Also:
RegSetValue, SendMessageW
SendMessageW
Issues a Windows "SendMessage", with lParam as a Unicode string. (Windows NT
and newer)
Syntax:
SendMessageW(window-id/handle,message-id,wParam,lParam)
552
ShellExecute
Parameters:
(i) window-id/handle
(i) message-id
(i) wParam
(s) lParam
Returns:
(s)
window id or handle to send to.
message ID number (in decimal).
wParam value (message-specific information).
lParam value (message-specific information
assumed to be a Unicode string).
result of the message processing; it depends on the message
sent.
The lParam string is copied to a GMEM_LOWER buffer, and a LPSTR to the copied
string is passed as lParam. The GMEM_LOWER buffer is freed immediately upon
return from the SendMessageW.
Example:
; Send WM_SETTINGCHANGE to all top-level windows
; when they make changes to system parameters
HWND_BROADCAST = -1
WM_SETTINGCHANGE = 26
SendMessageW( HWND_BROADCAST, WM_SETTINGCHANGE, 0, "")
See Also:
RegSetValue, SendMessageA
ShellExecute
Runs a program via the Windows ShellExecute command
Syntax:
ShellExecute(program-name,params,directory,displaymode,operation)
Parameters:
(s) program-name
(s) params
(s) directory
(i) display mode
(i) operation
Returns:
(i)
the name of the desired .EXE, .COM, .PIF, .BAT file or a
data file.
optional parameters as required by the application.
current working directory (if applicable).
@NORMAL, @ICON, @ZOOMED, @HIDDEN,
@NOACTIVATE or 0 for the default mode.
operation to perform on the specified file.
@TRUE on success; @FALSE on failure.
This function uses the Windows ShellExecute API to launch the specified file. The
similar RunShell function also uses the ShellExecute API in the 16-bit version, but
553
ShortcutDir
uses the CreateProcess API in the 32-bit version. Note that RunShell has a "wait"
parameter, while this function does not.
The @NOACTIVATE value causes the targeted application's window to be
displayed in its most recent size and position but without making the application's
window the active window when another top-level window is already active.
"operation" is the operation to perform on the file ("Open", "Print", etc.), which may
or may not correspond to an available "verb" on the context menu for the file. This
parameter may be case-sensitive. Specify a blank string "" for the file's default
operation.
Note: If you use this function to launch a shortcut, and the shortcut points to an
invalid path, Windows will display a "Missing Shortcut" dialog box asking if you
wish to update the shortcut. This would not be suitable to use in unattended
operation. Instead, you could use one of the Run functions to launch the shortcut,
which would return an error #1932 if the shortcut could not be launched. This error
can be trapped using the ErrorMode function.
Example:
; launches a shortcut to a "Dial-Up Networking" item on the desktop
startdir=ShortcutDir("Desktop",0,0)
ShellExecute(StrCat( startdir, "netcom.lnk"), "", "", @NORMAL, "")
WinWaitClose("Connect To")
Message("ShellExecute"," Executed.")
See Also:
RunShell
ShortcutDir
Gets the path of a folder identified by a name or CSIDL value.
Syntax:
ShortcutDir(name/CSIDL[,source[,add-slash]])
Parameters:
(s) name or CSIDL
(i) source
(i) add-slash
Returns:
(s)
554
see list below.
[optional] flag which can under 'certain' circumstances
specify the location from which the information will be
retrieved. see below.
[optional] if @TRUE, a backslash will be appended to the
returned string if it doesn't already have a trailing backslash.
The default is @FALSE.
a directory name on success; a blank string
("") if no corresponding value was found.
ShortcutDir
Name
CSIDL
Meaning
Desktop
0
CSIDL_DESKTOP Desktop (namespace root)
Programs
2
CSIDL_PROGRAMS Programs folder (under
Start menu in [user] profile)
Personal
5
CSIDL_PERSONAL Personal folder ([user]
profile)
Favorites
6
CSIDL_FAVORITES Favorites folder ([user]
profile)
Startup
7
CSIDL_STARTUP Startup folder ([user]
profile)
Recent
8
CSIDL_RECENT Recent folder
([user] profile)
SendTo
9
CSIDL_SENDTO SendTo folder ([user]
profile)
Start Menu
11
CSIDL_STARTMENU Start menu ([user]
profile)
My Music
13
CSIDL_MYMUSIC My Music ([user] profile)
My Video
14
CSIDL_MYVIDEO My Videos ([user] profile)
16
CSIDL_DESKTOPDIRECTORY Desktop
folder ([user] profile)
NetHood
19
CSIDL_NETHOOD Network Neighborhood
directory
Fonts
20
CSIDL_FONTS Fonts virtual folder
Templates
21
CSIDL_TEMPLATES Templates folder ([user]
profile)
Common Start
Menu
22
CSIDL_COMMON_STARTMENU Start menu
(All Users profile)
Common
Programs
23
CSIDL_COMMON_PROGRAMS Programs
folder (under Start menu in All Users profile)
Common Startup
24
CSIDL_COMMON_STARTUP Startup folder
(All Users profile)
Common Desktop
25
CSIDL_COMMON_DESKTOPDIRECTORY
Desktop folder (All Users profile)
AppData
26
CSIDL_APPDATA Application Data ([user]
profile)
PrintHood
27
CSIDL_PRINTHOOD PrintHood folder ([user]
profile)
555
ShortcutDir
28
CSIDL_LOCAL_APPDATA Local (nonroaming) data repository for apps
29
CSIDL_ALTSTARTUP Alternate Startup
([user], DBCS)
30
CSIDL_COMMON_ALTSTARTUP Alternate
Startup folder (All Users profile, DBCS)
Common
Favorites
31
CSIDL_COMMON_FAVORITES Favorites
folder (All Users profile)
Cache
32
CSIDL_INTERNET_CACHE Internet Cache
folder
Cookies
33
CSIDL_COOKIES Cookies folder
History
34
CSIDL_HISTORY History folder
Common
AppData
35
CSIDL_COMMON_APPDATA Application
Data (All Users Profile)
36
CSIDL_WINDOWS Windows directory or
SYSROOT
37
CSIDL_SYSTEM System folder
38
CSIDL_PROGRAM_FILES Program Files
folder
39
CSIDL_MYPICTURES My Pictures folder
40
CSIDL_PROFILE Users profile folder
41
CSIDL_SYSTEM System folder
43
CSIDL_PROGRAMS_FILES_COMMON
Common files folder, e.g., C:\Program
Files\Common Files
Common
Templates
45
CSIDL_COMMON_TEMPLATES Templates
folder (All Users profile)
Common
Documents
46
CSIDL_COMMON_DOCUMENTS
Documents folder (All Users profile)
Common
Administrative
Tools
47
CSIDL_COMMON_ADMINTOOLS Admin
Tools folder (All Users profile)
Administrative
Tools
48
CSIDL_ADMINTOOLS Admin Tools folder
CommonMusic
53
CSIDL_COMMON_MUSIC My Music (All
Users profile)
CommonPictures
54
CSIDL_COMMON_PICTURES My Pictures
(All Users profile)
Local AppData
My Pictures
556
ShortcutEdit
CommonVideo
CD Burning
55
CSIDL_COMMON_VIDEO My Videos (All
Users profile)
56
CSIDL_RESOURCES Windows resources
folder
59
CSIDL_CDBURN_AREA to CD. A typical
path is C:\Documents and
Settings\username\Local Settings\Application
Data\Microsoft\CD Burning.
For more examples of possible 'names', see the appropriate registry key.
Source [optional]
The source parameter is only used if a name string is specified. If a CSIDL code is
specified this parameter is ignored.
If the Name specified cannot be found, this flag specifies the registry location from
which the information will be retrieved:
Flag
Location
0
Current user: HKEY_CURRENT_USER\Software\Microsoft\
Windows\CurrentVersion\Explorer\Shell Folders
1
All users:HKEY_LOCAL_MACHINE\Software\Microsoft\
Windows\CurrentVersion\Explorer\Shell Folders
Example:
startdir=ShortcutDir("Desktop",0,0)
DirChange(startdir)
dest = StrCat(DirWindows(0),"notepad.exe")
ShortcutMake("mynotepad.lnk", dest, "", "", @NORMAL,0)
ShortcutEdit("mynotepad.lnk", "", "", startdir, @NORMAL,0)
exit
; Get Programs folder (under Start menu in [user] profile)
csidlcode = 2 ;CSIDL_PROGRAMS
progdir = ShortCutDir( csidlcode, 0, 0 )
Message("Programs directory path", progdir )
exit
See Also:
ShortCutExtra, ShortcutInfo, ShortcutMake
ShortcutEdit
Modifies the specified shortcut file.
557
ShortcutEdit
Syntax:
ShortcutEdit(link-name,target,params,start-dir,show-mode[,shortcut-type])
Parameters:
(s) link-name
(s) target
(s) params
(s) start-dir
(i) show-mode
(i) shortcut-type
Returns:
(i)
the name of shortcut .LNK file to be created.
file or directory name which "link-name" will point to.
optional command-line parameters for "target"
"Start in" directory for "target".
"Run" mode for "target": @NORMAL, @ZOOMED, or
@ICON.
[optional] specifies the type of shortcut. see below.
@TRUE if the shortcut was successfully modified;
@FALSE if it wasn't.
"shortcut-type" specifies the type of shortcut, and can be one of the following:
Type
0
1
Meaning
Normal shortcut (default)
Folder shortcut (Windows 2000 and newer)
You can specify "-1" for "target", "params", or "start-dir" to set NULL values.
See ShortcutMake for further information on these parameters.
Note: In the ShortcutMake and ShortcutEdit functions, if the "target" parameter
specifies a UNC, and it does not exist at the time this function is called, then the
"target" field in the shortcut may not be properly set. Specifically, it may get
truncated after the share name. For example, if you use:
ShortcutMake("test.lnk", "\\server\public\testdir\myprog.exe", "", "",
@normal,0)
and \\server\public\testdir\myprog.exe doesn't exist, then the target of the share may
get set to: \\server\public.
This is due to the behavior of the API function we are calling, and is consistent with
the behavior when trying to create or edit a shortcut interactively from Explorer (i.e.,
you are prevented from specifying an invalid target).
Example:
startdir=ShortcutDir("Desktop",0,0)
DirChange(startdir)
dest = StrCat(DirWindows(0),"notepad.exe")
ShortcutMake("mynotepad.lnk", dest, "", "", @NORMAL,0)
ShortcutEdit("mynotepad.lnk", "", "", startdir, @NORMAL,0)
See Also:
ShortCutExtra, ShortcutInfo, ShortcutMake
558
ShortcutExtra
ShortcutExtra
Sets additional information for the specified shortcut file.
Syntax:
ShortcutExtra(link-name,description,hotkey,icon-file,icon-index[,shortcut-type])
Parameters:
(s) link-name
(s) description
(s) hotkey
(s) icon-file
(i) icon-index
(i) shortcut-type
Returns:
(i)
the name of shortcut .LNK file to be modified.
the internal description for the shortcut.
the "shortcut key" to be assigned to the shortcut.
a file containing an icon to be used for the shortcut, with
optional path.
the 0-based index position of the desired icon within "iconfile".
[optional] specifies the type of shortcut. see below
@TRUE if the shortcut was successfully modified;
@FALSE if it wasn't.
"shortcut-type" specifies the type of shortcut, and can be one of the following:
Type
0
1
Meaning
Normal shortcut (default)
Folder shortcut (Windows 2000 and newer)
You can specify "-1" for "description", "hotkey", or "icon-file" to set NULL values.
The "description" parameter only sets an internal description, which is not actually
displayed anywhere.
If "hotkey" is not a blank string (""), it specifies the hotkey ("shortcut key") for the
shortcut. This can be an alphanumeric or special character (see below), optionally
preceded by one or more of the following modifiers:
!
^
+
(Alt)
(Control)
(Shift)
This function can be used to set hotkeys which would be impossible to set from
within the shortcut properties dialog in Explorer. Note: some key combinations may
not be supported on all Windows platforms.
List of special keys for ShortcutExtra:
{BACKSPACE}
{CLEAR}
{DEL}
{END}
{BS}
{DELETE}
{DOWN}
{ENTER}
{F13}
{F14}
{F15}
{F16}
559
ShortcutInfo
{ESCAPE}
{HOME}
{INS}
{NUMPAD*}
{NUMPAD-}
{NUMPAD/}
{NUMPAD1}
{NUMPAD3}
{NUMPAD5}
{NUMPAD7}
{NUMPAD9}
{PGUP}
{RIGHT}
{SP}
{UP}
{F1}
{F2}
{F3}
{F4}
{F5}
{F6}
{ESC}
{HELP}
{INSERT}
{LEFT}
{NUMPAD+}
{NUMPAD.}
{NUMPAD0}
{NUMPAD2}
{NUMPAD4}
{NUMPAD6}
{NUMPAD8}
{PGDN}
{PRTSC}
{SPACE}
{TAB}
{F7}
{F8}
{F9}
{F10}
{F11}
{F12}
"Icon-file" can be used to specify an .EXE (or .DLL) file or an .ICO file containing
an icon which you want to be used for the shortcut. If "icon-file" specifies an .EXE
(or .DLL) file (which can contain multiple icons), then "icon-index" can be used to
specify the offset of a particular icon within "icon-file", where 0 indicates the first
icon in the file, 1 indicates the second icon, etc. If "icon-file" specifies an .ICO file,
then "icon-index" should be 0.
You can specify a blank string ("") for "icon-file", and 0 for "icon-index", to use the
default icon.
Example:
startdir=ShortcutDir("Desktop",0,0)
DirChange(startdir)
dest = StrCat(DirWindows(0),"notepad.exe")
ShortcutMake("mynotepad.lnk", dest, "", "", @NORMAL,0)
ShortcutEdit("mynotepad.lnk", "", "", startdir, @NORMAL,0)
ShortcutExtra("mynotepad.lnk", "Notepad shortcut", "^!n", "", 0,0)
See Also:
ShortcutEdit, ShortcutInfo, ShortcutMake
ShortcutInfo
Returns information on the specified shortcut file.
560
ShortcutInfo
Syntax:
ShortcutInfo(link-name[, shortcut-type])
Parameters:
(s) link-name
(i) shortcut type
the name of shortcut .LNK file.
[optional] specifies the type of shortcut. see below.
Returns:
(s)
a TAB delimited list of information on the shortcut file.
ShortcutInfo returns a TAB-delimited list containing the following items (some of
which may be blank):
target
params
start-dir
show-mode
file or directory name which the shortcut points to.
command-line parameters for "target".
"Start in" directory for "target".
"Run" mode for "target": 1 (@ICON), 2 (@NORMAL), or
3 (@ZOOMED).
description
the internal description for the shortcut.
hotkey
the "shortcut key" for the shortcut.
icon-file
the name of the icon file being used by the shortcut.
icon-index
the 0-based index position within "icon-file" of the icon
being used.
"shortcut-type" specifies the type of shortcut, and can be one of the following:
Type
0
1
Meaning
Normal shortcut (default)
Folder shortcut (Windows 2000 and newer)
Example:
startdir=ShortcutDir("Desktop",0,0)
DirChange(startdir)
dest = StrCat(DirWindows(0),"notepad.exe")
ShortcutMake("mynotepad.lnk", dest, "", "", @NORMAL,0)
ShortcutEdit("mynotepad.lnk", "", "", startdir, @NORMAL,0)
ShortcutExtra("mynotepad.lnk", "Notepad shortcut", "^!n", "", 0,0)
info=ShortcutInfo("mynotepad.lnk")
target=
ItemExtract(1, info, @tab)
params=
ItemExtract(2, info, @tab)
workdir=
ItemExtract(3, info, @tab)
showmode= ItemExtract(4, info, @tab)
desc=
ItemExtract(5, info, @tab)
hotkey=
ItemExtract(6, info, @tab)
iconfile= ItemExtract(7, info, @tab)
iconindex= ItemExtract(8, info, @tab)
editinfo=StrCat("filename=",target,@crlf,"params=",params,@crlf,
"workdir=",workdir,@crlf,"showmode=",showmode)
extrainfo=StrCat("desc=",desc,@crlf,"hotkey=",hotkey,@crlf,
561
ShortcutMake
"iconfile=", iconfile,@crlf,"iconindex=",iconindex)
Message("ShortcutInfo Syntax", StrCat(editinfo,@crlf, extrainfo))
See Also:
ShortcutEdit, ShortCutExtra, ShortcutMake
ShortcutMake
Creates a shortcut for the specified filename or directory.
Syntax:
ShortcutMake(link-name,target,params,start-dir,show-mode[,shortcut-type])
Parameters:
(s) link-name
(s) target
(s) params
(s) start-dir
(i) show-mode
(i) shortcut type
Returns:
(i)
the name of shortcut .LNK file to be created.
file or directory name which "link-name" will point to.
command-line parameters for "target" or NULL string.
"Start in" directory for "target".
"Run" mode for "target": 1 (@ICON), 2 (@NORMAL), or
3 (@ZOOMED).
[optional] specifies the type of shortcut. see below.
@TRUE if the shortcut was successfully created;
@FALSE if it wasn't.
This function can be used to create a shortcut file which points to a filename or to a
directory.
"Link-name" the name of shortcut to be created. For a file shortcut you should
specify the {filename}.LNK. For a directory shortcut specify just the name of the
shortcut. For Example, to create a directory shortcut:
ShortcutMake("Test", "\\server\public\testdir\", "", "", @normal,1)
"Params" and "start-dir" are optional, and can be set to blank strings (""). "Showmode" is optional, and can be set to 0.
If "target" specifies a directory, the other parameters are meaningless.
Note: In the ShortcutMake and ShortcutEdit functions, if the "target" parameter
specifies a UNC, and it does not exist at the time this function is called, then the
"target" field in the shortcut may not be properly set. Specifically, it may get
truncated after the share name. For example, if you use:
ShortcutMake("test.lnk", "\\server\public\testdir\myprog.exe", "",
"", @normal,0)
and \\server\public\testdir\myprog.exe doesn't exist, then the target of the share may
get set to: \\server\public.
562
Sinh
This is due to the behavior of the API function we are calling, and is consistent with
the behavior when trying to create or edit a shortcut interactively from Explorer (i.e.,
you are prevented from specifying an invalid target).
"shortcut-type" specifies the type of shortcut, and can be one of the following:
Type
0
1
Meaning
Normal shortcut (default)
Folder shortcut (Windows 2000 and newer)
Example:
dest = StrCat(DirWindows(0),"notepad.exe")
ShortcutMake("mynotepad.lnk", dest, "", "", @NORMAL,0)
See Also:
ShortcutEdit, ShortCutExtra, ShortcutInfo
Sin
Calculates the sine.
Syntax:
Sin(x)
Parameters:
(f) x
angle in radians.
Returns:
(f)
The Sin function returns the sine of x.
Calculates the sine. If the passed parameter is large, a loss in significance in the
result or significance error may occur.
Note: To convert an angle measured in degrees to radians, simply multiply by the
constant @Deg2Rad.
Example:
real=AskLine("Sine", "Enter an angle between 0 and 360", "45", 0)
answer=sin(real * @Deg2Rad)
Message("Sine of %real% degrees is", answer)
See Also:
Acos, Asin, Atan, Cos, Tan, Sinh
Sinh
Calculates the hyperbolic sine.
563
SnapShot
Syntax:
Sinh(x)
Parameters:
(f) x
angle in radians.
Returns:
(f)
the hyperbolic sine of x.
Calculates the hyperbolic sine. If the passed parameter is large, a loss in significance
in the result or significance error may occur.
Note: To convert an angle measured in degrees to radians, simply multiply by the
constant @Deg2Rad.
Example:
real=AskLine("SinH", "Enter an angle between 0 and 360", "45", 0)
answer=sinh(real * @Deg2Rad)
Message("Hyperbolic Sine of %real% degrees is", answer)
See Also:
Acos, Asin, Atan, Cos, Cosh, Sin, Tan, Tanh
SnapShot
Takes a bitmap snapshot of the screen and pastes it to the clipboard.
Syntax:
SnapShot(request#)
Parameters:
(i) request#
see below.
Returns:
(i)
@FALSE.
Req#
0
1
2
3
4
5
Meaning
Take snapshot of entire screen
Take snapshot of client area of parent window of active window
Take snapshot of entire area of parent window of active window
Take snapshot of client area of active window
Take snapshot of entire area of active window
Take snapshot of entire virtual screen (Windows 98+) On versions of
Windows, that do not support virtual screens, this will be treated the
same as request 0.
This function supports multi-monitor systems.
564
Sounds
Example:
;Takes a bitmap snapshot of the screen and pastes it to the
clipboard.
Snapshot(0)
;returns the size of buffer needed for a subsequent BinaryAlloc,
;but doesn't attempt to place the contents of clipboard into a buffer
size=BinaryClipGet(0,8)
;allocates a data buffer
bb=BinaryAlloc(size)
;read file format type CF_DIB
BinaryClipGet(bb,8)
; need to add first 14 bytes to make it
; a BMP file format
bmpdatasize=14
bb2=BinaryAlloc(size + bmpdatasize)
;The characters identifying the bitmap.'BM'
BinaryPokeStr(bb2, 0, "BM")
;Complete file size in bytes.
BinaryPoke4(bb2,2,size + bmpdatasize)
;Reserved
BinaryPoke4(bb2,6,0)
;Data offset
headersize=BinaryPeek4(bb,0)
dataoffset = headersize + bmpdatasize
BinaryPoke4(bb2,10,dataoffset)
BinaryCopy(bb2,bmpdatasize,bb,0,size)
BinaryWrite(bb2,"c:\temp\screenshot.bmp")
BinaryFree(bb)
BinaryFree(bb2)
Message("All","Done")
See Also:
ClipPut
Sounds
Controls sound effects generated by WIL. This feature is off by default as windows
generally supplies its own sound effects.
Syntax:
Sounds(request#)
Parameters:
(i) request#
0 to turn sounds off; 1 to turn sounds on.
Returns:
(i)
previous Sound setting.
If Windows multimedia sound extensions are present, this function turns sounds
made by the WIL Interpreter on or off. Specify a request# of 0 to turn sounds off,
and a request# of 1 to turn them on.
565
Sqrt
Example:
Sounds(1)
Message("Sounds"," Sounded.")
See Also:
Beep, PlayMedia, PlayMidi, PlayWaveForm
SoundVolume
Sets the speaker volume.
Syntax:
SoundVolume(level)
Parameters:
(i) level
Returns:
(i)
specifies the volume level, from 0 (min) to 100 (max).
specify -1 to get the current volume setting.
if level 0 to 100 it returns previous volume level.
if level is -1 it returns the current volume level.
Example:
Sounds(1)
currentlevel = SoundVolume (-1)
Message("SoundVolume - Current level", currentlevel)
;lower volume 10%
level = SoundVolume (currentlevel -10)
Message("SoundVolume - Sound lowered 10%%", currentlevel -10)
;Set back to original volume
SoundVolume (currentlevel)
See Also:
Sounds, Beep, PlayMedia PlayMidi, PlayWaveForm
Sqrt
Calculates the square root.
Syntax:
Sqrt(x)
Parameters:
(f) x
floating point number.
Returns:
(f)
the square root result.
The Sqrt function calculates the square root of the passed parameter. If the passed
parameter is negative, a domain error occurs.
566
StrCat
Example:
real=AskLine("Square Root", "Enter a positive number", "269", 0)
answer=sqrt(real)
Message("Square root of %real% is", answer)
See Also:
Operator ** (the power operator)
StrByteCount
Returns the length of a string, in bytes.
Syntax:
StrByteCount(string,request)
Parameters:
(s) string
(i) request
specifies an ANSI or Unicode string.
specifies how "string" should be treated in order to calculate
its length.
Returns:
(i)
Request
-1
0
1
the length of a string, in bytes.
Meaning
current format (ANSI or Unicode)
ANSI string (including double-byte ANSI character sets)
Unicode string
Example:
myname = AskLine("Firstname", "Enter your first name:", "", 0)
numbytes = StrByteCount(myname, -1)
Message("Number of bytes in first name", numbytes)
See Also:
StrLen
StrCat
Concatenates two or more strings.
Syntax:
StrCat(string1,string2[,...,stringN])
Parameters:
(s) string1, etc.
at least two strings you want to concatenate.
Returns:
(s)
concatenation of the entire list of input strings.
567
StrCharCount
Use this command to stick character strings together, or to format display messages.
Although the substitution feature of the WIL (putting percent signs on both side of a
variable name) is a little quicker and easier than the strcat function, substitution
should only be used for simple, short cases. Use StrCat when concatenating large
strings.
Note: The ':' string concatenation operator can also concatenate two strings (or values
which can be converted to strings). For example:
Message("Windows version", WinVersion(1) : "." : WinVersion(0))
StrCat allows a maximum of 1024 parameters.
Example:
user = AskLine("Login", "Your Name:", "", 0)
msg = StrCat("Hi, ", user)
Message("Login", msg)
; note that this is the same as the second line above:
msg = "Hi, %user%"
See Also:
StrFill, StrFix, StrTrim
StrCharCount
Counts the number of characters in a string.
Syntax:
StrCharCount(string)
Parameters:
(s) string
any text string.
Returns:
(i)
the number of characters in a string,
Use this function to count the number of characters in a string. This function is
useful when dealing with double-byte character sets such as those containing Kanji
characters. When using single byte character sets, such as those found in English
versions of Windows, this function is identical to the StrLen function.
Example:
name = AskLine("Data Entry", "Please enter your name", "", 0)
len = StrLen(name)
chars = StrCharCount(name)
Message(name, "Is %len% bytes long and %@CRLF% has %chars%
characters")
See Also:
StrLen, StrByteCount, StrScan, StrReplace, StrFill
568
StrClean
StrClean
Removes or replaces characters in a string.
Syntax:
StrClean(source-string,characters,replacement,match-case,mode)
Parameters:
(s) source-string
(s) characters
(s) replacement
(i) match-case
(i) mode
Returns:
(s)
the string to be operated upon.
a string that specifies the characters in "source-string" to be
replaced or retained.
the replacement string to be inserted in place of matching
(or non-matching) characters.
@TRUE or @FALSE, indicating whether string
comparisons are case-sensitive or case-insensitive,
respectively.
see below.
the new string, with all changes made. The original string
("source-string") is untouched.
"characters" is a string that specifies the characters in "source-string" to be replaced
or retained. This parameter can be a single character (e.g., "x"), a list of characters
(e.g., "[email protected]#"), or a blank string ("").
"replacement" specifies the replacement string to be inserted in place of matching (or
non-matching) characters. It can be a string, one or more characters long. It can also
be a blank string (""), in which case matching characters are removed.
"mode" can be one of the following:
Value
1
2
Meaning
Replace all occurrences of "characters" with "replacement"
Replace all non-occurrences of "characters" with "replacement"
This function can be used to remove or replace specific characters in a string, or to
retain only specific characters in a string.
If "mode" is 1, then any characters which appear in "characters" will be replaced
with "replacement". If "replacement" is a blank string, then any characters which
appear in "characters" will be removed. If "characters" is a blank string, then no
changes will be made.
If "mode" is 2, then any characters which DON'T appear in "characters" will be
replaced with "replacement". If "replacement" is a blank string, then any characters
which DON'T appear in "characters" will be removed. If "characters" is a blank
string, then ALL characters will be replaced.
569
StrCnt
Example:
; Remove all spaces from a string
StrClean("Have a nice day", " ", "", @FALSE, 1)
; Replace all ampersands with the HTML code "&amp;"
StrClean("Here & there & everywhere", "&", "&amp;", @FALSE, 1)
; Remove all characters other then letters and spaces
StrClean("Healthy, wealthy, & wise.", "abcdefghijklmnopqrstuvwxyz ",
"", @FALSE, 2)
See Also:
StrReplace, ItemReplace
StrCmp
Compares two strings.
Syntax:
StrCmp(string1,string2)
Parameters:
(s) string1,string2
Returns:
(i)
strings to compare.
-1, 0, or 1; depending on whether string1 is less than, equal
to, or greater than string2, respectively.
Use this command to determine whether two strings are equal, or which precedes the
other in an ANSI sorting sequence.
Example:
a = AskLine("STRCMP", "Enter a test line", "", 0)
b = AskLine("STRCMP", "Enter another test line", "", 0)
c = StrCmp(a, b)
c = c + 1
d = StrSub("less than
equal to
greater than", (c * 12)+ 1, 12)
; Note that above string is grouped into 12-character chunks.
; Desired chunk is removed with the StrSub statement.
Message("STRCMP", "%a% is %d% %b%")
See Also:
StriCmp, StrIndex, StrLen, StrScan, StrSub
StrCnt
Counts the occurrences of a substring within a string.
Syntax:
StrCnt(string,sub-string,start-pos,end-pos,flags)
570
StrFill
Parameters:
(s) string
specifies the main string.
(s) sub-string
specifies the substring to search for within "string".
(i) start-pos
specifies the position in "string" at which to begin
searching, or -1 to indicate the end of the string. The
first character of the string is at position 1.
(i) end-pos
specifies the position in "string" at which to end
searching, or -1 to indicate the end of the string. The
first character of the string is at position 1. Note that if
the string begins at or before "end-pos" and continues
past "end-pos", it will be counted.
(i) flags
can be set to 0, or can specify one or more of the
following values combined with the bitwise OR ('|')
operator:
Value
Meaning
1
match case
Returns:
(i)
number of occurrences.
Example:
str = "How many I's are in this string?"
rslt = StrCnt(str, "i", 1, -1, 0)
Message("STRCNT - number of occurrences of the letter i", rslt)
See Also:
StriCmp, StrIndex, StrLen, StrScan, StrSub
StrFill
Creates a string filled with a series of characters.
Syntax:
StrFill(filler,length)
Parameters:
(s) filler
(i) length
Returns:
(s)
a string to be repeated to create the return string. If the filler
string is null, spaces will be used instead.
the length of the desired string.
character string.
571
StrFix
Use this function to create a string consisting of multiple copies of the filler string
concatenated together.
Example:
Message("My Stars", StrFill("*", 30))
which produces…
See Also:
StrCat, StrFix, StrLen, StrTrim
StrFix
Pads or truncates a string to a fixed length using characters.
Syntax:
StrFix(base-string,pad-string,length)
Parameters:
(s) base-string
(s) pad-string
(i) length
Returns:
(s)
string to be adjusted to a fixed length.
appended to base-string if needed to fill out the
desired length. If pad-string is null, spaces are
used instead.
character count of the string.
fixed size string.
This function is identical to StrFixChars function. This function "fixes" the length
of a string, either by truncating it on the right, or by appending enough copies of padstring to achieve the desired length.
Example:
a = StrFix("Henry", " ", 15)
b = StrFix("Betty", " ", 15)
572
StrFixBytes
c = StrFix("George", " ", 15)
Message("Spaced Names", StrCat(a, b, c))
which produces…
See Also:
StrFixBytes, StrFixBytesL, StrFixChars, StrFixCharsL, StrFixLeft, StrFill, StrLen,
StrTrim
StrFixBytes
Pads or truncates a string to a fixed length using bytes.
Syntax:
StrFixBytes(base-string,pad-string,length)
Parameters:
(s) base-string
(s) pad-string
(i) length
Returns:
(s)
string to be adjusted to a fixed length.
appended to base-string if needed to fill out the
desired length. If pad-string is null, spaces are
used instead.
specifies length in bytes.
fixed size string.
This function "fixes" the length of a string, either by truncating it on the right, or by
appending enough copies of pad-string to achieve the desired length.
If either 'base-string' or 'pad-string' is a Unicode string, then 'length' must be an even
number (each character has two bytes).
Example:
a = StrFixBytes
b = StrFixBytes
c = StrFixBytes
Message("Spaced
("Henry", " ", 15)
("Betty", " ", 15)
("George", " ", 15)
Names", StrCat(a, b, c))
573
StrFixChars
See Also:
StrFix, StrFixBytesL, StrFixChars, StrFixCharsL, StrFixLeft, StrFill, StrLen,
StrTrim
StrFixBytesL
Pads or truncates the left side of a string to a fixed length using bytes.
Syntax:
StrFixBytesL(base-string,pad-string,length)
Parameters:
(s) base-string
(s) pad-string
(i) length
Returns:
(s)
string to be adjusted to a fixed length.
appended to base-string if needed to fill out
the desired length. If pad-string is null, spaces
are used instead.
specifies the length in bytes.
fixed size string.
If either 'base-string' or 'pad-string' is a Unicode string, then 'length' must be an even
number (each character has two bytes).
Example:
a = StrFixBytesL("Henry", " ", 15)
b = StrFixBytesL ("Betty", " ", 15)
c = StrFixBytesL ("George", " ", 15)
Message("Spaced Names", StrCat(a, b, c))
See Also:
StrFix, StrFixBytes, StrFixChars, StrFixCharsL, StrFixLeft, StrFill, StrLen, StrTrim
StrFixChars
Pads or truncates a string to a fixed length using characters.
Syntax:
StrFixChars(base-string,pad-string,length)
Parameters:
(s) base-string
(s) pad-string
(i) length
574
string to be adjusted to a fixed length.
appended to base-string if needed to fill out
the desired length. If pad-string is null, spaces
are used instead.
character count of the string.
StrFixLeft
Returns:
(s)
fixed size string.
This function is identical to StrFix in that it "fixes" the length of a string, either by
truncating it on the right, or by appending enough copies of pad-string to achieve the
desired length
Example:
a = StrFixChars("Henry", " ", 15)
b = StrFixChars("Betty", " ", 15)
c = StrFixChars("George", " ", 15)
Message("Spaced Names", StrCat(a, b, c))
See Also:
StrFix, StrFixBytes, StrFixBytesL, StrFixCharsL, StrFixLeft, StrFill
StrFixCharsL
Pads or truncates the left side of a string to a fixed length using characters.
Syntax:
StrFixCharsL(base-string,pad-string,length)
Parameters:
(s) base-string
(s) pad-string
(i) length
Returns:
(s)
string to be adjusted to a fixed length.
appended to base-string if needed to fill out the desired
length. If pad-string is null, spaces are used instead.
character count of the string.
fixed size string.
This function is indentical to StrFixLeft. It "fixes" the length of a string, either by
truncating it on the left, or by prepending enough copies of pad-string to achieve the
desired length.
Example:
a = StrFixCharsL("Henry", " ", 15)
b = StrFixCharsL("Betty", " ", 15)
c = StrFixCharsL("George", " ", 15)
Message("Spaced Names", StrCat(a, b, c))
See Also:
StrFix, StrFixBytes, StrFixBytesL, StrFixChars, StrFixLeft, StrFill, StrLen, StrTrim
StrFixLeft
Pads or truncates the left side of a string to a fixed length using characters.
575
StriCmp
Syntax:
StrFixLeft(base-string,pad-string,length)
Parameters:
(s) base-string
(s) pad-string
(i) length
Returns:
(s)
string to be adjusted to a fixed length.
appended to base-string if needed to fill out the desired
length. If pad-string is null, spaces are used instead.
character count of the string.
fixed size string.
This function is identical to StrFixCharsL. This function "fixes" the length of a
string, either by truncating it on the left, or by prepending enough copies of padstring to achieve the desired length.
Example:
a = StrFixLeft("Henry", " ", 15)
b = StrFixLeft("Betty", " ", 15)
c = StrFixLeft("George", " ", 15)
Message("Spaced Names", StrCat(a, b, c))
See Also:
StrFix, StrFixBytes, StrFixBytesL, StrFixChars, StrFixCharsL, StrFill, StrLen,
StrTrim
StriCmp
Compares two strings without regard to case.
Syntax:
StriCmp(string1,string2)
Parameters:
(s) string1,string2
Returns:
(i)
strings to compare.
-1, 0, or 1; depending on whether string1 is less than, equal
to, or greater than string2, respectively.
Use this command to determine whether two strings are equal, or which precedes the
other in an ANSI sorting sequence, when case is ignored.
Example:
a
b
c
c
d
;
576
= AskLine("STRICMP", "Enter a test line", "", 0)
= AskLine("STRICMP", "Enter another test line", "", 0)
= StriCmp(a, b)
= c + 1
= StrSub("less than
equal to
greater than", (c * 12)+ 1, 12)
Note that above string is grouped into 12-character chunks.
StrIndex
; Desired chunk is removed with the StrSub statement.
Message("STRICMP", "%a% is %d% %b%")
See Also:
StrCmp, StrIndex, StrLen, StrScan, StrSub
StrIndex
Searches a string for a sub-string.
Syntax:
StrIndex(string,sub-string,start,direction)
Parameters:
(s) string
(s) sub-string
(i) start
(i) direction
Returns:
(i)
the string to be searched for a sub-string.
the string to look for within the main string.
the position in the main string to begin search. The first
character of a string is position 1.
the search direction. @FWDSCAN searches forward, while
@BACKSCAN searches backwards.
position of sub-string within string, or 0 if not found.
This function searches for a sub-string within a "target" string. Starting at the "start"
position, it goes forward or backward depending on the value of the "direction"
parameter. It stops when it finds the "sub-string" within the "target" string, and
returns its position.
A start position of 0 has special meaning depending on which direction you are
scanning. For forward searches, zero indicates the search should start at the
beginning of the string. For reverse searches, zero causes it to start at the end of the
string.
If the sub-string is a blank (NULL) string and the specified start position is ZERO,
this function returns the start position of the string for a @FWDSCAN search and the
position of the last item for a @BACKSCAN search.
If both the string and the sub-string are blank (NULL) strings this function
returns zero.
Example:
instr = AskLine("STRINDEX", "Type a sentence:", "", 0)
start = 1
daend = StrIndex(instr, " ", start, @FWDSCAN)
If daend == 0
Message("Sorry...", "No spaces found")
else
a = StrCat("First word is: ", StrSub(instr, start, daend - 1))
577
StrIndexNc
Message("STRINDEX", a)
endif
See Also:
StrLen, StrScan, StrSub
StrIndexNc
Searches a string for a sub-string, ignoring case.
Syntax:
StrIndexNc(string,sub-string,start,direction)
Parameters:
(s) string
(s) sub-string
(i) start
(i) direction
Returns:
(i)
the string to be searched for a sub-string.
the string to look for within the main string.
the position in the main string to begin search. The first
character of a string is position 1.
the search direction. @FWDSCAN searches forward, while
@BACKSCAN searches backwards.
position of sub-string within string, or 0 if not found.
This function searches for a sub-string within a "target" string. Starting at the "start"
position, it goes forward or backward depending on the value of the "direction"
parameter. It stops when it finds the "sub-string" within the "target" string, and
returns its position. It is not case-sensitive.
A start position of 0 has special meaning depending on which direction you are
scanning. For forward searches, zero indicates the search should start at the
beginning of the string. For reverse searches, zero causes it to start at the end of the
string.
If the sub-string is a blank (NULL) string and the specified start position is ZERO,
this function returns the start position of the string for an @FWDSCAN search and
the position of the last item for a @BACKSCAN search.
If both the string and the sub-string are blank (NULL) strings this function
returns zero.
Example:
instr = AskLine("STRINDEX", "Type a sentence:", "", 0)
start = 1
daend = StrIndexNc(instr, " ", start, @FWDSCAN)
If daend == 0
Message("Sorry...", "No spaces found")
else
a = StrCat("First word is: ", StrSub(instr,
start, daend - 1))
578
StrInsert
Message("STRINDEX", a)
endif
See Also:
StrIndex, StrIndexWild, StrLen, StrScan, StrSub
StrIndexWild
Finds wildcarded text within a larger string.
Syntax:
StrIndexWild(string,pattern,start)
Parameters:
(s) string
(s) pattern
(i) start
Returns:
(i)
the string to be searched for a sub-string.
the wildcarded text to search for.
the position in the main string to begin search.
The first character of a string is position 1.
position of sub-string within string, or 0 if not found.
In the wildcard pattern, "*" matches zero or more characters, and "?" matches any
one character.
If the pattern is a blank (NULL) string, and the specified start position is ZERO, this
function returns the start position of the string.
If both the string and the pattern are blank (NULL) strings, this function
returns zero.
Example:
StrIndexWild("abcd1234wxyz",
StrIndexWild("abcd1234wxyz",
StrIndexWild("abcd1234wxyz",
StrIndexWild("abcd1234wxyz",
"ab*wx", 1)
"1*9", 1)
"1*4", 1)
"1?34*z", 1)
;
;
;
;
would
would
would
would
return
return
return
return
1
0(no match)
5
5
See Also:
StrIndex, StrIndexNC, StrLen, StrScan, StrSub
StrInsert
Inserts a new string into an existing string. (Windows NT and newer)
Syntax:
StrInsert(base-string,new-string,[pad-string[,start[,length]]])
Parameters:
(s) base-string
specifies the existing string.
579
StrLen
(s) new-string
(s) pad-string
(i) start
(i) length
Returns:
(s)
specifies the string to be inserted into "base-string".
[optional] specifies a character or string to be used for
padding, if necessary. The default is a space (' ').
[optional] specifies the position in "base-string" before
which "new-string" is to be inserted, where the position of
the first character of the string is 1. To insert at the very
beginning of "base-string", specify a value of 1. You can
specify -1 to insert after the end of "base-string". If "start"
is past the end of "base-string", padding will be inserted
between the end of "base-string" and the beginning of "newstring". The default is 1.
[optional] specifies the number of characters to insert. If
"length" is shorter than the length of "new-string", "newstring" will be truncated. If "length" is longer than the
length of "new-string", padding will be inserted after the
end of "new-string". The default is the length of "newstring".
the modified string.
Example:
Name = "Joe"
ret = StrInsert("Hello my name is ",name," ",-1,StrLen(name))
Message( "StrInsert() Example", ret )
See Also:
StrCharCount, StrByteCount, StrFill, StrFix, StrIndex, StrIndexNc, StrOverlay,
StrScan, StrTrim
StrLen
Provides the number of characters in a string.
Syntax:
StrLen(string)
Parameters:
(s) string
any text string.
Returns:
(i)
number of characters in a string.
Example:
myfile = AskLine("Filename", "File to process:", "", 0)
namlen = StrLen(myfile)
If namlen > 13
Message("Error", "Filename too long!")
endif
580
StrLower
See Also:
StrCharCount, StrByteCount, StrFill, StrFix, StrIndex, StrIndexNC, StrScan, StrTrim
StrLenWild
Finds wildcarded text within a larger string.
Syntax:
StrLenWild(string,pattern,start)
Parameters:
(s) string
(s) pattern
(i) start
Returns:
(i)
any text string.
The wildcarded text to match.
The position (in characters) within the string to begin
matching.
the length (in characters) of the portion of the string that
matches the wildcard pattern, or 0 if no match at the
specified position.
In the wildcard pattern, "*" matches zero or more characters, and "?" matches any
one character.
Example:
StrLenWild("abcd1234wxyz",
StrLenWild("abcd1234wxyz",
StrLenWild("abcd1234wxyz",
StrLenWild("abcd1234wxyz",
"ab*wx", 1)
"1*9", 1)
"1*4", 5)
"1?34*z", 5)
;
;
;
;
would
would
would
would
return
return
return
return
10
0
4
8
See Also:
StrFill, StrLen, StrFix, StrIndex, StrIndexNc, StrScan, StrTrim
StrLower
Converts a string to lowercase.
Syntax:
StrLower(string)
Parameters:
(s) string
any text string.
Returns:
(s)
lowercase string.
Use this command to convert a text string to lower case.
581
StrOverlay
Example:
a = AskLine("STRLOWER", "Enter text", "", 0)
b = StrLower(a)
Message(a, b)
See Also:
StriCmp, StrUpper
StrOverlay
Overlays a new string onto an existing string. (Windows NT and newer)
Syntax:
StrOverlay(base-string,new-string,[pad-string[,start[,length]]])
Parameters:
(s) base-string
(s) new-string
(s) pad-string
(i) start
(i) length
Returns:
(s)
specifies the existing string.
specifies the string to be overlaid onto "base-string".
[optional] specifies a character or string to be used for
padding, if necessary. The default is a space (' ').
[optional] specifies the position in "base-string" after which
"new-string" is to be overlaid, where the position of the first
character of the string is 1. You can specify -1 to overlay
after the end of "base-string". If "start" is past the end of
"base-string", padding will be inserted between the end of
"base-string" and the beginning of "new-string". The
default is 1.
[optional] specifies the number of characters to overlay. If
"length" is shorter than the length of "new-string", "newstring" will be truncated. If "length" is longer than the
length of "new-string", padding will be overlaid after the
end of "new-string". The default is the length of "newstring".
the modified string.
Example:
Name = "Joe"
ret = StrOverlay( "Hello my name is ", name, " ", -1, StrLen(name) )
Message( "StrOverlay() Example", ret )
See Also:
StrCharCount, StrByteCount, StrFill, StrFix, StrIndex, StrInsert, StrIndexNc,
StrScan, StrTrim
582
StrScan
StrReplace
Replaces all occurrences of a sub-string with another.
Syntax:
StrReplace(string,old,new)
Parameters:
(s) string
(s) old
(s) new
string in which to search.
target sub-string.
replacement sub-string.
Returns:
(s)
updated string, with old replaced by new.
StrReplace scans the "string", searching for occurrences of "old" and replacing each
occurrence with "new".
Example:
; Copy all INI files to clipboard
a = FileItemize("*.ini")
;in file list replace tabs with crlf's.
b = StrReplace(a, @tab, @CRLF)
ClipPut(b)
newlist=StrCat("Before", @CRLF, a,@CRLF,@CRLF,"After", @CRLF, b)
Message("StrReplace",newlist)
See Also:
StrIndex, StrIndexNC, StrIndexWild, StrScan, StrSub
StrScan
Searches string for occurrence of delimiters.
Syntax:
StrScan(string,delimiters,start,direction)
Parameters:
(s) string
(s) delimiters
(i) start
(i) direction
Returns:
(i)
the string that is to be searched.
a string of delimiters to search for within string.
the position in the main string to begin search. The first
character of a string is position 1.
the search direction. @FWDSCAN searches forward, while
@BACKSCAN searches backwards.
position of delimiter in string, or 0 if not found.
This function searches for delimiters within a target "string". Starting at the "start"
position, it goes forward or backward depending on the value of the "direction"
583
StrSub
parameter. It stops when it finds any one of the characters in the "delimiters" string
within the target "string".
A start position of 0 has special meaning depending on which direction you are
scanning. For forward searches, zero indicates the search should start at the
beginning of the string. For reverse searches, zero causes it to start at the end of the
string.
Example:
; Parse a string with multiple delimiters into standard param format
thestr = "123,456.789:abc"
length=StrLen(thestr)
start = 1
count=0
while @TRUE
finish = StrScan(thestr, ",.:", start, @FWDSCAN)
If finish == 0
break
else
count = count+1
param%count% = StrSub(thestr, start, finish - start)
start=finish+1
Message("Parameter number %count% is", param%count%)
If finish == length then Break
endif
endwhile
If start <= length
finish = length+1
count = count+1
param%count% = StrSub(thestr, start, finish - start)
Message("Parameter number %count% is", param%count%)
endif
param0 = count
Message("Parameter count is",param0)
See Also:
StrLen, StrSub
StrSub
Extracts a sub-string out of an existing string.
Syntax:
StrSub(string,start,length)
Parameters:
(s) string
(i) start
584
the string from which the sub-string is to be extracted.
character position within string where the sub-string starts.
(The first character of the string is at position 1).
StrSubWild
(i) length
Returns:
(s)
length of desired sub-string. If you specify a length of zero
it will return a null string. If you specify a length of -1 it
will extract the rest of the string.
sub-string of parameter string or "".
This function extracts a sub-string from within a "target" string. Starting at the "start"
position, it copies up to "length" characters into the sub-string.
This function will return "", if illegal bounds are given.
Example:
a = "My dog has fleas"
animal = StrSub(a, 4, 3)
Message("STRSUB", "My animal is a %animal%")
See Also:
StrLen, StrScan
StrSubWild
Extracts a substring matching wildcarded text from within a larger string.
Syntax:
StrSubWild(string,pattern,start)
Parameters:
(s) string
(s) pattern
(i) start
Returns:
(s)
the string from which the sub-string is to be extracted.
the wildcarded text to match.
the position (in characters) within the string to begin
matching.
the portion of the string matched by the wildcard pattern.
In the wildcard pattern, "*" matches zero or more characters, and "?" matches any
one character.
Example:
StrSubWild("abcd1234wxyz",
StrSubWild("abcd1234wxyz",
StrSubWild("abcd1234wxyz",
StrSubWild("abcd1234wxyz",
"ab*wx", 1)
"1*9", 1)
"1*4", 5)
"1?34*z", 5)
;
;
;
;
would
would
would
would
return
return
return
return
"abcd1234wx"
""
"1234"
"1234wxyz"
See Also:
StrSub, StrLen, StrScan
585
StrTypeInfo
StrTrim
Removes leading and trailing blanks from a character string.
Syntax:
StrTrim(string)
Parameters:
(s) string
a string with unwanted blanks at the beginning and/or end.
Returns:
(s)
string devoid of leading and trailing blanks.
This function removes spaces and tab characters from the beginning and end of a text
string.
Example:
mydata = ""
while mydata != "exit"
mydata = AskLine("STRTRIM", "Type stuff ('exit' quits)", "", 0)
mydata = StrTrim(mydata)
Display(4,"STRTRIM",">%mydata%<")
endwhile
exit
See Also:
StrFill, StrFix, StrLen
StrTypeInfo
Gets character-type information for a string, or information for a character-type.
Syntax:
StrTypeInfo(string,flag)
Parameters:
(s) string
(i) flag
a character or a string.
a flag specifying the information to retrieve (see below).
Returns:
(i/s)
depends on the flag specified. See below.
If "flag" = 0 or 1, "value" specifies a string of 1 or more characters. For each
character in the string, a character-type is determined. The character-type is
comprised of one or more of the following values, combined using the bitwise OR
('|') operator:
Value
1
2
586
Name
C1_UPPER
C1_LOWER
Meaning
Uppercase
Lowercase
StrTypeInfo
4
8
16
32
64
128
256
C1_DIGIT
C1_SPACE
C1_PUNCT
C1_CNTRL
C1_BLANK
C1_XDIGIT
C1_ALPHA
512
C1_DEFINED
Decimal digits
Space characters
Punctuation
Control characters
Blank characters
Hexadecimal digits
Any linguistic character: alphabetical, syllabary,
or ideographic
A defined character (not used in Windows
95/98/ME
If "flag" = 0, the function returns a value comprised of the character-types of all the
characters in the string, combined using the bitwise AND ('&') operator.
If "flag" = 1, the function returns a value comprised of the character-types of all the
characters in the string, combined using the bitwise OR ('|') operator.
If "flag" = -1, "value" specifies a character-type, and the function returns a string
describing the bits that make up the character-type. The string is comprised of a
space-delimited list of words, with one word describing each bit contained within the
character-type:
Value
1
2
4
8
16
32
64
128
256
512
Name
C1_UPPER
C1_LOWER
C1_DIGIT
C1_SPACE
C1_PUNCT
C1_CNTRL
C1_BLANK
C1_XDIGIT
C1_ALPHA
C1_DEFINED
Word in string
"Upper"
"Lower"
"Digit"
"Space"
"Punct"
"Cntrl"
"Blank"
"HexDg"
"Alpha"
"Undef" if the C1_DEFINED bit is NOT set. (not
used in Windows 95/98/ME )
String parameters and return values are ANSI in Windows 95/98/ME, and Unicode
in Windows NT and newer.
Example:
str= "[email protected]#abcxyz123%@CRLF%111%@TAB%"
While @TRUE
str = AskLine( "Test", "Enter Something", str )
typeAND = StrTypeInfo( str, 0 )
typeOR = StrTypeInfo( str, 1)
dalen = StrLen( str)
587
StrUpper
allinfo = ""
if typeAND==0
allinfo = StrCat(allinfo,"No defined characters
found",@crlf,@crlf)
else
if typeAND==512
allinfo= StrCat(allinfo,"No common type matches found in
string",@crlf,@crlf)
else
allinfo= StrCat(allinfo,"Entire string is
:",@crlf,StrTypeInfo(typeAND,-1),@crlf,@crlf)
endif
endif
allinfo= StrCat(allInfo,"String contains
:",@crlf,StrTypeInfo(typeOR,-1),@crlf,@crlf)
; Loop once for each character
For index = 1 to dalen
char = StrSub( str, index, 1 )
typeinf = StrTypeInfo(StrTypeInfo(char,0),-1)
allinfo = StrCat(allinfo,char," : ",typeinf,@crlf)
Next
Pause(str,allinfo)
endwhile
exit
See Also:
StrSub, StrLower, StrUpper
StrUpper
Converts a string to uppercase.
Syntax:
StrUpper(string)
Parameters:
(s) string
any text string.
Returns:
(s)
uppercase string.
Use this function to convert a text string to upper case.
Example:
a = AskLine("STRUPPER", "Enter text","", 0)
b = StrUpper(a)
Message(a, b)
See Also:
StriCmp, StrLower
588
Switch
Switch
The Switch statement allows selection among multiple blocks of statements.
Syntax:
Switch expression
case expression
statements
break
case expression
statements
break
EndSwitch
Parameters:
(s) expression
an expression that must evaluate to an integer.
The Switch statement allows selection among multiple blocks of statements,
depending on the value of an expression. The expression must evaluate to an integer.
The Switch statement causes the statements in the switch body to be scanned by the
parser as it attempts to find a case statement. When a case statement is found, the
expression following the case statement is evaluated, and if the expression evaluates
to the same value as the expression following the Switch statement, execution of the
following statements is initiated. The EndSwitch statement terminates the Switch
structure.
If a matching case expression was found, and execution was initiated, the following
statements will affect continued execution:
Break
Terminates the Switch structure and transfers control to
the statement following the next matching EndSwitch.
Continue
Stops execution and resumes scanning for a case
statement.
Case
Ignored. Treated as a comment
EndSwitch
Terminates the Switch structure and transfers control to
the next statement.
Note: Switch and Select may be used interchangeably. They are synonyms for the
same statement. EndSwitch, EndSelect, "End Switch", and "End Select" may be
used interchangeably.
Example:
response=AskLine("Switch", "Enter a number between 1 and 3", 1, 0)
Switch response
case 1
Message("Switch", "Case 1 entered")
589
SysParamInfo
break
case 2
Message("Switch",
break
"Case 2 entered")
case 3
Message("Switch", "Case 3 entered")
break
case response
; default case
Message("Switch", "Default case entered")
break
EndSwitch
See Also:
If, For, GoSub, While
SysParamInfo
Retrieves or sets the value of one of the system-wide parameters.
Syntax:
SysParamInfo(request,value,INI-update)
Parameters:
(i) request
(s/i) value
(i) INI-update
Returns:
(s/i)
nteger that specifies the system-wide parameter to retrieve
or set.
depends on specified request. (see below)
ignored when retrieving information. When setting values
this parameter determines to what extent the value gets
updated:
Value
Meaning
0 Set system value in memory only for
future reference.
1 Write new value to appropriate INI file.
2 Broadcast message to all applications
informing them of new value.
3 Both 1 and 2.
depends on specified request. Note: If this function is
unable to execute for any reason, it returns the string
"*UNSUPPORTED*"
For a complete list of request numbers see the Windows Interface Language
help file.
Example:
request = 114 ;GetScreenSaverRunning
value = 0
update = 0
590
Tanh
if SysParamInfo( request, value, update) == 1 Then
Message("SysParamInfo ", "Screen saver is active")
See Also:
Environment MouseInfo, NetInfo, WinMetrics, WinSysInfo, WinResources
Tan
Calculates the tangent.
Syntax:
Tan(x)
Parameters:
(f) x
angle in radians.
Returns:
(f)
the Tan function returns the tangent of x.
Calculates the tangent. If x is large, a loss in significance in the result or significance
error may occur.
Note: To convert an angle measured in degrees to radians, simply multiply by the
constant @Deg2Rad.
Example:
real=AskLine("Tangent", "Enter an angle between 0 and 360", "45", 0)
answer=tan(real * @Deg2Rad)
Message("Tangent of %real% degrees is", answer)
See Also:
Acos, Asin, Atan, Cos, Sin, Tanh
Tanh
Calculates the hyperbolic tangent.
Syntax:
Tanh(x)
Parameters:
(f) x
angle in radians.
Returns:
(f)
the Tanh function returns the hyperbolic tangent of x.
Calculates the hyperbolic tangent. There is no error value.
Note: To convert an angle measured in degrees to radians, simply multiply by the
constant @Deg2Rad.
591
Terminate
Example:
real=AskLine("TanH", "Enter an angle between 0 and 360", "45", 0)
answer=Tanh(real * @Deg2Rad)
Message("Hyperbolic Tangent of %real% degrees is", answer)
See Also:
Acos, Asin, Atan, Cos, Cosh, Sin, Sinh, Tan
Terminate
Conditionally ends a WIL program.
Syntax:
Terminate(expression,title,message)
Parameters:
(s) expression
(s) title
(s) message
Returns:
(i)
any logical expression.
the title of a message box to be displayed before
termination.
the message in the message box.
@TRUE.
This command ends processing for the WIL program if "expression" is nonzero.
Note that many functions return @TRUE (1) or @FALSE (0), which you can use to
decide whether to cancel a menu item.
If either "title" or "message" contains a string, a message box with a title and a
message is displayed before exiting.
Examples:
;Example 1
; basically a no-op:
Terminate(@FALSE, "", "This will never terminate")
Message("Terminate"," Terminated.")
;Example 2
; exits w/o message if answer isn't "YES":
Terminate(answer != "YES", "", "")
Message("Terminate"," Terminated.")
;Example 3
; unconditional termination w/o message box (same as Exit)
Terminate(@TRUE, "", "")
Message("Terminate"," Terminated.")
;Example 4
; exits with message if variable is less than zero:
Terminate(a < 0, "Error", "Cannot use negative numbers")
Message("Terminate"," Terminated.")
592
TerminateApp
See Also:
Display, Exit, Message, Pause
TerminateApp
Terminates an application.
Syntax:
TerminateApp(winname/appname,name-type,flags)
Parameters:
(s) winname/appname specifies a window name or application name, depending on
the value of "name-type".
(i) name-type
number that specifies what type of value was passed in
"winname/appname". See below.
(i) flags
see below.
Returns:
(i)
@TRUE on success and @FALSE on failure.
"winname/appname" specifies a window name or application name, depending on
the value of "name-type"
Name-type
0
2
3
Winname/appname
full or partial windowname of a WinBatch program window
full or partial windowname of a Windows program window
application file name of a Windows program
"flags" can be set to 0, or can specify one or more of the following values combined
with the bitwise OR ('|') operator:
Value
0
1
Meaning
Default
"current-session-only" flag (valid only if "name-type" == 3). If
this flag is specified, and the script is running in a Terminal
Services environment, then the specified application will only
match if it is running in the same session as the script. Otherwise,
the specified application will match regardless of what session it is
running in.
This function lets you terminate an application abruptly. Normally, you should use
WinClose to close an application gracefully, but sometimes that may not be
possible. Using this function is a drastic, last-resort method of terminating an app.
593
TimeAdd
Note: You will not receive any warning from the operating system before the
application is closed, even if it contains unsaved work. Also, this function may leave
the system in an unstable state. Use this function carefully.
Windows Vista or newer: This function may require an Administrator level
account, because it relies on performance monitoring.
Examples:
appname = "notepad.exe"
Run(appname, "")
Message( appname, "Running")
TerminateApp(appname, 3, 0)
Message( appname, "Terminated")
See Also:
IntControl 12, WinClose
TimeFunctions
Most, but not all, time functions use the "datetime" format, which is actually just a
special form of a string or list.
It looks like
"YYYY:MM:DD:HH:MM:SS"
For example, December 25, 2014, at 3:50:23 PM would be
"2014:12:25:15:50:23"
Note: If you choose to specify two digit dates see IntControl 41. The YY’s in the
range 50 to 99 are assumed to be in the range 1950 to 1999. YY’s in the range 00 to
49 are assumed to be in the range of 2000 to 2049.
If you need to compare two times in this format, use the TimeDiff, TimeDiffSecs or
TimeDiffDays function to compute the difference in the times and return a positive
or negative result.
TimeAdd
Adds two YmdHms datetime variables
Syntax:
TimeAdd(datetime1,datetime2)
Parameters:
(s) datetime1
594
a datetime using the format of
YYYY:MM:DD:HH:MM:SS.
TimeDate
(s) datetime2
Returns:
(s)
a datetime to be added to the original using the same format.
a new datetime
Use this function to add a specified datetime to an original datetime. TimeAdd uses
normalized conversion so a valid datetime will be returned.
Example:
Now=TimeYmdHms( )
AddTime = "0000:00:00:157:00:00"
; 157 hours
Later=TimeAdd(Now, AddTime)
Message("157 hours from now will be", Later)
See Also:
FileTimeGet, FileTimeGetEx, TimeDate, TimeYmdHms, TimeDiffSecs, TimeDelay,
TimeSubtract, TimeWait
TimeDate
Provides the current date and time in a human-readable format. For computations
with times and dates the TimeYmdHms function should be used instead.
Syntax:
TimeDate()
Parameters:
(none)
Returns:
(s)
the current date and time.
This function will return the current date and time in a pre-formatted string. The
format of the string depends on the current settings in the [Intl] section of the registry
key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows
NT\CurrentVersion\IniFileMapping\win.ini[Intl]
The registry value will be examined to determine which format to use. You can
adjust the registry value via the Regional and Language Options icon in Control
Panel if the format isn't what you prefer.
Note: This function is the same as the DateTime function, which it replaces.
Example:
a=Timedate( )
Message("Current date and time", a)
may produce, depending on Control Panel settings:
595
TimeDelay
See Also:
FileTimeGet, FileTimeGetEx, TimeAdd, TimeYmdHms, TimeDiffSecs, TimeDelay,
TimeWait
TimeDayofWeek
Using the WIL language it is possible to grab the day of the week. The following
example from TimeJulianDay grabs the current time and day of the week.
Example:
;This example grabs the Time/Day of the Week.
a=TimeYmdHms( )
b=TimeJulianDay(a)
c=(b+5) mod 7
day=ItemExtract(c+1, "Sun Mon Tue Wed Thu Fri Sat", " ")
line=StrCat("Julian Date-> ", b,@CRLF,"Day of week-> ",day)
Message(TimeDate( ), line)
See Also:
TimeJulianDay
TimeDelay
Pauses execution for a specified amount of time.
Syntax:
TimeDelay(seconds)
Parameters:
(f) seconds
seconds to delay. (max 3600)
Returns:
(i)
@TRUE.
This function causes the currently-executing WIL program to be suspended for the
specified period of time. Seconds can be a floating point number: TimeDelay(2.5).
596
TimeDiff
Smaller or larger numbers will be adjusted accordingly.
Note: You can specify a negative number for "seconds", in which case the negative
number will be treated exactly the same as a positive number.
Example:
Message("Wait", "About 15 seconds")
TimeDelay(15)
Message("Hi", "I'm Baaaaaaack")
See Also:
TimeWait, Yield
TimeDiff
Returns the difference between two points in time.
Syntax:
TimeDiff(datetime1,datetime2)
Parameters:
(s) datetime1
(s) datetime2
format YYYY:MM:DD.
format YYYY:MM:DD.
Returns:
(i)
difference between the two times, in YmdHms format.
"datetime1" and "datetime2" must be valid date-time strings, in YmdHms format.
"datetime1" must be the later (more recent) of the two times.
Because some months have more days than others, an adjustment may need to be
made when converting the resulting "day" field into months. In the example:
TimeDiff("1998:09:30:00:00:00", "1998:08:31:00:00:00")
the result is, logically, "0000:00:30:00:00:00" (30 days). But in this example:
TimeDiff("1998:10:01:00:00:00", "1998:08:31:00:00:00")
where the operation wraps past the end of the month, there is some question what the
result should be, since there is no such date as September 31. This function handles
this by treating the period from August 31 to September 30 as one month, so the
result would be "0000:01:01:00:00:00" (one month and one day).
Example:
; How long has it been since the beginning of the decade
diff = TimeDiff(TimeYmdHms(), "1990:01:01:00:00:00")
Message("How long since beginning of decade?",diff)
597
TimeDiffSecs
See Also:
FileTimeGet, FileTimeGetEx, TimeDate, TimeAdd, TimeYmdHms, TimeDiffSecs,
TimeDelay, TimeWait, TimeDiffDays
TimeDiffDays
Returns the difference in days between the two dates.
Syntax:
TimeDiffDays(datetime1,datetime2)
Parameters:
(s) datetime1
(s) datetime2
Returns:
(i)
uses format YYYY:MM:DD:HH:MM:SS, or
YYYY:MM:DD
uses format YYYY:MM:DD:HH:MM:SS, or
YYYY:MM:DD
the difference in days between the two dates.
Use this function to return the difference in days between two dates. Hours, mins,
secs, if specified, are ignored.
"datetime1" must be the later (more recent) of the two times.
Example:
;Shopping days til Christmas
Now=TimeYmdHms( ); Get current time
Year=ItemExtract(1, Now, ":")
Xmas=strcat(Year, ":12:25:00:00:00")
Shopping=TimeDiffDays(Xmas, Now)
if Shopping>0
Message("Shopping Days to Christmas", Shopping)
else
if Shopping<0
Message("You missed it by", abs(Shopping))
else
Message("Merry Christmas", "And a Happy New year")
endif
endif
See Also:
FileTimeGet, FileTimeGetEx, TimeDate, TimeAdd, TimeYmdHms, TimeDiffSecs,
TimeDelay, TimeWait
TimeDiffSecs
Returns time difference in seconds between the two datetimes.
598
TimeJulianDay
Syntax:
TimeDiffSecs(datetime1,datetime2)
Parameters:
(s) datetime1
(s) datetime2
format YYYY:MM:DD:HH:MM:SS.
format YYYY:MM:DD:HH:MM:SS.
Returns:
(i)
difference in seconds between the two times.
Use this function to return the time difference between two datetimes. The time
difference should not exceed 68 years or else an error will occur.
"datetime1" must be the later (more recent) of the two times.
Example:
Now=TimeYmdHms( )
Midnight=strcat(strsub(Now,1,11), "00:00:00")
Seconds=TimeDiffSecs(Now, Midnight)
Message("Seconds since midnight", Seconds)
See Also:
FileTimeGet, FileTimeGetEx, TimeDate, TimeAdd, TimeDiffDays, TimeYmdHms,
TimeDelay, TimeWait
TimeJulianDay
Returns the Julian day given a datetime.
Syntax:
TimeJulianDay(datetime)
Parameters:
(s) datetime
use format YYYY:MM:DD.
Returns:
(i)
the Julian day.
Use this function to return the Julian date given a datetime. The Julian date is often
used in banking and similar calculations as it provides an easy way to compute the
difference between two dates.
Note: Julian date 1= Jan.1,0000.
Example:
;This example grabs the Time/Day of the Week.
a=TimeYmdHms( )
b=TimeJulianDay(a)
c=(b+5) mod 7
day=ItemExtract(c+1, "Sun Mon Tue Wed Thu Fri Sat", " ")
line=StrCat("Julian Date-> ", b,@CRLF,"Day of week-> ",day)
Message(TimeDate( ), line)
599
TimeSubtract
See Also:
FileTimeGet, FileTimeGetEx, TimeDate, TimeAdd, TimeDiffDays, TimeYmdHms,
TimeDelay, TimeWait
TimeJulToYmd
Given a Julian day, returns the datetime.
Syntax:
TimeJulToYmd(julian-date)
Parameters:
(i) julian-date
a Julian date.
Returns:
(s)
the datetime corresponding to the specified Julian date.
This function converts the specified (numeric) Julian date value to a datetime in
YmdHms format. The "Hms" portion of the returned YmdHms string will always be
"00:00:00".
Example:
today = TimeYmdHms( )
jul_today = TimeJulianDay(today)
jul_lastweek = jul_today - 7
lastweek = TimeJulToYmd(jul_lastweek)
FileTimeSet("stuff.txt", lastweek)
Message("TimeJulToYmd","Done.")
See Also:
TimeJulianDay
TimeSubtract
Subtracts one YmdHms variable from another.
Syntax:
TimeSubtract(datetime,datetime-diff)
Parameters:
(s) datetime
(s) datetime-diff
Returns:
(s)
600
a datetime using the format of
YYYY:MM:DD:HH:MM:SS.
amount of time to be subtracted from the original using the
same format
time string in YmdHms format.
TimeYmdHms
"datetime-difference" is an amount of time to be subtracted from "datetime", in
YmdHms format.
Use this function to subtract a specified datetime from an original datetime.
TimeSubtract uses normalized conversion so a valid datetime will be returned.
"datetime difference" can not be larger than "datetime".
TimeSubtract is NOT designed to determine the difference between two points in
time. For that, use TimeDiffDays, TimeDiffSecs, or the TimeDiff function.
Example:
time_now = TimeYmdHms( )
time_yesterday = TimeSubtract(time_now, "0000:00:01:00:00:00")
FileTimeSet("stuff.txt", time_yesterday)
Message("TimeSubtract","Time Subtracted.")
See Also:
TimeAdd, TimeDiffDays, TimeDiffSecs, TimeDiff
TimeWait
Pauses execution and waits for the datetime to pass.
Syntax:
TimeWait(datetime)
Parameters:
(s) datetime
format YYYY:MM:DD:HH:MM:SS.
Returns:
(i)
returns @TRUE.
Use this function to pause execution to wait for the datetime to pass. To wait for the
next occurrence of the specified time, (i.e., today or tomorrow), specify
"0000:00:00:Hours:Minutes:Seconds" for the date.
Example:
a=TimeYmdHms( )
; Gets Current Time
b=TimeAdd(a,"0000:00:00:00:00:07") ; Adds 7 seconds to current time
TimeWait(b)
; Waits for that time to occur
Display(3, "Time now should be", b)
See Also:
FileTimeGet, FileTimeGetEx, TimeDate, TimeAdd, TimeDiffDays, TimeDiffSecs,
TimeYmdHms, TimeDelay
TimeYmdHms
Returns current date and time in the datetime format.
601
UacElevationLevel
Syntax:
TimeYmdHms()
Parameters:
(none)
Returns:
(s)
format YYYY:MM:DD:HH:MM:SS.
Use this function to return the current date and time in the datetime format.
Example:
a=TimeYmdHms( )
Message("Time is", a)
See Also:
FileTimeGet, FileTimeGetEx, TimeDate, TimeAdd, TimeDiffSecs, TimeDelay,
TimeWait
UacElevationLevel
Gets the current UAC elevation level. (Windows Vista or newer only)
Syntax:
UacElevationLevel()
Parameters:
none
Returns:
(i)
UAC elevation level.
Return value is one of the following levels:
Level
0
1
2
3
Meaning
Error, or unsupported platform.
Process is default (UAC is disabled, or standard user).
Process is running elevated.
Process is not running elevated (user is in Administrators group).
Example:
level = UacElevationLevel( )
Message( "Current UAC elevation level", level )
See Also:
UacManifestSettings, UacExePromptTest
602
UacManifestSettings
UacExePromptTest
Determines whether a program would require a UAC elevation prompt.
Syntax:
UacExePromptTest(programname)
Parameters:
(s) programname
specifies path and filename of the EXE to be tested.
Returns:
(i)
see below.
Return
-1
0
1
Meaning
running program would return an error.
program would not require elevation.
program would require elevation.
Example:
val = UacExePromptTest("notepad.exe")
Message( "UacExePromptTest Returned", val )
Exit
See Also:
UacElevationLevel, UacManifestSettings
UacManifestSettings
Gets information on manifest and signature.
Syntax:
UacManifestSettings (request)
Parameters:
(i) request
see below.
Returns:
(i/s)
depends on request value specified.
Request
0
1
2
3
Meaning
(i) Manifest present. @TRUE or @FALSE.
(s) Manifest requested execution level (Vista and newer). Returns a
blank string on earlier Windows Platforms.
(s) Manifest uiAccess (Vista and newer). Returns a blank string on
earlier Windows Platforms.
(i) Valid signature. @TRUE or @FALSE.
603
VarType
Example:
level = UacManifestSettings( 1 )
Message( "Manifest Requested Execution Level", level )
See Also:
UacElevationLevel, UacExePromptTest
VarType
Gets the type of a WIL variable.
Syntax:
VarType(varname)
Parameter:
(s) varname
variable name to check.
Returns:
(i)
type of variable (see below).
This function returns the type of WIL variable that "varname" specifies. The return
value will be one or more of the following type flags, combined using the bitwise
OR ('|') operator:
Type
-1
0
1
2
5
32
65
128
256
512
1536
Meaning
specified name is a function name, reserved word or string constant.
undefined
integer
string
file handle
floating point value
binary buffer
Unicode string
array
variant
COM/OLE Object
Example:
#DefineFunction CheckBits(bitmask)
totalbitmask = bitmask
typelist = ""
bit = 1
While bitmask ;while there's still a bitmask value
If bitmask & bit ;check bit
if bit&1 then typelist = strCat(typelist,@cr,"Integer(1)")
if bit&2 then typelist = strCat(typelist,@cr,"String(2)")
if bit&4 then typelist = strCat(typelist,@cr,"FileHandle(4)")
604
Version
if bit&32 then typelist = strCat(typelist,@cr,"FloatingPoint(32)")
if bit&64 then typelist =strCat(typelist,@cr,"BinaryBuffer(64)")
if bit&256 then typelist = strCat(typelist,@cr,"Array(256)")
if bit&512 then typelist = strCat(typelist,@cr,"Variant(512)")
if bit&1024 then typelist = strCat(typelist,@cr,"COMObject(1024)")
;decrement working bitmask number by existing byte increments
bitmask = bitmask & ~bit
Endif
bit = bit * 2 ;increment byte
EndWhile
typelist = strCat(typelist,@cr,"---------------")
typelist = strCat(typelist,@cr,"Total = ",totalbitmask)
Return StrTrim(typelist)
#EndFunction
var1 = 1
Message(StrCat("var1 = ", var1), CheckBits(VarType(var1)))
var2 = "abc"
Message(StrCat("var2 = ",var2), CheckBits(VarType(var2)))
var3 = FileOpen(StrCat(DirWindows(0),"win.ini"),"Read")
Message(StrCat("var3 = ",var3), CheckBits(VarType(var3)))
fileclose(var3)
var4 = 1.1
Message(StrCat("var4 = ",var4), CheckBits(VarType(var4)))
var5 = BinaryAlloc(4)
Message(StrCat("var5 = ",var5), CheckBits(VarType(var5)))
BinaryFree(var5)
var6 = ArrDimension(2,2)
Message("var6 = {ARRAY}", CheckBits(VarType(var6)))
var7 = ObjectCreate("WbemScripting.SWbemLocator")
Message(StrCat("var7 = ",var7), CheckBits(VarType(var7)))
Exit
See Also:
isDefined
Version
Returns the version number of the WIL exe program currently running.
Syntax:
Version()
Parameters:
(none)
Returns:
(s)
WIL exe program version number.
Use this function to determine the version of the WIL exe program that is currently
running.
605
WaitForKey
Example:
ver = Version( )
Message("Version number", ver)
See Also:
DOSVersion, Environment, FileVerInfo, VersionDLL, WinVersion
VersionDLL
Returns the version number of the WIL Interpreter DLL currently running.
Syntax:
VersionDLL()
Parameters:
(none)
Returns:
(s)
WIL Interpreter DLL version number.
Use this function to determine the version of the WIL Interpreter DLL that is
currently running. It is useful to verify that a WIL program generated with the latest
version of the language will operate properly on what may be a different machine
with a different version of the WIL Interpreter DLL installed.
Example:
ver = VersionDLL( )
If ver < "2.0a"
Message("Sorry", "WIL version 2.0a or higher required")
Exit
endif
Message("VersionDll", ver)
See Also:
DOSVersion, Environment, FileVerInfo, Version, WinVersion
WaitForKey
Waits for a specific key to be pressed.
Syntax:
WaitForKey(key1,key2,key3,key4,key5)
Parameters:
(s) key1 - key5
five keystrokes to wait for.
Returns:
(i)
position of the selected keystroke (1-5).
606
WaitForKey
WaitForKey requires five parameters, each of which represents a keystroke. The
WIL program will be suspended until one of the specified keys is pressed, at which
time the WaitForKey function will return a number from 1 to 5, indicating the
position of the "key" that was selected, and the program will continue. You can
specify a null string ("") for one or more of the "key" parameters if you don't need to
use all five.
WaitForKey will detect its keystrokes in most, but not all, Windows applications.
Any keystroke that is pressed is also passed on to the underlying application.
WaitForKey supports the following keycodes:
{BACKSPACE}
{CLEAR}
{DEL}
{END}
{ESCAPE}
{F1}
{F3}
{F5}
{F7}
{F9}
{F11}
{F13}
{F15}
{HELP}
{INSERT}
{LEFT}
{NUMPAD+}
{NUMPAD.}
{NUMPAD0}
{NUMPAD2}
{NUMPAD4}
{NUMPAD6}
{NUMPAD8}
{PGDN}
{PRTSC}
{SPACE}
{TAB}
{BS}
{DELETE}
{DOWN}
{ENTER}
{ESC}
{F2}
{F4}
{F6}
{F8}
{F10}
{F12}
{F14}
{F16}
{HOME}
{INS}
{NUMPAD*}
{NUMPAD-}
{NUMPAD/}
{NUMPAD1}
{NUMPAD3}
{NUMPAD5}
{NUMPAD7}
{NUMPAD9}
{PGUP}
{RIGHT}
{SP}
{UP}
Note that NumLock must be on for the codes {NUMPAD0} through {NUMPAD9}
to be generated. Also, it cannot distinguish between the two "Enter" keys on the
keyboard (both will generate an {Enter} code).
Note: Certain special keycodes, such as {ALT} and {F10} may not work with this
function and should be avoided.
607
WaitForKeyEx
IntControl 80 can be used to wait for user to release *all* keys before proceeding.
Example:
k = WaitForKey("{F11}", "{F12}", "{INSERT}", "", "")
switch k
case 1
Message("WaitForKey", "You pressed the F11 key")
break
case 2
Message("WaitForKey", "You pressed the F12 key")
break
case 3
Message("WaitForKey", "You pressed the Insert key")
break
endswitch
See Also:
IsKeyDown, IntControl 80, WaitForKeyEx
WaitForKeyEx
Waits for a specific key to be pressed within timeout period.
Syntax:
WaitForKeyEx(keycodes,timeout)
Parameters:
(s) keycodes
(i) timeout
Returns:
(i)
a tab-delimited list of up to 100 keys to wait for. See
WaitForKey for a list of key codes.
the number of seconds to wait before returning.
position of the selected keystroke, or 0 if none of the
specified keys were pressed before the timeout occured.
This function is like WaitForKey, but it allows you specify up to 100 keys to wait
for and allows for a timeout. Note: Any items in the list past the first 100 will be
silently ignored.
If "keycodes" is a blank string (""), then the keycodes from the most recent use of
this function will be used again, which will save the overhead of re-parsing the
string.
Specify 0 "timeout" to have the function return immediately without waiting. Specify
-1 for no timeout (wait forever).
If one of the specified keys is pressed before the timeout occurs, the function will
return the value corresponding to the position in “keycodes” of the key that was
pressed. The first key in the list is 1.
608
WallPaper
If none of the specified keys are pressed before the timeout occurs, the function will
return 0.
Example:
key = "{BACKSPACE},{BS},{CLEAR},{DELETE},{DEL},{DOWN},{END},{ENTER}"
key = key:",{ESC},{F1},{F2},{F3},{F4},{F5},{F6}"
key = key:",{F7},{F8},{F9},{F10},{F11},{F12},{F13},{F14},"
key = key:",{F15},{F16},{HELP},{HOME},{INSERT},{INS},{LEFT}"
key = key:"{PGDN},{PGUP},{PRTSC},{RIGHT},{SPACE},{SP},{TAB},{UP},"
key = key:"0,1,2,3,4,5,6,7,8,9,`,-,=,[,],\,;,',.,/,"
key = key:"a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z"
key = StrReplace(key,",",@tab)
BoxOpen("WaitForKeyEx","Press a key")
item = WaitForKeyEx(key,-1)
dakey = ItemExtract(item,key,@tab)
BoxShut()
Message("WaitForKeyEx", StrCat("You pressed the '",dakey,"' key"))
exit
See Also:
WaitForKey
WallPaper
Changes the Windows wallpaper.
Syntax:
WallPaper(bmp/html-name,tile)
Parameters:
(s) bmp/html-name
(i) tile
Returns:
(i)
Name of the bmp/html wallpaper file.
@TRUE if wallpaper should be tiled;
@FALSE if wallpaper should not be tiled.
2 - if the wallpaper should be stretched.
@FALSE.
This function immediately changes the Windows wallpaper. It can even be used for
wallpaper "slide shows".
This function supports the Active Desktop wallpaper in Internet Explorer 4.0.
Example:
DirChange("c:\windows")
a = FileItemize("*.bmp")
a = AskItemList("Select New paper",a,@tab,@unsorted,@single,@false)
tile = @FALSE
If FileSize(a) < 40000 Then tile = @TRUE
Wallpaper(a, tile)
609
While
See Also:
SysParamInfo
While
Conditionally and/or repeatedly executes a series of statements.
Syntax:
While continuation-condition
series
of
statements
EndWhile
Parameters:
(s) continuation-condition
an expression to be evaluated.
(s) series of statements statements to be executed repeatedly until the condition
following the While keyword evaluates to @FALSE.
The While statement causes a series of statements to be repeatedly executed until the
"continuation-condition" evaluates to zero or @FALSE. The test of the
"continuation-condition" takes place before each execution of the loop. A While
loop executes zero or more times, depending on the continuation-condition.
The following statements affect continued execution:
Note:
Break
Terminates the While structure and transfers control to the
statement following the next matching EndWhile.
Continue
Returns to the While statement and re-evaluates the
expression.
EndWhile
Returns to the While statement and re-evaluates the
expression.
EndWhile and "End While" may be used interchangeably.
Example:
a=10
while a>5
Display(3, "The value of a is now", a)
a=a-1
endwhile
Message("The value of a should now be 5",a)
See Also:
If, For, GoSub, Switch, Select
610
WinActiveChild
WinActivate
Activates a previously running parent window.
Syntax:
WinActivate(partial-winname)
Parameters:
(s) partial-winname
Returns:
(i)
either an initial portion of, or an entire window
name. The most-recently used window whose title matches
the name will be activated.
@TRUE if a window was found to activate; @FALSE if
no windows were found.
Use this function to activate windows for user input.
This function works only with top-level (parent) application windows.
Example:
Run("notepad.exe", "")
WinActivate("~Notepad")
See Also:
WinActiveChild, WinGetActive, WinName, WinShow, Partial Window Names
(pg.65)
WinActiveChild
Activates a previously running child window.
Syntax:
WinActiveChild(main-winname,child-winname)
Parameters:
(s) main-winname
(s) child-winname
Returns:
(i)
the initial part of, or an entire parent window name.
the initial part of, or an entire child window name.
@TRUE if the window was found to activate; @FALSE if
no windows were found.
Use this function to activate a child window for user input. The most recently used
window whose title matches the name will be activated.
Note: The partial window name you give must match the initial portion of the
window name (as it appears in the title bar) exactly, including proper case (upper or
lower) and punctuation. The parent window must exist or this function will return an
error.
611
WinClose
Example:
Run(StrCat(DirHome(),"winbatch studio.exe"),"")
list = WinItemChild("WinBatch Studio")
choice = AskItemList("Choose the child window to activate", list,
@TAB, @UNSORTED,@SINGLE)
if WinExistChild("WinBatch Studio",choice)
WinActiveChild("WinBatch Studio",choice)
endif
See Also:
WinActivate, WinGetActive, WinShow, Partial Window Names (pg.65)
WinArrange
Arranges, tiles, and/or stacks application windows.
Syntax:
WinArrange(style)
Parameters:
(i) style
Returns:
(i)
one of the following: @STACK, @TILE (or
@ARRANGE), @ROWS, or @COLUMNS.
@TRUE.
Use this function to rearrange the open windows on the screen. (Any iconized
programs are unaffected.)
If there are more than four open windows and you specify @ROWS, or if there are
more than three open windows and you specify @COLUMNS, @TILE will be used
instead.
This function works only with top-level (parent) application windows.
Example:
; Reveal all windows
WinArrange(@TILE)
See Also:
WinHide, WinIconize, WinItemize, WinPlace, WinShow, WinZoom
WinClose
Closes an open window.
Syntax:
WinClose(partial-winname)
612
WindowOnTop
Parameters:
(s) partial-winname
Returns:
(i)
either an initial portion of, or an entire window name. The
most-recently used window whose title matches the name
will be closed.
@TRUE if a window was found to close; @FALSE if no
windows were found.
Use this function to close windows.
WinClose will not close the window which contains a currently executing WIL
program. See IntControl 47.
You can use EndSession to end the current Windows session.
This function works only with top-level (parent) application windows.
Example:
Run("notepad.exe", "")
Message("WinClose","Window is about to close.")
WinClose("~Notepad")
See Also:
EndSession, WinHide, WinIconize, WinItemize, WinWaitClose, IntControl 47,
Partial Window Names (pg.65)
WindowOnTop
Keep window on top.
Syntax:
WindowOnTop(partial-winname,mode)
Parameters:
(s) partial-winname
(i) mode
partial windowname of the window to be affected.
A number specifying what action to take. See below.
Returns:
(i)
returns @TRUE on success, @FALSE on failure.
This function tells the specified window to remain on top of all other windows, or to
return to a normal (non-topmost) state.
Mode
0
1
-1
Meaning
Don't stay on top
Stay on top
Return window's current topmost state: @TRUE = topmost;
@FALSE = not topmost
613
WinExeName
Example:
Run("calc.exe","")
;Place calc window on top
WindowOnTop("Calculator",1)
See Also:
WinState
WinExeName
Returns the name of the executable file which created a specified window.
Syntax:
WinExeName(partial-winname)
Parameters:
(s) partial-winname
the initial part of, or an entire, window name.
Returns:
(s)
name of the EXE file, or "" on failure.
Returns the name of the EXE file which created the first window found whose title
matches "partial-winname".
"Partial-winname" is the initial part of a window name, and may be a complete
window name. It is case-sensitive. You should specify enough characters so that
"partial-winname" matches only one existing window.
A "partial-winname" of "" (null string) specifies the window making the current call
to the WIL Interpreter. WinExeName("") will return a full path to the program
making the current call to the WIL Interpreter.
Notes:
This function works only with top-level (parent) application windows.
WinExeName will return the string "(16-bit application)" for ANY 16 bit
application.
If WinExeName returns "" (null string), it means the function failed. You might be
able to get extended error information from the wwwbatch.ini file.
Windows NT or newer, this function returns module names instead of full program
names. The module name is usually the same as the root name of the program,
without the extension.
Windows Vista or newer, this function may require an Administrator level account,
because it relies on performance monitoring.
Example:
Run("notepad.exe,"")
614
WinExistChild
prog = WinExeName("~Notepad")
WinClose("~Notepad")
TimeDelay(5)
Run(prog, "")
See Also:
AppExist, AppWaitClose, Run, WinExist, WinGetActive, WinName, Partial
Window Names (pg.65)
WinExist
Tells if specified window exists.
Syntax:
WinExist(partial-winname)
Parameters:
(s) partial-winname
Returns:
(i)
the initial part of, or an entire, window name.
@TRUE if a matching window is found; @FALSE if a
matching window is not found.
Note: The partial window name you give must match the initial portion of the
window name (as appears in the title bar) exactly, including proper case (upper or
lower) and punctuation.
This function works only with top-level (parent) application windows.
Most of the "win" functions have a built-in wait (where required). WinExist does
not.
Example:
if WinExist("~Notepad") == @FALSE Then RunIcon("Notepad", "")
See Also:
AppExist, WinActivate, WinClose, WinExeName, WinExistChild, WinGetActive,
WinItemize, WinState, WinWaitExist, Partial Window Names (pg.65)
WinExistChild
Tells if specified child window exists.
Syntax:
WinExistChild (parent-winname, child-winname)
Parameters:
(s) parent-winname
(s) child-winname
the initial part of, or an entire parent window name.
the initial part or, or an entire child window name.
615
WinHelp
Returns:
(i)
@TRUE if a matching window is found; @FALSE if a
matching window is not found.
Use this function to test for the existence of a child window.
Note: The partial window names you give must match the initial portion of the
window name exactly, as it appears in the title bar, including proper case (upper or
lower) and punctuation. The parent window must exist or this function will return an
error.
Example:
Run(StrCat(DirHome(),"winbatch studio.exe"),"")
list = WinItemChild("WinBatch Studio")
choice = AskItemList("Choose the child window to activate", list,
@TAB, @UNSORTED,@SINGLE)
if WinExistChild("WinBatch Studio",choice)
WinActiveChild("WinBatch Studio",choice)
endif
See Also:
AppExist, WinActivate, WinClose, WinExeName, WinGetActive, WinItemize,
WinItemChild, WinState, Partial Window Names (pg.65)
WinGetActive
Gets the title of the active window.
Syntax:
WinGetActive()
Parameters:
(none)
Returns:
(s)
title of active window.
Use this function to determine which window is currently active.
Example:
currentwin = WinGetActive( )
Message("WinGetActive", "Current window is %currentwin%.")
See Also:
WinActivate, WinExeName, WinItemize, WinName, WinPlaceGet, WinPosition,
WinTitle
WinHelp
Calls a Windows help file.
616
WinHelp
Syntax:
WinHelp(help-file,function,keyword)
Parameters:
(s) help-file
(s) function
(s) keyword
name of the Windows help file, with an optional full path.
function to perform (see below).
keyword to look up in the help file (if applicable), or "".
Returns:
(i)
@TRUE if successful; @FALSE if unsuccessful.
This command can be used to perform several functions from a Windows help
(.HLP) file. It requires that the Windows help program WINHELP.EXE or
WINHLP32.EXE be accessible. The desired function is indicated by the "function"
parameter (which is not case-sensitive). The possible choices for "function" are:
Function
"Contents"
"Key"
"PartialKey"
"Context"
"Command"
"Quit"
"HelpOnHelp"
"HTML"
Keyword
Brings up the Contents page for the help file. Specify a null
string ("") for the "keyword" parameter.
Brings up help for the keyword specified by the "keyword"
parameter. You must specify a complete keyword, and it must
be spelled correctly. If there is more than one occurrence of
"keyword" in the help file, a search box will be displayed
which allow you to select the desired topic from the available
choices.
Brings up help for the keyword specified by the "keyword"
parameter. You may specify a partial keyword name: if it
matches more than one keyword in the help file, a search box
will be displayed which allow you to select the desired one
from the available choices. You may also specify a null string
("") for "keyword", in which case you will get a search dialog
containing all keywords in the help file.
Brings up help for the topic specified by "keyword".
"Keyword" must be a numeric context identifier defined in the
[MAP] section of the .HPJ file that was used to build the help
file.
Executes the help macro specified by the "keyword" parameter.
Closes the WINHELP.EXE window, unless another application
is still using it. Specify a null string ("") for the "keyword"
parameter.
Brings up the help file for the Windows help program
(WINHELP.HLP). Specify a null string ("") for the "keyword"
parameter.
Launches HH.EXE to view a topic in an HTML help (.CHM)
file. "Keyword" specifies the topic to display, or "" to view the
starting topic in the file.
617
WinHide
Example:
WinHelp("iexplore.chm", "HTML",
"web_collect_favorites.htm")
Which is identical to:
Run("HH.EXE",
"iexplore.chm::/web_collect_favorites.htm")
Note: WILHH.EXE is a WinBatch utility that augments
HTML Help. WILHH can be used in addition to or as a
complete replacement for HH.EXE. WILHH offers solutions
for some known bugs in HTML Help.
WILHH helps you to resolve these problems with HH.EXE:
- Open a standalone HTML Help window. Ask WILHH to
create a standalone HTML Help window. This window
remains open until the user closes it. Once this window is
created, you can open new topics in the window without
creating a new window, just as you can with WinHelp.
- Open an HTML Help window based on a keyword search.
A common way of linking topics in a help system is through
keyword and associative links--KLinks and ALinks, in
WinHelp terminology. However, WILHH also allows you to
open the new topics in a window that is already open. In
addition, WILHH allows you to use ALinks and KLinks in
ways that HH.EXE doesn't support.
WILHH Commandline:
WILHH.EXE {CHM}
Opens a CHM file to its main page.
WILHH.EXE {CHM} [{KEYWORD}:]
Opens a CHM file and loads a topic based on keyword.
Note: KEYWORD can specifie one or more ALink names
or KLink keywords to look up. Multiple entries are
delimited by a semicolon.
Example:
WinHelp("wil.hlp", "Key", "AskItemList")
WinHide
Hides a window.
618
WinIconize
Syntax:
WinHide(partial-winname)
Parameters:
(s) partial-winname
Returns:
(i)
either an initial portion of, or an entire window
name. The most-recently used window whose title matches
the name will be hidden.
@TRUE if a window was found to hide;
@FALSE if no windows were found.
Use this function to hide windows. The programs are still running when they are
hidden.
A partial-window name of "" (null string) hides the window making the current call
to the WIL Interpreter.
This function works only with top-level (parent) application windows.
Example:
Run("notepad.exe", "")
WinHide("~Notepad")
TimeDelay(3)
WinShow("~Notepad")
See Also:
RunHide, WinClose, WinIconize, WinPlace, Partial Window Names (pg.65)
WinIconize
Iconizes a window.
Syntax:
WinIconize(partial-winname)
Parameters:
(s) partial-winname
Returns:
(i)
either an initial portion of, or an entire window name. The
most-recently used window whose title matches the name
will be iconized.
@TRUE if a window was found to iconize;
@FALSE if no windows were found.
Use this function to turn a window into an icon at the bottom of the screen.
A partial-window name of "" (null string) iconizes the current WIL Interpreter
window.
This function works only with top-level (parent) application windows.
619
WinIsDOS
Example:
Run("notepad.exe", "")
WinIconize("~Not")
; partial window name used here
See Also:
RunIcon, WinClose, WinHide, WinPlace, WinShow, WinZoom, Partial Window
Names (pg.65)
WinIdGet
Returns a unique "Window ID" (pseudo-handle) for the specified window name.
Syntax:
WinIdGet(partial-winname)
Parameters:
(s) partial-winname
the initial part of, or an entire, window name.
Returns:
(s)
the unique "Window ID".
Use this function to obtain the unique "Window ID" (pseudo-handle) for the
specified parent window name. All functions which accept a partial window name as
a parameter now accept the Window ID obtained with WinIdGet. This can be useful
to distinguish between multiple windows with the same name, or to track a window
whose title changes.
Example:
Run("notepad.exe", "")
winid1 = WinIdGet("~Notepad"); most-recently-accessed Notepad
Run("notepad.exe", "")
winid2 = WinIdGet("~Notepad"); most-recently-accessed Notepad
WinPlace(0, 0, 500, @noresize, winid1)
WinPlace(500, 0, 1000, @noresize, winid2)
WinActivate(winid1)
See Also:
DllHwnd, WinExist, WinGetActive, WinItemNameId, WinTitle, Partial Window
Names (pg.65)
WinIsDOS
Tells whether or not a particular window is a DOS or console-type window.
Syntax:
WinIsDOS("partial-winname")
620
WinItemChild
Parameters:
(s) partial-winname
Returns:
(i)
the initial part of, or an entire, window
name.
@TRUE if the window is a DOS window.
@FALSE if it is not a DOS window.
Use this function to determine if the application which created the specified window
is a DOS or Windows Program.
Note: "Partial-winname" is the initial part of a window name, and may be a complete
window name. It is case-sensitive. You should specify enough characters so that
"partial-winname" matches only one existing window. If it matches more than one
window, the most recently accessed window which it matches will be used.
Example:
comspec = Environment("COMSPEC")
Run(comspec, "")
TimeDelay(1)
title= comspec
a=WinIsDOS(title)
if [email protected] then message(title, "is a DOS window")
else message(title, "is NOT a DOS window")
See Also:
WinExeName, WinExist, WinGetActive, WinItemize, WinName, WinState,
WinTitle, Partial Window Names (pg.65)
WinItemChild
Returns a list of all the child windows under this parent.
Syntax:
WinItemChild(parent-winname)
Parameters:
(s) parent-winname
initial part of, or an entire, parent window name.
Returns:
(s)
a list of all the child windows under the parent.
Use this function to return a tab-delimited list of all child windows existing under a
given parent window.
Note: "parent-winname" is the initial part of a window name, and may be a complete
window name. It is case-sensitive. You should specify enough characters so that
"parent-winname" matches only one existing window. If it matches more than one
window, the most recently accessed window which it matches will be used.
621
WinItemizeEx
Example:
Run(StrCat(DirHome(),"winbatch studio.exe"),"")
list = WinItemChild("WinBatch Studio")
choice = AskItemList("Choose the child window to activate", list,
@TAB, @UNSORTED,@SINGLE)
if WinExistChild("WinBatch Studio",choice)
WinActiveChild("WinBatch Studio",choice)
endif
See Also:
AppExist, WinActivate, WinClose, WinExeName, WinGetActive, WinItemize,
WinState, Partial Window Names (pg.65)
WinItemize
Returns a tab-delimited list of all open windows.
Syntax:
WinItemize()
Parameters:
(none)
Returns:
(s)
list of the titles of all open windows.
This function compiles a list of all the open application windows' titles and separates
the titles by tabs. This is especially useful in conjunction with the AskItemList
function, which enables the user to choose an item from such a tab-delimited list.
This function works only with top-level (parent) application windows. See
WinItemChild to work with child windows.
Example:
; Find a window
allwins = WinItemize( )
mywind = AskItemList("Windows", allwins, @TAB, @unsorted, @single,
@false)
WinActivate(mywind)
exit
See Also:
DirItemize, FileItemize, AskItemList, WinClose, WinGetActive, WinItemNameId,
WinName, WinPlaceGet, WinPosition
WinItemizeEx
Returns the full name of window(s) matching a partial window name.
622
WinItemizeEx
Syntax:
WinItemizeEx(partial-winname,multiple,hidden[,return-type])
Parameters:
(s) partial-winname
(i) multiple
(i) hidden
(i) return-type
Returns:
(s)
specifies a partial window name to look for.It can be a blank
string (""), in which case it will match any window.
@TRUE or @FALSE. see below.
@TRUE or @FALSE. see below.
[optional] specifies the format in which the list of windows
will be returned.
list of the titles of all open windows.
If 'multiple' is @TRUE, then this function returns a tab-delimited list of all open
windows that match 'partial-winname'. If 'multiple' is @FALSE, then it returns the
name of the first open window found that matches 'partial-winname'. If no
appropriate matching windows are found, it returns a blank string ("").
If 'hidden' is @TRUE, then hidden windows are included in the list of returned
windows. If 'hidden' is @FALSE, then hidden windows are not included. If 'hidden'
is @FALSE and 'multiple' is @FALSE, then this function returns the name of the
first visible (non-hidden) open window found that matches 'partial-winname'.
"return-type" specifies the format in which the list of windows will be returned, and
can be one of the following:
Type
0
1
2
Meaning
Tab-delimited list of window titles (default)
Tab-delimited list of window ID's
List of window titles and their corresponding window ID's,in the form:
"window1-name|window1-ID|window2-name|window2-ID|..."
The "return-type" values are numbered differently than in WinItemProcID.
Note: this function does not accept a Window ID as the 'partial-winname' parameter.
Example:
; Find all windows that are not hidden
wins = WinItemizeEx("",@TRUE,@FALSE)
mywind = AskItemList("Windows", wins, @TAB, @unsorted, @single,
@false)
WinActivate(mywind)
See Also:
DirItemize, FileItemize, AskItemList, WinClose, WinGetActive, WinItemNameId,
WinName, WinPlaceGet, WinPosition, WinItemize
623
WinItemProcId
WinItemNameId
Returns a list of all open windows and their Window ID's.
Syntax:
WinItemNameId()
Parameters:
(none)
Returns:
(s)
list of the titles and Window ID's of all open windows.
This function returns a list of top-level window titles and their corresponding
"Window ID's", in the form:
"window1-name|window1-ID|window2-name|window2-ID|..."
Example:
#DefineFunction UDFReformat_List (list)
newlist = ""
count = ItemCount( list,"|")
count = count/2
For x = 1 to count by 2
title= ItemExtract(x,list,"|")
id= ItemExtract(x+1,list,"|")
newlist = StrCat(newlist,title,"|",id,@tab)
Next
newlist = StrTrim(newlist)
Return newlist
#EndFunction
winlist = WinItemNameId( )
list = UDFReformat_List (winlist)
AskItemList("Windows and ID's", list, @tab, @unsorted,@single,
@false)
See Also:
WinIdGet, WinItemize
WinItemProcId
Returns a list of windows for the specified process.
Syntax:
WinItemProcID(process-id,flags,return-type)
Parameters:
(i) process-id
(i) flags
(i) return-type
624
returned from RunShell.
see below.
see below.
WinItemProcId
Returns:
(s)
a tab-delimited list of all top-level (parent)
window ID's owned by the process specified
by "process-id".
This function is designed to be used in correlation with RunShell.
You can obtain the process ID of an application that is launched with the RunShell
function by specifying @GETPROCID as the "waitflag". This is the same as
specifying @NOWAIT, except that on success the function will return the process
ID of the application that was launched. This process ID can be used with the
WinItemProcID function . The process ID may be a negative number. If a process
ID cannot be obtained a 1 will be returned to indicate success. In all cases, a return
value of 0 indicates failure.
"flags" can be 0, or one or more of the following values combined with the binary
OR ("|") operator:
Flag
0
1
2
4
8
Meaning
Default list of window ID's
Include windows with blank titles
Include hidden windows
Include windows which are not enabled for keyboard and mouse input
Include windows with the title "WinOldAp"
"return-type" specifies the format in which the list of windows will be returned,
and can be one of the following:
Type
0
1
2
Meaning
Tab-delimited list of window ID's
Tab-delimited list of window titles
List of top-level window titles and their corresponding "Window ID's",
in the form:
"window1-name|window1-ID|window2-name|window2-ID|..."
Example:
procid = RunShell("calc.exe", "", "", @NORMAL, @GETPROCID)
TimeDelay(3)
If (procid != 0) && (procid != 1) ; if we got a valid process ID
winids = WinItemProcId(procid, 2, 0)
Message("Window ID(s)", winids)
Endif
See Also:
RunShell
625
WinMetrics
WinMetrics
Returns Windows system information.
Syntax:
WinMetrics(request#)
Parameters:
(i) request#
see below.
Returns:
(i)
see below.
The request# parameter determines what piece of information will be returned.
Req#
-7
-6
-5
-4
-3
-2
-1
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
626
Return value
2 if WOW64 (32-bit emulation under 64-bit Windows), 0 otherwise
pixels per horizontal dialog unit
pixels per vertical dialog unit
Windows Platform; 0 = Other, 1 = Windows 3.x, 2 = Windows for
Workgroups, 3 = Win32s, 4 = Windows NT Family, 5 = Windows
95/98/ME
WIL EXE type; 0=Win16, 1=Intel32, 2=Alpha32, 3=Mips32,
4=PowerPC32, 5=64-bit WinBatch on Intel64/AMD64
WIL platform; 1=Win16, 2=Win32, 3=Win64
Number of colors supported by video driver
Width of screen, in pixels
Height of screen, in pixels
Width of arrow on vertical scrollbar
Height of arrow on horizontal scrollbar
Height of window title bar
Width of window border lines
Height of window border lines
Width of dialog box frame
Height of dialog box frame
Height of thumb box on scrollbar
Width of thumb box on scrollbar
Width of an icon
Height of an icon
Width of a cursor
Height of a cursor
Height of a one line menu bar
Width of full screen window
WinMetrics
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
41
42
43
44
63
67
70
73
74
75
76
77
78
79
80
Height of a full screen window
Height of Kanji window (Japanese)
Is a mouse present (0 = No, 1 = Yes)
Height of arrow on vertical scrollbar
Width of arrow on horizontal scrollbar
Is debug version of Windows running (0 = No, 1 = Yes)
Are Left and Right mouse buttons swapped (0 = No, 1 = Yes)
Reserved
Reserved
Reserved
Reserved
Minimum width of a window
Minimum height of a window
Width of bitmaps in title bar
Height of bitmaps in title bar
Width of sizeable window frame
Height of sizeable window frame
Minimum tracking width of a window
Minimum tracking height of a window
@TRUE or non-zero if the Microsoft Windows for Pen computing
extensions are installed; zero, or @FALSE, otherwise.
@TRUE or non-zero if the double-byte character set (DBCS)
version of USER.EXE is installed; @FALSE, or zero otherwise.
Number of buttons on mouse, or zero if no mouse is installed.
Not supported.
Not supported.
Not supported.
@TRUE or non-zero if the user requires an application to present
information visually in situations where it would otherwise present
the information only in audible form; @FALSE, or zero, otherwise.
Not supported.
Not supported.
(WinNT 4.0+,) Non-zero if a mouse with a wheel is installed, zero
otherwise
(Win2000) Coordinates for the left side of the virtual screen
(Win2000) Coordinates for the top of the virtual screen
(Win2000) Width of the virtual screen, in pixels
(Win2000) Height of the virtual screen, in pixels
(Win2000) Number of display monitors on the desktop
627
WinPlace
81
(Win2000) Non-zero if all the display monitors have the same color
format, zero otherwise.
There are a number of other request #'s which can be specified, but are of limited
usefulness and therefore not documented here. Details on these can be obtained from
Win32 programming references, available from Microsoft (and others).
Example:
mouse = "NO"
If WinMetrics(19) == 1 Then mouse = "YES"
Message("Is there a mouse installed?", mouse)
See Also:
Environment, MouseInfo, NetInfo, WinResources, WinSysInfo, SysParamInfo
WinName
Returns the name of the window calling the WIL Interpreter.
Syntax:
WinName()
Parameters:
(none)
Returns:
(s)
window name.
Returns the name of the window making the current call to the WIL Interpreter.
Example:
allwins = WinItemize( )
win = AskItemList("Close window", allwins, @tab, @sorted, @single,
@false)
If win == WinName( )
Message("Sorry", "I can't close myself")
else
WinClose(win)
endif
Exit
See Also:
WinActivate, WinExeName, WinGetActive, WinItemize, WinTitle
WinPlace
Places a window anywhere on the screen.
Syntax:
WinPlace(x-ulc,y-ulc,x-brc,y-brc,partial-winname)
628
WinPlaceChild
Parameters:
(i) x-ulc
(i) y-ulc
(i) x-brc
(i) y-brc
(s) partial-winname
Returns:
(i)
how far from the left of the screen to place the upper-left
corner (0-1000).
how far from the top of the screen to place the upper-left
corner (0-1000).
how far from the left of the screen to place the bottom-right
corner (10-1000) or @NORESIZE.
how far from the top of the screen to place the bottom-right
corner (10-1000) or @NORESIZE.
either an initial portion of, or an entire window
name. The most-recently used window whose title matches
the name will be moved to the new position.
@TRUE if a window was found to move;
@FALSE if no windows were found.
Use this function to move windows on the screen. (You cannot, however, move
icons or windows that have been maximized to full screen).
The "x-ulc", "y-ulc", "x-brc", and "y-brc" parameters are based on a logical screen
that is 1000 points wide by 1000 points high.
You can move the window without changing the width and/or height by specifying
@NORESIZE for the "x-brc" and/or "y-brc" parameters, respectively.
Some sample parameters:
Upper left quarter of the screen: 0, 0, 500, 500
Upper right quarter: 500, 0, 1000, 500
Center quarter: 250, 250, 750, 750
Lower left eighth: 0, 750, 500, 1000
This function works only with top-level (parent) application windows.
Note: 1000x1000 virtual screen size is based on the primary monitor in a multimonitor display configuration
Example:
Run("Notepad.exe","")
WinPlace(0, 0, 200, 200, "~Notepad")
See Also:
WinArrange, WinHide, WinIconize, WinPlaceChild, WinPlaceSet, WinPosition,
WinShow, WinZoom, Partial Window Names (pg.65)
WinPlaceChild
Places a child window.
629
WinPlaceChild
Syntax:
WinPlaceChild(x-ulc,y-ulc,x-brc,y-brc,parent-winname,child-winname)
Parameters:
(i) x-ulc
(i) y-ulc
(i) x-brc
(i) y-brc
(s) parent-winname
(s) child-winname
Returns:
(i)
how far from the left of the screen to place
the upper-left corner (0-1000).
how far from the top of the screen to place
the upper-left corner (0-1000).
how far from the left of the screen to place
the bottom-right corner (10-1000) or @NORESIZE.
how far from the top of the screen to place
the bottom-right corner (10-1000) or @NORESIZE.
specifies the parent of the window to place.
specifies the child window to be placed.
@TRUE if a window was found to move.
This function is like WinPlace, but places a child window. The coordinates are
specified as virtual coordinates within the client area of the parent window, where
the parent window is 1000 x 1000.
Use this function to move child windows on the screen. (You cannot, however,
move icons or windows that have been maximized to full screen).
The "x-ulc", "y-ulc", "x-brc", and "y-brc" parameters are based on a logical screen
that is 1000 points wide by 1000 points high.
You can move the window without changing the width and/or height by specifying
@NORESIZE for the "x-brc" and/or "y-brc" parameters, respectively.
Some sample parameters:
Upper left quarter of the screen: 0, 0, 500, 500
Upper right quarter: 500, 0, 1000, 500
Center quarter: 250, 250, 750, 750
Lower left eighth: 0, 750, 500, 1000
This function works only with child application windows.
Note: 1000x1000 virtual screen size is based on the primary monitor in a multimonitor display configuration
Example:
Run(StrCat(DirHome(),"winbatch studio.exe"),"")
list = WinItemChild("WinBatch Studio")
choice = AskItemList("Choose the child window to activate", list,
@TAB, @UNSORTED,@SINGLE)
if WinExistChild("WinBatch Studio",choice)
WinActiveChild("WinBatch Studio",choice)
WinPlaceChild(0, 0, 200, 200, "WinBatch Studio", choice)
630
WinPlaceGet
Endif
See Also:
WinArrange, WinHide, WinIconize, WinPlace, WinPlaceSet, WinPosition,
WinShow, WinZoom, Partial Window Names (pg.65)
WinPlaceGet
Returns window coordinates.
Syntax:
WinPlaceGet(win-type,partial-winname)
Parameters:
(i) win-type
(s) partial-winname
@ICON, @NORMAL, or @ZOOMED
the initial part of, or an entire, window name.
Returns:
(s)
window coordinates (see below).
This function returns the coordinates for an iconized, normal, or zoomed window.
"Partial-winname" is the initial part of a window name, and may be a complete
window name. It is case-sensitive. You should specify enough characters so that
"partial-winname" matches only one existing window. If it matches more than one
window, the most recently accessed window which it matches will be used.
The returned value is a string of either 2 or 4 numbers, as follows:
Iconic windows "x y"
(upper left corner of the icon)
Normal windows "upper-x upper-y lower-x lower-y"
Zoomed windows"x y"
(upper left corner of the window)
All coordinates are relative to a virtual 1000x1000 screen.
This function works only with top-level (parent) application windows.
Note: 1000x1000 virtual screen size is based on the primary monitor in a multimonitor display configuration
Example:
Run("notepad.exe", "")
pos = WinPlaceGet(@NORMAL, "~Notepad")
TimeDelay(2)
WinPlaceSet(@NORMAL, "~Notepad", "250 250 750 750")
TimeDelay(2)
WinPlaceSet(@NORMAL, "~Notepad", pos)
See Also:
WinGetActive, WinItemize, WinPlaceSet, WinPosition, WinState, Partial Window
Names (pg.65)
631
WinPosition
WinPlaceSet
Sets window coordinates.
Syntax:
WinPlaceSet(win-type,partial-winname,position-string)
Parameters:
(i) win-type
(s) partial-winname
(s) position-string
@ICON, @NORMAL, or @ZOOMED
the initial part of, or an entire, window name.
window coordinates (see below).
Returns:
(s)
previous coordinates.
This function sets the coordinates for an iconized, normal, or zoomed window. The
window does not have to be in the desired state to set the coordinates; for example,
you can set the iconized position for a normal window so that when the window is
subsequently iconized, it will go to the coordinates that you've set.
"Partial-winname" is the initial part of a window name, and may be a complete
window name. It is case-sensitive. You should specify enough characters so that
"partial-winname" matches only one existing window. If it matches more than one
window, the most recently accessed window which it matches will be used.
"Position-string" is a string of either 2 or 4 numbers, as follows:
Iconic windows "x y"
(upper left corner of the icon)
Normal windows "upper-x upper-y lower-x lower-y"
Zoomed windows"x y"
(upper left corner of the window)
All coordinates are relative to a virtual 1000x1000 screen.
This function works only with top-level (parent) application windows.
Note: 1000x1000 virtual screen size is based on the primary monitor in a multimonitor display configuration
Example:
Run("Notepad.exe","")
WinPlaceSet(@ICON, "~Notepad", "10 950")
See Also:
WinActivate, WinArrange, WinPlace, WinPlaceGet, WinState, Partial Window
Names (pg.65)
WinPosition
Returns Window position.
632
WinPositionChild
Syntax:
WinPosition(partial-winname)
Parameters:
(s) partial-winname
the initial part of, or an entire window name.
Returns:
(s)
window coordinates, delimited by commas.
Returns the current window position information for the selected window. It returns
4 comma-separated numbers (see WinPlace for details).
This function works only with top-level (parent) application windows.
Example:
Run("notepad.exe", "")
; start Notepad
WinPlace(0,0,300,300, "~Notepad") ; place Notepad
pos = WinPosition("~Notepad")
; save position
TimeDelay(2)
WinPlace(200,200,300,300, "~Notepad")
; move Notepad
TimeDelay(2)
WinPlace(%pos%, "~Notepad") ; restore Notepad
See Also:
WinGetActive, WinItemize, WinPlace, WinPlaceGet, WinState, Partial Window
Names (pg.65)
WinPositionChild
Returns child window position.
Syntax:
WinPositionChild(parent-winname,child-winname)
Parameters:
(s) parent-winname
(s) child-winname
the initial part of, or an entire parent window name.
the initial part of, or an entire child window name.
Returns:
(s) window coordinates
window coordinates delimited by commas.
This function is like WinPosition, but returns coordinates for a child window. The
coordinates are specified as virtual coordinates within the client area of the parent
window, where the parent window is 1000 x 1000.
This function works only with child application windows.
Example:
allwins = WinItemize( )
parentwnd = AskItemList("Top Level Windows", allwins, @tab, @sorted,
@single, @false)
633
WinResources
childwins=WinItemChild(parentwnd)
childwnd = AskItemList("Choose a child window to get coordinates
from", childwins, @tab, @sorted, @single, @false)
ret = WinPositionChild(parentwnd,childwnd)
Message(StrCat("Parent: ",parentwnd, " Child: ",childwnd),
StrCat("coordinates = ",ret))
Exit
See Also:
WinGetActive, WinItemize, WinPosition, WinPlace, WinPlaceGet, WinState, Partial
Window Names (pg.65)
WinResources
Returns information on available memory and resources.
Syntax:
WinResources(request#[,format])
Parameters:
(i) request#
(i) format
see below.
[optional] see below.
Returns:
(i)
see below.
The value of request# determines the piece of information returned.
Req#
10
11
12
13
14
15
16
17
634
Return value
Number between 0 and 100 giving a general idea of current memory
utilization, in which 0 indicates no memory use and 100 indicates full
memory use.
Total number of bytes of physical memory.
Number of bytes of physical memory available.
Total number of bytes that can be stored in the paging file. Note: that
this number does not represent the actual physical size of the paging file
on disk.
Number of bytes available in the paging file.
Total number of bytes that can be described in the user mode portion of
the virtual address space of the calling process.
Number of bytes of unreserved and uncommitted memory in the user
mode portion of the virtual address space of the calling process.
Number of bytes of unreserved and uncommitted memory in the
extended portion of the virtual address space of the calling process
(Windows 2000 and newer).
WinShow
Format is an optional parameter that controls the format in which the size is returned.
If the result is too large to be returned as an integer (larger than 2 gigabytes).
Format
Meaning
0
(Default) Floating Point
1
Huge number. This is a long decimal number string, which may
represent a number too large to be converted to an integer.'Huge
number' is a special data type. It is a long decimal number string,
which may represent a number too large to be converted to an
integer. This value cannot be modfied with standard arithmetic
operations, it requires the use of the Huge Math extender.
Example:
mem = WinResources(10)
Message("Current memory utilization ", mem)
See Also:
WinMetrics, WinSysInfo, SysParamInfo
WinShow
Shows a window in its "normal" state.
Syntax:
WinShow(partial-winname)
Parameters:
(s) partial-winname
Returns:
(i)
either an initial portion of, or an entire window
name. The most-recently used window whose
title matches the name will be shown.
@TRUE if a window was found to show;
@FALSE if no windows were found.
Use this function to restore a window to its "normal" size and position.
A partial-window name of "" (null string) restores the current WIL interpreter
window.
Example:
RunZoom("Notepad.exe", "")
; other processing...
WinShow("~Notepad")
See Also:
WinArrange, WinHide, WinIconize, WinZoom, Partial Window Names (pg.65)
635
WinSysInfo
WinState
Returns the current state of a window.
Syntax:
WinState(partial-winname)
Parameters:
(s) partial-winname
the initial part of, or an entire, window name.
Returns:
(i)
window state (see below).
"Partial-windname" is the initial part of a window name, and may be a complete
window name. It is case-sensitive.
You should specify enough characters so that "partial-winname" matches only one
existing window. If it matches more than one window, the most recently accessed
window which it matches will be used.
Possible return values are as follows.
Value
-1
0
1
2
3
Symbolic name
@HIDDEN
@FALSE
@ICON
@NORMAL
@ZOOMED
Meaning
Specified window exists, but is hidden
Specified window does not exist
Specified window is iconic (minimized)
Specified window is a normal window
Specified window is zoomed (maximized)
This function works only with top-level (parent) application windows.
Example:
RunIcon("Notepad.exe","")
If WinState("~Notepad") == @ICON Then WinShow("~Notepad")
See Also:
Run, WinExist, WinGetActive, WinHide, WinIconize, WinItemize, WinPlace,
WinPlaceGet, WinPlaceSet, WinPosition, WinShow, WinZoom, Partial Window
Names (pg.65)
WinSysInfo
Returns system configuration information.
Syntax:
WinSysInfo()
Parameters:
(none)
636
WinTitle
Returns:
(s)
a TAB delimited list of system configuration information.
WinSysInfo returns a TAB-delimited list containing the following items:
1.
2.
3.
4.
5.
6.
7.
8.
9.
computer name of the current system.
processor architecture.
page size (specifies granularity of page protection and commitment).
mask representing the set of processors configured into the system.
number of processors in the system.
processor type.
granularity in which memory will be allocated.
system's architecture-dependent processor level.
architecture-dependent processor revision.
Example:
sysinfo = WinSysInfo( )
computer = ItemExtract(1, sysinfo, @TAB)
processor = ItemExtract(6, sysinfo, @TAB)
Message(computer, "is a %processor%")
See Also:
WinMetrics, WinResources, SysParamInfo
WinTitle
Changes the title of a window.
Syntax:
WinTitle(partial-winname,new-name)
Parameters:
(s) partial-winname
(s) new-name
Returns:
(i)
either an initial portion of, or an entire window
name. The most-recently used window whose
title matches the name will be shown.
the new name of the window.
@TRUE if a window was found to rename;
@FALSE if no windows were found.
Use this function to change a window's title.
A "partial-window name" of "" (null string) refers to the current WIL interpreter
window.
Warning: Some applications may rely upon their window's title staying the same!
Therefore, the WinTitle function should be used with caution and adequate testing.
This function works only with top-level (parent) application windows.
637
WinVersion
Example:
; Capitalize title of window
allwinds = WinItemize( )
mywin = AskItemList("Uppercase Windows", allwinds, @TAB, @unsorted,
@single, @false)
WinTitle(mywin, StrUpper(mywin))
Drop(allwinds, mywin)
See Also:
WinGetActive, WinItemize, WinName, Partial Window Names (pg.65)
WinVersion
Provides the version number of the current Windows system.
Syntax:
WinVersion(level)
Parameters:
(i) level
see below.
Returns:
(i)
Windows version number.
Level
0
Returns
(i) Minor version: returns the decimal part of the Windows version
number; i.e. 1.0, 2.11, 3.0, etc.
1
(i) Major version: returns the integer part of the Windows version
number; i.e. 1.0, 2.11, 3.0, etc.
2
3
(i) Build number
(s) CSD version: returns a string indicating the latest service pack that
has been installed (e.g., "Service Pack 1"), or a blank string ("") if no
service pack has been installed.
(i) Windows platform [same as WinMetrics(-4)]
Value Meaning
0
Other
1
Windows 3.X
2
Windows for Workgroups
3
Win32s
4
Windows NT Family
5
Windows 95/98/ME
(s) Version string
This is a string in the form: "platform-major-minor"
where "platform" is one of the following:
Value Meaning
0
Win32s
4
5
638
WinVersion
6
7
8
9
10
1
Windows 95/98/ME
2
Windows NT Family
Major version number of the latest Service Pack installed.
Minor version number of the latest Service Pack installed.
Bit flags that identify the product suites available on the system. This
can be 0, or one or more of the following values, combined using the
bitwise OR ('|') operator:
Value Meaning
1
Microsoft Small Business Server was once installed on the
system, but may have been upgraded to another version of
Windows (see note below).
2
Windows Server 2003, Enterprise Edition, Windows 2000
Advanced Server, or Windows NT Server 4.0 Enterprise Edition
is installed (see note below).
4
Microsoft BackOffice components are installed.
16
Terminal Services is installed.
32
Microsoft Small Business Server is installed with the restrictive
client license in force (see note below).
64
Windows XP Embedded is installed.
128
Windows Server 2003, Datacenter Edition or Windows 2000
Datacenter Server is installed.
256
Terminal Services is installed, but only one interactive session is
supported.
512
Windows XP Home Edition is installed.
1024
Windows Server 2003, Web Edition is installed.
Note that you should not solely rely upon the '1' flag to determine
whether Small Business Server has been installed on the system, as both
this flag and the '32' flag are set when this product suite is installed. If
you upgrade this installation to Windows Server, Standard Edition, the
'32' flag will be unset, however, the '1' flag will remain set. In this case,
this indicates that Small Business Server was once installed on this
system. If this installation is further upgraded to Windows Server,
Enterprise Edition, the '1' flag will remain set.
Additional information about the system. This can be one of the
following values:
Value Meaning
1
The operating system is Windows "Longhorn", Windows XP
Professional, Windows XP Home Edition, Windows 2000
Professional, or Windows NT Workstation 4.0.
2
The system is a domain controller.
3
The system is a server.
System Architecture.
639
WinVersion
Value
1
2
Meaning
32-bit operating system architecture.
64-bit operating system architecture.
Notes: A server that is also a domain controller is reported as '2', not '3'.
A blank string will be returned for levels 6-9 on unsupported Windows platforms.
To decipher between all Windows platforms. Use the function WinVersion(5) to tell
which one you have:
Windows
Platform
Major
Minor
95
1
4
0
98
1
4
10
ME
1
4
90
NT3.51
2
3
51
NT 4
2
4
0
NT 2000
2
5
0
XP
2
5
1
2003 Server
2
5
2
Vista / 2008 Server
2
6
0
7 / 2008 R2 Server
2
6
1
8 / 2012 Server
2
6
2
v = WinVersion(5)
Platform="Unknown"
if v=="1-4-0" then Platform="Windows 95"
if v=="1-4-10" then Platform="Windows 98"
if v=="1-4-90" then Platform="Windows ME"
if v=="2-3-51" then Platform="Windows NT 3.51"
if v=="2-4-0" then Platform="Windows NT 4.0"
if v=="2-5-0" then Platform="Windows 2000"
if v=="2-5-1" then Platform="Windows XP"
if v=="2-5-2" then Platform="Windows 2003 Server"
if v=="2-6-0" then Platform="Windows Vista/2008 Server"
if v=="2-6-1" then Platform="Windows 7/2008 R2 Server "
if v=="2-6-2" then Platform="Windows 8/2012 Server "
Message("Platform",platform)
Example:
minorver = WinVersion(0)
majorver = WinVersion(1)
640
WinWaitClose
buildver = WinVersion(2)
csdver = WinVersion(3)
Message("Windows Version", StrCat(majorver, ".", minorver, "
",buildver, " ", csdver))
See Also:
Environment, FileVerInfo, Version, VersionDLL
WinWaitChild
Waits for a child window to exist.
Syntax:
WinWaitChild(parent-winname,child-winname,timeout)
Parameters:
(s) parent-winname
(s) child-winname
(i) timeout
Returns:
(s)
the initial part of, or an entire parent window name.
the initial part of, or an entire child window name.
the number of seconds to wait (maximum = 86400). Specify
0 to return immediately (no wait). Specify -1 for no timeout
(wait forever).
@TRUE if the window appeared; @FALSE if it didn't.
Note: This function has a built in ВЅ second time delay. This can be modified by
IntControl 70.
Example:
Run(StrCat(DirHome(),"winbatch studio.exe"),"")
WinWaitExist("WinBatch Studio", 5)
TimeDelay(1)
SendMenusTo("WinBatch Studio", "File Open")
SendKeysTo("Open", "c:\config.sys{enter}")
ret = WinWaitChild("WinBatch Studio", "c:\CONFIG.SYS", 5)
if ret == @True
Message("Notice","Child window found")
else
Message("Notice","Child window found")
Endif
See Also:
AppWaitClose, IntControl 70, TimeDelay, RunWait, WinExist, WinExistChild,
WinWaitClose, WinWaitExist, Partial Window Names (pg.65)
WinWaitClose
Suspends the WIL program execution until a specified window has been closed.
641
WinWaitExist
Syntax:
WinWaitClose(partial-winname[,timeout])
Parameters:
(s) partial-winname
(i) timeout
Returns:
(i)
either an initial portion of, or an entire window
name.
[optional] number of seconds to wait (maximum = 86400).
Specify 0 to have the function return immediately. Specify 1 for no timeout (wait forever). The default is -1.
@TRUE if at least one window was found to wait for;
@FALSE if no windows were found.
Use this function to suspend the WIL program's execution until the user has finished
using a given window and has manually closed it.
This function works only with top-level (parent) application windows.
If the window doesn’t exist, the function will immediately return the value
@FALSE. If the window exists, the function will wait for it close or until the
timeout period has elapsed, whichever comes first, and then return the value
@TRUE.
Note: This function has a built in ВЅ second time delay. This can be modified by
IntControl 70.
Example:
Run("notepad.exe", "")
Display(4, "Note", "Close Notepad to continue")
WinWaitClose("~Notepad")
Message("Continuing...", "Notepad closed")
See Also:
AppWaitClose, IntControl 70, TimeDelay, RunWait, WinExist, WinWaitChild,
WinWaitExist, Yield, Partial Window Names (pg.65)
WinWaitExist
Waits for a window to exist.
Syntax:
WinWaitExist(partial-winname, timeout)
Parameters:
(s) partial-winname
(i) timeout
642
the initial part of, or an entire, window name.
the number of seconds to wait (maximum = 86400). Specify
0 to return immediately (no wait). Specify -1 for no timeout
(wait forever).
WinZoom
Returns:
(s)
@TRUE if the window appeared; @FALSE if it didn't.
Note: This function has a built in ВЅ second time delay. This can be modified by
IntControl 70.
Example:
Run("notepad.exe", "")
WinWaitExist("~Notepad", 5)
TimeDelay(1)
SendMenusTo("~Notepad", "File Open")
SendKeysTo("File Open", "c:\config.sys~")
See Also:
AppWaitClose, IntControl 70, TimeDelay, RunWait, WinExist, WinWaitChild,
WinWaitClose, Partial Window Names (pg.65)
WinWaitReady
Waits until an application is waiting for user input.
Syntax:
WinWaitReady(partial-winname,timeout)
Parameters:
(s) partial-winname
(i) timeout
Returns:
(i)
the initial part of, or an entire, window name.
the number of milliseconds to wait.
Specify 0 to return immediately (no wait).
Specify -1 for no timeout (wait forever).
It returns @TRUE if it successfully waits, or @FALSE if a
time-out occurred (or if it was unable to initiate a wait).
This function waits until the process which created the specified window is waiting
for user input with no input pending, or until the specified time-out interval has
elapsed. It can only be used with 32-bit GUI applications.
Example:
Run("Notepad.exe","")
retvalue = WinWaitReady("~Notepad", 5)
WinClose("~Notepad")
See Also:
WinWaitChild, WinWaitExist
WinZoom
Maximizes a window to full-screen.
643
Yield
Syntax:
WinZoom(partial-winname)
Parameters:
(s) partial-winname
Returns:
(i)
either an initial portion of, or an entire window name. The
most-recently used window whose title matches the name
will be shown.
@TRUE if a window was found to zoom;
@FALSE if no windows were found.
Use this function to "zoom" windows to full screen size.
A partial-winname of " " (null string) zooms the current WIL interpreter window.
This function works only with top-level (parent) application windows.
Example:
Run("notepad.exe", "")
WinZoom("~Notepad")
TimeDelay(3)
WinShow("~Notepad")
See Also:
RunZoom, WinHide, WinIconize, WinPlace, WinShow, Partial Window Names
(pg.65)
Yield
Provides time for other windows to do processing.
Syntax:
Yield
Parameters:
(none)
Returns:
(not applicable)
Use this command to give other running windows time to process. This command
will allow each open window to process 20 or more messages.
The Yield waits a very short time. The TimeDelay function gives other running
windows time to process messages, like the Yield does. TimeDelay might be better
to use for longer time delays.
Example:
; run Excel and give it some time to start up
sheet = AskLine ("Excel", "File to run:", "", 0)
644
Yields
Run("excel.exe", sheet)
Yield
Yield
Yield
See Also:
TimeDelay, TimeWait, Exclusive, WinWaitChild, WinWaitExist,Yields
Yields
Provides time for other windows to do processing.
Syntax:
Yields(count)
Parameters:
(s) count
number of yields to perform.
Returns:
(not applicable)
Use this command to give other running windows time to process. This command
will allow each open window to process 20 or more messages.
This function is the same as the "Yield" command, but allows you to specify the
number of yields to perform; i.e., "Yields(5)" is the same as 5 consecutive "Yield"
commands.
The Yield waits a very short time. The TimeDelay function gives other running
windows time to process messages, like the Yield does. TimeDelay might be better
to use for longer time delays.
Example:
; run Excel and give it some time to start up
Run("excel.exe", "")
Yields(300)
See Also:
TimeDelay, TimeWait, Exclusive, WinWaitChild, WinWaitExist,Yield
645
Menu File Structure
MENU FILES
If you are using a batch file-based implementation of WIL, you can skip this section
and move on to the WIL Tutorial (pg. 19). WinBatch and WebBatch are batch file
applications. FileMenu, PopMenu and WinBatch Studio are menu file applications.
About Menu Files
This section of the manual shows how to create WIL menu files. It is not important
at this point to understand the actual commands which are shown in the menus.
WIL Batch processes can be run from batch files or from menu files. WinBatch uses
batch files. Several other applications use WIL as their macro language in the form
of menu files.
The single workstation version of WinBatch, (not the Compiler), includes two
accessory applications, PopMenu and FileMenu. These run batch processes from
menu files. WIL is also available to software developers for use as the macro
language in their own software.
How Menu Files are used
WIL scripts can be implemented in two ways: via a batch process or a menu file. In a
batch process, WIL scripts are associated with the WIL processor allowing them to
be initiated and run on the desktop just as any true executable is launched and run.
WIL scripts can also be launched as menu items from a drop down menu. However,
you must have an implementation of WIL with the capability of generating the menu
either within one of our applications or as an enhancement to standard Windows
applications. WIL adds menu capability to the Windows Task Bar and the Shortcut
Menu in the Windows Explorer via the utilities FileMenu and PopMenu.
Menu File Structure
WIL menus are defined in a menu file which is simply a standard ASCII text file
(the kind created by Notepad). Each menu file consists of one or more lines of menu
statements. Each line is terminated with a carriage return / line feed (CRLF)
combination, and can be up to 2048 characters long. Generally, these files have an
extension of .MNW, or .MNU. See your product documentation for the name of the
default menu file that it uses.
647
Menu File Structure
Every menu file contains one or more menu items. When activated they appear as
drop-down menus. They may also contain top-level menu names which show up in a
main menu bar (refer to your product documentation for more information). Each
menu item consists of a title which identifies the item, followed by one or more lines
of menu code which the WIL Interpreter will execute when you choose the item.
Essentially, your menu file is an outline of menu options, formatted with specific
spacing and containing sections of code.
There are two main parts of a menu file: The first section, which is optional, is the
initialization code. This section is executed once when the menu is first loaded and
run. It's located before the first menu item.
The remainder of the menu file consists of menu item titles and their associated
statements. The code under each menu title is executed when the corresponding
menu item is selected. Execution begins at the first s