wil reference manual apr 2012 - www tech support - winbatch

648
WIL Reference Manual Manual Revision ~ April 2012

Upload: others

Post on 10-Feb-2022

3 views

Category:

Documents


0 download

TRANSCRIPT

WIL Reference Manual Manual Revision ~ April 2012

Copyright © 1988-2012 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

iii

CONTENTS WIL Reference Manual i 

CONTENTS iii 

INTRODUCTION 15 What is WIL? 15 What is WIL good for? 15 Products that use WIL 16 Notational Conventions 17 Acknowledgments 17 

WIL TUTORIAL 19 Creating WIL Scripts Files 19 Running WIL Utilities 19 Command Line Parameters 20 What is a WIL Program? 21 Our First WIL Program 22 Functions and Parameters 22 Displaying Text 25 User Input 26 Using Variables 28 Making Decisions 29 Control of Program Flow 32 

Exploring WIL 37 Running Programs 38 Display and Input 40 Manipulating Windows 42 Files and Directories 45 Handling Errors 47 Debugging WIL Scripts 50 Selection Methods 50 Nicer File Selection 54 Nicer Messages 54 Running DOS Programs 56 Sending Keystrokes to Programs 56 Our Completed WIL File 58 

THINGS TO KNOW 61 Recovering from Cancel 61 Extenders: Networking, TCP/IP, Microsoft 62 Terminating WIL processing 64 Carriage Return Line Feed 64 Extension Associations and the Run Functions 64 Debug 64 Internal Control Functions 65 Partial Window Names 65 

CONTENTS

iv

System.ini and its device= lines 66 Dividing Floating Point Numbers 66 File Delimiters 67 Sounds 68 

WIL LANGUAGE 69 Language Components 69 

Constants 69 Identifiers 70 Variables 71 Variable Substitution 71 Lists Explained 72 Keywords 73 Operators 73 Precedence and Evaluation Order 74 Comments 75 Assignment Statements 75 Control Statements 75 Function Parameters 76 

User Defined Functions 77 Arrays 80 Error Handling 81 

Using ErrorMode 81 Using IntControl 73 82 

WIL FUNCTION REFERENCE 83 Introduction 83 About 84 Abs 84 Acos 85 AddExtender 85 AppExist 87 AppWaitClose 88 ArrayFileGet 89 ArrayFileGetCsv 90 ArrayFilePut 91 ArrayFilePutCsv 92 ArrayFromStr 93 ArrayInsert 94 Arrayize 95 ArrayLocate 96 ArrayRedim 97 ArraySearch 98 ArraySort 99 ArraySwapElements 100 ArrayToStr 101 ArrDimension 102 ArrInfo 103 ArrInitialize 104 ArrRemove 105 Asin 106 AskColor 107 

CONTENTS

v

AskDirectory 108 AskFileName 110 AskFileText 113 AskFont 114 AskItemList 116 AskLine 117 AskPassword 119 AskTextBox 119 AskYesNo 120 Atan 121 Average 122 Beep 122 Binary Operations 123 BinaryAlloc 123 BinaryAllocArray 124 BinaryAnd 126 BinaryBufInfo 128 BinaryCheckSum 128 BinaryClipGet 129 BinaryClipPut 131 BinaryCompare 132 BinaryConvert 133 BinaryCopy 134 BinaryEodGet 135 BinaryEodSet 136 BinaryFree 136 BinaryHashRec 137 BinaryIncr 139 BinaryIndex 139 BinaryIndexBin 140 BinaryIndexEx 141 BinaryIndexNc 142 BinaryOleType 144 BinaryOr 146 BinaryPeek 147 BinaryPeekHex 148 BinaryPeekStr 149 BinaryPeekStrW 150 BinaryPoke 150 BinaryPokeHex 151 BinaryPokeStr 152 BinaryPokeStrW 153 BinaryRead 154 BinaryReadEx 154 BinaryReplace 156 BinarySort 156 BinaryStrCnt 158 BinaryTagExtr 159 BinaryTagFind 160 BinaryTagIndex 162 BinaryTagInit 163 BinaryTagLen 165 

CONTENTS

vi

BinaryTagRepl 166 BinaryWrite 169 BinaryWriteEx 169 BinaryXlate 170 BinaryXor 172 Break 173 ButtonNames 174 Call 175 Ceiling 176 Char2Num 177 ChrGetCodePage 178 ChrHexToString 178 ChrHexToUnicode 179 ChrSetCodePage 179 ChrStringToHex 180 ChrStringToUnicode 180 ChrUnicodeToHex 181 ChrUnicodeToString 181 ClipAppend 182 ClipGet 182 ClipGetEx 183 ClipHasFormat 183 ClipPut 185 ComputerNameGet 185 ComputerNameSet 186 Continue 187 Cos 188 Cosh 189 CreateObject 189 CurrentFile {*M} 189 CurrentPath {*M} 190 CurrFilePath {*M} 191 DataCast 192 DDEExecute 192 DDEInitiate 193 DDEPoke 194 DDERequest 195 DDETerminate 196 DDETimeout 197 Debug 198 DebugData 200 DebugTrace 200 Decimals 205 Dialog 206 

User-Defined-Callback Function or Subroutine 225 Using Internet Explorer Controls in WIL Dialogs 233 

DialogControlGet 242 DialogControlSet 246 DialogControlState 250 DialogObject 254 DialogProcOptions 258 DirAttrGet 264 

CONTENTS

vii

DirAttrGetEx 265 DirAttrSet 267 DirAttrSetEx 268 DirChange 270 DirExist 271 DirGet 272 DirHome 272 DirInfoToArray 273 DirItemize 274 DirMake 275 DirRemove 276 DirRename 276 DirScript 277 DirSize 277 DirWindows 278 DiskExist 279 DiskFree 280 DiskInfo 281 DiskScan 281 DiskSize 282 DiskVolInfo 283 Display 284 DllCall 285 DllCallbackCreate 287 DllCall Additional Information 290 DllCallCdecl 291 DllFree 294 DllHinst 294 DllHwnd 295 DllLastError 296 DllLoad 297 DOSVersion 297 Drop 298 DropWild 299 EndSession 300 Environment 300 EnvironSet 301 EnvItemize 302 ErrorEvent 303 ErrorMode 304 Exclusive 305 Execute 306 ExeTypeInfo 307 Exit 308 Exp 308 Fabs 309 FileAppend 309 FileAttrGet 310 FileAttrGetEx 311 FileAttrSet 313 FileAttrSetEx 314 FileBaseName 316 

CONTENTS

viii

FileClose 316 FileCompare 317 FileCopy 318 FileCopyAttr 320 FileCreateTemp 321 FileDelete 322 FileDigest 322 FileExist 323 FileExtension 324 FileFullName 325 FileGet 325 FileGetW 326 FileInfoToArray 326 FileItemize 328 FileItemPath 329 FileLocate 330 FileMapName 330 FileMove 332 FileMoveAttr 333 FileNameLong 334 FileNameShort 334 FileOpen 335 FilePath 337 FilePut 337 FilePutW 338 FileRead 338 FileRename 339 FileRoot 340 FileSize 340 FileSizeEx 341 FileTimeCode 342 FileTimeGet 343 FileTimeGetEx 344 FileTimeSet 345 FileTimeSetEx 345 FileTimeTouch 346 FileVerInfo 347 FileWrite 349 FileYmdHms 350 FindWindow 351 Floor 351 For 352 ForEach 353 GetExactTime 355 GetObject 355 GetTickCount 355 GoSub 356 Goto 357 IconExtract 357 IconInfo 358 IconReplace 360 If … Endif 361 

CONTENTS

ix

IgnoreInput 364 IniDelete 364 IniDeletePvt 365 IniItemize 365 IniItemizePvt 366 IniRead 367 IniReadPvt 368 IniWrite 368 IniWritePvt 369 InstallFile 370 Int 371 IntControl 372 IsDefined 406 IsFloat 407 IsInt 407 IsKeyDown 408 IsLicensed 408 IsNumber 409 ItemCount 410 ItemCountCsv 410 ItemExtract 412 ItemExtractCsv 412 ItemInsert 414 ItemLocate 415 ItemLocateWild 415 ItemRemove 416 ItemReplace 417 ItemSort 417 KeyToggleGet 418 KeyToggleSet 419 LastError 419 Log10 420 LogDisk 420 LogE 421 Max 421 Message 422 Min 423 Mod 423 MouseClick 424 MouseClickBtn 425 MouseCoords 425 MouseInfo 426 MouseMove 428 MousePlay 428 MsgTextGet 431 Net101 431 NetInfo 432 Num2Char 433 OLE / COM 433 ObjectAccess 439 ObjectClose 441 ObjectConstantsGet 441 

CONTENTS

x

ObjectConstToArray 443 ObjectCreate 444 ObjectEventAdd 447 ObjectEventRemove 449 ObjectGet 451 ObjectOpen 453 ObjectType 453 ObjectTypeGet 456 ParseData 460 Pause 460 PipeClientClose 461 PipeClientOpen 462 PipeClientSendRecvData 464 PipeInfo 465 PipeServerClose 467 PipeServerCreate 468 PipeServerRead 470 PipeServerWrite 471 PlayMedia 473 PlayMidi 474 PlayWaveForm 474 Print 475 PtrGlobal 476 PtrGlobalDefine 477 PtrGlobalTest 478 PtrPersistent 478 Random 479 Registration Database Operations 480 RegApp 481 RegCloseKey 482 RegConnect 483 RegCreateKey 484 RegDeleteKey 484 RegDelValue 485 RegEntryType 486 RegExistKey 490 RegExistValue 490 RegLoadHive 491 RegOpenFlags 492 RegOpenKey 493 RegOpenKeyEx 494 RegQueryBin 495 RegQueryDword 496 RegQueryEx 497 RegQueryExpSz 497 RegQueryItem 499 RegQueryKey 500 RegQueryKeyLastWriteTime 500 RegQueryKeys 501 RegQueryMulSz 501 RegQueryQword 502 RegQueryStr 503 

CONTENTS

xi

RegQueryValue 504 RegSetBin 505 RegSetDword 506 RegSetEx 506 RegSetExpSz 507 RegSetMulSz 509 RegSetQword 509 RegSetValue 510 RegUnloadHive 511 Reload {*M} 512 Return 512 RtStatus 513 Run 514 RunEnviron 515 RunHide 516 RunHideWait 517 RunIcon 518 RunIconWait 518 RunShell 519 RunWait 520 RunWithLogon 521 RunZoom 525 RunZoomWait 526 Select 527 SendKey 528 SendKeysChild 532 SendKeysTo 533 SendMenusTo 533 SendMessageA 534 SendMessageW 535 ShellExecute 536 ShortcutDir 537 ShortcutEdit 540 ShortcutExtra 541 ShortcutInfo 543 ShortcutMake 544 Sin 545 Sinh 546 SnapShot 547 Sounds 548 SoundVolume 548 Sqrt 549 StrByteCount 549 StrCat 550 StrCharCount 551 StrClean 551 StrCmp 552 StrCnt 553 StrFill 554 StrFix 555 StrFixBytes 556 StrFixBytesL 556 

CONTENTS

xii

StrFixChars 557 StrFixCharsL 558 StrFixLeft 558 StriCmp 559 StrIndex 560 StrIndexNc 561 StrIndexWild 562 StrInsert 562 StrLen 563 StrLenWild 564 StrLower 564 StrOverlay 565 StrReplace 566 StrScan 566 StrSub 567 StrSubWild 568 StrTrim 569 StrTypeInfo 569 StrUpper 571 Switch 572 SysParamInfo 573 Tan 574 Tanh 574 Terminate 575 TerminateApp 576 TimeFunctions 577 TimeAdd 578 TimeDate 578 TimeDayofWeek 579 TimeDelay 579 TimeDiff 580 TimeDiffDays 581 TimeDiffSecs 581 TimeJulianDay 582 TimeJulToYmd 583 TimeSubtract 583 TimeWait 584 TimeYmdHms 584 UacElevationLevel 585 UacExePromptTest 586 UacManifestSettings 587 VarType 587 Version 589 VersionDLL 589 WaitForKey 590 WaitForKeyEx 592 WallPaper 593 While 593 WinActivate 594 WinActiveChild 595 WinArrange 596 WinClose 596 

CONTENTS

xiii

WindowOnTop 597 WinExeName 597 WinExist 598 WinExistChild 599 WinGetActive 600 WinHelp 600 WinHide 602 WinIconize 603 WinIdGet 604 WinIsDOS 604 WinItemChild 605 WinItemize 606 WinItemizeEx 606 WinItemNameId 607 WinItemProcId 608 WinMetrics 609 WinName 612 WinPlace 612 WinPlaceChild 613 WinPlaceGet 614 WinPlaceSet 615 WinPosition 616 WinPositionChild 617 WinResources 618 WinShow 619 WinState 619 WinSysInfo 620 WinTitle 621 WinVersion 622 WinWaitChild 624 WinWaitClose 625 WinWaitExist 626 WinWaitReady 627 WinZoom 627 Yield 628 Yields 628 

MENU FILES 631 About Menu Files 631 How Menu Files are used 631 Menu File Structure 631 Modifying Menus 635 Menu Hotkeys 635 Menu Items 636 

APPENDIX Constants 639 Predefined Constants 639 String Constants 640 Floating Point Constants 640 

INDEX 642 

INTRODUCTION

15

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

INTRODUCTION

16

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

INTRODUCTION

17

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.

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.

{*Explorer} For use with the Microsoft Explorer.

{*M} menu-based implementations of WIL Interpreter.

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.

WIL TUTORIAL

19

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. 83, 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.

WIL TUTORIAL

20

from macros in word processors and spreadsheets.

from a command line entry such as "Run..." from the Explorer Start button.

by double clicking.

from menu items via the FileMenu and PopMenu utilities.

from other WIL scripts to serve as single or multiple "agents", event handlers, or schedulers.

from any Windows application or application macro language that can execute another Windows program. Software suite macro languages and application builders like Visual Basic and PowerBuilder are examples of these.

Command Line Parameters WIL utilities run like any other Windows program. They can be

run from a command line, a shortcut or an icon in a shell program like the Windows Explorer, or a Start menu selection.

WIL utilities are usually run as files with the extension .WBT. When some WIL utilities are used, they need information passed to them when they run. This is easily done by passing command line parameters to them.

This capability can be used from the command line in the Start|Run menu.

Parameters can be also be passed through the command line entry included in the item properties of any shortcut icon. Finally, an application can send parameters to a WIL utility it launches from a command line or from a function in a macro language.

A command like this runs a WinBatch system utility from a command line or a shortcut icon.

Command line:

Winbatch.exe filename.wbt p1 p2... p[n]

This command line can be entered into a Command Line text entry box like this one:

W

What is a

"filename.parameter

"p1 p2 ... pfile on starcharacter.

Parameterinto variabutility willgives you

WIL ProgA WIL procommandsrun more tcommandscandidate suppose yoWindows:

First:

cd \win

then:

win

and then:

cd \

Here, you Windows,having to Windows,which con

.wbt" is any va.

p[n]" are optiortup. Each is d

rs passed to a Wbles named parl be able to usethe total numb

gram? ogram, like a Ds for the computhan once, or ws or even a singfor automationou regularly en:

ndows

are changing t, and then returtype these thre, you can createntains those exa

W

alid WBT file,

nal parameterselimited from t

WBT file will bram1, param2e these. An addber of comman

DOS batch fileuter to process

which requires gle complex con as a WIL pronter the followi

to the Windowrning to the rooee commands ee a DOS batch act same comm

WIL TUT

and is a requir

s to be passed tthe next by one

be automaticall2, etc. The Winditional variabld-line paramet

, is simply a liss. Any task whientering multipommand, is a ggram. For examing commands

ws directory, runot directory. Inevery time you

file, called WImands:

TORIAL

21

red

to the WBT e space

ly inserted nBatch le, param0, ters.

st of ich will be ple good mple, s to start

nning nstead of

run I.BAT,

WIL TUTORIAL

22

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. 631) 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:

Run("sol.exe", "")

Save the program, 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("sol.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

WIL TUTORIAL

23

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. 83). The entry for Run starts off as follows:

Syntax: Run(program-name,parameters)

Parameters: (s) program-name the name of the desired .EXE, .COM,

.PIF, .BAT file, or a data file. (s) parameters 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("sol.exe", "")

Notes: 1. Strings are delimited by quotes, ("", "")

2. '(s)' denotes the parameter requires a string.

"sol.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.

Solitaire, for example, does not take parameters. The way we

WIL TUTORIAL

24

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.

Example 2 1. Open Notepad.

2. Type in the line.

3. Save the file as notetest.wbt.

4. Close Notepad

5. Run the wbt by double-clicking on the filename.

To illustrate this further, let's create a WIL program containing the following line:

Run("notepad.exe", "")

This is just like our previous file, with only the 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")

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 semi-colon. For example:

Run("sol.exe", "") ;this is 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.

D

Tc1

2o

3

4li

5

6do

Displaying

Tutor Examplecontinued... 1. Exit Solitaire.

2. Activate or open your editor

3. Load tutor.wb

4. Add the new ines.

5. Save the file.

6. Run the wbt bydouble-clicking on the filename.

g Text

e

.

t.

y

Now, let's

; solitDisplayRun("so

And run itscreen wit

That's donHere's the

Syntax:

Display

Paramete(i) secon(s) title(s) text

The Displthe numbescreen (yoany key orunlike striquotes (alttry to convnecessary,displayingtitle of thedisplayed

Note: In ofront of a pthat it is anparameterreference athe functio

modify our or

tare.programy(5,"Good Lucol.exe", "")

t. Notice the litth words of enc

ne by the Displreference for D

(seconds, title

ers: nds

ay function haer of seconds wou can make thr mouse buttonng constants —though it can bvert string vari, and vice versag the box for 5 e message box,in the box.

our shorthand mparameter indin integer, (f) in, (a) indicates and (t) indicateon’s text.

W

riginal WIL pro

ck!","Remembe

ttle dialog box couragement:

lay function in Display:

e, text)

seconds to disTitle of the wiText of the wi

as three paramewhich the displae box disappea

n). This is a nu— it does not nebe, if you wish,ables to numera). In our examseconds. The s and the third p

method for indicates that it is ndicates a floatan array, (r) ines special type

WIL TUT

ogram as follow

er … it's onl

which pops up

the second lin

splay the messaindow to be disindow to be dis

eters. The first ay box will remar before then bmeric constaneed to be enclo, as WIL will aric variables wh

mple above, wesecond parameparameter is th

dicating syntax a string. An (i)ting point numbndicates a COM

information d

TORIAL

25

ws:

ly a game")

p on the

ne above.

age (1-3600). splayed. splayed.

parameter is main on the by pressing nt, and — osed in automatically hen

e are eter is the he actual text

the (s) in ) indicates ber

M object described in

WIL TUTORIAL

26

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.

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:

; solitare.program Display(5,"Good Luck","Remember … it's only a game") ; Run("sol.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 title of the question box. (s) question question to be put to the user.

Returns: (i) @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.

You will notice that there is also a new section here, called

WIL TUTORIAL

27

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.639). 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.)

Tutor Example continued... 1. Edit tutor.wbt -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.

Now, let's modify our WIL program as follows:

AskYesNo("Really?", "Play Solitaire now?") Run("sol.exe", "")

and run it. You should have gotten a nice dialog box which asked if you wanted to play Solitaire:

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

WIL TUTORIAL

28

explore the concept and use of variables.

Using Variables

Tutor Example continued... 1. Exit Solitaire.

2. Edit tutor.wbt -Add variable name.

3. Save the file.

4. Run the wbt by double-clicking on the filename.

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

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.

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.

WIL TUTORIAL

29

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("sol.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("sol.exe", "")

Experiment with In this example, we are using If ... Then to test whether the

WI

30

additistructu

IL TUTO

onal If ures.

vSfvcz

Taeae

A

TAs

wwdTvpm

ORIAL

value of the vaSolitaire. If it ifollowing the Ivalue, then thecondition follozero value, the

There is sometabout the syntaequal signs (==assignment opequal sign to th

As in:

response=As

This is saying, AskYesNo funstatement:

If response

we do not wanwant to test whdouble equal siThe statement variable namedprogram SOL.Emistake, you w

ariable responsisn't @YES, wIf keyword is tre statement(s) fowing the If keen the statemen

thing extremelyax of these If ..=). In WIL, a sperator — it ahe variable on

skYesNo("Real

in English: "Anction to the va

e == @YES The

nt to assign a nehether it is equaigns (==), whicabove is sayin

d response is eEXE." If you u

would get an er

se is @YES. Ifwe don't. The ru

rue or works ofollowing are pyword is false

nt(s) following

y important tha.. Endif commsingle equal sigssigns the valuthe left of the e

lly?", "Play

Assign the valuariable named r

en Run("sol.e

ew value to resal to @YES. Tch is the equalg, in English: "

equal to @YESused a single eqrror message:

f it is @YES, wule is: if the conout to a non-zerperformed. If th

or works out tare ignored.

at you should nmands: the doubgn (=) is an ue on the right oequal sign.

Solitaire n

ue returned by tresponse." But

exe", "")

sponse, we meTherefore, we ulity operator i"If the value ofS, then run the qual sign (=) h

we start ndition ro he to a

note ble

of the

now?")

the ut in the

erely use the in WIL. f the

here by

WIL TUTORIAL

31

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("sol.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("sol.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 response==@YES Then Display(5,"","On your mark") If response==@YES Then Display(5,"", "Get set ...") If response==@YES Then Display(5, "", "Go!") If response==@YES Then Run("sol.exe", "") If response==@NO Then Display(5,"","Game canceled")

WIL TUTORIAL

32

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("sol.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)

Tutor Example continued...

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 amount of time entered.

1(I

2Athsfi

3do

1

2tos

mm S

1. Exit Solitaire. (If it is running.)

2. Edit tutor.wbt Add AskLine to he top of the

script.Save the file.

3. Run the wbt bydouble-clicking on the filename.

1. Exit Solitaire.

2. Edit tutor.wbt o add the Switch

statement.

mins = AskLinmins = Int(mi

Switch mins case 0

Displaexit break

case 1 Messagbreak

case 2 Messagbreak

case 3 Messagbreak

case 4 Messagbreak

-

y

Switch, asmultiple ba case.

In the folloSelection ominutes st

If the numaccounted

Type the fstatement running it

h Your

ne("Solitaireins)

ay(5, "", "G

ge("Only a m

ge("2 Minute

ge("3 Minute

ge("HA,HA,HA

s you remembeblocks of statem

owing sample,of one of the ctored in the var

mber is 3, then cd for will be exe

following codeby entering a nseveral times u

code should lo

e","How many

ame canceled

inute?", "Wo

s?", "This i

s?", "You've

", "I dare

W

er, allows selecments. Each blo

there are seveases is determiriable mins.

case 3 will be eecuted by the d

e into tutor.wbnumber into thusing various n

ook like the fol

statements.

mins do you

d")

w! You've go

sn't much of

barely got

you to try t

WIL TUT

ction from amoock of statemen

eral case statemined by the num

executed. All ndefault case, m

bt. Test the Swie AskLine dianumbers.

llowing. Remo

want to play

ot willpower.

f a break.")

time to shuf

to beat me.")

TORIAL

33

ong nts is called

ment blocks. mber of

numbers not mins.

itch alog box. Try

ove extra

y?","",0)

")

ffle")

WIL TUTORIAL

34

case mins ;default case - must be last in the switch Message("THAT LONG!!!", "Where did you get all that time?") break EndSwitch Run("sol.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.

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.

First let’s set up a couple of variables.

goal = mins * 60 timer = 0

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.

WIL TUTORIAL

35

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.

We can give ourselves the opportunity To add more time by adding another Askline statement.

mins=AskLine("More Time?","Enter additional minutes.", 0, 0)

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.

WIL TUTORIAL

36

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("sol.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

WIL TUTORIAL

37

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.

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.

Run("sol.exe","") 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

WIL TUTORIAL

38

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. 83).

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, parameters) 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, parameters) RunZoom is like Run, but starts a program as a full-screen window.

WIL TUTORIAL

39

Example: RunZoom("excel", "bigsheet.xls")

RunIcon (program-name, parameters) 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, parameters) 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, parameters) RunZoomWait starts a program as a full screen window and waits for it to exit before continuing.

RunIconWait (program-name, parameters) 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,parameters,target dir,view,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,parameters,target dir, display mode, operation)

Runs a program via the Windows ShellExecute command.

WIL TUTORIAL

40

Display and Input Here we have functions which display information to the user and prompt the user for information, plus a couple of relevant system functions.

Display (seconds, title, text) Displays a message to the user for a specified period of time. The message will disappear after the time expires, or after any keypress or mouse click.

Example: Display(2, "Please Wait", "Loading Solitaire Now")

Message (title, text) This command displays a message box with a title and text you specify, which will remain on the screen until the user presses the OK button.

Example: Message("Sorry", "That file cannot be found")

Pause (title, text) This command is similar to Message, except an exclamation-point icon appears in the message box, and the user can press OK or Cancel. If the user presses Cancel, the WIL program ends (or goes to the label :cancel, if one is defined).

Example: Pause("Delete Backups", "Last chance to stop!") ; if we got this far, the user pressed OK FileDelete("*.bak")

WIL TUTORIAL

41

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)

WIL TUTORIAL

42

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.

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

WIL TUTORIAL

43

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 SOLITARE.WBT in a Notepad window, the windowname will be Solitaire.wbt - Notepad.

You probably don't want to have to hard-code this entire name into your WIL program as:

WinZoom("Solitaire.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.

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("Sol")

would be correct,

WinZoom("Notepad")

would not result in a match.

Also, the case (upper or lower) of the title is significant, so

WinZoom("solitare")

WIL TUTORIAL

44

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("sol.exe", "")

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("sol.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:

WIL TUTORIAL

45

If WinExist("~Solitaire") == @TRUE WinActivate("Solitaire") Else Run("sol.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("sol.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.

Note: For additional methods of rebooting or restarting Windows, see IntControl(66,…) , IntControl(67,…) and IntControl(68,…).

Files and Directories

DirChange (pathname) 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", "")

WIL TUTORIAL

46

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")

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")

WIL TUTORIAL

47

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") Exit

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

WIL TUTORIAL

48

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") Exit

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.

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.

WIL TUTORIAL

49

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) a = FileCopy(file1,file2,@FALSE) ErrorMode(@CANCEL) if a == @TRUE Message("Info", "Copy worked") else Message("Error", "Copy failed") endif

WIL TUTORIAL

50

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("", "Enter Filename to edit?", "", 0) Run("notepad.exe", file)

This will prompt for a filename, and run Notepad on that file:

WIL TUTORIAL

51

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 [, selection-required] )

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.

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.DOC{TAB}FILE2.DOC{TAB}FILE3.DOC

WIL TUTORIAL

52

When we use AskItemList, we need to tell it that the delimiter is a TAB. We do this as follows:

files = FileItemize("*.doc|*.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. 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,

WIL TUTORIAL

53

@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 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

WIL TUTORIAL

54

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

WIL TUTORIAL

55

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

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

WIL TUTORIAL

56

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:

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 COMMAND.COM 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.

WIL TUTORIAL

57

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. 528). 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:

Here's another example:

RunZoom("sol.exe", "") SendKeysTo("Solitaire", "!gc{RIGHT}{SP}~")

This starts up Solitaire, brings up the Game menu (!g), and selects Deck (c) from that menu:

Then it moves the cursor to the next card back style on the right ({RIGHT}), selects that card back ({SP}), and then selects OK (~). The tilde sign (~) is SendKey shorthand for the Enter key.

WI

58

A

OurHere buildi

It incsome sectio

It canto you

If yousampwell o

; tmin"5"

IL TUTO

And voila! A d

r Completis the final woing throughout

orporates many arithmetic ( *,

on on the WIL

n also be improu.

u can understanle file, and canon your way to

tutor.wbt ns = AskLine(", 0)

ORIAL

ifferent card de

ted WIL Forking version ot this tutorial.

y of the concep, -, +, / ) and re Language (pg

oved and custom

nd and follow tn begin to incoro becoming a tr

ClubhoCongra

Let's tawritingpolish your ex

("Solitaire",

esign every tim

File of the WIL pro

pts that we've delational (<) opg. 83).

mized in a num

the structures arporate them inrue WIL guru!

ouse atulations! You

ake a look at thg, tutor.wbt. Ait up, but the mxample.

, "How many m

me you play!

ogram that we'v

discussed so faperators that ar

mber of ways, b

and processes into your own W

u've finished th

he completed scA few things hamajority of the

mins do you w

ve slowly been

ar, as well as use covered in th

but we'll leave

illustrated in thWIL programs,

he course.

cript we've beeave been addedcode should m

want to play?

n

sing he

that up

his , you are

en d to match

?",

WIL TUTORIAL

59

mins = Int(mins) Switch mins case 0 Display(5, "", "Game canceled") 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("sol.exe", "") Endif for i = 0 to 9 j=100-i*10 k=300+i*70 WinPlace(j,j,k,k,"Solitaire") next WinZoom("Solitaire") ;;ADDED to show an example of sending keystrokes. SendKeysTo("Solitaire", "!gc{RIGHT}{SP}~") 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

WIL TUTORIAL

60

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") WinTitle("Solitaire", "Solitaire (%remain% seconds left)") else exit endif TimeDelay(10) timer = timer + 10 EndWhile Return

THINGS TO KNOW

61

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 (s) name of the currently-executing script

wberrortextstring (s) description of the WIL error

wberroradditionalinfo (s) delimited string of additional error information, if any. ASCII 160 is delimiter character between each error incident.

wberrorinsegment (s) name of the Currently-executing UDF, or a blank string ("") if not in a UDF.

wberrorhandlerlinenumber (i) line number in the currently executing script or 0 if the cancel cannot be matched to a particular line.

wberrorarray (a) WIL array with the following elements: wberrorarray[0] = LastError() wberrorarray[1] = wberrorhandlerline wberrorarray[2] = wberrorhandleroffset wberrorarray[3] = wberrorhandlerassignment wberrorarray[4] = wberrorhandlerfile

THINGS TO KNOW

62

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

THINGS TO KNOW

63

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

THINGS TO KNOW

64

Message("Password","Successfully changed") else Message("Password","Not changed") 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.

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.

THINGS TO KNOW

65

Initialize debug by adding DebugTrace(@ON,"trace.txt") to a specific point in your script.

Note: For specific instructions see DebugTrace, in the WIL Function Reference. (pg. 200).

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. 372 )

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

THINGS TO KNOW

66

a window title of "My Notepad Application", as well as a window title of "Notepad - (Untitled)".

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.152) 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= " "

THINGS TO KNOW

67

a19= "To dig your code out of this trap, simply use floating point" a20= "numbers when you want a floating point answer." a21 = " " 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

THINGS TO KNOW

68

FileAttrSet FileCopy FileDelete FileItemize FileMove FileRename FileSize FileSizeEx FileTimeSet FileTimeTouch

Note: DiskFree and DiskSize continue to accept space-delimited lists as input.

Sounds If you have Windows Multimedia extensions, and hardware capable of playing WAV waveform files, there can be sounds audible at various points in the execution of WIL programs. By default, these sounds are disabled.

You can also use the Sounds function to turn sounds on and off from within a WIL program.

WIL LANGUAGE

69

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

WIL LANGUAGE

70

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 @TRUE @NO @YES @STACK @TILE A list of all the predefined constants can be found in the Appendix (pg. 639).

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:

WIL LANGUAGE

71

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.

WIL LANGUAGE

72

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

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.

WIL LANGUAGE

73

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.

ItemExtract ( index, list, delimiter ) Returns the selected item from a list.

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:

Beep DirChange @Yes FileCopy

Operators

WIL LANGUAGE

74

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 == Equality != or <> Inequality

Assignment operator = Assigns evaluated result of an expression to a variable

Precedence and Evaluation Order

WIL LANGUAGE

75

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 && || Logical 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

WIL LANGUAGE

76

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 While For ForEach Beep Case Yield Switch EndSwitch Continue Next Endwhile Break Select EndSelect Return Goto GoSub If Else ElseIf Then EndIf

Function Parameters Most of the functions and commands in the language require parameters. These come in several types:

Array Integer Floating point number 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:

WIL LANGUAGE

77

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 User-Defined-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:

#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

WIL LANGUAGE

78

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.

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

WIL LANGUAGE

79

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

If you want to debug the User-Defined-Function, then the debug function (Debug or Debugtrace), must be defined within the User-Defined-Function

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-Defined-Function 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 = StrCat("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)

WIL LANGUAGE

80

ret = FileCopy("C:\zippideedodah.txt","C:\temp\zippideedodah.txt",@FALSE) ErrorMode(@cancel) errtime = LogErrors(LastError()) Message("Last error logged at",errtime) exit

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]

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:

WIL LANGUAGE

81

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, Arrayize, ArrayLocate, ArrayRedim, ArrayRemove, ArraySearch, ArraySort, ArraySwapElements, ArrayToStr, ArrDimension, ArrInfo, ArrInitalize

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.

WIL LANGUAGE

82

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. 393).

Introduction

83

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.

{*Explorer} For use with the Microsoft Explorer.

{*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) 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.

Abs

84

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

AddExtender

85

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 64-

bit 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 "[ ]". When a function takes a variable number of parameters, the variable parts will be followed by ellipses ("...").

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

AddExtender

86

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 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 32-bit 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. Note that 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

AppExist

87

if speed < 66 BillBoard("Slow Down") ; Tooooo fast 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 name of a Windows EXE or DLL file. (i) flags [optional] a bitmask of values that may be combined using

the bitwise OR ('|')operator. See below. (i) retries [optional] number of retries.

Returns: (i) @TRUE if the specified application is running; @FALSE

if the specified application is not running.

Flags

The following values may be specified:

Value Meaning

1 current-session-only.

2 "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

AppWaitClose

88

extension or path information which is part of the 'program-name' parameter is ignored; so, for example,

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")==@FALSE 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 name of a Windows EXE or DLL file. (i) flags [optional] a bitmask of values that may be combined using

the bitwise OR ('|')operator. See below. (i) retries 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).

Returns: (i) @TRUE if the specified application is running; @FALSE

if the specified application is not running.

Flags

The following values may be specified:

Value Meaning

ArrayFileGet

89

1 current-session-only.

2 "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 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 path and file name of the file.

ArrayFileGetCsv

90

(s) null-char [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.

(i) extra-alloc [optional] specifies the number of additional elements to add to the end of the array. If omitted, it will be 0.

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, Arrayize, ArrayLocate, ArrayRedim, ArrayRemove, 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 path and file name of the file. (i) flags see below. (s) delimiter [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.

(i) extra-rows [optional] specifies the number of additional elements to add to the end of dimension 1 of the array. If omitted, it will be 0.

(i) extra-columns [optional] specifies the number of additional elements to add to the end of dimension 2 of the array. If omitted, it will be 0.

Returns: (a) a two dimensional array.

ArrayFilePut

91

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 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 Meaning

1 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, Arrayize, ArrayLocate, ArrayRedim, ArrayRemove, 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])

ArrayFilePutCsv

92

Parameters: (s) filename path and file name of the file to create. (a) array specifies an array. (i) write-undef [optional] see below.

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, 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 path and file name of the file to create. (a) array specifies an array. (s) delimiter [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.

(i) write-undef [optional] see below. (i) flags [optional] see below.

ArrayFromStr

93

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 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 Meaning

2 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, 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)

ArrayInsert

94

Parameters: (s) string string of characters to convert to an array.

Returns: (a) array a one dimensional array.

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.') Exit

See Also: Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv, ArrayFromStr, ArrayInsert, 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 in-place insertion of a row or column into a two dimension array.

Syntax: ArrayInsert(array,sub[,dim[,value]])

Parameters: (a) array specifies an array. (i) sub subscript of the element to insert into single dimension

array. Subscript of the row or column to insert into a two dimension array.

(i) dim [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.

(u/s/i/f) value [optional] initial value of inserted element(s).

Returns: (i) returns @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'

Arrayize

95

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) Exit

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)

Parameters: (s)list delimited list. (s)delimiter 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, Arrayize, ArrayLocate, ArrayRedim, ArrayRemove, ArraySearch, ArraySort, ArraySwapElements, ArrayToStr, ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop

ArrayLocate

96

ArrayLocate Searches an array for an element that matches a value.

Syntax: ArrayLocate(array,value[,sub1[,sub2[,sub3[,sub4[,sub5]]]]])

Parameters: (a) array specifies an array. (s) value case sensitive value to search for in "array". (i) sub1 [optional] subscript of first element (dimension 1) to search.

The default is zero. (i) sub2 [optional] subscript of first element (dimension 2) to search

The default is zero. (i) sub3 [optional] subscript of first element (dimension 3) to search.

The default is zero. (i) sub4 [optional] subscript of first element (dimension 4) to search.

The default is zero. (i) sub5 [optional] subscript of first element (dimension 5) to search.

The default is zero.

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) Exit

See Also: Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv, ArrayFromStr, ArrayInsert, Arrayize, ArrayLocate, ArrayRedim, ArrayRemove, ArraySearch, ArraySort, ArraySwapElements, ArrayToStr, ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop

ArrayRedim

97

ArrayRedim Changes array dimensions in-place.

Syntax: ArrayRedim(array,dim[,dim2[,dim3[,dim4[,dim5]]]])

Parameters: (a) array array to re-dimension. (i) "dim1"- "dim5" 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: (i) 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 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 array: ArrayRedim(array1, 10) 2-dimension array: ArrayRedim(array2,10, 10) 3-dimension array: ArrayRedim(array3, 10, 10, 10) 4-dimension array: ArrayRedim(array4, 10, 10, 10, 10) 5-dimension array: 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 ) )

ArraySearch

98

See Also: Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv, ArrayFromStr, ArrayInsert, Arrayize, ArrayLocate, ArrayRedim, ArrayRemove, 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 specifies an array. (s) value value to search for in "array". (i) options [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.

(i) search-column [optional] subscript of column to search for two- dimensional arrays. The default is zero. Always use zero when searching one dimensional arrays.

(i) start-sub [optional] subscript of first element or row to include in search. The default is zero.

(i) end-sub [optional] subscript of last element or row to include in search. The default is ArrInfo(array,1)-1.

Returns: (i) index 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.

Multidimensional arrays in WinBatch use 'Row Major' format. For example:

ArraySort

99

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) Exit

See Also: Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv, ArrayFromStr, ArrayInsert, Arrayize, ArrayLocate, ArrayRedim, ArrayRemove, 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 array to sort. (i) options [optional] @ASCENDING for an ascending sort (the

default) or @DESCENDING for a descending sort. (i) sort-column [optional] subscript of column to sort on for two-

dimensional arrays. The default is 0. Always use 0 for one dimensional arrays.

(i) start-sub [optional] subscript of first row to include in sort. The default is 0.

(i) end-sub [optional] subscript of last row to include in sort. The default is ArrInfo(array,1) - 1

Returns: (i) 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.

ArraySwapElements

100

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 ) Exit

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 specifies an array. (i) subA1 subscript (dimension 1) of element 'A' or zero. (i) subA2 subscript (dimension 2) of element 'A' or zero. (i) subA3 subscript (dimension 3) of element 'A' or zero. (i) subA4 subscript (dimension 4) of element 'A' or zero. (i) subA5 subscript (dimension 5) of element 'A' or zero. (i) subB1 subscript (dimension 1) of element 'B' or zero. (i) subB2 subscript (dimension 2) of element 'B' or zero. (i) subB3 subscript (dimension 3) of element 'B' or zero. (i) subB4 subscript (dimension 4) of element 'B' or zero. (i) subB5 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".

ArrayToStr

101

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, Arrayize, ArrayLocate, ArrayRedim, ArrayRemove, 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.') Exit

See Also: Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv, ArrayFromStr, ArrayInsert, Arrayize, ArrayLocate, ArrayRedim, ArrayRemove, ArraySearch, ArraySort, ArraySwapElements, ArrayToStr, ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop

ArrDimension

102

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: array1 = ArrDimension(10) 2-dimension array: array2 = ArrDimension(10, 10) 3-dimension array: array3 = ArrDimension(10, 10, 10) 4-dimension array: array4 = ArrDimension(10, 10, 10, 10) 5-dimension array: 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."

ArrInfo

103

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, Arrayize, ArrayLocate, ArrayRedim, ArrayRemove, ArraySearch, ArraySort, ArraySwapElements, ArrayToStr, ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop

ArrInfo Gets information about an array.

Syntax: ArrInfo(array,request)

ArrInitialize

104

Parameters: (a) array specifies an array. (i) request a flag specifying the information to retrieve (see below).

Returns: (i) depends on request.

Request Returns

-1 checks if array is valid. Returns @TRUE if valid, @FALSE if invalid.

0 number of dimensions in the array

1 number of elements in dimension 1

2 number of elements in dimension 2 (or 0 if unused)

3 number of elements in dimension 3 (or 0 if unused)

4 number of elements in dimension 4 (or 0 if unused)

5 number of elements in dimension 5 (or 0 if unused)

6 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, Arrayize, ArrayLocate, ArrayRedim, ArrayRemove, ArraySearch, ArraySort, ArraySwapElements, ArrayToStr, ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop

ArrInitialize Initializes an array.

Syntax: ArrInitialize(array,value)

Parameters: (a) array specifies an array. (i/f/s) value specifies an integer, floating point, or string value.

Returns: (i) always @TRUE.

This function sets all elements of "array" to "value".

ArrRemove

105

Example: myarray=ArrDimension(1,0,0,0,0) ArrInitialize(myarray, 0) message("Array","Initialized")

See Also: Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv, ArrayFromStr, ArrayInsert, Arrayize, ArrayLocate, ArrayRedim, ArrayRemove, ArraySearch, ArraySort, ArraySwapElements, ArrayToStr, ArrDimension, ArrInfo, ArrInitalize, ArrRemove, Drop

ArrRemove 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 the array in which to remove an element, row, or column. (i) sub 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.

(i) dim [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: (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('Element Count',ArrInfo(array,1)) ; Remove the first element ArrayRemove(array,0) Pause('Element Count',ArrInfo(array,1))

Asin

106

Exit ;------------------------------------------------------ ; 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)) Exit ;------------------------------------------------------ ; 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)) exit

See Also: Arrays, ArrayFileGet, ArrayFileGetCsv, ArrayFilePut, ArrayFilePutCsv, ArrayFromStr, ArrayInsert, Arrayize, ArrayLocate, ArrayRedim, ArrayRemove, 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.

AskColor

107

Example: real=AskLine("ArcSin", "Enter a real number between -1 and 1", "0.5",0) 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 specifies an RGB color value in the form "#RRGGBB". (s) reg-key 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.

(i) format specifies the format in which the selected color will be returned. See below.

Returns: (s) 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)

AskDirectory

108

See Also: AskFont

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

(s) browse-root 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.

(s) start-dir 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').

(s) confirm-prompt The title of the confirmation message box (see 'flags' #2, below).

(i) flags One or more of the optional flags (see below), combined using the binary OR ("|") operator, or 0 if none are desired.

Returns: (s) the string containing the directory path selected in the

browse dialog. If the user presses "Cancel", standard WIL ":cancel" processing will be performed.

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

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

AskDirectory

109

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) exit

Ask

110

and th

See AAskF

AskRetur

SyntaAsk

Param(s) (s) (s)

kFileName

hen:

Also: FileText, AskIte

kFileNarns the filenam

ax: kFileName(titl

meters: title directory filetypes

e

emList, AskLin

ame me as selected b

le,directory,file

title of thinitial drifile type s

ne, AskFileNa

by a File Open

etypes,default f

he file name selive and directoselection defin

me

dialog box.

filename,flag)

lect box. ry.

nition (see below).

AskFileName

111

(s) default filename default filename or mask. (i) flag 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.

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/7] Save style *

101 [Vista/7] Open style *

102 [Vista/7] Open style, allowing multiple files to be selected.* / **

103 [Vista/7] Save style, with no "Replace" confirmation.*

* Vista/Windows 7 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

Ask

112

Windolder

** If select

The cAskFcan bpoten

IMPOthe se

Examtypfn1Mes

which

and th

kFileName

dows predatingcommon file d

the "flag" spected), the select

combined file nFileName dialoe selected is lim

ntial number of

ORTANT: Aselected file.

mple: pes="All File1=AskFileNamessage("File s

h produces:

hen:

e

g Vista, the adddialog style.

cified is 2 or 10ed files will be

names selectedog will be re-dimited. Do not f files to be sele

skFileName ch

es|*.*|WIL Fie("SelectFileselected was"

ded 100 is igno

02 (Open Stylee returned as a

d cannot exceedisplayed. In othuse this functioected, could ex

hanges the cur

iles|*.wbt;*.e", "C:\WinBa", fn1)

red and the fun

e, allowing muldelimited list.

d 2048 characteher words, the on to select muxceed this maxi

rrent working

.mnu|Text Filatch", types,

nction reverts t

ltiple files to b

ers, otherwise number of file

ultiple files, if timum.

g directory to t

les|*.txt|", "Sol.wbt",

to the

be

the es that the

that of

1)

AskFileText

113

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 title of the list box. (s) filename path and filename of file to display. (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).

AskFont

114

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. (i) flags restricts the fonts that are listed. (s) reg-key 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.

(i) format specifies the format in which the selected font will be returned. See below.

Returns: (s) 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

AskFont

115

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 Meaning 0 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. 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 Meaning 256 The font weight is bold 512 The italic font attribute is set 1024 The font weight is normal 8192 The font is a screen font 16384 The font is a printer font 32768 The font is simulated by the graphics device interface (GDI)

Example: type=0 flags=0 customkeyword="test" format=0

AskItemList

116

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 title of the list box. (s) list variable a string containing a list of items. (s) delimiter a character to act as a delimiter between items in the list. (i) sort mode @sorted for an alphabetic list. @unsorted to display the list of items as is. (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.

AskLine

117

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:

See Also: AskFileText, AskFileName, AskDirectory

AskLine Prompts the user for one line of input.

Syntax: AskLine(title,prompt default[,format])

Parameters: (s) title title of the dialog box. (s) prompt question to be put to the user. (s) default default answer. (i) format [optional] specifies the format of the returned string.

AskLine

118

Returns: (s) user response.

'Format' specifies the format of the returned string.

Format Meaning 0 ANSI string (default) 1 Unicode string 2 hex string, with four hex bytes per Unicode character.

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:

AskTextBox

119

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 title of the dialog box. (s) prompt 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 exit

See Also: AskLine, AskYesNo, Dialog, AskDirectory

AskTextBox Prompts the user for multiple lines of input.

AskYesNo

120

Syntax: AskTextBox(title,prompt,default,flags,reserved)

Parameters: (s) title title of the dialog box. (s) prompt question to be put to the user. (s) default default answer. (i) flags see below. (i) reserved 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 Meaning

0 none of the following apply

1 do not automatically wrap text

2 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 exit

See Also: AskLine, AskYesNo, Dialog

AskYesNo Prompts the user for a Yes or No answer.

Atan

121

Syntax: AskYesNo(title,question)

Parameters (s) title title of the question box. (s) question 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"') exit

produces:

... and then, if the user presses No:

See Also: AskLine, AskPassword, Dialog, Display, AskItemList, Message, Pause, AskFileText

Atan Calculates the arc tangent.

Syntax: Atan(x)

Parameters: (f) x floating point number whose arc tangent is desired.

Beep

122

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.

Syntax: Beep

Parameters: (none)

Returns: (not applicable)

BinaryAlloc

123

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 re-combined 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), 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.

BinaryAllocArray

124

Syntax: BinaryAlloc(size)

Parameters: (i) size size in bytes of the desired memory buffer.

Returns: (i) 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

BinaryAllocArray Allocates a memory buffer and copies the contents of an array.

Syntax: BinaryAllocArray(array)

BinaryAllocArray

125

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 Value to specify

I1 A 1-byte integer value

I2 A 2-byte integer value

I4 A 4-byte integer value

I8 A 8-byte integer value

UI1 A 1-byte unsigned integer value

UI2 A 2- byte unsigned integer value

UI4 A 4- byte unsigned integer value

UI8 A 8- byte unsigned integer value

R4 32-bit IEEE floating point value.

R8 64-bit IEEE floating point value.

BOOL A Boolean (True/False) value

CY A currency value, specified as a string in the form "#CURRENCY:value".

DATE A date/time value, specified as a string in Ymd or YmdHms format

UI1 1-byte unsigned integer.

UI2 2-byte unsigned integer.

UI4 4-byte unsigned integer.

INT 4-byte signed integer value (equivalent to I4).

UINT 4-byte unsigned integer (equivalent to VT_UI4).

DECIMAL A decimal value, specified as a string in the form "#DECIMAL:value".

You can use the ObjectTypeGet function to determine the type of a COM array element.

BinaryAnd

126

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

BinaryAnd Performs a bitwise AND on portions of two binary buffers.

BinaryAnd

127

Syntax: BinaryAnd(target-handle,target-offset,source-handle,source-offset,count)

Parameters: (i) target-handle handle of target buffer. (i) target-offset 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.

(i) source-handle handle of source buffer. (i) source-offset zero-based offset into the source buffer specifying where

the data to be processed starts. (i) count the number of bytes to process.

Returns: (i) 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 "source-offset" 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) ; this stuffs 5's into buf1 BinaryPoke(buf2, i, 6) ; this stuffs 6's into buf2 next rc = BinaryAnd(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 ; you can write it out with BinaryWrite binaryWrite(buf2, "zzbin2.txt") ; AND LOGIC: ; 5 = 0101 ; 6 = 0110 ; ========

BinaryCheckSum

128

; 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 handle of binary buffer. (i) request -1,0,1, or 2. see below.

Returns: (i) depends on request.

Request Description

-1 Checks if binary buffer handle is valid. Returns @TRUE if valid, @FALSE if invalid.

0 Get the size of the allocated binary buffer.

1 Get the address of a pointer to a binary buffer. See also IntControl 42.

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

Syntax: BinaryCheckSum(handle,request)

BinaryClipGet

129

Parameters: (i) handle handle of buffer. (i) request 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 Meaning Return String Format (x=hex character)

0 MD5 digest "xxxxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxx"

1 16-bit CRC "xxxx"

2 32-bit CRC "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 handle of buffer. (i) format 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.

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.

BinaryClipGet

130

1 F_TEXT 2 F_BITMAP (not supported) 3 F_METAFILEPICT 4 F_SYLK 5 F_DIF 6 CF_TIFF 7 CF_OEMTEXT 8 CF_DIB 9 CF_PALETTE 10 CF_PENDATA 11 CF_RIFF 12 CF_WAVE 13 CF_UNICODETEXT 14 CF_ENHMETAFILE 15 CF_HDROP 16 CF_LOCALE 128 CF_OWNERDISPLAY 129 CF_DSPTEXT 130 CF_DSPBITMAP 131 CF_DSPMETAFILEPICT 142 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) dataoffset = headersize + bmpdatasize BinaryPoke4(bb2,10,dataoffset) BinaryCopy(bb2,bmpdatasize,bb,0,size) BinaryWrite(bb2,"c:\temp\screenshot.bmp")

BinaryClipPut

131

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 handle of buffer. (i) format 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 F_TEXT 2 F_BITMAP (not supported) 3 F_METAFILEPICT 4 F_SYLK 5 F_DIF 6 CF_TIFF 7 CF_OEMTEXT 8 CF_DIB 9 CF_PALETTE 10 CF_PENDATA 11 CF_RIFF 12 CF_WAVE 13 CF_UNICODETEXT 14 CF_ENHMETAFILE 15 CF_HDROP 16 CF_LOCALE 128 CF_OWNERDISPLAY 129 CF_DSPTEXT 130 CF_DSPBITMAP 131 CF_DSPMETAFILEPICT 142 CF_DSPENHMETAFILE

BinaryCompare

132

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 handle of first buffer. (i) offset1 zero-based offset into the first buffer specifying where the

data to be compared starts. (i) handle2 handle of second buffer. (i) offset2 zero-based offset into the second buffer specifying where

the data to be compared starts. (i) count the number of bytes to compare.

Returns: (i) @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)

See Also Binary Operations, BinaryAlloc, BinaryCopy, BinaryFree, BinaryRead, DllCall

BinaryConvert

133

BinaryConvert Converts a binary buffer.

Syntax: BinaryConvert(handle,source-type,target-type,code-page,flags)

Parameters: (i) handle handle of buffer. (i) source-type format of existing data in buffer. (i) target-type format of data which the buffer will be converted to. (i) code-page any valid code page on your system. (i) flags 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 Meaning 0 8-bit ANSI

1 8-bit OEM

2 Multibyte (e.g., double-byte)

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

Type Meaning 0 ANSI

1 OEM

2 Macintosh

BinaryCopy

134

For conversions which don't involve Unicode, "code-page" is ignored.

"Flags" can be one of the following:

Flag Meaning 1 Convert to uppercase

2 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 handle of target buffer. (i) offset targ zero-based offset into the target buffer specifying where the

data to be copied should be placed. (i) handle src handle of the source buffer. (i) offset src zero-based offset into the source buffer specifying where

the data to be copied starts. (i) count the number of bytes to copy.

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.

BinaryEodGet

135

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 ) 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%")

BinaryFree

136

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 handle of buffer. (i) offset 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.

Syntax: BinaryFree(handle)

BinaryHashRec

137

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 handle of buffer. (i) recsize specifies the fixed length of each record. (i) key offset the offset within a record of the key field (where the first

byte in the record is 0). (i) key size specifies the size of the key field, in bytes. (i) key value the value of the key field to be searched for.

Returns: (i) 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 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

BinaryHashRec

138

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)

See Also: BinarySort, BinaryIncr, BinaryPeek, BinaryPoke

BinaryIndex

139

BinaryIncr Peeks at a value, increments the value by 1 then pokes the value back into the buffer.

Syntax: BinaryIncr(handle,offset) Incr an 8 bit value. BinaryIncr2(handle,offset) Incr a 16 bit value. BinaryIncr4(handle,offset) Incr a 32 bit value. BinaryIncrFlt(handle,offset) Incr a 64 bit floating point number.

Parameters: (i) handle handle of buffer. (i) offset 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 handle of buffer. (i) offset zero-based offset in the buffer to begin search. (s) string the string to search for within the buffer. (i) direction the search direction. @FWDSCAN searches forwards,

while @BACKSCAN searches backwards.

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

BinaryIndexBin

140

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.

Syntax: BinaryIndexBin(handle,offset,item,direction,match-case)

Parameters: (i) handle handle of buffer. (i) offset zero-based offset in the buffer to begin search.

BinaryIndexEx

141

(s/i) item 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.

(i) direction the search direction. @FWDSCAN searches forwards, while @BACKSCAN searches backwards.

(i) match-case specify 1 for a case-sensitive search, or 0 for a case- insensitive search.

Returns: (i) offset 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.

Syntax: BinaryIndexEx(handle,offset,string,direction,match-case)

Parameters: (i) handle handle of buffer. (i) offset zero-based offset in the buffer to begin search. (s) string the string to search for within the buffer.

BinaryIndexNc

142

(i) direction the search direction. @FWDSCAN searches forwards, while @BACKSCAN searches backwards.

(i) match-case This function is almost the same as BinaryIndex (if "match-case"=1) and BinaryIndexNc (if "match-case =0).

Returns: (i) 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: ; 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 = 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

BinaryIndexNc Searches a buffer for a string, ignoring case.

Syntax: BinaryIndexNc(handle,offset,string,direction)

BinaryIndexNc

143

Parameters: (i) handle handle of buffer. (i) offset zero-based offset in the buffer to begin search. (s) string the string to search for within the buffer. (i) direction the search direction. @FWDSCAN searches forwards,

while @BACKSCAN searches backwards.

Returns: (i) 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 Message("Hmmm", "HIMEM found on line %c%") endif

See Also: Binary Operations, BinaryCopy, BinaryIndex, BinaryIndexBin, BinaryIndexEx, BinaryEodGet, BinaryEodSet, BinaryStrCnt

BinaryOleType

144

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 handle of buffer. (i) type specifies what type of parameter the buffer will represent,

see below. (i) reserved-1 reserved for future use, specify as 0. (i) reserved-2 reserved for future use, specify as 0. (i) reserved-3 reserved for future use, specify as 0.

Returns: (i) @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:

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.

BinaryOleType

145

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 undefined 1 BSTR (VT_BSTR) 2 BSTR* (VT_BSTR | VT_BYREF) 3 byte array (VT_UI1 | VT_ARRAY) 4 I1 pointer (VT_I1 | VT_BYREF) 5 I2 pointer (VT_I2 | VT_BYREF) 6 I4 pointer (VT_I4 | VT_BYREF) 7 UI1 pointer (VT_UI1 | VT_BYREF) 8 UI2 pointer (VT_UI2 | VT_BYREF) 9 UI4 pointer (VT_UI4 | VT_BYREF) 10 R4 pointer (VT_R4 | VT_BYREF) 11 R8 pointer (VT_R8 | VT_BYREF)

direction:

100 input parameter 200 output parameter 300 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 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)

BinaryOr

146

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-9ad6-0080c7e7b78d") == @FALSE ErrorMode(@off) flag=RegSetValue(@REGCLASSES,"Licenses\2c49f800-c2dd-11cf-9ad6-0080c7e7b78d","mlrljgrlhltlngjlthrligklpkrhllglqlrk") ErrorMode(@cancel) if flag==0 Message("Error","Admin access required to set registry key.") exit endif endif objSocket = ObjectOpen("MSWinsock.Winsock") objSocket.Protocol = 1 ;UDP objSocket.RemoteHost = BCastAddr objSocket.SendData(bbpacket) ObjectClose(objSocket) BinaryFree(bbpacket) Message("All","Doned") exit

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)

Parameters: (i) target-handle handle of target buffer. (i) target-offset 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.

(i) source-handle handle of source buffer.

BinaryPeek

147

(i) source-offset zero-based offset into the source buffer specifying where the data to be processed starts.

(i) count the number of bytes to process.

Returns: (i) 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 "source-offset" 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 "target-offset + 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%")

See Also: Binary Operations, BinaryAlloc, BinaryCopy, BinaryFree, BinaryRead, BinaryReadEx, BinaryCompare, BinaryAnd

BinaryPeek Returns the value of a byte from a binary buffer.

BinaryPeekHex

148

Syntax for BinaryPeek Functions: BinaryPeek(handle,offset) Peeks an 8 bit value. BinaryPeek2(handle,offset) Peeks a 16 bit value. BinaryPeek4(handle,offset) Peeks a 32 bit value. BinaryPeekFlt(handle,offset) Peeks a 64 bit floating point

number.

Parameters: (i) handle handle of buffer. (i) offset 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 handle of buffer. (i) offset zero-based offset in the buffer to obtain byte from. (i) count specifies the number of bytes to read from the buffer.

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

BinaryPeekStr

149

Message("Hmmm", "Hex value of A is %ret%" ) exit

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 handle of buffer. (i) offset offset in the buffer the string starts at. (i) maxsize maximum number of bytes in string.

Returns: (s) 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. 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)

BinaryPoke

150

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 handle of buffer. (i) offset zero-based offset in the buffer where the string starts. (i) maxsize maximum number of bytes in string. Must be an even

number. (i) reverse bytes @FALSE default. @TRUE the bytes in each Unicode

character are reversed from the normal byte order.

Returns: (s) 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, BinaryPeekStrBinaryPoke, BinaryPokeStr

BinaryPoke Pokes a new value into a binary buffer at offset returning the previous value.

Syntax for BinaryPoke Functions: BinaryPoke(handle,offset,value) Pokes an 8 bit value.

BinaryPokeHex

151

BinaryPoke2(handle,offset,value) Pokes a 16 bit value. BinaryPoke4(handle,offset,value) Pokes a 32 bit value. BinaryPokeFlt(handle,offset,value) Pokes a 64 bit floating

point number.

Parameters: (i) handle handle of buffer. (i) offset zero-based offset in the buffer to store byte(s). (i) or (f) value 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 handle of buffer. (i) offset zero-based offset in the buffer to store string. (s) hex-string is a hex string, containing 2 hex characters for each byte

that will be written to the buffer.

Returns: (i) number of bytes stored.

Example: binbuf=BinaryAlloc(1) BinaryPokeHex( binbuf, 0, "41" ) ret=BinaryPeekStr( binbuf, 0, 1) Message("Hmmm", "String value of hex 41 is %ret%" ) exit

BinaryPokeStr

152

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 handle of buffer. (i) offset offset in the buffer to store string. (s) 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) ; 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)

BinaryPokeStrW

153

; 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 handle of buffer. (i) offset zero-based offset in the buffer to store string. (s) string string to store into buffer. (i) reverse bytes @FALSE default. @TRUE the bytes in each Unicode

character are reversed from the normal byte order.

Returns: (i) 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) BinaryPokeStrW( buf, 0, unicodestr) unicodestr = BinaryPeekStrW( buf, 0, bytecnt ) BinaryFree(buf) Message("Unicode String", unicodestr)

BinaryReadEx

154

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 handle of buffer. (s) filename 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.

Syntax: BinaryReadEx (handle,binary-offset,filename,file-offset,count)

BinaryReadEx

155

Parameters: (i) handle handle of buffer. (i) binary-offset zero-based offset into the buffer specifying where the data

should be stored. (i) filename file to read into buffer. (i)/(t) file-offset zero-based offset into the file specifying

where the data to be read starts. This parameter accepts a huge number data type.

(i) count the number of bytes to read.

Returns: (i) 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

BinarySort

156

BinaryReplace Replaces strings in a binary buffer.

Syntax: BinaryReplace(handle,search-string,replace-string,match-case)

Parameters: (i) handle handle of buffer. (s) search string specifies the string to be replaced. Specify a

blank string ("") to indicate that the search string is a NULL character.

(s) replace-string 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.

(i) match-case @TRUE to indicate that "search-string" is case-sensitive, or @FALSE if case should be ignored.

Returns: (i) number of occurrences of "search-string" that were

replaced.

This function searches a binary buffer, and replaces all occurrences of "search-string" 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) exit

See Also: BinaryAlloc, BinaryIndexEx, BinaryIndexNC

BinarySort Sorts records in a binary buffer.

BinarySort

157

Syntax: BinarySort(handle,recsize,key offset,key size,flags)

Parameters: (i) handle handle of buffer. (i) recsize specifies the size of each record. (i) key offset the offset within a record of the key field (where the first

byte in the record is 0). (i) key size specifies the size of the key field, in bytes. (i) flags see below.

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") 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

BinaryStrCnt

158

; 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 handle of buffer. (i) start-offset zero-based offset for start of search. (i) end-offset zero-based offset for end of search. (s) string 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.

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 )

BinaryTagExtr

159

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 Structure returned from BinaryTagInit. (i) flags see below.

Returns: (s) the text, or "" on failure.

Flags Meaning

0 Default.

1 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) ;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)

BinaryTagFind

160

;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) exit

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 ;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")

BinaryTagFind

161

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 Value="Analog Osscilosophilator" return :salesperson Value="Fred Ficklemeyer" return :salespersonphone

BinaryTagIndex

162

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 structure returned from BinaryTagInit. (i) mode 0 offset of text

1 offset of start tag

Returns: (i) 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. 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}}.")

BinaryTagInit

163

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) exit

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). (s) start-tag specifies what beginning string (tag) to search for

( i.e. "{{" ) (s) end-tag specifies what ending string (tag) to search for

( i.e. "}}" )

BinaryTagInit

164

Returns: (s) 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) Value="???" ; keyword not found error value if keyword=="date" then Value=TimeDate() if keyword=="name" then Value="Ms. Jamie Dough"

BinaryTagLen

165

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 Structure returned from BinaryTagInit. (i) mode 0 length of text

1 length of text + tags

Returns: (s) 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 ;Setup input and output file names filedata=strcat(DirGet(),"filedata.txt") ;Set up a sample file for this example.

BinaryTagRepl

166

;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) exit

See Also: BinaryTagFind, BinaryTagInit, BinaryTagExtr, BinaryTagRepl

BinaryTagRepl Replaces a binary tag with text.

BinaryTagRepl

167

Syntax: BinaryTagRepl(tag-struct,new-string)

Parameters: (s) tag-struct Structure returned from BinaryTagInit. (s) new-string 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) ; Allocate a buffer much larger than required. bb=BinaryAlloc(10000)

BinaryTagRepl

168

;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="???" ; keyword not found error value gosub %param1% 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 randomlow=param2 randomhigh=param3 randomrange=randomhigh-randomlow

BinaryWriteEx

169

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 handle of buffer. (s) filename 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.

Syntax: BinaryWriteEx(handle,binary-offset,filename,file-offset,count)

BinaryXlate

170

Parameters: (i) handle handle of buffer. (i) binary-offset zero-based offset into the buffer specifying where the data

to be read starts. (i) filename file to write to. (i/t) file-offset zero-based offset into the file specifying where the data

should be stored.This parameter accepts a huge number data type.

(i) count the number of bytes to write, or -1 to specify new end of file marker.

Returns: (i) 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

BinaryXlate Converts a binary buffer using a translation table.

BinaryXlate

171

Syntax: BinaryXlate(data-buffer,table-buffer,mode)

Parameters: (i) data-buffer a binary buffer containing data to be converted. (i) table-buffer a binary buffer containing a translation table. (i) mode see below.

Returns: (i) new EOD of the buffer.

Mode Source buffer Target buffer Table size

0 byte byte 256

1 byte word 512

2 word byte 65536

3 word word 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 "data-buffer", 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 ASCII translation table ;Codes 0 1 2 3 4 5 6 7 8 9 A B C D E F row0 ="000 001 002 003 032 009 032 127 032 032 032 011 012 013 014 015" row1 ="016 017 018 019 032 032 008 032 024 025 032 032 032 032 032 032" row2 ="032 032 028 032 032 010 023 027 032 032 032 032 032 005 006 007" row3 ="032 032 022 032 032 030 032 004 032 032 032 032 020 021 032 032" row4 ="032 032 032 032 032 032 032 032 032 032 155 046 060 040 043 032" row5 ="038 032 032 032 032 032 032 032 032 032 033 036 042 041 059 191" row6 ="045 047 032 032 032 032 032 032 032 032 124 044 037 095 062 063" row7 ="032 032 032 032 032 032 032 032 032 032 058 035 064 039 061 034" row8 ="032 097 098 099 100 101 102 103 104 105 032 032 032 032 032 032" row9 ="032 106 107 108 109 110 111 112 113 114 032 032 032 032 032 032" row10="032 126 115 116 117 118 119 120 121 122 032 032 032 032 032 032" row11="032 032 032 032 032 032 032 032 032 032 032 032 032 032 032 032" row12="123 065 066 067 068 069 070 071 072 073 032 032 032 032 032 032" row13="125 074 075 076 077 078 079 080 081 082 032 032 032 032 032 032" row14="092 032 083 084 085 086 087 088 089 090 032 032 032 032 032 032" row15="048 049 050 051 052 053 054 055 056 057 032 032 032 032 032 032" ;Allocate 256 bytes for a 1:1 translation table bbxlate=BinaryAlloc(256) ;load translation table from ROW variables above.

BinaryXor

172

; 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 handle of target buffer. (i) target-offset 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.

(i) source-handle handle of source buffer. (i) source-offset zero-based offset into the source buffer specifying where

the data to be processed starts. (i) count the number of bytes to process.

Break

173

Returns: (i) 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 "source-offset" 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.

Example: a=15 b=21 while (a<100)

ButtonNames

174

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 new name for the OK button. (s) Cancel-name 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:

Call

175

Call Calls a WIL batch file as a subroutine.

Syntax: Call(filename,parameters)

Parameters: (s) filename the WIL batch file you are calling (including extension). (s) parameters the parameters to pass to the file, if any, in the form

"p1 p2 p3 ... pn". (maximum value of n = 9 )

Returns: (i) 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 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-Defined-Function.

Ceiling

176

Examples:

Return Return (10) Return "Okay" Return myvariable * 10 Return (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

Ceiling Calculates the ceiling of a value.

Syntax: Ceiling(x)

Parameters: (f) x value Ceiling is calculated from.

Char2Num

177

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%") exit

A= Ceiling= Floor= 25.2 26.0 25.0 25.7 26.0 25.0 24.9 25.0 24.0 -14.3 -14.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.

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)

ChrHexToString

178

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 a hex-string.

Returns: (s) returns a string.

Example: str = ChrHexToString("48656C6C6F");Hello Message("String", str)

ChrSetCodePage

179

See Also: ChrStringToHex

ChrHexToUnicode Converts a hex string to a Unicode string.

Syntax: ChrHexToUnicode(hex-string [, flag ])

Parameters: (s) hex-string a Unicode string in hex format with four hex bytes per

Unicode character. (i) flag [optional] 0 (default) or 1 to reverse the byte order of each

"hex-string" byte pair before converting to a Unicode character.

Returns: (s) 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");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.

"code page" specifies a valid available code page, or one of the following system default code pages:

Value Meaning

0 ANSI code page

ChrStringToUnicode

180

1 OEM code page

2 Macintosh code page

3 The current thread's ANSI code page

42 Symbol code page

65000 Translate using UTF-7

65001 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)

Parameters: (s) string specifies a string.

Returns: (s) a Unicode string.

ChrUnicodeToString

181

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 specifies a Unicode string. (i) flag [optional] 0 (default) or 1 to reverse the byte order of each

"hex-string" byte pair returned.

Returns: (s) a hex string, with four hex bytes per Unicode character.

Example: unicodestr = ChrStringToUnicode("Hello") hexstr = ChrUnicodeToHex(unicodestr) 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.

Example: unicodestr = ChrHexToUnicode("480065006C006C006F00");Hello ansistr = ChrUnicodeToString( unicodestr ) Message("String", ansistr) exit

ClipGet

182

See Also: ChrStringtoUnicode

ClipAppend Appends a string to the Clipboard.

Syntax: ClipAppend(string)

Parameters: (s) string text string to add to Clipboard.

Returns: (i) @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)

Returns: (s) clipboard contents.

Use this function to copy text from the Windows Clipboard into a string variable.

ClipHasFormat

183

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 Meaning 1 (CF_TEXT) Standard ANSI text (same as ClipGet).

7 (CF_OEMTEXT) Text containing characters in the OEM character set.

13 (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

ClipHasFormat Determines if the clipboard contains a particular format.

ClipHasFormat

184

Syntax: ClipHasFormat(format)

Parameters: (i) format format of clipboard data.

Returns: (i) 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 F_TEXT 2 F_BITMAP 3 F_METAFILEPICT 4 F_SYLK 5 F_DIF 6 CF_TIFF 7 CF_OEMTEXT 8 CF_DIB 9 CF_PALETTE 10 CF_PENDATA 11 CF_RIFF 12 CF_WAVE 13 CF_UNICODETEXT 14 CF_ENHMETAFILE 15 CF_HDROP 16 CF_LOCALE 128 CF_OWNERDISPLAY 129 CF_DSPTEXT 130 CF_DSPBITMAP 131 CF_DSPMETAFILEPICT 142 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 exit

ComputerNameGet

185

See Also: Binary Operations, BinaryAlloc, BinaryWrite, BinaryFree, BinaryClipGet, BinaryClipPut, ClipGet, ClipGetEx

ClipPut Copies a string to the Clipboard.

Syntax: ClipPut(string)

Parameters: (s) string any text string.

Returns: (i) @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 specifies what value to return. See below.

Returns: (s) 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:

ComputerNameSet

186

Value Meaning

0 The NetBIOS name of the local computer.

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

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

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

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

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

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

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

107 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)

Continue

187

Parameters: (s) new name new computer name. (i) format 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 Meaning

0 In Windows 95/98/ME, sets the NetBIOS name. In Windows NT and newer, same as 105 (below).

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

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

106 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

Cos

188

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.

CurrentFile {*M}

189

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.

CurrentPath {*M}

190

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 manager-type 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.

CurrFilePath {*M}

191

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 manager-type 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 manager-type 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

DDEExecute

192

DataCast Converts or casts a value from one data type to another.

Syntax: DataCast(value,mode)

Parameters: (f) value specifies the value to be converted or cast. (i) mode specifies the operation to perform:

Returns: (f) depends on mode specified. See below.

Mode Meaning 0 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)

DDEInitiate

193

Parameters: (i) channel same integer that was returned by DDEInitiate. (s) command string one or more commands to be executed by the server app.

Returns: (i) @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 name of the application (without the EXE extension). (s) topic name name of the topic you wish to access.

Returns: (i) communications channel, or 0 on error.

DDEPoke

194

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 same integer that was returned by DDEInitiate. (s) item name identifies the type of data being sent. (s) item value 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.

DDERequest

195

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 same integer that was returned by DDEInitiate. (s) item name identifies the data to be returned by the server.

Returns: (s) 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")

DDETerminate

196

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") ;Run Report channel = DDEInitiate("report", "YTD") ;Initialize DDE 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

DDETimeout

197

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

Debug

198

Debug Controls the debug mode.

Syntax: Debug(mode[,init-string])

Parameters: (i) mode @ON or @OFF (s) init-string [optional] the string placed in the edit field of the debug

dialog when the dialog is initialized.

Returns: (i) 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-Defined-Function.

Example: Debug(@ON) a = 6 q = AskYesNo("Testing Debug Mode", "Is the Pope Catholic") Debug(@OFF) b = a + 4

Debug

199

... then, if the user presses Next:

... and presses Next again:

... and then presses Yes:

DebugTrace

200

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 desired data. (s) string 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)

See Also: Debug, DebugTrace, Message

DebugTrace Controls and customizes the WIL debugging trace logs.

Syntax: DebugTrace(requestcode[,parm1[,parm2 ]])

Parameters: (i) requestcode numeric code indicating desired action (see below)

DebugTrace

201

(s/i) parm1 [optional] depends on requestcode (s/i) parm2 [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-Defined-Subroutine, 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 Description

Modes These control the DebugTrace line by line logging.

Mode Option Flags These control the log file names, formatting, and content.

Immediate Action Codes

These cause additional data to be immediately written to the Debug Trace log file.

Modes

Request code

Meaning Parm1 Parm2

0 (@OFF)

Stops statement by statement debug tracing.

1 (@ON) 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.

10 Same as 1 (@ON) with the

DebugTrace

202

addition that if the output file exists, one attempt will be made to delete the file before continuing.

22 Allow DebugTrace continuation (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

Request code

Meaning Parm1 Parm2

100 Specify output file name for subsequent debug trace logging.

Required filename parameter

101 Same as 100 with the addition that if the output file exists, one attempt will be made to delete the file before continuing.

102 Dump WIL variable table to the debug trace log file when a terminal error occurs.

0 - Do NOT dump variable table to debug trade log file. (default) 1 - Dump WIL variable table to the debug trace log file if a terminal error occurs.

103 Dump internal debug data for each keyword lookup.

0 - Do NOT dump debug data for keyword lookups. (default) 1 - Dump debug data for keyword lookups.

104 Suppress statement timestamp information.

0 - Include statement timing information (default). 1 - Suppress statement timing information.

DebugTrace

203

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 non-relevant 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

Meaning Parm1 Parm2

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

203 Write a string to the debug trace log file.

Specifies a string to be written to the debug trace log file.

204 Write a string, surrounded by "$" signs to the debug trace log file.

Specifies a string to be written to the debug trace log file.

205 Dump WIL and loaded extender function tables to the debug trace log file.

206 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

DebugTrace

204

variable types (Arrays, Binary Buffers, etc) will not have variables dumped.

207 Dump stack info to the debug trace log file.

208 Dump machine information block.

277 Dump formatted internal debugging information to the debug trace log file. Much of the same information as provided by IntControl 77 is available.

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.

Example: DT_OFF = 0 DT_ON = 1 DT_ON_DEL = 10 DT_RESUME = 22 DT_FILENAME = 100 DT_FILENAME_DEL = 101 DT_VARS_ON_ERR = 102 DT_KEY_LOOKUP = 103 DT_TIMING = 104 DT_RESET = 200 DT_LOG = 202 DT_LOG_MARK = 205 DT_VARTABLE = 206 DT_STACK = 207 DT_HEADERS = 208 DT_DEBUGINFO = 277 #DefineFunction MyUDF() DT_RESUME = 22 DebugTrace( DT_RESUME ) ccc = 1 ccc = 2 ccc = 3 ccc = 5 return #EndFunction a = 1 ; start debug tracing.

Decimals

205

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

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:

Dialog

206

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 name of the dialog box. (i) ignore-flag [optional] 1 to display dialog, or 0 to skip. Note: If not

specified one (1) is assumed.

Returns: (i) 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.

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:

Dialog

207

<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> is the internal name of the dialog box, as described above. <box-caption> is the text which will appear in the title bar of the dialog

box. <x-origin> 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.

<y-origin> 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.

<box-width> is the width of the dialog box. <box-height> is the height of the dialog box. <min-box-width> [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.

<min-box-height> [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.

<ctrl-count> is the total number of controls in the dialog box (see below). <procedure-name> a User-Defined-Subroutine or function name. Use the same

name you use as part of a #DEFINEFUNCTION or #DEFINESUBROUTINE statement. Your User-Defined-Function/subroutine must have five parameters. You do not

Dialog

208

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

209

<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

210

Dialog statement when it creates your dialog template. This 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, tab-

order/position, style, font, textcolor,

backgroundcolor`

where:

dlg-variable is the name of the dialog box, as described above. nn 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-Defined-

Callback 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

Dialog

211

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

Dialog

212

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-XXXX-XXXX-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-XXXX-XXXXXXXXXXXX}" 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

Dialog

213

Explorer Based Control in WIL Dialogs” (pg. 233) for more information.

value 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/position 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

does not accept any user input, it would

PUSHBUTTON

RADIOBUTTON

Dialog

214

otherwise accept input. CHECKBOX

PICTUREBUTTON

EDITBOX

MULTILINEBOX

ITEMBOX

FILELISTBOX

CALENDAR

DROPLISTBOX

SPINNER

GROUPBOX

MENUITEM

4 Control will only accept values already

in the drop down list portion of the

control

DROPLISTBOX

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 controls

by using the up and down arrows.)

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

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.

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 Turns off automatic height adjustment

feature of item and file box controls.

ITEMBOX

FILELISTBOX

Dialog

215

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

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

Note: Specifying 0 for this attribute is equivalent to using the DEFAULT keyword and means that the control will exhibit default behavior.

font 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

Dialog

216

is selected that doesn't exist on the user's system, a substitution will be made. We recommend using commonly available fonts.

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/4 width of system font. 1 height unit = 1/8 height of system font. 4 units wide = Average width of the system font. 8 units high = 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

Dialog

217

top left or top right of the control. To select a non-adjacent 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 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

Dialog

218

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. 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. 233).

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

Dialog

219

list. In addition, DROPLISTBOX controls save space on your dialog, because the full list is not displayed until the user clicks the down arrow. 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.

Dialog

220

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

Dialog

221

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

Dialog

222

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

Dialog

223

this by assigning a default "value" to the variable before calling the Dialog function.

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

Dialog

224

Controls and Their Attributes

Variable/ License String /

Parent Name [*]

Text/ pre-sel/ moniker

[**]

Value Style TabOrd / Pos

[***]

Font Text color

Back ground [****]

Pushbutton T TO C

Picture T TO B CheckBox V T TO C PictureButton T TO B EditBox V T TO C MultiLineBox V T TO C GroupBox T TO C ItemBox V P TO C FileListBox V P TO C RadioButton V T TO C Spinner V T TO C StaticText T TO C VaryText V T TO C Calendar V P TO DropListBox V P TO C ComControl L M TO C MenuItem PN T RP MenuBar PN [*] V = variable, L = license string, PN = parent name [**] 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 User-Defined-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"

Dialog

225

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,change-

info)

Parameters: (i) dialog-handle handle to dialog (i) event-code event code for event that produced call to UDC (i) control-name name of control associated with event (i) event-info event information object (valid only when event-code = 14) (i) change-info On RESIZE returns a space delimited list of dialog-units.

Returns: (i) 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.

Dialog

226

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

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)

Dialog

227

You can return information to a control too

; 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 fifth parameter of the User-Defined-Callback Procedure contains a space delimited list of items that represent the change in width and height of the dialog resulting from resizing activity. 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 <dlg-variable>MinHeight variables in order to use this option.

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.

Codes Meaning

0 Initialization: Dialog has been created but not displayed. This event is only generated once per Dialog session.

1 Timer: Set a Timer event

2 Pushbutton or Picturebutton Pushed: User has pressed a PUSHBUTTON or PICTUREBUTTON control.

Dialog

228

3 Radiobutton Selected: User has selected a RADIOBUTTON.

4 Checkbox Checked/Unchecked: User has checked or unchecked a CHECKBOX control.

5 Changed text in Editbox or Multilinebox: User has changed the text in an EDITBOX or MULTILINEBOX control

6 Filelistbox File Selected: User has selected a file in a FILELISTBOX control

7 Itembox Item Selected: User has selected one or more items in a ITEMBOX control.

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.

9 Calendar Date Change: User has selected a new date in a CALENDAR control.

10 Spinner Number Change: User has changed the value of a SPINNER control.

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 DialogProcOption code 1002.

12 Filelistbox File Double-Clicked: the user has used the mouse to double-click an item in an FILELISTBOX.

13 Itembox Item Double-Clicked: the user has used the mouse to double-click an item in an ITEMBOX.

15 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 sub-menus. The associated drop-down or sub-menu is displayed instead. Hot-keys should not be used with menu items that display a drop-down or sub-menu.

16 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 user-defined callback as the value of its third parameter. For example: This event be used to dynamically modify the menu itself.

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

Dialog

229

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

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

1001 Change Background: Change the dialog's background bitmap or color.

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.

1003 Change Dialog Title: Change the dialog’s title. Note: the maximum dialog title length is 254 characters.

1004 Get Control Name: Returns the name of the control associated with the number.

1005 Get Control Number: Returns the control number associated with the name.

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.

Dialog

230

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.

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,"Good Bye",0,2,DEFAULT,DEFAULT,DEFAULT,DEFAULT`

Dialog

231

ButtonPushed=Dialog("ExampleOne",1) Exit

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 MyDialog001=`109,157,58,14,PUSHBUTTON,"PushButton_Cancel",DEFAULT,"&Cancel",0,1,DEFAULT,DEFAULT,DEFAULT,DEFAULT` MyDialog002=`111,77,60,14,PUSHBUTTON,"PushButton_Notepad",DEFAULT,"&Notepad",1,2,DEFAULT,DEFAULT,DEFAULT,DEFAULT` MyDialog003=`111,95,60,14,PUSHBUTTON,"PushButton_WBS",DEFAULT,"&WinBatch 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,"WinW&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,"&Zoomed",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,"&Directory:",DEFAULT,10,DEFAULT,DEFAULT,DEFAULT,DEFAULT` MyDialog011=`41,3,130,20,VARYTEXT,"VaryText_FileName",editfile,"*EMPTY*",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,DEFAULT,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

Dialog

232

: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 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")

UYC

IvaE

C

TccH

TeChCothc

Ib

Using InteYou can displayControl or the

In order to use version 4.0 of Iaccompanying Explorer.

Choosing the C

The WebBrowcapabilities to ycontainer for thHTML.

The WebBrowevents and MSHControl. This mhandler for MSControl. Thereonkeypress in yhe other hand,

consider the W

It is still possibby the WebBro

ernet Exply rendered HTMSHTML co

Internet ExploInternet Explorexamples may

Correct Comp

wser Control adyour WIL dialohe MSHTML c

wser Control anHTML docummeans that youSHTML compoefore, if you wiyour dialog call

if you wish toWebBrowser Co

ble to handle Mowser control.

lorer ContTML in WIL Domponent of In

orer controls in rer installed ony require an eve

ponent

dds browsing, dogs. The Webcomponent wh

nd the MSHTMment events do u cannot set youonent events wish to handle htlback, you shosimply add we

ontrol.

MSHTML com However, it r

trols in Wialogs using ei

nternet Explore

WIL dialogs yn the system. Sen more recent

document viewb Browser Conhich provides p

ML componentnot bubble up ur dialog callb

when it is hostetml document uld use the MSeb or local file

mponent events equires using t

IL Dialogither the WebBer.

you must have Some features st version of Inte

wing, and data dntrol also acts aparsing and ren

t each have theto the WebBrack procedure d by the WebBevents like onCSHTML compbrowsing to y

when MSHTMthe ObjectEve

Dialog

233

gs Browser

at least shown in the ernet

downloading as a

ndering of

eir own rowser

as the event Browser Click or ponent. On your dialog,

ML is hosted entAdd

Dialog

234

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,DEFAULT,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

objHtmlDoc=DialogObject(Exam_Handle,"Com_Mshtml",

DLGOBJECT_GETOBJECT)

objHtmlDoc.write('<HTML>')

objHtmlDoc.write('<HEAD>')

Dialog

235

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

ExamFormat=`WWWDLGED,6.2`

ExamCaption=`MSHTML Example`

ExamX=021

ExamY=058

ExamWidth=179

Dialog

236

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

Dialog

237

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)

Now when the newWindow2 event fires, the second WebBrowser control is made visible and accepts the navigation request.

Dialog

238

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 = 0 ; The one-time initialization MSG_BUTTONPUSHED = 2 ; Pushbutton or Picturebutton DCSTATE_ADDSTYLE = 3 ; Add control style DCSTATE_REMOVESTYLE = 4 ; Remove control style DCSTYLE_INVISIBLE = 1 ; Set Control Invisible DCSTYLE_DISABLED = 2 ; Disable control ; New message. MSG_COMEVENT = 14 ;COM control event fired. ; 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. ; 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) return(-1)

case MSG_COMEVENT ; COM event message ; Test in case more events or COM controls are added later

Dialog

239

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_INVISIBLE ) 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 return -2 ; Don't quit. endif if Exam_ControlName == 004 ; Forward button

Dialog

240

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://techsupt.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` 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,"Foreward",2,4,DEFAULT,DEFAULT,DEFAULT,DEFAULT`

Dialog

241

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 object reference. See the Dialog function topic for more information on control events.

DialogControlGet

242

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)

Parameters: (i) dialog-handle handle to dialog (s) control-name name of control to retrieve information from (i) request-code information to return

Returns: (s/i) requested information

DialogControlGet

243

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 Applicable Controls Function Return Values

1 CHECKBOX (i) 1 box checked, 0 box unchecked

2 RADIOBUTTON (i) 1 button is dotted, 0 button is not dotted

3 EDITBOX MULTILINEBOX

(s) all text currently in the control.

4 PICTURE RADIOBUTTON CHECKBOX PICTUREBUTTON VARYTEXT STATICTEXT GROUPBOX PUSHBUTTON MENUITEM

(s) control’s title.

5 ITEMBOX FILELISTBOX DROPLISTBOX

(s) tab delimited list of all the items currently in the control, or a File wildcard mask if a FILELISTBOX is specified (i.e., "c:\temp\*.*").

6 ITEMBOX FILELISTBOX DROPLISTBOX

(s) tab delimited list of the currently selected item(s) in the control. An empty string, if no item is selected.

7 CALENDAR (s) the date shown in the control in YYYY:MM:DD:HH:MM:SS format

8 SPINNER (s) current value displayed in control

9 No operation. Valid for DialogControlSet only

10 ITEMBOX (i) one-based index of the first currently visible item in the list. (1 is the first item

DialogControlGet

244

FILELISTBOX MULTILINEBOX

in the list.)

11 RADIOBUTTON CHECKBOX VARYTEXT STATICTEXT GROUPBOX PUSHBUTTON ITEMBOX FILELISTBOX DROPLISTBOX SPINNER EDITBOX MULTILINEBOX COMCONTROL

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

12 PICTURE PICTUREBUTTON

(s) The file specification of the controls currently displayed bitmap. If the control is not displaying a bitmap, the "DEFAULT" key string is returned.

13 RADIOBUTTON CHECKBOX VARYTEXT STATICTEXT GROUPBOX PUSHBUTTON ITEMBOX FILELISTBOX DROPLISTBOX SPINNER EDITBOX MULTILINEBOX

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

14 ITEMBOX FILELISTBOX 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.

15 ITEMBOX FILELISTBOX 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.

16 RADIOBUTTON (i) Control-name (control-number for legacy dialogs) of the radio button from a

DialogControlGet

245

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) the window handle of a dialog control. Note: The request cannot be used on MENUITEM and MENUBAR controls because these controls are not windows.

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

DialogControlSet

246

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,"",DEFAULT,3,0,"Modern|6656|40|65330","0|0|0",DEFAULT` GetExample004=`005,011,068,072,ITEMBOX,"Itembox_Colors",ItemList,DEFAULT,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,set-request-code,set-info)

Parameters: (i) dialog-handle handle to dialog (s) control-name name of control to modify (i) set-request-code control property to set (s/i) set-info information to set

Returns: (i) @TRUE if successful otherwise @FALSE.

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

DialogControlSet

247

set-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 Applicable Controls Set-info

1 CHECKBOX (i) 1 means check the box, 0 means uncheck the box.

2 RADIOBUTTON (i) 1 means select button, 0 means clear the selection.

3 EDITBOX MULTILINEBOX

(s) text replaces the existing text.

4 PICTURE RADIOBUTTON CHECKBOX PICTUREBUTTON VARYTEXT STATICTEXT GROUPBOX PUSHBUTTON MENUITEM

(s) text replaces the existing title.

5 ITEMBOX DROPLISTBOX FILELISTBOX

(s) ITEMBOX and DROPLISTBOX: tab delimited list of items to replace the existing list displayed by the control. FILELISTBOX: a file mask to change or modify the default of “*.*”

6 ITEMBOX DROPLISTBOX FILELISTBOX

(s) tab delimited list of one or more items you wish to be highlighted as 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 multi-select.)

7 CALENDAR (s) date shown in the control in

DialogControlSet

248

YYYY:MM:DD:HH:MM:SS format.

8 SPINNER (i) displayed value of control.

9 MULTILINEBOX (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 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.

10 ITEMBOX FILELISTBOX 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.

11 RADIOBUTTON CHECKBOX VARYTEXT STATICTEXT GROUPBOX PUSHBUTTON ITEMBOX FILELISTBOX DROPLISTBOX SPINNER EDITBOX MULTILINEBOX COMCONTROL

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

12 PICTURE PICTUREBUTTON

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

13 RADIOBUTTON CHECKBOX VARYTEXT STATICTEXT GROUPBOX PUSHBUTTON ITEMBOX

(s) text color. The color is specified by three vertical bar (|) delimited numbers ranging from 0 to 255. To give the control the dialog's default text color, use an empty string ""or the "DEFAULT "key string for this parameter.

DialogControlSet

249

FILELISTBOX DROPLISTBOX SPINNER EDITBOX MULTILINEBOX

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.

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

DialogControlState

250

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` SetExample003=`017,015,049,008,STATICTEXT,"StaticText_1",DEFAULT,"Select a &Number:",DEFAULT,3,0,DEFAULT,DEFAULT,DEFAULT` SetExample004=`100,028,032,025,STATICTEXT,"StaticText_2",DEFAULT,DEFAULT,DEFAULT,4,0,"Microsoft Sans Serif|18944|40|34","0|0|0",DEFAULT` SetExample005=`100,015,043,009,STATICTEXT,"StaticText_3",DEFAULT,"ASCII 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 handle to dialog (s) control-name name of control to change (i) request-code 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

(i) style style to change

Returns: (i/s) @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.)

DialogControlState

251

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 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 User-Defined-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 Meaning

1 Give a control the input focus

2 Query a control's style

3 Add one or more styles to a control

4 Remove styles from a control

5 Get control that has focus

6 Position mouse cursor over control

style

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.

DialogControlState

252

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 CALENDAR DROPLISTBOX SPINNER GROUPBOX VARYTEXT STATICTEXT MENUITEM

4 Note: Not supported in this function. This style can only be set in the dialog template.

Control will only accept values already in the drop down list portion of the control

DROPLISTBOX

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,

EDITBOX MULTILINEBOX

DialogControlState

253

it is still possible to paste non-digits into the edit control.

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 in this function. This style can only be set in the dialog template.

ITEMBOX FILELISTBOX

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

Example: #DEFINESUBROUTINE Flash(Handle,DialogMessage,DialogControlID,param4,param5) switch (DialogMessage) case 0 ; Initialization

DialogObject

254

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` 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,"Stop!",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/image-

file[,event-id]])

Parameters (i) dialog-handle handle to dialog. (s) control-name name of a COM control or 0 (depends on request-code.)

DialogObject

255

(i) request-code number of task to perform (s) event-name [optional] name of control event, image file or do not

specify (depends on request-code) (i) event-id [optional] number to associate with an event or do not

specify (depends on request-code)

Returns: (r) @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 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 request-code 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 Meaning

1 Call dialog callback when the specified event occurs

2 Stop calling dialog callback when an event previously requested with request-code 1 occurs

3 Return an object references to the specified control

4 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).

DialogObject

256

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 Event-name

1, 2 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.

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.

DialogObject

257

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) ; 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,"Enough Already",1,1,32,DEFAULT,DEFAULT,DEFAULT`

DialogProcOptions

258

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)

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)

DialogProcOptions

259

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

(i) 1- turn on event callback 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

DialogProcOptions

260

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) 1- turn on event callback 0 - turn off callback -1 - return current setting

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

(i) 1- turn on event callback 0 - turn off callback -1 - return current setting

16 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 user-defined callback as the value of its third parameter. For example: This event be used to dynamically modify the menu itself.

(i) 1- turn on event callback 0 - turn off callback -1 - return current setting

17 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

(i) 1- turn on event callback 0 - turn off callback -1 - return current setting

DialogProcOptions

261

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

Other non-events supported by DialogProcOptions:

1000 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

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

(i) -1 – return current title

DialogProcOptions

262

is 254 characters.

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

DialogProcOptions

263

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) 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

DirAttrGet

264

Timer001=`013,083,034,014,PUSHBUTTON,"PushButton_OK",DEFAULT,"OK",1,DEFAULT,DEFAULT,DEFAULT,DEFAULT,DEFAULT` Timer002=`067,083,034,014,PUSHBUTTON,"PushButton_Cancel",DEFAULT,"Cancel",0,DEFAULT,DEFAULT,DEFAULT,DEFAULT,DEFAULT` Timer003=`023,015,070,052,VARYTEXT,"VaryText_1",clock,"10",DEFAULT,DEFAULT,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 Meaning

R Read-only ON

A Archive ON

S System ON

H 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

265

DirAttrGetEx Gets directory attributes (extended).

Syntax: DirAttrGetEx(directory path)

Parameters: (s) directory path directory pathname 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 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.

16 * DIRECTORY Identifies a directory.

32 ARCHIVE The file or directory is an archive file or directory. Applications use this attribute to mark 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.

DirAttrGetEx

266

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.

16384*

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

Example: READONLY = 1 HIDDEN = 2 SYSTEM = 4 DIRECTORY = 16 ARCHIVE = 32 NORMAL = 128 TEMPORARY = 256 COMPRESSED = 2048 OFFLINE = 4096 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

DirAttrSet

267

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)

Parameters: (s) dir-list a tab or vertical bar delimited list of one or more sub-

directory names. (s) settings new attribute settings for the directories.

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 read only ON A archive ON S system ON H hidden ON

r read only OFF a archive OFF s system OFF h hidden OFF

DirAttrSetEx

268

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 a tab or vertical bar delimited list of one or more sub-

directory names. (i) attributes new attribute settings for the directories. (i) mode 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

Returns: (i) @TRUE on success, or @FALSE if unable to change the

attributes on any of the specified directory(s).

Note: DirAttrSetEx does not accept wildcards.

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.

16* DIRECTORY Identifies a directory.

32 ARCHIVE The file or directory is an archive file or directory. Applications use this attribute to mark

DirAttrSetEx

269

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.

16384* ENCRYPTED 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.

Example: READONLY = 1 HIDDEN = 2 SYSTEM = 4 DIRECTORY = 16 ARCHIVE = 32 NORMAL = 128 TEMPORARY = 256 COMPRESSED = 2048 OFFLINE = 4096 NOT_CONTENT_INDEXED = 8192

DirChange

270

ENCRYPTED = 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 if attr & ENCRYPTED Message(tmpdir, "ENCRYPTED") Endif exit

See Also: DirAttrSet, DirAttrGetEx, FileAttrGetEx, FileAttrSetEx, FileTimeGet, FileTimeTouch

DirChange Changes the current directory. Can also log a new drive.

Syntax: DirChange([d:]path)

DirExist

271

Parameters: (s) [d:] path the desired directory name with optional drive.

Returns: (i) @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 complete drive and path.

Returns: (i) @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 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. If it ;doesn’t one is created. wpdir = "c:\wp" If !DirExist(wpdir) Then DirMake(wpdir) DirChange(wpdir) ; 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)

DirHome

272

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

DirHome Returns directory containing the WIL Interpreter's executable files.

Syntax: DirHome()

Parameters: (none)

Returns: (s) pathname of the home directory.

DirInfoToArray

273

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 specifies a set of sub-directory names, which may be

wildcarded. (i) flags [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 Value 0 default.

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

2 return directory 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 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 Value 0 number of directories returned

1 total directory size. Note: Set to 0

DirItemize

274

2-6 (unused, set to 0)

Other rows:

Column Value 0 directory name

1 directory size. Note: all sizes for directories will be 0.

2 directory last modified time, in YmdHms format

3 directory last accessed time, in YmdHms format

4 directory created time, in YmdHms format

5 directory attribute string in the form "RASH" (see DirAttrGet)

6 directory attribute bitmask (see DirAttrGetEx)

Example: dirlist = StrCat(ShortCutDir("Personal",0,@TRUE),"*.*") infoarray = DirInfoToArray(dirlist, 1|2) infostr = StrCat("Number of directories: ",infoarray[0,0],@Crlf, @Crlf) For xx = 1 to infoarray[0,0] infostr = StrCat(infostr,"Directory Name: ", infoarray[xx,0],@Crlf) ;Note that all sizes (column 1) for directories will be 0. infostr = StrCat(infostr,"Directory 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("Directory Data",tmpfile,@unsorted,@single,@false) FileDelete(tmpfile) exit

See Also: DirItemize, DirAttrGet, DirAttrGetEx, DirTimeGet, DirSize

DirItemize Returns a delimited list of directories.

Syntax: DirItemize(dir-list)

DirMake

275

Parameters: (s) dir-list a string containing a set of sub-directory names, which may

be wildcarded.

Returns: (s) 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 sub-directories 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.

Returns: (i) @TRUE if the directory was successfully created, or

already exists.

Use this function to create a new directory.

DirRename

276

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 a delimited list of directory pathnames.

Returns: (i) @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 existing directory name, with optional drive. (s) newpath new name for directory.

Returns: (i) @TRUE if the directory was successfully renamed;

@FALSE if it wasn't.

Example: ;Do a dirmake so the example runs smoothly.

DirSize

277

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) exit

See Also: DirHome, DirGet, IntControl 1004

DirSize Finds the total size of a directory.

Syntax: DirSize(dir-name,flags[,format])

Parameters: (s) dir-name specify a single directory name (no wildcards). (i) flags specifies the format of the returned value. (see below)

DirWindows

278

(i) format [optional] controls the format in which the size is returned.

Returns: (i/f) 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 Meaning

0 actual size of the files.

1 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

DirWindows Returns the name of the Windows or Windows System directory.

DiskExist

279

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# Return value

0 Windows directory

1 Windows System directory

2 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 drive being tested.

Returns: (i) @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.

Example: b="A:" a=DiskExist(b) if a Message("Disk Exists", b)

DiskFree

280

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 one or more drive letters or "UNC Shares" in the format

"\\UNC\sharename",separated by"|", or the current file delimiter (usually a tab).

(i) format controls the format in which the size is returned.

Returns: (i/f) 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 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.

DiskScan

281

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 a drive letter (i) request# see below.

Returns: (i) depends on request specified.

Req# Return value 1 sectors per cluster

2 bytes per sector

3 number of free clusters

4 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#)

Parameters: (i) request# see below.

Returns: (s) drive list.

DiskSize

282

Req# Return value

0 List of unused disk IDs

1 List of removable drives (floppies, zip, Jaz drives etc.)

2 List of local fixed (hard) drives

4 List of remote (network) drives

8 CD-ROM (32 bit)

16 RamDisk (32 bit)

32 List of persistent non-connected drives

64 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 one or more drive letters or "UNC Shares" in the format

"\\UNC\sharename", separated by"|", or the current file delimiter (usually a tab).

(i) format This controls the format in which the size is returned.

Returns: (i/f) the total size of a selected disk.

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

DiskVolInfo

283

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 specifies the root directory of a file system volume (i.e.

"C:\" or "\\SERVER\PUBLIC\") (i) request the request number for desired information. See below.

Returns: (i/s/t) depends on the request number specified. (see below).

Request Return value 1 (s) volume name

2 (s) file system name (e.g., "FAT" or "NTFS")

3 (s) volume serial number (hex string; e.g., "1234-ABCD")

4 (i) volume serial number (decimal)

5 (i) max length of filename component (portion between backslashes)

6 (b) volume preserves the case of filenames when storing files

Display

284

7 (b) volume supports case-sensitive filenames

8 (b) volume supports Unicode in filenames

9 (b) volume preserves and enforces ACL's

10 (b) volume supports file-based compression

11 (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 seconds to display the message (max 3600). (s) title title of the window to be displayed. (s) text 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.

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:

DllCall

285

See Also: Message, Pause

DllCall Calls an external DLL.

Syntax: DllCall(dllname,returntype:epname[,paramtype:parameter ...])

Parameters: (s) dllname the name of the Dll to be called, or a handle returned by the

DllLoad function. (t) returntype: type of value the Dll entry point will return (see below). (s) epname entry point name into the Dll. (t) paramtype type of parameter (see below). (t) parameters parameters as required by the entry point.

Returns: (i/s) 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.

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) Name of the DLL. 2) Entry point name of the desired function within the Dll.

DllCall

286

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) word 16 bit integer 2) long 32 bit integer 3) lpstr 32 bit pointer to an ANSI string 4) lpwstr 32 bit pointer to a Unicode string 5) void no return value 6) double 64-bit floating point value

WIL supports the following parameter types to pass data to a Dll:

1) word 16 bit integer 2) long 32 bit integer 3) lpstr 32 bit pointer to an ANSI string 4) lpwstr 32 bit pointer to a Unicode string 5) lpnull 32 bit NULL pointer 6) lpbinary 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. 123).

7) double 64-bit floating point value 8) callback 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 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

DllCallbackCreate

287

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

DllCallbackCreate Associates a user defined function or subroutine with a callback handle.

DllCallbackCreate

288

Syntax: DllCallbackCreate(UDF-name,return-type,parameter-types)

Parameters: (s) UDF-name name of previously defined user defined function or

subroutine. (s) return-type expected return data type. May be one of WORD,

LONG, VOID, or DOUBLE. (s) parameter-types space delimited list of the expected types of each

parameter for the WORD, LPSTR, LPWSTR, LPNULL, LONG or DOUBLE.

Returns: (i) 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,long: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:']') If ret == @YES Then WinClose(title) ;Close Window EndIf EndIf BinaryFree(lptitle)

DllCallbackDestroy

289

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) Exit

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

DllCall Additional Information

290

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

DllCallCdecl

291

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:

_MyFunction@4

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 the name of the Dll to be called, or a handle

returned by the DllLoad function. (t) returntype: type of value the Dll entry point will return (see below). (s) epname entry point name into the Dll. (t) paramtype type of parameter (see below). (t) parameters parameters as required by the entry point.

Returns: (i/s) 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.

DllCallCdecl

292

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) word 16 bit integer 2) long 32 bit integer 3) lpstr 32 bit pointer to an ANSI string 4) lpwstr 32 bit pointer to a Unicode string 5) void no return value 6) double 64-bit floating point value

WIL supports the following parameter types to pass data to a Dll:

1) word 16 bit integer 2) long 32 bit integer 3) lpstr 32 bit pointer to an ANSI string

4) lpwstr 32 bit pointer to a Unicode string 5) lpnull 32 bit NULL pointer 6) lpbinary 32 bit pointer to a memory block allocated with

the BinaryAlloc function. See section on Binary Operations (pg. 123).

7) double 64-bit floating point value 8) callback 32-bit integer created using DllCallbackCreate

DllCallCdecl

293

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"

DllHinst

294

buffer = BinaryAlloc(512) dllname = StrCat(DirWindows(1), "USER32.DLL") len = DllCallCdecl(dllname, long:"wsprintfA", lpbinary:buffer, lpstr:format, lpstr:username) BinaryEodSet(buffer, len) 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)

DllHwnd

295

Parameters: (s) partial-winname the initial part of, or an entire, window name.

Returns: (i) an application instance handle.

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) a window handle.

DllLastError

296

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 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)

DOSVersion

297

See Also: DllCall Additional Information, DllCall

DllLoad This function loads a Dll for later use via the DllCall function

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

DOSVersion Returns the version numbers of the current version of DOS.

Syntax: DOSVersion(level)

Parameters: (i) level @MAJOR or @MINOR.

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:

Drop

298

DOSVersion(@MAJOR) == 5 DOSVersion(@MINOR) == 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 one or more variable names to remove, delimited with a

comma.

Returns: (i) @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.

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"

DropWild

299

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" a2= "Another variable" DropWild("a*") ; This removes A1 and A2 from memory Message("DropWild","Dropped from memory.")

See Also: IsDefined, Drop

Environment

300

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 any defined environment variable.

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.

EnvironSet

301

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 name of environment variable. (See Note 1). (s) value desired value.

Returns: (i) @TRUE Environment variable was modified; @FALSE

Unable to modify environment.

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.

EnvItemize

302

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 "command.com" 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 command.com")

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()

Parameters: (none)

Returns: (s) a list containing all variables in the current environment

(See Note).

ErrorEvent

303

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. 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, Num2Char(10), @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 severity, which can be one of the following:

-1 minor error -2 moderate error -3 severe error

(i) error-code error code, which must be a number between 7000 and 7999.

(s) error-message error message, which is a string describing the error

Returns: (i) 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

See Also: ErrorMode, User-Defined-Functions

ErrorMode

304

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

Exclusive

305

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)

Parameters: (i) mode @ON or @OFF.

Execute

306

Returns: (i) previous Exclusive mode.

Exclusive(@OFF) is the default mode. In this mode, the WIL Interpreter is well-behaved 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( ) crlf = StrCat(Num2Char(13), Num2Char(10)) Message("Times", "Start: %start%%crlf%Stop: %stop%") Exclusive(@OFF)

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 built-in 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.

ExeTypeInfo

307

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 the name of the desired .EXE file or data file.

Returns: (i) 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)

Exp

308

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

FileAppend

309

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 a string containing one or more filenames, which may be

wildcarded. (s) destination target file name.

Returns: (i) @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.

FileAttrGet

310

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 A archive ON S system ON H hidden ON

- read only OFF - archive OFF - system OFF - 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

FileAttrGetEx

311

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

16* DIRECTORY Identifies a directory.

32 ARCHIVE The file or directory is an archive file or directory. Applications use this attribute to mark 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.

FileAttrGetEx

312

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.

16384* ENCRYPTED 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 FileAttrSetEx.

Example: READONLY = 1 HIDDEN = 2 SYSTEM = 4 DIRECTORY = 16 ARCHIVE = 32 NORMAL = 128 TEMPORARY = 256 COMPRESSED = 2048 OFFLINE = 4096 NOT_CONTENT_INDEXED = 8192 ENCRYPTED = 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

FileAttrSet

313

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 exit

See Also: FileAttrSetEx, FileInfoToArray, FileAttrSet, FileTimeGet

FileAttrSet Sets file attributes.

Syntax: FileAttrSet(file-list,settings)

Parameters: (s) file-list a delimited list of files. (s) settings 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 Meaning Symbol Meaning

R read only ON A archive ON S system ON H hidden ON

r read only OFF a archive OFF s system OFF h hidden OFF

FileAttrSetEx

314

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 a delimited list of files. May contain wildcards. (i) attributes specifies the attributes to apply to the specified file(s). see

below. (i) mode 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

Returns: (i) @TRUE on success; @FALSE if unable to change the

attributes on any of the specified files.

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.

16* DIRECTORY Identifies a directory.

32 ARCHIVE The file or directory is an archive file or

FileAttrSetEx

315

directory. Applications use this attribute to mark 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.

16384* ENCRYPTED 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 FileAttrSetEx.

Examples: ADD = 1 TEMPORARY = 256

FileClose

316

curdir = DirGet() 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 fully qualified file name. (i) flag [optional] 0, or 1. See below.

Returns: (i) base filename.

The optional 'flag' can be one of the following values:

Value Meaning 0 (default) do not include a dot '.' on the end of a filename with no

extension.

1 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)

FileCompare

317

Parameters: (i) filehandle same integer that was returned by FileOpen.

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 name of first file to compare (s) filename2 name of second file to compare

Returns: (i) compare result (see below).

Possible return values are:

Return Meaning 0 Files contents are identical.

1 Files are same size but different - first file is newer.

-1 Files are same size but different - second file is newer.

2 Files are different - first file is newer.

-2 Files are different - second file is newer.

3 Second file missing - only first file exists.

-3 First file missing - only second file exists.

FileCopy

318

4 Neither file exists.

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 a string containing one or more filenames, which may be

wildcarded. (s) destination target path and/or file name/wildcard. (i) warning @TRUE if you want a warning before overwriting

existing files; @FALSE if no warning desired.

Returns: (i) @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.

FileCopy

319

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)

FileCopyAttr

320

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 a string containing one or more filenames, which

may be wildcarded. (s) destination target path and/or file name/wildcard. (i) warning @TRUE if you want a warning before overwriting

existing files; @FALSE if no warning desired. (s) attributes attributes to be modified.

Returns: (i) @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 Meaning Symbol Meaning

R read only ON A archive ON

r read only OFF a archive OFF

FileCreateTemp

321

S system ON H hidden ON

s system OFF h 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 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).

Returns: (s) 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")

FileDigest

322

FileClose(filehandle) Message(tempfile,"Temp file created") FileDelete(tempfile) Message(tempfile,"Temp file deleted") exit

See Also: FileDelete, FileOpen

FileDelete Deletes files.

Syntax: FileDelete(file-list)

Parameters: (s) file-list a string containing one or more filenames, which may be

wildcarded.

Returns: (i) @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.

FileExist

323

Syntax: FileDigest(filename,algorithm,format)

Parameters: (s) filename either a fully qualified filename with drive and path, or just

a filename and extension. (s) algorithm 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).

(i) format specifies the format of the returned string.

Returns: (s) 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 (MD2/MD5 = 16 bytes) 00112233445566778899AABBCCDDEEFF00112233 (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 (MD2/MD5 = 16 bytes) 00112233 44556677 8899AABB CCDDEEFF 00112233 (SHA/SHA1 = 20 bytes)

See Also: FileExist, FileLocate

FileExist Tests for the existence of files.

Syntax: FileExist(filename)

Parameters: (s) filename either a fully qualified filename with drive and path, or just

a filename and extension.

Returns: (i) 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

FileExtension

324

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

FileGet

325

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 possibly incomplete filename - missing drive

and/or path.

Returns: (s) 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 name of the file to read. (s) null-char [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.

FileInfoToArray

326

Returns: (s) a string containing the file contents.

Example: filename = "c:\temp\readme.txt" data = FileGet(filename , "") Message(StrCat("Contents of ",filename),data) exit

See Also: FilePut, FileRead, IntControl 39

FileGetW Converts a file to a Unicode string variable.

Syntax: FileGetW(filename[,null-char])

Parameters: (s) filename name of the file to read. (s) null-char [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.

Returns: (s) 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) exit

See Also: FileGet, FilePutW, IntControl 39

FileInfoToArray Returns information on a set of files, as an array.

FileInfoToArray

327

Syntax: FileInfoToArray(file-list[,flags])

Parameters: (s) file-list specifies a list of filenames, which may be wildcarded. (i) flags [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 Meaning

0 default

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

2 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 Value 0 number of files returned

1 total size of files returned

2-6 (unused, set to 0)

Other rows:

Column Value 0 file name

1 file size

2 file last modified time, in YmdHms format

3 file last accessed time, in YmdHms format

4 file created time, in YmdHms format

5 file attribute string in the form "RASH" (see FileAttrGet)

6 file attribute bitmask (see FileAttrGetEx)

FileItemize

328

Example: filelist = StrCat(ShortCutDir("Personal",0,@TRUE),"*.*") infoarray = FileInfoToArray(filelist, 1|2) infostr = StrCat("Number of files: ",infoarray[0,0],@Crlf) 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) exit

See Also: FileItemize, FileAttrGet, FileAttrGetEx, FileTimeGet, FileTimeGetEx, FileSize, FileSizeEx

FileItemize Returns a delimited list of files.

Syntax: FileItemize(file-list)

Parameters: (s) file-list a string containing a list of filenames, which may be

wildcarded.

Returns: (s) 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.

FileItemPath

329

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.

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 a string containing a list of filenames, which may be

wildcarded.

Returns: (s) 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

FileMapName

330

; Get which .INI file to edit 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 full or partial file name. (s) mapping-data mapping and wildcard definition string (see below).

FileMapName

331

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) If drive is specified in the mapping-data use specified drive, else use current drive.

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.

FileMove

332

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 one or more filenames separated by a delimiter. (s) destination target filename. (i) warning @TRUE for a warning before overwriting existing files;

@FALSE if no warning desired.

Returns: (i) @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"

FileMoveAttr

333

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 one or more filenames separated by a delimiter. (s) destination target filename. (i) warning @TRUE for a warning before overwriting existing files;

@FALSE if no warning desired. (s) attributes attributes to be modified.

Returns: (i) @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):

FileNameShort

334

Symbol Meaning Symbol Meaning

R read only ON A archive ON S system ON H hidden ON

r read only OFF a archive OFF s system OFF h 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.

FileOpen

335

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 name of the file to open. (s) mode "READ", "WRITE", or "APPEND" (i) Unicode If "Unicode" is @TRUE, the file will be treated as

containing Unicode data, otherwise it will be treated as containing ANSI data.

(i) timeout number of seconds to spend retrying the file open operation if it fails due to a sharing violation.

Returns: (i) 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.

FileOpen

336

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 Unicode Text in file FileWrite output format

APPEND ignored ANSI ANSI

APPEND ignored Unicode Unicode

WRITE @FALSE(default) ignored ANSI

WRITE @TRUE ignored 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 Unicode Text in file FileRead return format

READ @FALSE(default) ANSI ANSI

READ @FALSE(default) Unicode Unicode

READ @TRUE ignored 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")

FilePut

337

filewrite(handle, "dummy data one") fileclose(handle) Message("FileOpen","File %testfile1% created")

See Also: Binary Operations, BinaryRead, BinaryReadEx, BinaryWrite,BinaryWriteEx, IntControl 40, IntControl 39, 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 name of the file to write to. (s) string 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"

FileRead

338

str = "Hello World" data = FilePut(filename , str) Message("Done", "Writing string to file") exit

See Also: FileGet, FilePutW, FileWrite, IntControl 40

FilePutW Writes a Unicode string to a file.

Syntax: FilePutW(filename,Unicode string)

Parameters: (s) filename name of the file to write to. (s) Unicode string Unicode string to write to the file.

Returns: (i) 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") exit

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.

FileRename

339

Returns: (s) line of data read from file.

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 one or more filenames, separated by a tab delimiter. (s) destination 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.

FileSize

340

Note: Unlike FileMove, you cannot make a file change its resident disk drive with FileRename.

"Source-list" and "destination" may contain * and ? wildcards.

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])

FileSizeEx

341

Parameters: (s) file-list zero or more filenames, separated by a delimiter and may

contain wildcards. (i) format [optional] controls the format in which the size is returned.

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 zero or more filenames which may contain * and ?

wildcards., separated by a delimiter. (i) format [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.

FileTimeCode

342

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.

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

FileTimeGet

343

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.

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 name of file for which you want the date and time.

Returns: (s) 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")

FileTimeGetEx

344

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: 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 specifies a file or directory name. (i) time-field see below.

Returns: (s) 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

FileTimeSetEx

345

FileTimeSet Sets the date and time of one or more files.

Syntax: FileTimeSet(file-list,datetime)

Parameters: (s) file-list filename, list of files, or list of wildcards of files to set. (s) datetime datetime in the YmdHms format

Returns: (i) @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 filename, list of files, or list of wildcards of files to set. (s) datetime datetime in the YmdHms format (i) time-field see below.

Returns: (i) @TRUE on success; @FALSE if any of the specified files

could not be changed.

FileTimeTouch

346

"Time-field" can be one of the following:

1 file created 2 file last modified 3 file last accessed

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%*.*")

FileVerInfo

347

a=TimeYmdHms( ) Message("FileTimeTouch","All files in %temp% set to %a%")

See Also: FileAttrSet, FileTimeGet, IntControl 29

FileVerInfo Returns a version resource string from a binary file.

Syntax: FileVerInfo(filename,language-key,resource-string)

Parameters: (s) filename name of the EXE, DLL, or other binary file containing

version resource information. (s) language-key a hexadecimal string identifying the desired language and

character-set block within the file's resource table. (s) resource-string specifies the item to return. (see below.)

Returns: (s) 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 language character set 040904E4 U.S. English Windows Multilingual 040904B0 U.S. English Unicode 000004E4 Neutral Windows Multilingual 04090000 U.S. English Neutral 00000000 Neutral Neutral 000004B0 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):

FileVerInfo

348

"Comments" "LegalCopyright" "CompanyName" "LegalTrademarks" "FileDescription" "OriginalFilename" "FileVersion" "ProductName" "InternalName" "ProductVersion"

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`

FileWrite

349

DlgConfig=0 Dlg001=`067,003,168,014,VARYTEXT,"VaryText_1",FComments,DEFAULT,DEFAULT,1,DEFAULT,DEFAULT,DEFAULT,DEFAULT` Dlg002=`003,003,066,014,STATICTEXT,"StaticText_Comments:",DEFAULT,"Comments:",DEFAULT,2,DEFAULT,DEFAULT,DEFAULT,DEFAULT` Dlg003=`003,017,064,014,STATICTEXT,"StaticText_Company:",DEFAULT,"Company:",DEFAULT,3,DEFAULT,DEFAULT,DEFAULT,DEFAULT` Dlg004=`067,017,168,014,VARYTEXT,"VaryText_2",FCompany,DEFAULT,DEFAULT,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,DEFAULT,6,DEFAULT,DEFAULT,DEFAULT,DEFAULT` Dlg007=`003,045,064,014,STATICTEXT,"StaticText_Version:",DEFAULT,"Version:",DEFAULT,7,DEFAULT,DEFAULT,DEFAULT,DEFAULT` Dlg008=`067,045,168,014,VARYTEXT,"VaryText_4",FVersion,DEFAULT,DEFAULT,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,DEFAULT,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,DEFAULT,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,DEFAULT,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)

FileYmdHms

350

Parameters: (i) filehandle same integer that was returned by FileOpen. (s) output-data data to write to file.

Returns: (i) @FALSE.

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 Unicode Text in file FileWrite output format

APPEND ignored ANSI ANSI

APPEND ignored Unicode Unicode

WRITE @FALSE(default) ignored ANSI

WRITE @TRUE ignored 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)

Floor

351

See Also: FileTimeGet, FileTimeGetEx, TimeDate, TimeAdd, TimeDiffDays, TimeYmdHms, TimeDelay, TimeWait

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 value Floor is calculated from.

Returns: (f) 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.

For

352

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= Ceiling= Floor= 25.2 26.0 25.0 25.7 26.0 25.0 24.9 25.0 24.0 -14.3 -14.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 a variable name to be used for the loop index. (f) initial-value an expression used to set the initial value of the loop index. (f) last-value 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.

(f) increment 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.

ForEach

353

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 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 A variable name. (r) Collection 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

ForEach

354

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.

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 = ""

GetTickCount

355

colInstalledPrinters = "" objWMIService = ""

See Also For, ObjectCreate, ObjectGet

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)

GoSub

356

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)

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

IconExtract

357

y = a*(x**2) + b*x + c return

See Also: For, Goto, Return, Switch, Select, While

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("sol.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 specifies a fully qualified filename of the EXE or DLL

from which the icon group will be extracted.

IconInfo

358

(s) icon filename specifies the name of the ICO file to which the icon group will be written. If the file exists, it will be overwritten.

(i) index specifies the ordinal position in "filename" of the icon group to be extracted, where the first icon group is 1.

Returns: (i) the number of images in the icon group that was extracted.

Example: num = IconExtract(StrCat(DirWindows(0),"notepad.exe"),"ICONFILE.ICO",1) Message("Number of images in icon group extracted ",num) exit

See Also: IconInfo, IconReplace

IconInfo Returns information about the icons in an EXE/DLL or ICO file.

Syntax: IconInfo(filename,filetype)

Parameters: (s) filename specifies a fully qualified filename of the file from which

the icon information will be returned. (i) filetype specifies the type of file:

0 = EXE or DLL (Win32) 1 = ICO file

Returns: (a) 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

IconInfo

359

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"

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 Colors 1 2 2 4 4 16 8 256 16 65536 24 16 million 32 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) exit

IconReplace

360

See Also: IconExtract, IconReplace

IconReplace Replaces an existing icon group with a new icon group.

Syntax: IconReplace(filename,icon filename[,index[,flags]])

Parameters: (s) filename either a fully qualified filename with drive and path,

or just a filename and extension. (s) icon filename the filename of the icon. (i) index [optional] specifies the ordinal position of the icon

group to modify, where the first icon group is 1. (i) flags [optional] see below.

Returns: (i) 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 Meaning 0 Default

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

If … Endif

361

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 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 Color Depth

16x16 4 bit color

16x16 8 bit color

16x16 32 bit color

32x32 4 bit color

32x32 8 bit color

32x32 32 bit color

48x48 4 bit color

48x48 8 bit color

48x48 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

If … Endif

362

of statements endif

if ... else ... endif (structured): if expression series of statements else series 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

If … Endif

363

... 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 non-zero 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 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

IniDelete

364

IgnoreInput Turns off hardware input to Windows.

Syntax: IgnoreInput(mode)

Parameters: (i) mode @TRUE or @FALSE. Specify -1 to retrieve the current

state.

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 the major heading under which the item is located. (s) keyname 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".

IniItemize

365

Note: INI files are mapped to registry

Example: IniDelete("Desktop", "Wallpaper") IniDelete("Quicken", @WHOLESECTION) Message("IniDelete","Ini Deleted.")

See Also: IniDeletePvt, IniItemize, IniRead, IniWrite

IniDeletePvt Removes a line or section from a private INI file.

Syntax: IniDeletePvt(section,keyname,filename)

Parameters: (s) section the major heading under which the item is located. (s) keyname the keyword name of the item to delete. (s) filename 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.

IniItemizePvt

366

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.

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 the major heading to itemize. (s) filename 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 tab-delimited 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.

IniRead

367

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.")

See Also: IniDeletePvt, IniItemize, IniReadPvt, IniWritePvt

IniRead Reads data from the WIN.INI file.

Syntax: IniRead(section,keyname,default)

Parameters: (s) section the major heading to read the data from. (s) keyname the name of the item to read. (s) default 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

IniWrite

368

IniReadPvt Reads data from a private INI file.

Syntax: IniReadPvt(section,keyname,default,filename)

Parameters: (s) section the major heading to read the data from. (s) keyname the name of the item to read. (s) default string to return if the desired item is not found. (s) filename 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 major heading to write the data to.

IniWritePvt

369

(s) keyname name of the data item to write. (s) data string to write to the WIN.INI file.

Returns: (i) @TRUE.

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 major heading to write the data to. (s) keyname name of the data item to write. (s) data string to write to the INI file. (s) filename 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.

InstallFile

370

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) )

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 source file to be installed. (path optional, short , 8.3 version

required) (s) targname the name of the target file to be created. (without path) (s) default-targdir directory where the file is to be installed. (i) delete-old @TRUE - to delete existing same name files. @FALSE - to ignore existing same name files. (i) flags 1 - shared file 2 - force install

Returns: (s) "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|"

Int

371

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.

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

IntControl

372

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.

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# specifies which sub-function is to be performed (see below). (s) p1 - p4 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.

Returns 1.

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.

IntControl

373

p1 Meaning

0 Allows no item to be selected. Returns "NOFILESSELECTED"

1 An item must be selected. Returns a file name (default)

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 Meaning

0 Pop up message box giving user a chance to either cancel bat file or continue.

1 Allow Windows to be exited with no warning.

2 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)

3 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)

0 Provide notification message when program terminated by user.

4 Allow quiet termination.

8 Refuse to terminate.

IntControl

374

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.

Returns previous setting.

Example:

; We want to refuse any attempt to exit Windows until the WIL ; 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 Window handle p2 Message ID number (in decimal) p3 wParam p4 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.

IntControl

375

p1 Meaning

0 proportional font (default)

1 fixed pitch font

2 GUI font Note: that this option applies to AskLine, AskPassword, AskFileText and AskItemList

Returns the current font type (0 or 1, as above)

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 source file p2 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

376

IntControl(31,p1,0,0,0) Returns "Window ID's" for all Explorer windows.

p1 Meaning

0 Enumerate Explorer windows of class ExploreWClass.

1 32-bit Windows: Enumerates 32 bit Explorer windows id's of class CabinetWClass

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 address of a memory location. (s) data type specifies the type of data to be retrieved:

"BYTE" - returns a byte "WORD" - returns a word "LONG" - returns a long integer

(i) operation can be one of the following: value meaning 0 Read from memory 1 Write to memory

(s/i) new-value 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

377

IntControl(34,p1,p2,0,0) Returns the error message string which corresponds to the specified error.

p1 Meaning

{error number} returns the error message string which corresponds to the specified error

-1 returns the error message string corresponding to the last extender error or user-defined error.

Type of error passed.

p2 Meaning 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

378

IntControl(37,p1,p2,p3,p4) Replaces multiple images in an icon group in an EXE file. Note: This function is now obsolete. Use IconReplace instead.

IntControl(38,p1,p2,0,0) Sets quiet mode.

p1 Meaning

-1 Don't change (just return current setting)

0 Disable quiet mode (default).

1 Enable quiet mode.

p2 = error log filename, or a blank string ("") for no error log.

In "quiet mode":

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 Meaning -1 don't change (keep current setting)

0 prevent the file from being shared

1 allow other open operations for read access

2 allow other open operations for write access

3 allow other open operations for read and write access

IntControl 39 will affect the following functions:

ArrayFileGet ArrayFileGetCsv BinaryRead BinaryReadEx

IntControl

379

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 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 Meaning 0 2-digit year (YY:MM:DD:HH:MM:SS)

1 4-digit year (YYYY:MM:DD:HH:MM:SS) (default)

-1 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).

IntControl

380

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 Meaning

0 Don't wait for application to be ready.

1 Wait for application to be ready (default).

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

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 Meaning -1 Don't change (returns current setting)

0 Don't speed up SendKey in DOS programs in Windows NT.

1 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

381

IntControl(46,p1,0,0,0) Sets window retry timeout.

p1 Meaning

-1 Don't change (returns current setting)

0 No retries

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

IntControl(49,p1,p2,0,0) Adds system menus to WIL popup windows.

p1 specifies which popup windows will have system menus:

p1 Meaning -1 Don't change (return current setting)

0 No system menus (default).

1 Dialog boxes (created with Dialog or the WIL Dialog Editor). Note: If using dialog callback procedure use DialogProcOption code 1002 instead.

2 Item listboxes (e.g., created with "AskItemList", "AskFileText" or related functions).

3 Both Dialog boxes (1) and Item list boxes (2).

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

382

IntControl(50,p1,p2,0,0) Controls whether "Go to web page" button is added to WIL error boxes.

p1 Meaning

-1 Don't change (return current setting)

0 Remove "Go to web page" button from error boxes.

1 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 default "http://www.winbatch.com/"

user defined "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 Flag Name/ Meaning

IntControl

383

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

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

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

8 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 flag.

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

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

1024 CREATE_UNICODE_ENVIRONMENT If set, the environment block pointed to by lpEnvironment uses Unicode characters. If clear, the environment block uses ANSI characters.

2048 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 Windows-

IntControl

384

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

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

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

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 Flag Name/Meaning

32 NORMAL_PRIORITY_CLASS Indicates a normal process with no special scheduling needs.

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

128 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

IntControl

385

the operating system. Use extreme care when using the high-priority class, because a high-priority class CPU-bound application can use nearly all available cycles.

256 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 Terminator -1 Don't change (just return current setting)

0 No line terminator

1 CR/LF (DOS) (default)

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

386

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 Meaning handle window handle of the window to send the message to, or -1 for all

top-level windows.

p2 Meaning key 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.

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 Meaning

handle window handle of the window to send the message to, or minus one (-1) for all top-level windows.

p2 Meaning device 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.

IntControl

387

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.

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:

IntControl

388

p1 = left (upper-x) p2 = top (upper-y) p3 = right (lower-x) p4 = bottom (lower-y)

To explicitly indicate the default values that should be used, use:

IntControl(63, 0, 0, 0, 0)

Always @TRUE.

IntControl(64,0,0,0,0) Gets the exit code returned by the last program run.

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 Meaning -1 Don't change (just return current setting)

-2 (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.

IntControl

389

p2 Meaning

0 default. Normal shutdown. User is prompted for open files.

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

Returns 0.

IntControl(67,0,p2,0,0) Reboot system.

p2 Meaning 0 default. Normal shutdown. User is prompted for open files.

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

Returns 0.

IntControl(68,0,p2,p3,0) This will cause a shutdown of the machine, awaiting power off.

p2 Meaning 0 default. Normal shutdown. User is prompted for open files.

1 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 Meaning 0 Power-off if supported by the computer (*see note below*)

1 Don't attempt to power-off

2 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

390

Returns 0.

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.

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

IntControl

391

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

The return value of the cancel handling UDF has special meaning. The following values may be specified:

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

IntControl

392

line, or "" if none

wberrorhandlerfile (s) name of the currently-executing script

wberrortextstring (s) description of the WIL error

wberroradditionalinfo (s) delimited string of additional error information, if any. ASCII 160 is delimiter character between each error incident.

wberrorinsegment (s) name of the currently-executing UDF, or a blank string ("") if not in a UDF.

wberrorhandlerlinenumber (i) line number in the currently executing script or 0 if the cancel cannot be matched to a particular line.

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.

IntControl

393

If you want to have cancel handling in a User-Defined-Function/UserDefined Subroutine, then IntControl 72 must either:

1) Be defined within the User-Defined-Function/User-Defined-Subroutine. The :CANCEL label must also be contained within the User-Defined-Function/User-Defined-Subroutine.

2) 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.

p1 Meaning

-1 Don't change (just return current setting)

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. The following values may be specified:

IntControl

394

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 (s) name of the currently-executing script

wberrortextstring (s) description of the WIL error

wberroradditionalinfo (s) delimited string of additional error information, if any. ASCII 160 is delimiter character between each error incident.

wberrorinsegment (s) name of the currently-executing UDF, or a blank string ("") if not in a UDF.

wberrorhandlerlinenumber (i) line number in the currently executing script or 0 if the error cannot be matched to a particular line.

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 error occurred or 0. wberrorarray[10]= a positive number if reported

IntControl

395

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.

Note: 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 in a User-Defined-Function / User-Defined-Subroutine, then IntControl 73 must be defined with in the User-Defined-Function/User-Defined-Subroutine.

Returns previous setting.

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

IntControl

396

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.

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:

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 number of binary buffers open

31 number of binary buffer slots available

40 number of extenders loaded

41 number of extender slots available

42 tab-delimited list of extenders loaded

IntControl

397

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 Value

1 Index

2 Entry Type

Value 0 1 2 3 4 5 6 7 8

Type BINARYOP UNARYOP FUNCTION CONSTANT COMMAND COMPOP FUNCTBYNAME UNDEFINED STRUCTOP

3 Parameter type mask

4 Parameter count OR constant value

5 Name length

6 Name

Returns the indicated integer or string.

IntControl

398

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

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

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

399

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

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

400

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 Meaning

0 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)

location (URL) of information about file (can be "" if not needed)

URL of timestamp server (can be "" if not needed)

1 Get the thumbprint of a certificate in a file p2 specifies a .CER or .SPC file

2 Set the friendly name of a certificate p2 specifies the thumbprint of a certificate

p3 specifies the friendly name to set

IntControl(94,p1,0,0,0) Returns the real file handle corresponding to a WIL file handle.

p1 Meaning WIL file handle A file handle returned by one of the WIL functions.

IntControl

401

(i.e., FileOpen)

Returns a Windows file handle, or 0 if "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(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 Meaning 0 Run as a normal application (default).

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

IntControl

402

p1 Meaning

-1 Don't change (returns current setting)

0 Hide WinBatch icon.

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

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.

IntControl

403

p1 Meaning

-1 Don't change (returns current setting)

0 WinBatch icon cannot be opened.

1 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 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 currently-running script to the system tray

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

IntControl

404

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.

2 p2, p3, p4 ignored

Remove currently-running 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 currently-running 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

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

IntControl

405

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 exit

IntControl(1008,p1,0,0,0) Enables/disables Close command.

This function sets the "allow close" flag for the WinBatch icon/window.

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/Ctrl-Break command.

p1 Meaning -1 Don't change (just return current setting)

0 Close command is disabled (default).

1 Close command is enabled.

IsDefined

406

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 a variable name.

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.

IsInt

407

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)

See Also: IsInt, IsNumber

IsInt Tests whether a variable is or can be converted into a valid integer.

Syntax: IsInt(x)

Parameters: (s) x value to be tested.

IsLicensed

408

Returns: (i) @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.

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.

IsNumber

409

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

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

ItemCountCsv

410

ItemCount Returns the number of items in a list.

Syntax: ItemCount(list,delimiter)

Parameters: (s) list a string containing a list of items. (s) delimiter 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 comma-delimited 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. 72)

ItemCountCsv Returns the number of items in a comma separated values line.

Syntax: ItemCountCsv(line,flag[,delimiter])

Parameters: (s) line specifies a comma separated values line (see below). (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 treat leading and trailing whitespace as

significant

(s)delimiter [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.

ItemCountCsv

411

Returns: (i) 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

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. 72)

ItemExtractCsv

412

ItemExtract Returns the selected item from a list.

Syntax: ItemExtract(index,list,delimiter)

Parameters: (i) index the position in list of the item to be selected. (s) list a string containing a list of items. (s) delimiter 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. 72)

ItemExtractCsv Returns the selected item from a CSV line.

Syntax: ItemExtractCsv(index,line,flags[,delimiter])

Parameters: (i) index the ordinal position of the item to be returned. (s) line a CSV line (see below). (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 treat leading and trailing whitespace as significant

ItemExtractCsv

413

(s) delimiter [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.

Returns: (s) 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:

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"

ItemInsert

414

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. 72)

ItemInsert Adds an item to a list.

Syntax: ItemInsert(item,index,list,delimiter)

Parameters: (s) item a new item to add to list. (i) index the position in list after which the item will be inserted. (s) list a string containing a list of items. (s) delimiter 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 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)

ItemLocateWild

415

See Also: ItemCount, ItemCountCsv, ItemExtract, ItemExtractCsv, ItemLocate, ItemLocateWild, ItemRemove, ItemReplace, ItemSort, Lists Explained (pg. 72)

ItemLocate Returns the position of an item in a list.

Syntax: ItemLocate(item,list,delimiter)

Parameters: (s) item item to search for in list. (this is case sensitive) (s) list a string containing a list of items. (s) delimiter 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. 72)

ItemLocateWild Searches for an item in that list that fully matches a 'pattern'.

Syntax: ItemLocateWild (pattern, list, delimiter, start)

Parameters: (s) pattern the pattern to search for. May contain wild cards. (s) list a string containing a list of items. (s) delimiter a character to act as a delimiter between items in the list. (i) start position of first item to search.

Returns: (i) position in list of item, or 0 if no match found.

ItemRemove

416

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. 72)

ItemRemove Removes an item from a list.

Syntax: ItemRemove(index,list,delimiter)

Parameters: (i) index the position in list of the item to be removed. (s) list a string containing a list of items. (s) delimiter a character to act as a delimiter between items in the list.

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)

ItemSort

417

See Also: ItemCount, ItemCountCsv, ItemExtract, ItemExtractCsv, ItemInsert, ItemLocate, ItemLocateWild, ItemReplace, ItemSort, Lists Explained (pg. 72)

ItemReplace Replaces an item in a list.

Syntax: ItemReplace(item,index,list,delimiter)

Parameters: (s) item replacement item. (i) index the position in list of the item to be replaced. (s) list a string containing a list of items. (s) delimiter 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)

See Also: ItemCount, ItemCountCsv, ItemExtract, ItemExtractCsv, ItemInsert, ItemLocate, ItemLocateWild, ItemRemove, ItemSort, Lists Explained (pg. 72)

ItemSort Sorts a list.

Syntax: ItemSort(list,delimiter)

Parameters: (s) list a string containing a list of items.

KeyToggleGet

418

(s) delimiter 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. 72)

KeyToggleGet Returns the status of a toggle key.

Syntax: KeyToggleGet(@key)

Parameters: (i) @key 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

Returns: (i) @ON key was set; @OFF key was unset.

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

LastError

419

KeyToggleSet Sets the state of a toggle key and returns the previous value.

Syntax: KeyToggleSet(@key,value)

Parameters: (i) @key 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

(i) value The new value of the toggle key.

@OFF for the unset state @ON for the set state

Returns: (i) 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.

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.

LogDisk

420

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 .

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.

Max

421

Syntax: LogDisk(drive-letter)

Parameters: (s) drive-letter the disk drive to log into.

Returns: (i) @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.

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...])

Message

422

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 title of the message box. (s) text 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:

See Also: Display, Pause

Mod

423

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.

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

424

MouseClick Clicks mouse button(s).

Syntax: MouseClick(click-type,modifiers)

Parameters: (i) click-type a mouse button press. (i) modifiers 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 left click @RCLICK right click @MCLICK middle click @LDBLCLICK left double-click @RDBLCLICK right double-click @MDBLCLICK middle double-click

Modifiers (multiple modifiers can be linked together with a logical OR, "|"):

@SHIFT hold down shift key @CTRL hold down control key @LBUTTON hold down left mouse button @RBUTTON hold down right mouse button @MBUTTON hold down middle mouse button

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

MouseCoords

425

MouseClickBtn Clicks on the specified button control.

Syntax: MouseClickBtn(parent-winname,child-winname,button-text)

Parameters: (s) parent-winname the initial part of, or an entire parent window name. (s) child-winname the initial part or, or an entire child window name. (s) button-text 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")

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 the initial part of, or an entire parent window name. (s) child-winname the initial part or, or an entire child window name.

Returns: (s) coordinates the x and y coordinates of the mouse cursor, relative to the

window specified by "win-name" and "child-win".

MouseInfo

426

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#)

Parameters: (i) request# see below.

Returns: (s) see below.

The information returned by MouseInfo depends on the value of request#.

Req# Return value 0 Window name under mouse

1 Top level parent window name under mouse

2 Mouse coordinates, assuming a 1000x1000 virtual screen

3 Mouse coordinates in absolute numbers

4 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

MouseInfo

427

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

5 returns mouse coordinates relative to the client area of the window under the cursor, in virtual (1000x1000) screen units.

6 returns mouse coordinates relative to the client area of the window under the cursor, in virtual (1000x1000) client units.

7 returns mouse coordinates relative to the bounding rectangle of the window under the cursor, in virtual (1000x1000) screen units.

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

9 Window ID of top level parent window under mouse.

10 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# Return value 0 "Clock"

1 "Clock"

2 "500 500"

3 "320 240"

4 "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

MousePlay

428

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 integer specifying the coordinate X. (i) Y integer specifying the coordinate Y. (s) parent-winname the initial part of, or an entire parent window name. (s) child-winname 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".

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)

MousePlay

429

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.

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.

MousePlay

430

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 Meaning

@MPLAYLCLK Click left mouse button.

@MPLAYRCLK Click right mouse button.

@MPLAYMCLK Click middle mouse button.

@MPLAYLDBLCK Double click left mouse button.

@MPLAYRDBLCK Double click right mouse button.

@MPLAYMDBLCK Double click middle mouse button.

@MPLAYLBUTTON Hold down the left mouse button.

@MPLAYRBUTTON Hold down the right mouse button.

@MPLAYMBUTTON Hold down the middle mouse button.

@SHIFT Hold down the shift key.

@CTRL 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.

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)

Net101

431

MousePlay("1000 0", "", "", 0, 0.2) exit

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 case-sensitive.

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.

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.

NetInfo

432

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 0 for primary network name

1 for secondary subnet list

Returns: (s) 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:

Provider ID Description LanmanWorkstation Microsoft Windows Network NetWareWorkstation NetWare Services NWCWorkstation 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

OLE / COM

433

Num2Char Converts a number to its character equivalent.

Syntax: Num2Char(number)

Parameters: (i) number any number from 0 to 255.

Returns: (s) 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

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

OLE / COM

434

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:

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

OLE / COM

435

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

OLE / COM

436

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

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

OLE / COM

437

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. 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")

OLE / COM

438

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

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 Name Meaning

UI1 VT_UI1 An unsigned 1-byte integer.

UI2 VT_UI2 An unsigned 2-byte integer.

UI4 VT_UI4 An unsigned 4-byte integer.

UI8 VT_UI8 An unsigned 8-byte integer.

I1 VT_I1 A 1-byte integer value.

I2 VT_I2 A 2-byte integer value.

I4 VT_I4 A 4-byte integer value.

I8 VT_I8 A 8-byte integer value.

BOOL VT_BOOL A Boolean (True/False) value.

DATE VT_DATE A date/time string, in Ymd or YmdHms format.

DECIMAL VT_DECIMAL A decimal value, specified as a string in the form "#DECIMAL:value".

CURRENCY VT_CY A currency value, specified as a string in the form "#CURRENCY:value".

NULL VT_NULL A blank string ("").

DISPATCH VT_DISPATCH A pointer to an object was specified. This object is known only to implement IDispatch.

ObjectAccess

439

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.

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.

ObjectAccess Opens or creates an COM/OLE Automation object.

Syntax: ObjectAccess(app.objname,create-flag)

Parameters: (s) app.objname name of the desired object. (i) create-flag @TRUE, it will create an instance of the object, and return

a handle to it. @FALSE, it will fail and return an error.

Returns: (i) a special object handle to be used when referring to the

object.

ObjectAccess has been superceded with the function ObjectGet

If there is already a running instance of the object specified by "app.objname", this function will return a handle to that object.

If there is not a running instance of the specified object, the behavior will depend on the value of 'create-flag':

If 'create-flag' == @TRUE, it will create an instance of the object, and return a handle to it.

ObjectAccess

440

If 'create-flag' == @FALSE, it will fail and return an error.

This function is similar to ObjectOpen, except that ObjectOpen always

creates a new object and cannot be used to access an existing one.

Example: types = "Doc Files|*.doc" file = AskFileName("SelectFile", "C:\", types, "", 1) wdGoToLine = 3 wdLine = 5 wdExtend = 1 wdCharacter = 1 if AppExist("winword.exe") oWORD = ObjectAccess("Word.Application", @false) newWord = @false else oWORD = ObjectOpen("Word.Application") newWord = @TRUE endIf oDOCS = oWORD.Documents oDOC = oDOCS.Open(file) oWORD.visible=@TRUE oActiveDoc = oWORD.activedocument oSel=oWORD.selection oSel.GoTo(wdGoToLine,1) while @TRUE oSel.EndKey(:: Unit=wdLine, Extend=wdExtend) oSel.Copy line = clipGet() Message("Line",line) oSel.MoveRight(:: Unit=wdCharacter, Count=1) if oSel.MoveRight == 0 then break oSel.MoveLeft(:: Unit=wdCharacter, Count=1) ; compensate for MoveRight endWhile oActiveDoc.close() objectclose(oSel) objectclose(oActiveDoc) objectclose(oDOC) objectclose(oDOCS) if newWord oWord.Quit endIf objectclose(oWORD) exit

ObjectConstantsGet

441

See Also: See discussion in COM section, ObjectGet

ObjectClose Closes an COM/OLE Automation object

Syntax: ObjectClose(objecthandle)

Parameters: (r) objecthandle handle of object to close.

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

ObjectConstantsGet Creates a Constants object.

Syntax: ObjectConstantsGet(object)

Parameters (r) object reference COM object reference.

Returns: (r) constants object reference.

ObjectConstantsGet

442

Use this function to create a constants object for a COM Automation object:

adoApp = ObjectCreate("ADODB.Connection") adoConst = ObjectConstantsGet(adoApp)

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 read-only.

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

ObjectConstToArray

443

objRs.Fields.Append("MyBoolean",conRs.adBoolean) objRs.Fields.Append("MyDate",conRs.adDate) ; Commit the record metadata 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.

ObjectCreate

444

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]

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

ObjectCreate

445

(s) progid The programmatic identifier of the object to create, usually in the form servername.classname.

(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

446

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") 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 = ""

ObjectEventAdd

447

See Also:

ObjectGet, CreateObject, ObjectConstantsGet, ObjectConstToArray

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 variable containing an object reference (s) event-name name of event to be handled (s) UDF-name 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

ObjectEventAdd

448

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 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()

ObjectEventRemove

449

; Remove the event. ObjectEventRemove(objWmiSink, "OnObjectReady") ; To be safe shut down the WMI event sink objWmiSink.Cancel() objWbemObject = 0 objWbemAsyncContext = 0 objWmiSink = 0 objWmiServices = 0 exit

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 variable containing an object reference (s) event-name name of event being handled as a string

Returns: (i) @TRUE on success; @FALSE on failure.

ObjectEventRemove breaks the previously established link between a User-Defined-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.

ObjectEventRemove

450

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. #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)"

ObjectGet

451

objWorkbook = 0 objTarget = 0 objSheet = 0 objXlBook = 0 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 [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.

(s) progId [optional] The programmatic identifier of the object to create, usually in the form servername.classname.

Returns: (r) 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.

ObjectGet

452

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"

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

ObjectType

453

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 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.ServicePackMinorVersion) 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 see below. (s/i) value value of the variable.

ObjectType

454

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

BSTR A string

I1 A 1-byte character value

I2 A 2-byte integer value

I4 A 4-byte integer value.

I8 A 8-byte integer value.

UI1 An unsigned 1-byte character.

UI2 An unsigned 2-byte character.

UI4 An unsigned 2-byte character.

BOOL A Boolean (True/False) value.

CY A currency value, specified as a string in the form "#CURRENCY:value".

DATE A date/time value, specified as a string in Ymd or YmdHms format

DECIMAL A decimal value, specified as a string in the form "#DECIMAL:value".

NULL A blank string ("").

ARRAY A safe array.

DISPATCH A pointer to an object was specified. This object is known only to implement IDispatch.

Note that "variant-type" may optionally be preceded by the prefix "VT_", so for example you could specify either "BOOL" or "VT_BOOL".

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 visible = 0 ExcelApp.Visible = visible

ObjectType

455

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,pvaIn, pvaOut)

;Give the browser enough time to print before closing the object TimeDelay(1) objBrowserDoc = "" objAll = "" objBrowser = "" Return(1) #EndFunction file = "c:\temp\test.jpg"

ObjectTypeGet

456

If FileExist(file)then PrintGraphic(File) else Message("Error","Unable to locate file. Check file path.") Exit

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 variable containing an object reference.

Returns: (s) 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 Meaning

EMPTY No data, the size of the value is zero.

NULL This is like a pointer to NULL.

I1 1-byte signed integer.

UI1 1-byte unsigned integer.

I2 Two bytes representing a 2-byte signed integer value.

UI2 2-byte unsigned integer.

I4 4-byte signed integer value.

INT 4-byte signed integer value (equivalent to VT_I4).

UI4 4-byte unsigned integer.

UINT 4-byte unsigned integer (equivalent to VT_UI4).

I8 8-byte signed integer.

UI8 8-byte unsigned integer.

R4 32-bit IEEE floating point value.

R8 64-bit IEEE floating point value.

DECIMAL A decimal value, specified as a string in the form "#DECIMAL:value".

CY A currency value, specified as a string in the form "#CURRENCY:value".

ObjectTypeGet

457

DATE A date/time value, specified as a string in Ymd or YmdHms format.

BSTR A string.

BOOL A Boolean (True/False) value.

ERROR A DWORD containing a status code.

FILETIME 64-bit FILETIME structure as defined by Win32. It is recommended that all times be stored in Universal Coordinate Time (UTC).

LPSTR Pointer to a null-terminated ANSI string in the system default code page.

LPWSTR Pointer to a null-terminated Unicode string in the user's default locale.

CLSID Pointer to a class identifier (CLSID) (or other globally unique identifier (GUID)).

CF Pointer to a CLIPDATA structure.

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

BSTR_BLOB Reserved for system use.

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

STREAM Pointer to an IStream interface, representing a stream which is a sibling to the "Contents" stream.

STREAMED_OBJECT As in VT_STREAM, but indicates that the stream contains a serialized object, which is a CLSID followed by initialization data for the class. The stream is a sibling to the "Contents" stream that

ObjectTypeGet

458

contains the property set.

STORAGE Pointer to an IStorageinterface, representing a storage object that is a sibling to the "Contents" stream.

STORED_OBJECT As in VT_STORAGE, but indicates that the designated IStoragecontains a loadable object.

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

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

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

VARIANT A DWORD type indicator followed by the corresponding value. VT_VARIANT can be used only with VT_VECTOR or VT_BYREF.

ObjectTypeGet

459

DISPATCH A pointer to an object was specified. This object is known only to implement IDispatch.

UNKNOWN A pointer to an object that implements the IUnknown interface.

VOID VOID.

HRESULT Standard return type.

SAFEARRAY VT_ARRAY in VARIANT.

CARRAY C-style array.

USERDEFINED User-defined type.

RECORD User-defined type.

RESERVED

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 = ""

Pause

460

objLocator = ""

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 title of pause box. (s) text text of the message to be displayed.

Returns: (i) @TRUE.

PipeClientClose

461

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.

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 A:") exit

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

PipeClientOpen

462

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" 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: PipeClientOpen, PipeClientSendRecvData, PipeInfo, PipeServerClose, PipeServerCreate, PipeServerRead, PipeServerWrite

PipeClientOpen Connects to a named pipe.

Syntax: PipeClientOpen(pipe-name,timeout)

PipeClientOpen

463

Parameters: (s) pipe-name specifies the name of a pipe, in one of these forms:

\\ServerName\pipe\PipeName or \\.\pipe\PipeName (i) timeout specifies the timeout period in seconds, or -1 for no timeout.

Returns: (i/s) 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" response= TimeYmdHms() else response = "ERROR: UNKNOWN REQUEST"

PipeClientSendRecvData

464

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 pipe handle returned by PipeClientOpen. (s) data message/data to send to named pipe. (i) read-timeout specifies the timeout period in seconds, or -1 for no timeout.

Returns: (s) Returns a message string on success; "*ERROR*" on error;

"*TIMER*" on timeout.

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")

PipeInfo

465

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" 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, PipeClientOpen, PipeInfo, PipeServerClose, PipeServerCreate, PipeServerRead, PipeServerWrite

PipeInfo Returns information about a pipe or pipe operation.

Syntax: PipeInfo(request,pipe-handle)

Parameters: (i) request see below. (i) pipe-handle pipe handle returned by PipeClientOpen.

Returns: (i) depends on request.

Request Returns

PipeInfo

466

0 Error code for last unsuccessful pipe function ("pipe-handle" is ignored)

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*" Message("PipeClientOpen Error", PipeInfo(0, 0)) continue ; try again endif 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*" Message("PipeServerCreate Error", PipeInfo(0, 0)) continue ; try again endif readinfo = PipeServerRead(pipehandle, timeout) if readinfo=="*ERROR*" || readinfo=="*TIMER*" Message("PipeServerRead Error", PipeInfo(0, 0)) PipeServerClose(pipehandle,0) continue ; try again endif if readinfo == "GET_TIME" response= TimeYmdHms()

PipeServerClose

467

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, PipeClientOpen, PipeClientSendRecvData, PipeServerClose, PipeServerCreate, PipeServerRead, PipeServerWrite

PipeServerClose Closes a named pipe instance.

Syntax: PipeServerClose(pipe-handle,timeout)

Parameters: (i) pipe-handle pipe handle returned by PipeServerCreate. (i) timeout 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: ;------------ ; 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))

PipeServerCreate

468

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" 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, 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)

Parameters: (s) pipe-name specifies the name of a pipe, in the form:

\\.\pipe\PipeName (i) timeout specifies the timeout period in seconds that it will wait for a

client to connect., or -1 for no timeout.

PipeServerCreate

469

Returns: (i/s) a pipe handle on success; "*TIMER*" on timeout.

A maximum of 100 instances of a pipe can be created.

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" response= TimeYmdHms() else response = "ERROR: UNKNOWN REQUEST" endif rslt=PipeServerWrite(pipehandle,response) BoxText(StrCat("Data sent to client = ",response, notice))

PipeServerRead

470

PipeServerClose(pipehandle,timeout) Endwhile Message("Server","Exited") Exit

See Also: PipeClientClose, PipeClientOpen, PipeClientSendRecvData, PipeInfo, PipeServerClose, PipeServerRead, PipeServerWrite

PipeServerRead Reads a message from a named pipe.

Syntax: PipeServerRead(pipe-handle,timeout)

Parameters: (i) pipe-handle pipe handle returned by PipeServerCreate. (i) timeout specifies the timeout period in seconds, or -1 for no timeout.

Returns: (s) a message string on success; "*ERROR*" upon error;

"*TIMER*" on timeout.

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

PipeServerWrite

471

;------------ 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" 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, 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. (s) data message/data to send to named pipe.

Returns: (i/s) returns @TRUE on success; "*ERROR*" upon error.

Example: ;------------ ; CLIENT.WBT ;------------ server = "myserver" ; Or "." for the local machine pipename = "fluggle"

PipeServerWrite

472

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" 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, PipeClientOpen, PipeClientSendRecvData, PipeInfo, PipeServerClose, PipeServerCreate, PipeServerRead

PlayMedia

473

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.

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?")

PlayWaveForm

474

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 name of the MID or RMI sound file. (i) mode 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.

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.

Print

475

Syntax: PlayWaveForm(filename,mode)

Parameters: (s) filename name of the WAV sound file. (i) mode 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 Meaning

0 Wait for the sound to end before continuing.

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

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.

PtrGlobal

476

Syntax: Print(data file,directory,display mode,reserved)

Parameters: (s) data file the name of the file to print. (s) directory current working directory (if applicable). (i) display mode @NORMAL, @ICON, @ZOOMED, @HIDDEN. (i) reserved reserved.

Returns: (i) @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.

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.

PtrGlobalDefine

477

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.

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)

PtrPersistent

478

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

PtrPersistent Creates a "pointer" to a persistent variable.

Syntax: PtrPersistent(variable-name,value)

Parameters: (s) variable-name specifies a variable name which CANNOT be longer than

25 characters. (s/i) value specifies a value which will be assigned to "variable-name"

if the variable does not already exist.

Random

479

Returns: (s) 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

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.

Registration Database Operations

480

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

RegApp

481

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

Syntax: RegApp(program-name,path)

Parameters: (s) program-name the name of an executable program (EXE), optionally

containing a path. (s) path optional desired "PATH" setting for the specified program.

Returns: (i) @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:

RegCloseKey

482

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 semi-colons) 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. 480)

RegCloseKey Closes a key to the Registration Database.

Syntax: RegCloseKey(handle)

Parameters: (i) handle handle to a registration database key.

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)

RegConnect

483

See Also: RegOpenKey, RegCreateKey, RegSetValue, RegQueryValue and the section on Registration Database Operations (pg. 480)

RegConnect Connects to a predefined registry handle on another computer.

Syntax: RegConnect(computer-name,handle[,remoteOSflag])

Parameters: (s) computer-name the name of the computer in the form of "\\computername". (i) handle either @REGMACHINE OR @REGUSERS (s) remoteOSflag [optional] indicate the processor architecture

used by the remote operating system.

Returns: (s) 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).

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)

RegDeleteKey

484

See Also: RegCreateKey, RegCloseKey, RegDeleteKey, RegSetValue, RegQueryValue, RegQueryKey and the section on Registration Database Operations (pg. 480)

RegCreateKey Returns a handle to a new registration database key.

Syntax: RegCreateKey(handle,subkey-string[,view-flag])

Parameters: (i) handle handle to a registration database key. (s) subkey-string a path from the key provided to the desired key. (i) view-flag [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.

Returns: (i) 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 pre-defined 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. 480)

RegDeleteKey Deletes a key and data items associated with the key.

Syntax: RegDeleteKey(handle,subkey-string[,view-flag])

RegDelValue

485

Parameters: (i) handle an open registration database key (see below). (s) subkey-string a path from the key provided to the desired key. (i) view-flag [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.

Returns: (i) @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. 480)

RegDelValue Deletes a named value data item for the specified subkey from the registry.

Syntax: RegDelValue(handle,subkey-string[,view-flag])

Parameters: (i) handle handle to a registration database key. (s) subkey-string 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.

(i) view-flag [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.

RegEntryType

486

Returns: (i) @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. 480)

RegEntryType Returns the type of data for the specified subkey.

Syntax: RegEntryType(handle,subkey-string[,view-flag])

Parameters: (i) handle an open registration database key. (see below). (s) subkey-string a path from the key provided to the desired key. (i) view-flag [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.

Returns: (s) data type of specified subkey. (see below).

The return value will be one of the following:

Value DataType Description 0 (REG_NONE) No value type

1 (REG_SZ) An ANSI string

2 (REG_EXPAND_SZ) ANSI string that contains unexpanded references to environment variables (for example,

RegEntryType

487

%PATH%).

3 (REG_BINARY) Free form binary

4 (REG_DWORD) 32-bit number

5 (REG_DWORD_BIG_ENDIAN) 32-bit number, high byte first

6 (REG_LINK) Symbolic Link (Unicode)

7 (REG_MULTI_SZ) A delimited list of ANSI strings.

8 (REG_RESOURCE_LIST) Resource list in the resource map

9 (REG_FULL_RESOURCE_DESCRIPTOR) Resource list in the hardware description

10 (REG_RESOURCE_REQUIREMENTS_LIST) Resource requirements

11 (REG_QWORD) 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.

;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

RegEntryType

488

;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 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

RegEntryType

489

;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!") 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. 480)

RegExistValue

490

RegExistKey Checks whether a registry key exists.

Syntax: RegExistKey(handle,subkey-string[,view-flag])

Parameters: (i) handle handle to an open registration database key. (s) subkey-string a path from the key provided to the desired key. (i) view-flag [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.

Returns: (i) @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. 480)

RegExistValue Checks whether a value for a registry key exists.

Syntax: RegExistValue(handle,subkey-string[,view-flag])

Parameters: (i) handle an open registration database key. (s) subkey-string 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.

RegLoadHive

491

(i) view-flag [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.

Returns: (i) @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. 480)

RegLoadHive Loads a hive into a registry subkey.

Syntax: RegLoadHive(handle,subkey,filename)

Parameters: (i) handle either @REGUSERS or @REGMACHINE. (s) subkey the name of the key to be created (s) filename specifies the name of a hive file.

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: This function may require an Administrator level account, because it attempts to access to the HKEY_LOCAL_MACHINE registry key.

RegOpenFlags

492

Example: RegLoadHive(@REGMACHINE, "WinWare", "winware")

See Also: RegUnloadHive and the section on Registration Database Operations (pg. 480)

RegOpenFlags Specifies the registry view of the various Reg[..] functions.

Syntax: RegOpenFlags(flag)

Parameters: (i) flag a flag which specifies which view of the registry

the various Reg[..] functions will see.

Returns: (i) 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 Meaning

0 32-bit view under Win32, 64-bit view under WOW64 (default)

32 32-bit view

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

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:

RegOpenKey

493

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. 480)

RegOpenKey Returns a handle to an existing registration database key.

Syntax: RegOpenKey(handle,subkey-string[,view-flag])

Parameters: (i) handle handle to a registration database key. (s) subkey-string a path from the key provided to the desired key. (i) view-flag [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.

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)

RegOpenKeyEx

494

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. 480)

RegOpenKeyEx Opens a registry key with specified access rights.

Syntax: RegOpenKeyEx(handle,subkey-string,mode[,view-flag[,reserved]])

Parameters: (i) handle handle to a registration database key (s) subkey-string a path from the key provided to the desired key (s/i) mode access mode (see below) (i) view-flag [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.

(s) reserved [optional] reserved for future use; should be set to "".

Returns: (i) 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:

Value Name Meaning READ KEY_READ KEY_QUERY_VALUE |

KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY | STANDARD_RIGHTS_READ

WRITE KEY_WRITE KEY_SET_VALUE | KEY_CREATE_SUB_KEY | STANDARD_RIGHTS_WRITE

FULL KEY_ALL_ACCESS (KEY_QUERY_VALUE | KEY_SET_VALUE |

RegQueryBin

495

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 Name Meaning

1 KEY_QUERY_VALUE Permission to query subkey data.

2 KEY_SET_VALUE Permission to set subkey data.

4 KEY_CREATE_SUB_KEY Permission to create subkeys.

8 KEY_ENUMERATE_SUB_KEYS Permission to enumerate subkeys.

16 KEY_NOTIFY Permission for change notification.

32 KEY_CREATE_LINK Permission to create a symbolic link.

See Also: RegCloseKey, RegOpenFlags, RegOpenKey and the section on Registration Database Operations (pg. 480)

RegQueryBin Returns binary value at subkey position.

Syntax: RegQueryBin(handle,subkey-string[,view-flag])

Parameters: (i) handle handle to a registration database key. (s) subkey-string 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.

(i) view-flag [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.

RegQueryDword

496

Returns: (s) 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. 480)

RegQueryDword Returns DWORD value at subkey position.

Syntax: RegQueryDword(handle,subkey-string[,flags])

Parameters: (i) handle handle to a registration database key. (s) subkey-string 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.

(i) flags [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.

Returns: (i) contents of data item at key position desired.

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. 480)

RegQueryExpSz

497

RegQueryEx Retrieves a value from the registry.

Syntax: RegQueryEx(handle,subkey-string,delimiter,type[,view-flag])

Parameters: (i) handle an open registration database key (see below). (s) subkey-string 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.

(s) delimiter a character to act as a delimiter between items. "Delimiter" is ignored unless "type" is 7.

(i) type see below. (i) view-flag [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.

Returns: (s) a value from the registry.

"type" can be one of the following:

Value Meaning 1 REG_SZ - Unicode null terminated string

2 REG_EXPAND_SZ - Unicode null terminated string (with environment variable references)

3 REG_BINARY - Free form binary

4 REG_DWORD - 32-bit number

7 REG_MULTI_SZ - Multiple Unicode strings

11 REG_QWORD - 64-bit number

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. 480)

RegQueryExpSz Retrieves a REG_EXPAND_SZ value from the registry.

RegQueryExpSz

498

Syntax: RegQueryExpSz(handle,subkey-string[,view-flag])

Parameters: (i) handle an open registration database key. (s) subkey-string 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.

(i) view-flag [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.

Returns: (i) 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 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

RegQueryItem

499

See Also: RegApp, RegEntryType, RegQueryBin, RegQueryDword, RegQueryEx, RegQueryItem, RegQueryMulSz, RegQueryStr, RegQueryValue and the section on Registration Database Operations (pg. 480)

RegQueryItem Returns a list of named data items for a subkey.

Syntax: RegQueryItem(handle,subkey-string[,view-flag])

Parameters: (i) handle handle to a registration database key. (s) subkey-string a path from the key provided to the desired key. (i) view-flag [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.

Returns: (s) 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)

See Also: RegApp, RegEntryType, RegQueryBin, RegQueryDword, RegQueryEx, RegQueryExpSz, RegQueryMulSz, RegQueryValue and the section on Registration Database Operations (pg. 480)

RegQueryKeyLastWriteTime

500

RegQueryKey Returns subkeys of the specified key.

Syntax: RegQueryKey(handle,index)

Parameters: (i) handle handle to a registration database key. (i) index 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. 480)

RegQueryKeyLastWriteTime Returns the last write time for a registry key. (Windows NT or newer)

Syntax: RegQueryKeyLastWriteTime(handle,subkey-string[,view-flag])

Parameters: (i) handle handle to a registration database key. (s) subkey-string 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.

(i) view-flag [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.

RegQueryMulSz

501

Returns: (s) 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. 480)

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. 480)

RegQueryMulSz Retrieves a REG_MULTI_SZ value from the registry.

Syntax: RegQueryMulSz(handle,subkey-string,delimiter[,view-flag])

Parameters: (i) handle an open registration database key.

RegQueryQword

502

(s) subkey-string 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.

(s) delimiter a character to act as a delimiter between items. (i) view-flag [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.

Returns: (s) 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. 480)

RegQueryQword Retrieves a QWORD value from the registry.

Syntax: RegQueryQword(handle,subkey-string[,view-flag])

Parameters: (i) handle an open registration database key. (s) subkey-string 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.

(i) view-flag [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.

RegQueryStr

503

Returns: (s) 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. 480)

RegQueryStr Retrieves and expands a string value from the registry.

Syntax: RegQueryStr(handle,subkey-string[,view-flag])

Parameters: (i) handle an open registration database key. (s) subkey-string 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.

(i) view-flag [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.

Returns: (i) the expanded registry value.

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]"

RegQueryValue

504

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. 480)

RegQueryValue Returns data item string at subkey position.

Syntax: RegQueryValue(handle,subkey-string[,view-flag])

Parameters: (i) handle handle to a registration database key. (s) subkey-string 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.

RegSetBin

505

(i) view-flag [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.

Returns: (s) 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. 480)

RegSetBin Sets a binary value in the Registration Database.

Syntax: RegSetBin(handle,subkey-string,value[,view-flag])

Parameters: (i) handle handle to a registration database key. (s) subkey-string 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.

(s) value data to be stored into the database at desired key. (i) view-flag [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.

Returns: (i) @TRUE.

RegSetEx

506

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. 480)

RegSetDword Sets a DWORD value in the Registration Database.

Syntax: RegSetDword(handle,subkey-string,value[,flags])

Parameters: (i) handle handle to a registration database key. (s) subkey-string 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.

(i) value dword value to be stored into the database at desired key. (i) flags [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.

Returns: (i) @TRUE data item value was stored.

Example: RegSetDword(@REGCURRENT, "A Test Key[My DWORD Value]", 32,0) Message("RegSetDWord","Done.")

See Also: RegApp, RegEntryType, RegSetBin, RegSetEx, RegSetExpSz, RegSetMulSz, RegSetValue and the section on Registration Database Operations (pg. 480)

RegSetEx Sets a value in the registry.

RegSetExpSz

507

Syntax: RegSetEx(handle,subkey-string,value,delimiter,type[,view-flag])

Parameters: (i) handle an open registration database key. (s) subkey-string 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.

(s) value data to be stored in the database at desired key. (s) delimiter a character to act as a delimiter between items. "Delimiter"

is ignored unless "type" is 7. (i) type see below. (i) view-flag [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.

Returns: (s) @TRUE data item value was stored.

Type Meaning

1 (REG_SZ) Unicode null terminated string

2 (REG_EXPAND_SZ) Unicode null terminated string with environment variable references

3 (REG_BINARY) Free form binary

4 (REG_DWORD) 32-bit number

7 (REG_MULTI_SZ) Multiple Unicode strings

11 (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. 480)

RegSetExpSz Sets a REG_EXPAND_SZ value in the registry.

Syntax: RegSetExpSz(handle,subkey-string,value[,view-flag])

RegSetExpSz

508

Parameters: (i) handle an open registration database key. (s) subkey-string 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.

(s) value data to be stored in the database at desired key. (i) view-flag [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.

Returns: (i) @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") DllCall(DaDll,long:"SendMessageA",long:-1, long:WININICHG,long:0, lpstr:"Environment") endif exit else Message("RegQueryExpSz","Not supported by Non-NT registry") endif

RegSetQword

509

See Also: RegApp, RegEntryType, RegSetBin, RegSetDword, RegSetExpSz, RegSetMulSz, RegSetValue and the section on Registration Database Operations (pg. 480)

RegSetMulSz Sets a REG_MULTI_SZ value in the registry.

Syntax: RegSetMulSz(handle,subkey-string,value,delimiter[,view-flag])

Parameters: (i) handle an open registration database key. (s) subkey-string 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.

(s) value a list of strings, delimited with the specified delimiter character.

(s) delimiter a character to act as a delimiter between items. (i) view-flag [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.

Returns: (i) @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

See Also: RegApp, RegEntryType, RegSetBin, RegSetDword, RegSetEx, RegSetExpSz, RegSetValue and the section on Registration Database Operations (pg. 480)

RegSetQword Sets a QWORD value in the registry.

RegSetValue

510

Syntax: RegSetQword(handle,subkey-string,value[,view-flag])

Parameters: (i) handle an open registration database key. (s) subkey-string 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.

(i) value a space-delimited string of hex bytes, beginning with the low byte of the QWORD.

(i) view-flag [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.

Returns: (i) @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. 480)

RegSetValue Sets the value of a data item in the Registration Database.

Syntax: RegSetValue(handle,subkey-string,value[,view-flag])

Parameters: (i) handle handle to a registration database key. (s) subkey-string 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.

(s) value data to be stored into the database at desired key.

RegUnloadHive

511

(i) view-flag [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.

Returns: (i) @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. 480)

RegUnloadHive Unloads a hive from the registry.

Syntax: RegUnloadHive(handle,subkey)

Parameters: (i) handle either @REGUSERS or @REGMACHINE. (s) subkey the name of a key which is mapped to a hive file.

Returns: (i) @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")

Return

512

See Also: RegLoadHive and the section on Registration Database Operations (pg. 480)

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

Parameters: (dependent) depends on use, see below.

Returns: (dependent) 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.

RtStatus

513

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 (10) Return "Okay" Return myvariable * 10 Return (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)

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

Run

514

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,parameters)

Parameters: (s) program-name the name of the desired .EXE, .COM, .PIF, .BAT file, or a

data file. (s) parameters 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.

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.

RunEnviron

515

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 the name of the desired Windows EXE file. (s) params optional parameters as required by the application. (i) display mode @NORMAL, @ICON, @ZOOMED, @HIDDEN. (i) waitflag @WAIT, @NOWAIT.

Returns: (i) @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.

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 "command.com" 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%

RunHide

516

PAUSE %2 %3 %4 %5 %6 %7 %8 %9

WIL Run Command Run("dopath.bat", "c:\special command.com")

If the "program-name" has an extension other than .EXE, .COM, .PIF, or .BAT, it will be run with the associated application.

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,parameters)

Parameters: (s) program-name name of the desired .EXE, .COM, .PIF, .BAT, or data file. (s) parameters 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.

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.

RunHideWait

517

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,parameters)

Parameters: (s) program-name name of the desired .EXE, .COM, .PIF, .BAT, or data file. (s) parameters 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.

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

RunIconWait

518

RunIcon Runs a program as an iconic (minimized) window.

Syntax: RunIcon(program-name,parameters)

Parameters: (s) program-name name of the desired .EXE, .COM, .PIF, .BAT, or data file. (s) parameters 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.

Syntax: RunIconWait(program-name,parameters)

Parameters: (s) program-name name of the desired .EXE, .COM, .PIF, .BAT, or data file. (s) parameters 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.

RunShell

519

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,display mode,waitflag)

Parameters: (s) program-name name of the desired .EXE, .COM, .PIF, .BAT, or data file. (s) params optional parameters as required by the application. (s) directory target directory (if applicable). (i) display mode @NORMAL, @ICON, @ZOOMED, @HIDDEN. (i) waitflag @WAIT, @NOWAIT, @GETPROCID,

@GETEXITCODE.

Returns: (i) @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.

RunWait

520

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 @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,parameters)

Parameters: (s) program-name name of the desired .EXE, .COM, .PIF, .BAT, or data file. (s) parameters 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.

RunWithLogon

521

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 name of the desired .EXE, .COM, .PIF, .BAT, or data file. (s) params optional parameters as required by the application. (s) directory target directory (if applicable). (i) display mode @NORMAL, @ICON, @ZOOMED, @HIDDEN. (i) waitflag @WAIT, @NOWAIT, @GETPROCID. (s) username specifies the name of the user account to

log on to. Note: If you use the UPN format (user@DNS_domain_name), "domain" must be a blank string ("").

(s) domain 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.

(s) password specifies the password for the "username" account. (i) logon-flags see below.

"logon-flags" can be one of the following values:

Value Name Meaning

0 Default No logon-flag.

1 LOGON_WITH_PROFILE 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.

2 LOGON_NETCREDENTIALS_ONLY Log on, but use the specified

RunWithLogon

522

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 inter-domain 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.

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.

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,

RunWithLogon

523

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.") endif exit Example 2 ;This script supports four subroutines ; :SETINFO - code to specify Admin userid and password and domain ; :BEFORE - code that executes in user mode BEFORE running as admin ; :ADMIN - code that runs as ADMIN ; :AFTER - 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

RunWithLogon

524

; 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 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

RunZoom

525

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

RunZoom Runs a program as a full-screen (maximized) window.

Syntax: RunZoom(program-name,parameters)

Parameters: (s) program-name name of the desired .EXE, .COM, .PIF, .BAT, or data file. (s) parameters 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.

RunZoomWait

526

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,parameters)

Parameters: (s) program-name name of the desired .EXE, .COM, .PIF, .BAT, or data file. (s) parameters 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. 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

527

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.

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

SendKey

528

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.

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

~ {~} ; 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 }

SendKey

529

Alt {ALT} Backspace {BACKSPACE} or {BS} Clear {CLEAR} Ctrl-Break {CANCEL} Delete {DELETE} or {DEL} Down Arrow {DOWN} End {END} Enter {ENTER} or ~ Escape {ESCAPE} or {ESC} F1 through F16 {F1} through {F16} Help {HELP} Home {HOME} Insert {INSERT} or {INS} Left Arrow {LEFT} Page Down {PGDN} Page Up {PGUP} Pause {PAUSE} Right Arrow {RIGHT} Space {SPACE} or {SP} Tab {TAB} Up Arrow {UP}

Additional special characters to the SendKey (and SendKeysTo and SendKeysChild) functions:

Key SendKey equivalent 0 on numeric keypad {NUMPAD0} 1 on numeric keypad {NUMPAD1} 2 on numeric keypad {NUMPAD2} 3 on numeric keypad {NUMPAD3} 4 on numeric keypad {NUMPAD4} 5 on numeric keypad {NUMPAD5} 6 on numeric keypad {NUMPAD6} 7 on numeric keypad {NUMPAD7} 8 on numeric keypad {NUMPAD8} 9 on numeric keypad {NUMPAD9} * on numeric keypad {NUMPAD*} + on numeric keypad {NUMPAD+} - on numeric keypad {NUMPAD-} . on numeric keypad {NUMPAD.} / on numeric keypad {NUMPAD/} Enter on numeric keypad {NUMPAD~} Print Screen {PRTSC} % (single percent sign) %%

SendKey

530

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 {LALT} Right Alt key, standalone {RALT} Left Control key, standalone {LCONTROL} Right Control key, standalone {RCONTROL} Left Shift key, standalone {LSHIFT} Right Shift key, standalone {RSHIFT} Left Windows key, standalone {LWIN} Right Windows key, standalone {RWIN} Applications key, standalone {APPS} Left Alt key, combination {*LALT} Right Alt key, combination {*RALT} Left Control key, combination {*LCONTROL} Right Control key, combination {*RCONTROL} Left Shift key, combination {*LSHIFT} Right Shift key, combination {*RSHIFT} Left Windows key, combination {*LWIN} ;see notes below Right Windows key, combination {*RWIN} ;see notes below Applications key, combination {*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.

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 +

SendKey

531

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("{+}") ;always checks a checkbox SendKey("{-}") ;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*.*~")

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", "") crlf = StrCat(Num2Char(13), Num2Char(10)) ; 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.

SendKeysChild

532

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 the initial part of, or an entire parent window name. (s) child-winname the initial part of, or an entire child window name. (s) sendkey string string of regular and/or special characters.

Returns: (i) @FALSE.

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

SendMenusTo

533

; 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 the initial part of, or an entire parent window name. (s) sendkey string 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 "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.

SendMessageA

534

Syntax: SendMenusTo(parent-winname,menuname)

Parameters: (s) parent-winname the initial part of, or an entire parent window name. (s) menuname 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.

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 window id or handle to send to. (i) message-id message ID number (in decimal).

SendMessageW

535

(i) wParam wParam value (message-specific information). (s) lParam lParam value (message-specific information

assumed to be a character string).

Returns: (s) 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)

Parameters: (i) window-id/handle window id or handle to send to. (i) message-id message ID number (in decimal). (i) wParam wParam value (message-specific information). (s) lParam lParam value (message-specific information

assumed to be a Unicode string).

Returns: (s) 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

ShellExecute

536

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,display mode,operation)

Parameters: (s) program-name the name of the desired .EXE, .COM, .PIF, .BAT file or a

data file. (s) params optional parameters as required by the application. (s) directory current working directory (if applicable). (i) display mode @NORMAL, @ICON, @ZOOMED, @HIDDEN; or 0

for the default mode. (i) operation operation to perform on the specified file.

Returns: (i) @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 uses the CreateProcess API in the 32-bit version. Note that RunShell has a "wait" parameter, while this function does not.

"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.")

ShortcutDir

537

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 see list below. (i) source [optional] flag which can under 'certain' circumstances

specify the location from which the information will be retrieved. see below.

(i) add-slash [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.

Returns: (s) a directory name on success; a blank string

("") if no corresponding value was found.

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)

ShortcutDir

538

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)

Local AppData 28 CSIDL_LOCAL_APPDATA Local (non-roaming) 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

ShortcutDir

539

folder

My Pictures 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)

CommonVideo 55 CSIDL_COMMON_VIDEO My Videos (All Users profile)

56 CSIDL_RESOURCES Windows resources folder

CD Burning 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

ShortcutEdit

540

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.

Syntax: ShortcutEdit(link-name,target,params,start-dir,show-mode[,shortcut-type])

Parameters: (s) link-name the name of shortcut .LNK file to be created. (s) target file or directory name which "link-name" will point to. (s) params optional command-line parameters for "target" (s) start-dir "Start in" directory for "target". (i) show-mode "Run" mode for "target": @NORMAL, @ZOOMED, or

@ICON. (i) shortcut-type [optional] specifies the type of shortcut. see below.

Returns: (i) @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 Meaning 0 Normal shortcut (default)

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

ShortcutExtra

541

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

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 the name of shortcut .LNK file to be modified. (s) description the internal description for the shortcut. (s) hotkey the "shortcut key" to be assigned to the shortcut. (s) icon-file a file containing an icon to be used for the shortcut, with

optional path. (i) icon-index the 0-based index position of the desired icon within "icon-

file". (i) shortcut-type [optional] specifies the type of shortcut. see below

Returns: (i) @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 Meaning

ShortcutExtra

542

0 Normal shortcut (default)

1 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} {BS} {F13} {CLEAR} {DELETE} {F14} {DEL} {DOWN} {F15} {END} {ENTER} {F16} {ESCAPE} {ESC} {HOME} {HELP} {INS} {INSERT} {NUMPAD*} {LEFT} {NUMPAD-} {NUMPAD+} {NUMPAD/} {NUMPAD.} {NUMPAD1} {NUMPAD0} {NUMPAD3} {NUMPAD2} {NUMPAD5} {NUMPAD4} {NUMPAD7} {NUMPAD6} {NUMPAD9} {NUMPAD8} {PGUP} {PGDN} {RIGHT} {PRTSC} {SP} {SPACE} {UP} {TAB} {F1} {F7} {F2} {F8} {F3} {F9} {F4} {F10} {F5} {F11} {F6} {F12}

ShortcutInfo

543

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

Syntax: ShortcutInfo(link-name[, shortcut-type])

Parameters: (s) link-name the name of shortcut .LNK file. (i) shortcut type [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 file or directory name which the shortcut points to. params command-line parameters for "target". start-dir "Start in" directory for "target". show-mode "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.

ShortcutMake

544

"shortcut-type" specifies the type of shortcut, and can be one of the following:

Type Meaning

0 Normal shortcut (default)

1 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, "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 the name of shortcut .LNK file to be created. (s) target file or directory name which "link-name" will point to. (s) params command-line parameters for "target" or NULL string. (s) start-dir "Start in" directory for "target". (i) show-mode "Run" mode for "target": 1 (@ICON), 2 (@NORMAL), or

3 (@ZOOMED). (i) shortcut type [optional] specifies the type of shortcut. see below.

Sin

545

Returns: (i) @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 (""). "Show-mode" 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.

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 Meaning 0 Normal shortcut (default)

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

Sinh

546

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.

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

547

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# Meaning 0 Take snapshot of entire screen

1 Take snapshot of client area of parent window of active window

2 Take snapshot of entire area of parent window of active window

3 Take snapshot of client area of active window

4 Take snapshot of entire area of active window

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

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

SoundVolume

548

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.

Example: Sounds(1) Message("Sounds"," Sounded.")

See Also: Beep, PlayMedia, PlayMidi, PlayWaveForm

SoundVolume Sets the speaker volume.

Syntax: SoundVolume(level)

Parameters: (i) level specifies the volume level, from 0 (min) to 100 (max).

specify -1 to get the current volume setting.

Returns: (i) if level 0 to 100 it returns previous volume level.

if level is -1 it returns the current volume level.

StrByteCount

549

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.

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 specifies an ANSI or Unicode string. (i) request specifies how "string" should be treated in order to calculate

its length.

StrCat

550

Returns: (i) the length of a string, in bytes.

Request Meaning

-1 current format (ANSI or Unicode)

0 ANSI string (including double-byte ANSI character sets)

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

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%"

StrClean

551

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

StrClean Removes or replaces characters in a string.

Syntax: StrClean(source-string,characters,replacement,match-case,mode)

Parameters: (s) source-string the string to be operated upon. (s) characters a string that specifies the characters in "source-string" to be

replaced or retained. (s) replacement the replacement string to be inserted in place of matching

(or non-matching) characters. (i) match-case @TRUE or @FALSE, indicating whether string

comparisons are case-sensitive or case-insensitive, respectively.

(i) mode see below.

StrCmp

552

Returns: (s) 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., "~!@#"), 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 Meaning

1 Replace all occurrences of "characters" with "replacement"

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

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.

StrCnt

553

Syntax: StrCmp(string1,string2)

Parameters: (s) string1,string2 strings to compare.

Returns: (i) -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)

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.

StrFill

554

(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 a string to be repeated to create the return string. If the filler

string is null, spaces will be used instead. (i) length the length of the desired string.

Returns: (s) character string.

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…

StrFix

555

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 string to be adjusted to a fixed length. (s) pad-string appended to base-string if needed to fill out the

desired length. If pad-string is null, spaces are used instead.

(i) length character count of the string.

Returns: (s) 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 pad-string to achieve the desired length.

Example: a = StrFix("Henry", " ", 15) b = StrFix("Betty", " ", 15) c = StrFix("George", " ", 15) Message("Spaced Names", StrCat(a, b, c))

which produces…

StrFixBytesL

556

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 string to be adjusted to a fixed length. (s) pad-string appended to base-string if needed to fill out the

desired length. If pad-string is null, spaces are used instead.

(i) length specifies length in bytes.

Returns: (s) 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 ("Henry", " ", 15) b = StrFixBytes ("Betty", " ", 15) c = StrFixBytes ("George", " ", 15) Message("Spaced Names", StrCat(a, b, c))

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 string to be adjusted to a fixed length.

StrFixChars

557

(s) pad-string appended to base-string if needed to fill out the desired length. If pad-string is null, spaces are used instead.

(i) length specifies the length in bytes.

Returns: (s) 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 string to be adjusted to a fixed length. (s) pad-string appended to base-string if needed to fill out

the desired length. If pad-string is null, spaces are used instead.

(i) length character count of the string.

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))

StrFixLeft

558

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 string to be adjusted to a fixed length. (s) pad-string appended to base-string if needed to fill out the desired

length. If pad-string is null, spaces are used instead. (i) length character count of the string.

Returns: (s) 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.

Syntax: StrFixLeft(base-string,pad-string,length)

Parameters: (s) base-string string to be adjusted to a fixed length. (s) pad-string appended to base-string if needed to fill out the desired

length. If pad-string is null, spaces are used instead. (i) length character count of the string.

StriCmp

559

Returns: (s) 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 pad-string 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 strings to compare.

Returns: (i) -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 = AskLine("STRICMP", "Enter a test line", "", 0) b = AskLine("STRICMP", "Enter another test line", "", 0) c = StriCmp(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("STRICMP", "%a% is %d% %b%")

See Also: StrCmp, StrIndex, StrLen, StrScan, StrSub

StrIndex

560

StrIndex Searches a string for a sub-string.

Syntax: StrIndex(string,sub-string,start,direction)

Parameters: (s) string the string to be searched for a sub-string. (s) sub-string the string to look for within the main string. (i) start the position in the main string to begin search. The first

character of a string is position 1. (i) direction the search direction. @FWDSCAN searches forward, while

@BACKSCAN searches backwards.

Returns: (i) 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 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 = StrIndex(instr, " ", start, @FWDSCAN) If daend == 0 Message("Sorry...", "No spaces found") else a = StrCat("First word is: ", StrSub(instr, start, daend - 1)) Message("STRINDEX", a) endif

See Also: StrLen, StrScan, StrSub

StrIndexNc

561

StrIndexNc Searches a string for a sub-string, ignoring case.

Syntax: StrIndexNc(string,sub-string,start,direction)

Parameters: (s) string the string to be searched for a sub-string. (s) sub-string the string to look for within the main string. (i) start the position in the main string to begin search. The first

character of a string is position 1. (i) direction the search direction. @FWDSCAN searches forward, while

@BACKSCAN searches backwards.

Returns: (i) 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)) Message("STRINDEX", a) endif

See Also: StrIndex, StrIndexWild, StrLen, StrScan, StrSub

StrInsert

562

StrIndexWild Finds wildcarded text within a larger string.

Syntax: StrIndexWild(string,pattern,start)

Parameters: (s) string the string to be searched for a sub-string. (s) pattern the wildcarded text to search for. (i) start the position in the main string to begin search.

The first character of a string is position 1.

Returns: (i) 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", "ab*wx", 1) ; would return 1 StrIndexWild("abcd1234wxyz", "1*9", 1) ; would return 0(no match) StrIndexWild("abcd1234wxyz", "1*4", 1) ; would return 5 StrIndexWild("abcd1234wxyz", "1?34*z", 1) ; would return 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. (s) new-string specifies the string to be inserted into "base-string". (s) pad-string [optional] specifies a character or string to be used for

padding, if necessary. The default is a space (' ').

StrLen

563

(i) start [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 "new-string". The default is 1.

(i) length [optional] specifies the number of characters to insert. If "length" is shorter than the length of "new-string", "new-string" 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 "new-string".

Returns: (s) 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

StrLower

564

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 any text string. (s) pattern The wildcarded text to match. (i) start The position (in characters) within the string to begin

matching.

Returns: (i) 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", "ab*wx", 1) ; would return 10 StrLenWild("abcd1234wxyz", "1*9", 1) ; would return 0 StrLenWild("abcd1234wxyz", "1*4", 5) ; would return 4 StrLenWild("abcd1234wxyz", "1?34*z", 5) ; would return 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.

StrOverlay

565

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 specifies the existing string. (s) new-string specifies the string to be overlaid onto "base-string". (s) pad-string [optional] specifies a character or string to be used for

padding, if necessary. The default is a space (' '). (i) start [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.

(i) length [optional] specifies the number of characters to overlay. If "length" is shorter than the length of "new-string", "new-string" 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 "new-string".

Returns: (s) 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

StrScan

566

StrReplace Replaces all occurrences of a sub-string with another.

Syntax: StrReplace(string,old,new)

Parameters: (s) string string in which to search. (s) old target sub-string. (s) new 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 the string that is to be searched. (s) delimiters a string of delimiters to search for within string. (i) start the position in the main string to begin search. The first

character of a string is position 1. (i) direction the search direction. @FWDSCAN searches forward, while

@BACKSCAN searches backwards.

Returns: (i) 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"

StrSub

567

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 the string from which the sub-string is to be extracted. (i) start character position within string where the sub-string starts.

(The first character of the string is at position 1).

StrSubWild

568

(i) length 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.

Returns: (s) 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 the string from which the sub-string is to be extracted. (s) pattern the wildcarded text to match. (i) start the position (in characters) within the string to begin

matching.

Returns: (s) 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", "ab*wx", 1) ; would return "abcd1234wx" StrSubWild("abcd1234wxyz", "1*9", 1) ; would return "" StrSubWild("abcd1234wxyz", "1*4", 5) ; would return "1234" StrSubWild("abcd1234wxyz", "1?34*z", 5) ; would return "1234wxyz"

See Also: StrSub, StrLen, StrScan

StrTypeInfo

569

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 a character or a string. (i) flag 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 Name Meaning 1 C1_UPPER Uppercase

StrTypeInfo

570

2 C1_LOWER Lowercase

4 C1_DIGIT Decimal digits

8 C1_SPACE Space characters

16 C1_PUNCT Punctuation

32 C1_CNTRL Control characters

64 C1_BLANK Blank characters

128 C1_XDIGIT Hexadecimal digits

256 C1_ALPHA Any linguistic character: alphabetical, syllabary, or ideographic

512 C1_DEFINED 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 Name Word in string 1 C1_UPPER "Upper"

2 C1_LOWER "Lower"

4 C1_DIGIT "Digit"

8 C1_SPACE "Space"

16 C1_PUNCT "Punct"

32 C1_CNTRL "Cntrl"

64 C1_BLANK "Blank"

128 C1_XDIGIT "HexDg"

256 C1_ALPHA "Alpha"

512 C1_DEFINED "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= "!@#abcxyz123%@CRLF%111%@TAB%" While @TRUE str = AskLine( "Test", "Enter Something", str ) typeAND = StrTypeInfo( str, 0 )

StrUpper

571

typeOR = StrTypeInfo( str, 1) dalen = StrLen( str) 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)

Switch

572

See Also: StriCmp, StrLower

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.

SysParamInfo

573

Example: response=AskLine("Switch", "Enter a number between 1 and 3", 1, 0) Switch response case 1 Message("Switch", "Case 1 entered") break case 2 Message("Switch", "Case 2 entered") break 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 nteger that specifies the system-wide parameter to retrieve

or set. (s/i) value depends on specified request. (see below) (i) INI-update 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.

Returns: (s/i) depends on specified request. Note: If this function is

unable to execute for any reason, it returns the string "*UNSUPPORTED*"

Tanh

574

For a complete list of request numbers see the Windows Interface Language help file.

Example: request = 114 ;GetScreenSaverRunning value = 0 update = 0 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.

Terminate

575

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.

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 any logical expression. (s) title the title of a message box to be displayed before

termination. (s) message the message in the message box.

Returns: (i) @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.") exit ;Example 2 ; exits w/o message if answer isn't "YES": Terminate(answer != "YES", "", "") Message("Terminate"," Terminated.") exit

TerminateApp

576

;Example 3 ; unconditional termination w/o message box (same as Exit) Terminate(@TRUE, "", "") Message("Terminate"," Terminated.") exit ;Example 4 ; exits with message if variable is less than zero: Terminate(a < 0, "Error", "Cannot use negative numbers") Message("Terminate"," Terminated.") exit

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 Winname/appname 0 full or partial windowname of a WinBatch program window

2 full or partial windowname of a Windows program window

3 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 Meaning 0 Default

1 "current-session-only" flag (valid only if "name-type" == 3). If this flag is specified, and the script is running in a Terminal

TimeFunctions

577

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.

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, 2012, at 3:50:23 PM would be "2012: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.

TimeDate

578

TimeAdd Adds two YmdHms datetime variables

Syntax: TimeAdd(datetime1,datetime2)

Parameters: (s) datetime1 a datetime using the format of

YYYY:MM:DD:HH:MM:SS. (s) datetime2 a datetime to be added to the original using the same format.

Returns: (s) 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.

TimeDelay

579

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:

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.

Returns: (i) @TRUE.

TimeDiff

580

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

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 format YYYY:MM:DD. (s) datetime2 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)

TimeDiffSecs

581

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 uses format YYYY:MM:DD:HH:MM:SS, or

YYYY:MM:DD (s) datetime2 uses format YYYY:MM:DD:HH:MM:SS, or

YYYY:MM:DD

Returns: (i) 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.

TimeJulianDay

582

Syntax: TimeDiffSecs(datetime1,datetime2)

Parameters: (s) datetime1 format YYYY:MM:DD:HH:MM:SS. (s) datetime2 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)

TimeSubtract

583

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 a datetime using the format of

YYYY:MM:DD:HH:MM:SS. (s) datetime-diff amount of time to be subtracted from the original using the

same format

Returns: (s) time string in YmdHms format.

TimeYmdHms

584

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

UacElevationLevel

585

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 Meaning 0 Error, or unsupported platform.

1 Process is default (UAC is disabled, or standard user).

2 Process is running elevated.

3 Process is not running elevated (user is in Administrators group).

Example: level = UacElevationLevel( ) Message( "Current UAC elevation level", level ) Exit

See Also: UacManifestSettings, UacExePromptTest

UacExePromptTest

586

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.

VarType

587

Return Meaning

-1 running program would return an error.

0 program would not require elevation.

1 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 Meaning

0 (i) Manifest present. @TRUE or @FALSE.

1 (s) Manifest requested execution level (Vista and newer). Returns a blank string on earlier Windows Platforms.

2 (s) Manifest uiAccess (Vista and newer). Returns a blank string on earlier Windows Platforms.

3 (i) Valid signature. @TRUE or @FALSE.

Example: level = UacManifestSettings( 1 ) Message( "Manifest Requested Execution Level", level ) Exit

See Also: UacElevationLevel, UacExePromptTest

VarType Gets the type of a WIL variable.

VarType

588

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 Meaning

-1 specified name is a function name, reserved word or string constant.

0 undefined

1 integer

2 string

5 file handle

32 floating point value

65 binary buffer

128 Unicode string

256 array

512 variant

1536 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)") 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)

VersionDLL

589

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.

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.

WaitForKey

590

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

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} {BS}

WaitForKey

591

{CLEAR} {DELETE} {DEL} {DOWN} {END} {ENTER} {ESCAPE} {ESC} {F1} {F2} {F3} {F4} {F5} {F6} {F7} {F8} {F9} {F10} {F11} {F12} {F13} {F14} {F15} {F16} {HELP} {HOME} {INSERT} {INS} {LEFT} {NUMPAD*} {NUMPAD+} {NUMPAD-} {NUMPAD.} {NUMPAD/} {NUMPAD0} {NUMPAD1} {NUMPAD2} {NUMPAD3} {NUMPAD4} {NUMPAD5} {NUMPAD6} {NUMPAD7} {NUMPAD8} {NUMPAD9} {PGDN} {PGUP} {PRTSC} {RIGHT} {SPACE} {SP} {TAB} {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.

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")

WaitForKeyEx

592

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 a tab-delimited list of up to 100 keys to wait for. See

WaitForKey for a list of key codes. (i) timeout the number of seconds to wait before returning.

Returns: (i) 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.

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")

While

593

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 Name of the bmp/html wallpaper file. (i) tile @TRUE if wallpaper should be tiled;

@FALSE if wallpaper should not be tiled. 2 - if the wallpaper should be stretched.

Returns: (i) @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)

See Also: SysParamInfo

While Conditionally and/or repeatedly executes a series of statements.

Syntax: While continuation-condition series of

WinActivate

594

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:

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.

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

WinActivate Activates a previously running parent window.

Syntax: WinActivate(partial-winname)

Parameters: (s) partial-winname either an initial portion of, or an entire window

name. The most-recently used window whose title matches the name will be activated.

WinActiveChild

595

Returns: (i) @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 the initial part of, or an entire parent window name. (s) child-winname the initial part of, or an entire child window name.

Returns: (i) @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.

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)

WinClose

596

WinArrange Arranges, tiles, and/or stacks application windows.

Syntax: WinArrange(style)

Parameters: (i) style one of the following: @STACK, @TILE (or

@ARRANGE), @ROWS, or @COLUMNS.

Returns: (i) @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)

Parameters: (s) partial-winname either an initial portion of, or an entire window name. The

most-recently used window whose title matches the name will be closed.

Returns: (i) @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.

WinExeName

597

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 partial windowname of the window to be affected. (i) mode 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 Meaning 0 Don't stay on top

1 Stay on top

-1 Return window's current topmost state: @TRUE = topmost; @FALSE = not topmost

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.

WinExist

598

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,"") 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.

WinExistChild

599

Syntax: WinExist(partial-winname)

Parameters: (s) partial-winname the initial part of, or an entire, window name.

Returns: (i) @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 the initial part of, or an entire parent window name. (s) child-winname the initial part or, or an entire child window name.

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.

WinHelp

600

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.

Syntax: WinHelp(help-file,function,keyword)

Parameters: (s) help-file name of the Windows help file, with an optional full path. (s) function function to perform (see below). (s) keyword keyword to look up in the help file (if applicable), or "".

Returns: (i) @TRUE if successful; @FALSE if unsuccessful.

WinHelp

601

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 Keyword

"Contents" Brings up the Contents page for the help file. Specify a null string ("") for the "keyword" parameter.

"Key" 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.

"PartialKey" 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.

"Context" 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.

"Command" Executes the help macro specified by the "keyword" parameter.

"Quit" Closes the WINHELP.EXE window, unless another application is still using it. Specify a null string ("") for the "keyword" parameter.

"HelpOnHelp" Brings up the help file for the Windows help program (WINHELP.HLP). Specify a null string ("") for the "keyword" parameter.

"HTML" 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. 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

WinHide

602

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.

Syntax: WinHide(partial-winname)

Parameters: (s) partial-winname either an initial portion of, or an entire window

name. The most-recently used window whose title matches the name will be hidden.

Returns: (i) @TRUE if a window was found to hide;

@FALSE if no windows were found.

WinIconize

603

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 either an initial portion of, or an entire window name. The

most-recently used window whose title matches the name will be iconized.

Returns: (i) @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.

Example: Run("notepad.exe", "") WinIconize("~Not") ; partial window name used here

See Also: RunIcon, WinClose, WinHide, WinPlace, WinShow, WinZoom, Partial Window Names (pg.65)

WinIsDOS

604

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")

Parameters: (s) partial-winname the initial part of, or an entire, window

name.

Returns: (i) @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.

WinItemChild

605

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 a==@TRUE 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.

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)

WinItemizeEx

606

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.

Syntax: WinItemizeEx(partial-winname,multiple,hidden[,return-type])

Parameters: (s) partial-winname specifies a partial window name to look for.It can be a blank

string (""), in which case it will match any window. (i) multiple @TRUE or @FALSE. see below. (i) hidden @TRUE or @FALSE. see below. (i) return-type [optional] specifies the format in which the list of windows

will be returned.

Returns: (s) list of the titles of all open windows.

WinItemNameId

607

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 Meaning

0 Tab-delimited list of window titles (default)

1 Tab-delimited list of window ID's

2 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

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:

WinItemProcId

608

"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 returned from RunShell. (i) flags see below. (i) return-type see below.

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.

WinMetrics

609

"flags" can be 0, or one or more of the following values combined with the binary OR ("|") operator:

Flag Meaning

0 Default list of window ID's

1 Include windows with blank titles

2 Include hidden windows

4 Include windows which are not enabled for keyboard and mouse input

8 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 Meaning 0 Tab-delimited list of window ID's

1 Tab-delimited list of window titles

2 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

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.

WinMetrics

610

Req# Return value

-7 2 if WOW64 (32-bit emulation under 64-bit Windows), 0 otherwise

-6 pixels per horizontal dialog unit

-5 pixels per vertical dialog unit

-4 Windows Platform; 0 = Other, 1 = Windows 3.x, 2 = Windows for Workgroups, 3 = Win32s, 4 = Windows NT Family (e.g. 4.0/2000/XP/Vista/2003/7/2008), 5 = Windows 95/98/ME

-3 WIL EXE type; 0=Win16, 1=Intel32, 2=Alpha32, 3=Mips32, 4=PowerPC32, 5=64-bit WinBatch on Intel64/AMD64

-2 WIL platform; 1=Win16, 2=Win32, 3=Win64

-1 Number of colors supported by video driver

0 Width of screen, in pixels

1 Height of screen, in pixels

2 Width of arrow on vertical scrollbar

3 Height of arrow on horizontal scrollbar

4 Height of window title bar

5 Width of window border lines

6 Height of window border lines

7 Width of dialog box frame

8 Height of dialog box frame

9 Height of thumb box on scrollbar

10 Width of thumb box on scrollbar

11 Width of an icon

12 Height of an icon

13 Width of a cursor

14 Height of a cursor

15 Height of a one line menu bar

16 Width of full screen window

17 Height of a full screen window

18 Height of Kanji window (Japanese)

19 Is a mouse present (0 = No, 1 = Yes)

20 Height of arrow on vertical scrollbar

21 Width of arrow on horizontal scrollbar

22 Is debug version of Windows running (0 = No, 1 = Yes)

23 Are Left and Right mouse buttons swapped (0 = No, 1 = Yes)

24 Reserved

25 Reserved

26 Reserved

27 Reserved

WinMetrics

611

28 Minimum width of a window

29 Minimum height of a window

30 Width of bitmaps in title bar

31 Height of bitmaps in title bar

32 Width of sizeable window frame

33 Height of sizeable window frame

34 Minimum tracking width of a window

35 Minimum tracking height of a window

41 @TRUE or non-zero if the Microsoft Windows for Pen computing extensions are installed; zero, or @FALSE, otherwise.

42 @TRUE or non-zero if the double-byte character set (DBCS) version of USER.EXE is installed; @FALSE, or zero otherwise.

43 Number of buttons on mouse, or zero if no mouse is installed.

44 Not supported.

63 Not supported.

67 Not supported.

70 @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.

73 Not supported.

74 Not supported.

75 (WinNT 4.0+,) Non-zero if a mouse with a wheel is installed, zero otherwise

76 (Win2000) Coordinates for the left side of the virtual screen

77 (Win2000) Coordinates for the top of the virtual screen

78 (Win2000) Width of the virtual screen, in pixels

79 (Win2000) Height of the virtual screen, in pixels

80 (Win2000) Number of display monitors on the desktop

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

WinPlace

612

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)

Parameters: (i) x-ulc how far from the left of the screen to place the upper-left

corner (0-1000). (i) y-ulc how far from the top of the screen to place the upper-left

corner (0-1000). (i) x-brc how far from the left of the screen to place the bottom-right

corner (10-1000) or @NORESIZE. (i) y-brc how far from the top of the screen to place the bottom-right

corner (10-1000) or @NORESIZE. (s) partial-winname 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.

WinPlaceChild

613

Returns: (i) @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 multi-monitor 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.

Syntax: WinPlaceChild(x-ulc,y-ulc,x-brc,y-brc,parent-winname,child-winname)

Parameters: (i) x-ulc how far from the left of the screen to place

the upper-left corner (0-1000). (i) y-ulc how far from the top of the screen to place

the upper-left corner (0-1000). (i) x-brc how far from the left of the screen to place

the bottom-right corner (10-1000) or @NORESIZE. (i) y-brc how far from the top of the screen to place

the bottom-right corner (10-1000) or @NORESIZE. (s) parent-winname specifies the parent of the window to place.

WinPlaceGet

614

(s) child-winname specifies the child window to be placed.

Returns: (i) @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 multi-monitor 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) 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)

WinPlaceSet

615

Parameters: (i) win-type @ICON, @NORMAL, or @ZOOMED (s) partial-winname 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 multi-monitor 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)

WinPlaceSet Sets window coordinates.

Syntax: WinPlaceSet(win-type,partial-winname,position-string)

Parameters: (i) win-type @ICON, @NORMAL, or @ZOOMED (s) partial-winname the initial part of, or an entire, window name. (s) position-string window coordinates (see below).

WinPosition

616

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 multi-monitor 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.

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.

WinPositionChild

617

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 the initial part of, or an entire parent window name. (s) child-winname 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) 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

618

WinResources Returns information on available memory and resources.

Syntax: WinResources(request#[,format])

Parameters: (i) request# see below. (i) format [optional] see below.

Returns: (i) see below.

The value of request# determines the piece of information returned.

Req# Return value 10 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.

11 Total number of bytes of physical memory.

12 Number of bytes of physical memory available.

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

14 Number of bytes available in the paging file.

15 Total number of bytes that can be described in the user mode portion of the virtual address space of the calling process.

16 Number of bytes of unreserved and uncommitted memory in the user mode portion of the virtual address space of the calling process.

17 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).

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.

WinState

619

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 either an initial portion of, or an entire window

name. The most-recently used window whose title matches the name will be shown.

Returns: (i) @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)

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

WinSysInfo

620

"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 Symbolic name Meaning

-1 @HIDDEN Specified window exists, but is hidden

0 @FALSE Specified window does not exist

1 @ICON Specified window is iconic (minimized)

2 @NORMAL Specified window is a normal window

3 @ZOOMED 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)

Returns: (s) a TAB delimited list of system configuration information.

WinSysInfo returns a TAB-delimited list containing the following items:

1. computer name of the current system. 2. processor architecture. 3. page size (specifies granularity of page protection and commitment). 4. mask representing the set of processors configured into the system. 5. number of processors in the system. 6. processor type.

WinTitle

621

7. granularity in which memory will be allocated. 8. system's architecture-dependent processor level. 9. 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 either an initial portion of, or an entire window

name. The most-recently used window whose title matches the name will be shown.

(s) new-name the new name of the window.

Returns: (i) @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.

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

622

WinVersion Provides the version number of the current Windows system.

Syntax: WinVersion(level)

Parameters: (i) level see below.

Returns: (i) Windows version number.

Level Returns

0

(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 (i) Build number

3 (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.

4 (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

5

(s) Version string This is a string in the form: "platform-major-minor" where "platform" is one of the following: Value Meaning

0 Win32s 1 Windows 95/98/ME 2 Windows NT Family

6 Major version number of the latest Service Pack installed.

7 Minor version number of the latest Service Pack installed.

8 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

WinVersion

623

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.

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

10 System Architecture. Value Meaning 1 32-bit operating system architecture. 2 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:

WinWaitChild

624

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 2 6 0 7 2 6 1 2008 (Server) 2 6 0 2008 R2 (Server) 2 6 1

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" if v=="2-6-1" then Platform="Windows 7" Message("Platform",platform)

Example: minorver = WinVersion(0) majorver = WinVersion(1) 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 the initial part of, or an entire parent window name. (s) child-winname the initial part of, or an entire child window name.

WinWaitClose

625

(i) timeout the number of seconds to wait (maximum = 86400). Specify 0 to return immediately (no wait). Specify -1 for no timeout (wait forever).

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

Syntax: WinWaitClose(partial-winname[,timeout])

Parameters: (s) partial-winname either an initial portion of, or an entire window

name. (i) timeout [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.

Returns: (i) @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.

WinWaitExist

626

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 the initial part of, or an entire, window name. (i) timeout the number of seconds to wait (maximum = 86400). Specify

0 to return immediately (no wait). Specify -1 for no timeout (wait forever).

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)

WinZoom

627

WinWaitReady Waits until an application is waiting for user input.

Syntax: WinWaitReady(partial-winname,timeout)

Parameters: (s) partial-winname the initial part of, or an entire, window name. (i) timeout the number of milliseconds to wait.

Specify 0 to return immediately (no wait). Specify -1 for no timeout (wait forever).

Returns: (i) 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.

Syntax: WinZoom(partial-winname)

Parameters: (s) partial-winname either an initial portion of, or an entire window name. The

most-recently used window whose title matches the name will be shown.

Returns: (i) @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.

Yields

628

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

Yields

629

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

Menu File Structure

631

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.

Menu File Structure

632

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 statement under a menu item and continues up to the definition of the next item.

Menus can be up to four levels deep. Levels are determined by the column position of the first letter in the menu title. The top level menu starts at Column 1, the second starts in Column 2, and so on. The WIL code must begin at Column 5 or greater. Same level menu items must be separated by WIL code.

In the example below, Option #1 and Option #2 are separated by the WIL code which is to be executed.

&Top Menu (Level 1) Option #1 (Level 2) Submenu of Option #1 (Level 3) Submenu of Option #1 (Level 4) WIL code Option #2 (Level 2) Submenu (Level 3) WIL code

Your application probably included a pre-defined sample menu. Refer to it for a practical example of correct menu structure.

Here is another example of an extremely simple menu file:

Menu File Structure

633

&Games &Solitaire Run("sol.exe", "")

The first line, &Games, begins in column 1, and therefore defines a top-level menu item. Depending on the product you are using, it may either appear on a menu bar or it may appear on the first-level drop-down menu. The ampersand (&) is optional; it defines an Alt-key combination for the entry (Alt-G in this example). It will appear in the menu as Games.

The second line, &Solitaire, begins in column 2, and defines the title for an individual menu item. Again, the ampersand (&) is optional. It defines an Alt-key combination of Alt-S. This item will appear in the menu as Solitaire.

The third line, Run("sol.exe", ""), is the actual code which will be executed when this menu item is selected. Like all menu code, it must be indented at least four spaces (i.e., it must begin in column 5 or higher). This third line is really the entire WIL program; the two lines above it are simply titles which define the position of the program (i.e., the menu item) in the overall menu structure.

Here's a slightly expanded version of the program:

&Games &Solitaire Display(1, "Game Time", "About to play Solitaire") Run("sol.exe", "")

Here, we've simply added a line of code, changing this into a two-line program. Notice that each additional line of code is still indented the same four spaces.

Now, let's look at a menu file which contains two menu items:

&Games &Solitaire Run("sol.exe", "") &Minesweeper Run("winmine.exe", "")

We've added a new menu item, Minesweeper, which begins in column 2 (like Solitaire) and will appear under the top-level menu item Games.

To add a new top-level menu item, just create a new entry beginning in column 1:

&Games &Solitaire Run("sol.exe", "") &Minesweeper Run("winmine.exe", "") &Applications &Notepad Run("notepad.exe", "")

Menu File Structure

634

&WinBatch Studio Run("winbatch studio.exe", "")

Now there are two top-level menu titles, Games and Applications, each of which contains two individual items (the blank line between Games and Applications is not necessary, but is there just for readability).

In supported applications such as FileMenu, a comment can be displayed on the status bar in the Windows Explorer. This works only for top level menu items. The comment must be on the same line as the top level item. For example, the menu item below is a main menu for running Games. "Killers of Time" is the comment that appears in the status bar.

&Games ;Killers of Time &Solitaire Run("sol.exe", "")

In addition to top-level menus, you can optionally define up to three additional levels of sub-menus. The titles for the first-level, second-level and third-level sub-menus must begin in columns 2, 3, and 4 respectively, and the individual menu items they contain must be indented one additional column.

For example:

&Applications &Editors &Notepad Run("notepad.exe", "") &WinBatch Studio Run("winbatch studio.exe", "") &Excel Run("excel.exe", "")

In the above example, Editors is a sub-menu (beginning in column 2), which contains two menu items (beginning in column 3). Excel also begins in column 2, but since it does not have any sub-menus defined below it, it is a bottom-level (i.e., individual) menu item. Here's an even more complex example:

&Applications &Editors &Notepad Run("notepad.exe", "") &Winbatch Studio Run("winbatch studio.exe", "") |&Spreadsheets &Windows-based &Excel Run("excel.exe", "") _&DOS-based

Menu Hotkeys

635

&Quattro Run("q.exe", "")

We've added an additional level of sub-menus under Spreadsheets, so that the bottom-level menu items (Excel and Quattro) now begin in column 4. There are also two special symbols presented in this menu: the underscore (_), which causes a horizontal separator line to be drawn above the associated menu title, and the vertical bar (|), which causes the associated menu title to appear in a new column.

Some applications allow you to place an individual (bottom-level) menu item in column 1:

&Notepad Run("notepad.exe", "")

in which case it will appear on the top-level menu, but will be executed immediately upon being selected (i.e., there will be no drop-down menu).

Modifying Menus As stated earlier, menu files must be created and edited with an editor, such as WinBatch Studio, that is capable of saving files in pure ASCII text format. After you have edited your menu, it must be reloaded into memory for the changes to take effect. You may be able to do this manually, via the application's control menu (see your product documentation for information). Or, you can have a menu item use the Reload function. Otherwise, the menus will be reloaded automatically the next time you execute any menu item. However, if the menus are reloaded automatically, the WIL Interpreter will not be able to determine which menu item you had just selected, and it will therefore display a message telling you that you need to re-select it.

Menu Hotkeys In addition to the standard methods for executing a menu item (double-clicking on it, highlighting it and pressing Enter, or using Alt + the underlined letter), you may be able to define optional hotkeys for your menu items. (PopMenu and WinBatch Studio have this capability, FileMenu does not.) Hotkeys will cause an item to be executed immediately upon pressing the designated hot key. Hotkeys are defined by following the menu item with a backslash (\) and then the hotkey:

&Accessories &Notepad \ {F2} Run("notepad.exe", "") &Calculator \ ^C Run("calc.exe", "")

In the above example, the F2 key is defined as the hotkey for Notepad, and Ctrl-C is defined as the hotkey for Calculator.

Menu Items

636

Most single keys and key combinations may be used as hotkeys, except for the F10 key, and except for Alt and Alt-Shift key combinations (although you may use Alt-Ctrl key combinations).

Refer to the SendKey function (pg. 528) for a list of special keycodes which may also be used as hot keys.

If you always access a menu item by using its hotkey, you may not need or want the menu item to appear in the pull-down menus.

If so, you can make it a non-displayed menu item by placing a @ symbol in front of the title.

For example:

&Accessories @Notepad \ {F2} Run("notepad.exe", "")

In this case, Notepad would not appear in the pull-down menus, but could still be accessed by using the F2 hotkey.

Note: Hotkeys and non-displayed menu items may not work in all implementations of the WIL Interpreter.

Menu Items Menu titles can consist of letters, digits, spaces, punctuation marks - in fact any displayable ANSI characters your text editor can create.

There are special characters you can use to modify the appearance of items in the menus.

& Causes the following character to be underlined in the menu item. The user can select the item by pressing the ALT key with the character instead of using the mouse.

| In a main menu, puts this item on a new line.

| In a drop down menu, this item starts a new column.

_ Used to create a horizontal bar (in drop down menus only).

@ Causes the item not to be displayed in the menu.

In order to identify a menu item within a WIL statement, each menu item you define has an associated menu name. The menu name is built using only the letters and digits that make up the menu title. Menu names are case-insensitive; you don't have to worry about how the actual menu title is capitalized in order to identify it.

Menu Items

637

For menu items in a pop-up menu, the menu name consists of its parent menu's name, plus the pop-up menu item's name concatenated at the end.

Top-level menu names must begin in column 1. Sub-menu names are optional, and if used must begin in column 2-4; each column of indentation represents an additional level of sub-menu nesting. Actual menu code must begin in column 5 or higher, and must appear directly under the menu name to which it belongs.

Predefined Constants

639

APPENDIX Constants

Predefined Constants WIL has a number of built-in integer constants that can make your scripts much more readable. These start with the @-sign, and are case-insensitive.

Logical Conditions @NO

@OFF

@TRUE

@YES

@ON

@FALSE

Window Arranging @NORESIZE

@STACK

@ARRANGE

@TILE

@ROWS

@COLUMNS

Window Status @NORMAL

@ZOOMED

@ICON

@HIDDEN

@GETPROCID

OS Dependent @CAPSLOCK @NUMLOCK @REGCLASSES

Menu Handling @CHECK

@UNCHECK

@DISABLE

@ENABLE

String Handling @FWDSCAN

@BACKSCAN

System Control @MAJOR

@MINOR

Error Handling @CANCEL

@NOTIFY

@OFF

Keyboard Status @SHIFT

@CTRL

Mouse Control @LBUTTON @RBUTTON

Floating Point Constants

640

@REGCURRENT @REGMACHINE @REGUSERS @SCROLLLOCK @WHOLESECTION

BinarySort Control @ASCENDING @DESCENDING @STRING @WORD1 @WORD2 @WORD4 @FLOAT8

INI File Management @WHOLESECTION

@MBUTTON @LCLICK @RCLICK @MCLICK @LDBLCLICK @RDBLCLICK @MDBLCLICK

Miscellaneous @MULTIPLE @NOWAIT @OPEN @ROWS @SAVE @SINGLE @SORTED @STACK @TILE @UNSORTED

@WAIT

String Constants WIL defines a few string constants that are handy for formatting and processing text data. These start with the @-sign, and are case-insensitive.

@CRLF 13,10 cr,lf

@LF 10 lf

@CR 13, cr

@TAB 09 tab

Floating Point Constants WIL has several predefined floating point constants that can be handy for scientific and engineering scripts. Like all WIL constants, they start with the @-sign, and are case-insensitive.

@AMC Atomic Mass Constant 1.66043E-27

@GOLDENRATIO Goldenratio 1.6180339887498948

Floating Point Constants

641

@AVOGADRO Avogadro's Constant 6.02252E23

@GRAVITATION Gravity Constant 6.670E-11

@BOLTZMANN Boltzmann Entropy Constant 1.38054E-23

@LIGHTMPS Speed of Light (miles/sec) 186272

@DEG2RAD Degrees to radians conversion constant 0.017453292519943

@e Base of natural or Napierian logarithms 2.718281828459045

@LIGHTMTPS Lightmtps meters/sec 2.997925E8

@MAGFIELD Magnetic Field Constant 1.256637

@ELECTRIC Electric Field Constant 8.8541853E-12

@PARSEC Parsec (AU) 206.265

@EULERS Eulers's Constant 0.5772156649015338

@PI Pi 3.141592653589793

@FARADAY Faraday Constant 9.64870E4

@PLANCKERGS Planck's Constant (Ergs) 6.6252E-27

@GFTSEC Gravitational Acceleration feet/sec2 32.174

@PLANCKJOULES Planck's Constant (joules) 6.6256E-34

@GMTSEC Gravitational Acceleration meters/sec2 9.80665

@RAD2DEG Radians to Degrees Conversion Constant 57.29577951308232

INDEX

642

INDEX @CRLF, 55, 636 @TAB, 55, 636 About, 84 Abs, 84 Acos, 85 AddExtender, 85–87 AppExist, 87–88 AppWaitClose, 88–89 ArrayFileGet, 89–90 ArrayFileGetCsv, 90–91 ArrayFilePut, 91–92 ArrayFilePutCsv, 92–93 ArrayFromStr, 93–94 ArrayInsert, 94–95 Arrayize, 95 ArrayLocate, 95–96 ArrayRedim, 96–97 Arrays, 80–81 ArraySearch, 98–99 ArraySort, 99–100 ArraySwapElements, 100–101 ArrayToStr, 101 ArrDimension, 101–3 ArrInfo, 103–4 ArrInitialize, 104–5 ArrRemove, 105–6 Asin, 106–7 AskColor, 107 AskDirectory, 108–10 AskFileName, 110–12 AskFileText, 112–13 AskFont, 113–15 AskItemList, 51, 115–17 AskLine, 41, 117–18 AskPassword, 119 AskTextBox, 119–20 AskYesNo, 41, 120–21 Atan, 121 Average, 122

Beep, 42, 122 Binary Operations, 123 BinaryAlloc, 123–24 BinaryAllocArray, 124–26 BinaryAnd, 126–27 BinaryBufInfo, 127–28 BinaryCheckSum, 128–29 BinaryClipGet, 129–30 BinaryClipPut, 130–31 BinaryCompare, 132 BinaryConvert, 132–34 BinaryCopy, 134–35 BinaryEodGet, 135 BinaryEodSet, 135–36 BinaryFree, 136–37 BinaryHashRec, 137–38 BinaryIncr, 138–39 BinaryIndex, 139–40 BinaryIndexBin, 140–41 BinaryIndexEx, 141–42 BinaryIndexNC, 142–43 BinaryOleType, 143–46 BinaryOr, 146–47 BinaryPeek, 147–48 BinaryPeekHex, 148–49 BinaryPeekStr, 149–50 BinaryPeekStrW, 150 BinaryPoke, 150–51 BinaryPokeHex, 151–52 BinaryPokeStr, 152–53 BinaryPokeStrW, 153–54 BinaryRead, 154 BinaryReadEx, 154–55 BinaryReplace, 156 BinarySort, 156–58 BinaryStrCnt, 158–59 BinaryTagExtr, 159–60 BinaryTagFind, 160–62 BinaryTagIndex, 162–63

INDEX

643

BinaryTagInit, 163–65 BinaryTagLen, 165–66 BinaryTagRepl, 166–69 BinaryWrite, 169 BinaryWriteEx, 169–70 BinaryXlate, 170–72 BinaryXor, 172–73 Break, 173–74 ButtonNames, 174–75 Call, 175–76 Cancel, 61–62 Ceiling, 176–77 Char2Num, 177–78 ChrGetCodePage, 178 ChrHexToString, 178–79 ChrHexToUnicode, 179 ChrSetCodePage, 179–80 ChrStringToHex, 180 ChrStringToUnicode, 180–81 ChrUnicodeToHex, 181 ChrUnicodeToString, 181 ClipAppend, 181–82 ClipGet, 182–83 ClipGetEx, 183 ClipHasFormat, 183–84 ClipPut, 184–85 COM, 431–37 Command Line Parameters, 20 Comments, 75 ComputerNameGet, 185–86 ComputerNameSet, 186–87 Conditional Branching

For, 350–51 ForEach, 351–53 If, 359–61 Select, 525–26 Switch, 569–70 Terminate, 572–73 While, 590–91

Constants, 69, 635–37 Floating Point, 69, 636 Integer, 69 Predefined, 70, 635 String, 70, 636

Continue, 187–88

Cos, 188 Cosh, 188–89 CreateObject, 189 CRLF, 64 CurrentFile, 189–90 CurrentPath, 190 CurrFilePath, 191 DataCast, 191–92 DDEExecute, 192–93 DDEInitiate, 193–94 DDEPoke, 194–95 DDERequest, 195 DDETerminate, 196 DDETimeout, 196–97 Debug, 64–65, 197–99 DebugData, 199–200 DebugTrace, 200–205 Decimals, 205 Dialog, 206–41 Dialog - Using Internet Explorer Controls

in WIL Dialogs, 232–41 DialogControlGet, 241–45 DialogControlSet, 245–49 DialogControlState, 249–53 DialogObject, 253–57 DialogProcOptions, 257–63 DirAttrGet, 263 DirAttrGetEx, 264–66 DirAttrSet, 266–67 DirAttrSetEx, 267–69 DirChange, 45, 269–70 DirExist, 270–71 DirGet, 46, 271 DirHome, 271–72 DirInfoToArray, 272–73 DirItemize, 53–54, 273–74 DirMake, 274–75 DirRemove, 275 DirRename, 275–76 DirScript, 276 DirSize, 276–77 DirWindows, 277–78 DiskExist, 278–79 DiskFree, 279–80 DiskInfo, 280

INDEX

644

DiskScan, 280–81 DiskSize, 281–82 DiskVolInfo, 282–83 Display, 40, 283–84 DllCall, 284–86 DllCall Additional Information, 286–89 DllCallbackCreate, 286–87 DllCallCdecl, 289–91 DllFree, 292 DllHinst, 292–93 DllHwnd, 293–94 DllLastError, 294 DllLoad, 294–95 DOSVersion, 295 Drop, 295–96 DropWild, 296–97 Dynamic Dialogs, 224 EndSession, 45, 297–98 Environment, 56, 298 EnvironSet, 299–300 EnvItemize, 300–301 ErrorEvent, 300–301 ErrorMode, 47, 301–3 Errors, 47–49, 81–82

see also. LastError, IntControl 73, ErrorMode, Debug

Exclusive, 303 Execute, 304 ExeTypeInfo, 304–5 Exit, 305 Exp, 306 Extenders, 62–64 Fabs, 306 File Delimiters, 67–68 File Management, 45–47 FileAppend, 306–7 FileAttrGet, 307–8 FileAttrGetEx, 308–10 FileAttrSet, 311 FileAttrSetEx, 311–13 FileBaseName, 313–14 FileClose, 314 FileCompare, 314–15 FileCopy, 46, 315–17 FileCopyAttr, 317–18

FileCreateTemp, 318–19 FileDelete, 46, 319–20 FileDigest, 320–21 FileExist, 46, 321–22 FileExtension, 322 FileFullName, 322–23 FileGet, 323 FileGetW, 323–24 FileInfoToArray, 324–26 FileItemize, 51, 326 FileItemPath, 327 FileLocate, 327–28 FileMapName, 328–30 FileMove, 330–31 FileMoveAttr, 331–32 FileNameLong, 332 FileNameShort, 332–33 FileOpen, 333–35 FilePath, 335 FilePut, 335–36 FilePutW, 336 FileRead, 336–37 FileRename, 47, 337–38 FileRoot, 338 FileSize, 338–39 FileSizeEx, 339–40 FileTimeCode, 340–41 FileTimeGet, 341–42 FileTimeGetEx, 342 FileTimeSet, 343 FileTimeSetEx, 343–44 FileTimeTouch, 344–45 FileVerInfo, 345–47 FileWrite, 347–48 FileYmdHms, 348–49 FindWindow, 349 Floor, 349–50 Flow Control, 32–37 For, 350–51 ForEach, 351–53 GetExactTime, 353 GetObject, 353 GetTickCount, 353–54 GoSub, 354–55 Goto, 355

INDEX

645

IconExtract, 355–56 IconInfo, 356–58 IconReplace, 358–59 Identifiers, 70 If, 29–32, 359–61 IgnoreInput, 362 INDEX, 638 IniDelete, 362–63 IniDeletePvt, 363 IniItemize, 363–64 IniItemizePvt, 364–65 IniRead, 365 IniReadPvt, 366 IniWrite, 366–67 IniWritePvt, 367–68 InstallFile, 368–69 Int, 369–70 IntControl, 65, 370–404 IsDefined, 404–5 IsFloat, 405 IsInt, 405–6 IsKeyDown, 406 IsLicensed, 406–7 IsNumber, 407 ItemCount, 408 ItemCountCsv, 408–9 ItemExtract, 410 ItemExtractCsv, 410–12 ItemInsert, 412–13 ItemLocate, 413 ItemLocateWild, 413–14 ItemRemove, 413–15 ItemReplace, 415 ItemSort, 415–16 KeyToggleGet, 416 KeyToggleSet, 417 Keywords, 73 LastError, 417–18 Log10, 418 LogDisk, 418–19 LogE, 419 Max, 419–20 Menu Files, 627–33 Message, 40, 420 Min, 421

Mod, 421 MouseClick, 422 MouseClickBtn, 423 MouseCoords, 423–24 MouseInfo, 424–26 MouseMove, 426 MousePlay, 426–29 MsgTextGet, 429 Net101, 429–30 NetInfo, 430 Num2Char, 431 ObjectAccess, 437–38 ObjectClose, 439 ObjectConstantsGet, 439–41 ObjectConstToArray, 441–42 ObjectCreate, 442–45 ObjectEventAdd, 445–47 ObjectEventRemove, 447–49 ObjectGet, 449–51 ObjectOpen, 451 ObjectType, 451–54 ObjectTypeGet, 454–58 OLE, 431–37 Operators, 73–74

Precedence, 74–75 Parameters

Commandline, 20 Function, 76

ParseData, 458 Partial Window Names, 65–66 Pause, 40, 458–59 PipeClientClose, 459–60 PipeClientOpen, 460–62 PipeClientSendRecvData, 462–63 PipeInfo, 463–65 PipeServerClose, 465–66 PipeServerCreate, 466–68 PipeServerRead, 468–69 PipeServerWrite, 469–70 PlayMedia, 471–72 PlayMidi, 472 PlayWaveForm, 472–73 Predefined Constants, 635 Print, 473–74 PtrGlobal, 474–75

INDEX

646

PtrGlobalDefine, 475–76 PtrGlobalTest, 476 PtrPersistent, 476–77 Random, 477–78 RegApp, 479–80 RegCloseKey, 480–81 RegConnect, 481–82 RegCreateKey, 482 RegDeleteKey, 482–83 RegDelValue, 483–84 RegEntryType, 484–87 RegExistKey, 488 RegExistValue, 488–89 Registration Database Operations, 478–79 RegLoadHive, 489–90 RegOpenFlags, 490–91 RegOpenKey, 491–92 RegOpenKeyEx, 492–93 RegQueryBin, 493–94 RegQueryDword, 494 RegQueryEx, 495 RegQueryExpSz, 495–97 RegQueryItem, 497 RegQueryKey, 498 RegQueryKeyLastWriteTime, 498–99 RegQueryKeys, 499 RegQueryMulSz, 499–500 RegQueryQword, 500–501 RegQueryStr, 501–2 RegQueryValue, 502–3 RegSetBin, 503–4 RegSetDword, 504 RegSetEx, 504–5 RegSetExpSz, 505–7 RegSetMulSz, 507 RegSetQword, 507–8 RegSetValue, 507–9 RegUnloadHive, 509–10 Reload, 510 Return, 510–11 RtStatus, 511–12 Run, 38, 39, 512–13 RunEnviron, 513–14 RunHide, 514–15 RunHideWait, 515

RunIcon, 39, 516 RunIconWait, 516–17 Running DOS programs, 56 Running Programs, 38–39 RunShell, 39, 517–18 RunWait, 518–19 RunWithLogon, 39, 519–23 RunZoom, 38, 523–24 RunZoomWait, 524 Sample WBT File, 58–60 Select, 525–26 SendKey, 526–30 SendKeysChild, 530–31 SendKeysTo, 57, 531 SendMenusTo, 531–32 SendMessageA, 532–33 SendMessageW, 533–34 ShellExecute, 39, 534–35 ShortcutDir, 535–38 ShortcutEdit, 538–39 ShortcutExtra, 539–41 ShortcutInfo, 541–42 ShortcutMake, 542–43 Sin, 543–44 Sinh, 544 SnapShot, 545–46 Sounds, 68, 546 SoundVolume, 546–47 Sqrt, 547 StrByteCount, 547–48 StrCat, 548–49 StrCharCount, 549 StrClean, 549–50 StrCmp, 550–51 StrCnt, 551–52 StrFill, 552–53 StrFix, 553–54 StrFixBytes, 554 StrFixBytesL, 554–55 StrFixChars, 555–56 StrFixCharsL, 556 StrFixLeft, 556–57 StriCmp, 557 StrIndex, 558 StrIndexNc, 558–59

INDEX

647

StrIndexWild, 559–60 StrInsert, 560–61 StrLen, 561 StrLenWild, 561–62 StrLower, 562 StrOverlay, 562–63 StrReplace, 563–64 StrScan, 564–65 StrSub, 565–66 StrSubWild, 566 StrTrim, 566–67 StrTypeInfo, 567–69 StrUpper, 569 Substitution, 71–72

and StrCat, 548–49 Switch, 569–70 SysParamInfo, 571 Tan, 571–72 Tanh, 572 Terminate, 572–73 TerminateApp, 573–75 Termination of WIL, 64 Things To Know, 61–68 TimeAdd, 575–76 TimeDate, 576–77 TimeDayofWeek, 577 TimeDelay, 42, 577 TimeDiff, 578 TimeDiffDays, 578–79 TimeDiffSecs, 579–80 TimeFunctions, 575–83 TimeJulianDay, 580 TimeJulToYmd, 580–81 TimeSubtract, 581–82 TimeWait, 582 TimeYmdHms, 582–83 UacElevationLevel, 583 UacExePromptTest, 583–84 UacManifestSettings, 584 User Defined Functions, 77–79 User-Defined-Callback, 224 Variables, 28, 71 VarType, 584–86 Version, 586 VersionDLL, 586–87

WaitForKey, 587–89 WaitForKeyEx, 589–90 WallPaper, 590 While, 590–91 WIL Language Components, 69–76 WIL Tutorial, 19–60 WinActivate, 44, 591–92 WinActiveChild, 592 WinArrange, 593 WinClose, 44, 593–94 Window Management, 42–45 Window Names, 65–66 WindowOnTop, 594 WinExeName, 594–95 WinExist, 44–45, 595–96 WinExistChild, 596–97 WinGetActive, 597 WinHelp, 597–99 WinHide, 599–600 WinIconize, 42, 600 WinIdGet, 601 WinIsDOS, 601–2 WinItemChild, 602 WinItemize, 603 WinItemizeEx, 603–4 WinItemNameId, 604–5 WinItemProcId, 605–6 WinMetrics, 606–8 WinName, 609 WinPlace, 609–10 WinPlaceChild, 610–11 WinPlaceGet, 611–12 WinPlaceSet, 612–13 WinPosition, 613–14 WinPositionChild, 614 WinResources, 615–16 WinShow, 42, 616 WinState, 616–17 WinSysInfo, 617–18 WinTitle, 618 WinVersion, 619–21 WinWaitChild, 621–22 WinWaitClose, 622–23 WinWaitExist, 623 WinWaitReady, 623–24

INDEX

648

WinZoom, 42, 624–25 Yield, 625

Yields, 625–26