Batch Scripting

Embed Size (px)

Citation preview

  • Copyright 1999, 2011 by Wilson WindowWare 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.

    TRADEMARKS Microsoft and MS-DOS are registered trademarks of Microsoft Corporation.

    Windows is a trademark of Microsoft Corporation.

    WinBatch is a trademark of Wilson WindowWare, Inc.

  • Table of Contents

    TABLE OF CONTENTS TABLEOFCONTENTS..............................................................................................................................I

    INTRODUCTION:BECOMINGAPROGRAMMER....................................................................................XI

    THEREWILLBEATEST.........................................................................................................................XI

    CHAPTER1:THEGOLEMPRINCIPLE.....................................................................................................13

    BASICSOFPROGRAMMING....................................................................................................................13HOWCOMPUTERAPPLICATIONSWORK.......................................................................................................14LINGUACYBER........................................................................................................................................14THESORCERERSAPPRENTICE.....................................................................................................................16PRINCIPLESOFDESIGNINGAPPLICATIONS.....................................................................................................19

    StepOne:DefiningObjectives........................................................................................................19StepTwo:DefiningCommunications.............................................................................................20StepThree:DefiningTasks.............................................................................................................21StepFour:WritingtheCode...........................................................................................................22StepFive:Testing,Testing,andRetesting......................................................................................22StepSix:GettingOutsideOpinions................................................................................................23StepSeven:Documenting..............................................................................................................23

    SUMMARY..............................................................................................................................................24

    CHAPTER2:THEPROGRAMMER'SWORKROOM.................................................................................25

    THEINTEGRATEDDEVELOPMENTENVIRONMENT.........................................................................................25HOWTOUSETHISBOOK..........................................................................................................................25COMPILEDVERSUSINTERPRETEDPROGRAMS................................................................................................26ABRIEFHISTORYOFTHEIDE.....................................................................................................................27

    AnIntroductiontotheWinBatchIDE.............................................................................................28AFIRSTPROGRAM:HELLO,WORLD............................................................................................................29WINBATCHSTUDIOFEATURESANDTOOLS...................................................................................................32

    FileOperations...............................................................................................................................33Cut,Copy,andPasteOperations....................................................................................................34UndoandRedoOperations............................................................................................................34Find,FindNext,andReplaceOperations.......................................................................................34BookmarkOperations....................................................................................................................35Tools...............................................................................................................................................35DebuggingTools.............................................................................................................................36

    SUMMARY..............................................................................................................................................38

    CHAPTER3:DIALOGSANDTHEDIALOGEDITOR..................................................................................39

    HOLDINGAFORMALCONVERSATION.......................................................................................................39ANINTRODUCTIONTOTHEDIALOGEDITOR..................................................................................................39PREDEFINEDDIALOGS...............................................................................................................................40WILDIALOGEDITOR................................................................................................................................40ASAMPLEDIALOG:WILDIALOG.WBT..........................................................................................................44DIALOGCONTROLS...................................................................................................................................48

    Pushbuttons............................................................................................................50Radiobuttons..........................................................................................................51Checkboxes..................................................................................................................53EditBoxes.......................................................................................................................54

    i

  • Introduction to Programming

    Static(Fixed)Text......................................................................................................55VariableText................................................................................................................55Item(List)Boxes............................................................................................................56FileListBoxes.............................................................................................................57Calendar......................................................................................................................58ComControl............................................................................................................58TheDropListBox.....................................................................................................59TheGroupBoxcontrol................................................................................................60TheSpinnerControl.......................................................................................................60TheMultiLineBox.................................................................................................60ThePictureButtonControl.................................................................................61ThePictureControl........................................................................................................61

    MENUS..................................................................................................................................................61TABORDER............................................................................................................................................62SUMMARY..............................................................................................................................................63

    CHAPTER4:COMPUTERVOCABULARYPARTI..................................................................................65

    SIMPLENOUNSDATATYPESANDVARIABLES...........................................................................................65VARIABLESVERSUSCONSTANTS..................................................................................................................66WINBATCHDATATYPES...........................................................................................................................66

    IntegerConstants...........................................................................................................................66FloatingPointConstants................................................................................................................66StringConstants.............................................................................................................................67Array...............................................................................................................................................68HugeNumbers...............................................................................................................................73

    PREDEFINEDCONSTANTS...........................................................................................................................73PredefinedStringConstants...........................................................................................................74PredefinedFloatingPointConstants.............................................................................................75

    WINBATCHPROGRAMVARIABLES...............................................................................................................75VARIABLENAMES....................................................................................................................................76STRINGVARIABLECONVERSION..................................................................................................................77SUBSTITUTION.........................................................................................................................................77LISTS.....................................................................................................................................................79KEYWORDS.............................................................................................................................................79SUMMARY..............................................................................................................................................80

    CHAPTER5:COMPUTERVOCABULARYPARTII.................................................................................81

    SIMPLEVERBSOPERATORSANDOPERATIONS..........................................................................................81MATHOPERATORS...................................................................................................................................82GROUPINGOPERATORS().........................................................................................................................82THEASSIGNMENTOPERATOR(=)..............................................................................................................83THEADDITIONANDSUBTRACTIONOPERATORS(+AND)..............................................................................84THEMULTIPLICATIONANDDIVISIONOPERATORS(*AND/)...........................................................................86THEMODULUSOPERATOR(MOD).............................................................................................................87THEEXPONENTIALOPERATOR(**)............................................................................................................87LOGICALOPERATORS................................................................................................................................88

    TheLogicalANDOperator(&& )..................................................................................................88TheLogicalOROperator(|| ).....................................................................................................88TheLogicalNOTOperator(!).........................................................................................................89

    RELATIONALOPERATORS...........................................................................................................................89TheEqualityandInequalityOperators(==and!=or).............................................................89TheGreaterThanandLessThanOperators(>,>=,

  • Table of Contents

    TheLeftShiftandRightShiftOperators()...................................................................92TheBitwiseAND,OR,andXOROperators(&,|,and^)...............................................................93TheBitwiseNOTOperator(~)......................................................................................................94

    PRECEDENCEANDEVALUATIONORDER........................................................................................................94COMMENTS............................................................................................................................................96UNARYOPERATORS(VARIABLEREFERENCEOPERATORS).................................................................................96BINARYSTRINGOPERATIONS.....................................................................................................................97SUMMARY..............................................................................................................................................97

    CHAPTER6:COMPUTERVOCABULARYPARTIII................................................................................99

    STRINGSANDTEXTOPERATIONS.............................................................................................................99STRINGMANIPULATIONFUNCTIONS...........................................................................................................99STRINGPARSINGOPERATIONS.................................................................................................................100

    TheParseDataFunction...............................................................................................................101TheStrScanandStrSubFunctions................................................................................................102TheItemCountandItemExtractFunctions..................................................................................104UsingtheArrayFileGetfunction...................................................................................................104

    DIFFERENCESINTHESTRINGPARSINGTECHNIQUES.....................................................................................105SEARCHANDREPLACEOPERATIONS..........................................................................................................105

    TheStrIndexandStrIndexNcFunctions.......................................................................................105TheStrReplaceFunction..............................................................................................................107SelectiveSearchandReplace.......................................................................................................107

    STRINGCONVERSIONOPERATIONS...........................................................................................................109OTHERSTRINGCONVERSIONS..................................................................................................................110STRINGCOMPARISONOPERATIONS...........................................................................................................111OTHERSTRINGOPERATIONS....................................................................................................................113

    TheStrCharCountFunction..........................................................................................................113TheStrFillFunction.......................................................................................................................113TheStrFixFunctions.....................................................................................................................113TheStrTrimFunction....................................................................................................................114AdditionalStringFunctions..........................................................................................................114

    LISTSANDLISTSELECTIONOPERATIONS.....................................................................................................114ListInitialization...........................................................................................................................115ListCreation.................................................................................................................................116ListDisplay....................................................................................................................................119ListSelectionHandling.................................................................................................................120ListsofLists..................................................................................................................................122ListItemRemoval.........................................................................................................................124

    PASSWORDS.........................................................................................................................................124KEYBOARDINPUT...................................................................................................................................125SUMMARY............................................................................................................................................125

    CHAPTER7:ATOOLKITFOROPERATIONS.........................................................................................127

    FUNCTIONSANDSUBROUTINES.............................................................................................................127FUNCTIONS...........................................................................................................................................127

    UserDefinedFunctions................................................................................................................129SUBROUTINES.......................................................................................................................................131

    ThegosubStatements..................................................................................................................133TheSubroutines...........................................................................................................................134SubprocedureExecution..............................................................................................................137

    EXTERNALBATCHFILES...........................................................................................................................138TheFirstExternalProgram...........................................................................................................139TheSecondExternalProgram......................................................................................................141

    iii

  • Introduction to Programming

    EXECUTABLEPROGRAMS.........................................................................................................................142SUMMARY............................................................................................................................................143

    CHAPTER8:GOINGWITHTHEFLOW.................................................................................................145

    CONTROLLINGOPERATIONS.................................................................................................................145BRANCHINGANDPROGRAMCONTROLMECHANISMS...................................................................................145GOTOANDGOSUBBRANCHES..................................................................................................................146FORMSOFCONTROLLEDBRANCHING.........................................................................................................148IFDECISIONS.........................................................................................................................................148TRUEORFALSE......................................................................................................................................150SIMPLETESTS........................................................................................................................................151COMPOUNDTESTS.................................................................................................................................153COMPLEXTESTS.....................................................................................................................................154

    NestedIf..Else..EndifStatements.................................................................................................156SWITCH/CASEDECISIONS........................................................................................................................158FALLTHROUGHEXECUTION.....................................................................................................................160DUPLICATECASESTATEMENTS.................................................................................................................163DEFAULTCASES.....................................................................................................................................164LOOPS.................................................................................................................................................165

    ForLoops......................................................................................................................................165ForEachLoop................................................................................................................................167ForLoopInterruption...................................................................................................................168WhileLoops..................................................................................................................................169WhileLoopsInterruption.............................................................................................................170

    SUMMARY............................................................................................................................................170

    CHAPTER9:IT'SALLINTHENUMBERS..............................................................................................173

    MATHEMATICALOPERATIONS..............................................................................................................173SIMPLENUMERICALMANIPULATIONS........................................................................................................173

    TheAbsandFabsFunctions.........................................................................................................173TheAverageFunction..................................................................................................................174TheCeilingandFloorFunctions...................................................................................................175TheDecimalsFunction.................................................................................................................176TheIntFunction...........................................................................................................................177TheMinandMaxFunctions.........................................................................................................177

    NUMBERTESTING..................................................................................................................................177PseudoRandomNumbers...........................................................................................................178

    LARGEANDTRANSCENDENTALNUMBERS...................................................................................................180TheExpFunction..........................................................................................................................180TheLogEFunction........................................................................................................................180TheLog10Function......................................................................................................................181TheSqrtFunction.........................................................................................................................181

    TRIGONOMETRICOPERATIONS.................................................................................................................182TheSin,Cos,andTanFunctions...................................................................................................183TheASin,ACos,andATanFunctions............................................................................................184TheASinFunction.........................................................................................................................185TheACosFunction........................................................................................................................185TheATanFunction.......................................................................................................................186TheHyperbolicFunctions:SinH,CosHandTanH.........................................................................187

    DATEANDTIMEOPERATIONS...................................................................................................................188Date/TimeFormat........................................................................................................................188TheTimeDateFunction................................................................................................................188TheTimeYmdHmsFunction.........................................................................................................189

    iv

  • Table of Contents

    TheTimeJulianDayFunctionandtheDayoftheWeek...............................................................189TheTimeJulToYmdFunction........................................................................................................191TimeDifferenceCalculations.......................................................................................................191PauseandWaitFunctions............................................................................................................192

    MATHEMATICSINTHEREALWORLD..........................................................................................................193AcceptingInputVariants..............................................................................................................193

    DOINGTHEMATH..................................................................................................................................197FORMATTINGVALUES.............................................................................................................................199

    FormattingCurrency....................................................................................................................200FormattingaDate........................................................................................................................201

    SUMMARY............................................................................................................................................202

    CHAPTER10:SHOEBOXESANDFILECABINETS..................................................................................203

    DATASTORAGEANDFILEOPERATIONS...................................................................................................203FILEANDDIRECTORYCONCEPTS...............................................................................................................203HARDDRIVEMANAGEMENT....................................................................................................................204AUTILITYFORDIRECTORYOPERATIONS.....................................................................................................204

    PlanningtheUtility.......................................................................................................................205FileSpecification..........................................................................................................................205Drive/DirectorySpecification.......................................................................................................206ExploringtheCallFileListUtility....................................................................................................206

    THEWINDOWSCOMMONFILEDIALOG.....................................................................................................209FeaturesoftheCommonFileDialog............................................................................................210InvokingtheCommonFileDialog................................................................................................212TheLabelParameter....................................................................................................................213TheDirectoryParameter..............................................................................................................213TheFiletypesParameter..............................................................................................................213TheDefaultFilenameParameter.................................................................................................214TheFlagParameter......................................................................................................................214ReturningaFileName..................................................................................................................214

    DIRECTORYINFORMATIONFUNCTIONS....................................................................................................215ConvertingLongandShortFileNames........................................................................................215LocatingDefaultDirectories.........................................................................................................215GettingDriveInformation............................................................................................................217TheDiskScanFunction.................................................................................................................217TheDiskSizeandDiskFreeFunctions...........................................................................................219

    HUGENUMBERS....................................................................................................................................222FILEMANAGEMENT................................................................................................................................222ASHORTCUTFORLISTS...........................................................................................................................223FILEOPERATIONFUNCTIONS...................................................................................................................224

    HandlingFileI/O...........................................................................................................................225TheFileOpenFunction.................................................................................................................226TheFileReadFunction..................................................................................................................226TheFileWriteFunction.................................................................................................................227TheFileCloseFunction.................................................................................................................228ManipulatingFiles........................................................................................................................228TheFileAppendFunction.............................................................................................................228TheFileCopyFunction..................................................................................................................229TheFileMoveFunction.................................................................................................................229TheFileRenameFunction.............................................................................................................229TheFileCompareFunction...........................................................................................................230TheFileDeleteFunction...............................................................................................................230AdditionalFileFunctions..............................................................................................................230

    v

  • Introduction to Programming

    BINARYFILEOPERATIONS........................................................................................................................232SUMMARY............................................................................................................................................233

    CHAPTER11:WINDOWSANDGUIOPERATIONS...............................................................................235

    PAINTS,PENS,ANDWINDOWBOXES.....................................................................................................235CREATINGAWINDOW............................................................................................................................235WINDOWCOORDINATES.........................................................................................................................240LABELINGTHEWINDOW..........................................................................................................................241WINDOWSWITHINWINDOWS.................................................................................................................241DISPLAYINGTEXT...................................................................................................................................244

    FontStyles....................................................................................................................................244PitchandFamily...........................................................................................................................245DisplayingtheMessage................................................................................................................245

    ADDINGBUTTONS..................................................................................................................................247AQUICKREVIEW...................................................................................................................................248MOREABOUTCOLORS............................................................................................................................249DRAWINGINAWINDOW........................................................................................................................253ANALTERNATIVETOBOXBUTTONWAIT.....................................................................................................256THEBOXDRAWCIRCLEANDBOXDRAWRECTFUNCTIONS...............................................................................257DRAWINGSTACKMANAGEMENT..............................................................................................................259PARTIALCLEARING.................................................................................................................................259FORMATTINGTEXTINWINDOWS..............................................................................................................260SUMMARY............................................................................................................................................263

    CHAPTER12:MOUSINGAROUND.....................................................................................................265

    GETTINGAWAYFROMTHEKEYBOARD....................................................................................................265MOUSEOPERATIONSINWINDOWS...........................................................................................................265

    ForcingMouseOperations...........................................................................................................265TrackingtheMouse......................................................................................................................267

    SUMMARY............................................................................................................................................271

    CHAPTER13:POKINGINSIDETHEBOX..............................................................................................273

    THEINTCONTROLFUNCTIONS...............................................................................................................273THEINTERNALCONTROLTESTFUNCTION...................................................................................................273GENERALPURPOSEFUNCTIONS................................................................................................................274WINDOWINTERACTIONSANDWINDOWHANDLES.......................................................................................274SYSTEMFONTSELECTION........................................................................................................................274FILEOPERATIONS...................................................................................................................................275

    FileMoves....................................................................................................................................275FileSharingMode........................................................................................................................275

    FILELISTBOXSETTINGS..........................................................................................................................276GENERALLISTBOXSETTINGS...................................................................................................................277APPLICATIONCONTROLFUNCTIONS...........................................................................................................277

    WindowsMessages......................................................................................................................277WINBATCHCONTROL.............................................................................................................................279

    ExitCode......................................................................................................................................279IconStates....................................................................................................................................279ProgramFileNames.....................................................................................................................280WILTerminationCodes................................................................................................................280

    WINDOWSRESTARTING..........................................................................................................................280WindowsSystemRestart.............................................................................................................281

    APPLICATIONCLOSING............................................................................................................................281ERRORMESSAGES..................................................................................................................................281

    vi

  • Table of Contents

    ERRORHANDLING..................................................................................................................................282CREATEPROCESSFLAGS...........................................................................................................................283MEMORYACCESS..................................................................................................................................283INPUTTIMINGANDWAITS.......................................................................................................................283

    Timeouts......................................................................................................................................284TheSendKeyFunction..................................................................................................................284

    MISCELLANEOUSOPERATIONS..................................................................................................................285LanguageControl.........................................................................................................................285SystemMenus..............................................................................................................................285

    SUMMARY............................................................................................................................................286

    CHAPTER14:DYNAMICDIALOGS,MENUS,CALLBACKS.....................................................................287

    MAKINGDYNAMICDIALOGS................................................................................................................287ADDINGDIALOGPROCEDURECODE...........................................................................................................289

    FunctionsvsSubroutines.............................................................................................................297Exercise_C....................................................................................................................................300Exercise_D....................................................................................................................................301Exercise_E....................................................................................................................................303Exercise_F.....................................................................................................................................304

    SUMMARY............................................................................................................................................304

    CHAPTER15:WHENTHINGSGOWRONG..........................................................................................307

    DEBUGGINGAPPLICATIONS..................................................................................................................307LEARNINGTODEBUG..............................................................................................................................308DEBUGGINGINANIDE...........................................................................................................................308DEBUGGINGTOOLS................................................................................................................................311

    DebuggingduringExecution........................................................................................................311TracingExecutionStepbyStep....................................................................................................314TerminatingExecution.................................................................................................................316

    DEBUGGINGOPTIONS.............................................................................................................................318Debug...........................................................................................................................................318DebugTrace..................................................................................................................................319Modes:.........................................................................................................................................320ModeOptionFlags:......................................................................................................................321ImmediateActionCodes:.............................................................................................................322MessageorPauseStatements.....................................................................................................323DebugData...................................................................................................................................324

    DEBUGGINGASAPROCESS......................................................................................................................324DebugStep1:RuntheProgram...................................................................................................324DebugStep2:TesttheElements.................................................................................................324DebugStep3:WatchBranches,Tests,andVariableTests..........................................................325

    UNAVOIDABLEBUGS..............................................................................................................................326SUMMARY............................................................................................................................................326

    CHAPTER16:WINBATCHEXTENDERS................................................................................................327

    ADDINGEXTENDEDANDCUSTOMFUNCTIONS..........................................................................................327THEWILXLANGUAGEEXTENDER.............................................................................................................327

    GettingLibraryInformation.........................................................................................................328ConvertingbetweenNumericSystems........................................................................................328AccessingDrives...........................................................................................................................329AccessingWindowsAPIFunctions...............................................................................................329VerifyingCreditCardNumbers....................................................................................................330UsingUtilityFunctions.................................................................................................................330

    vii

  • Introduction to Programming

    NETWORKEXTENDERS........................................................................................................................331IdentifyingtheNetwork...............................................................................................................331WindowsPlatformVersion..........................................................................................................332

    QUERYINGACROSSTHENETWORK............................................................................................................332ADSIEXTENDER:WWADS44I.DLL.........................................................................................................334COMPILEROPTIONSFORWILEXTENDERS..................................................................................................334CUSTOMEXTENDERDLLS........................................................................................................................335SUMMARY............................................................................................................................................335

    APPENDIXA:WINBATCHDEMOS......................................................................................................337

    REALWORLDWILSCRIPTS..................................................................................................................337CHAPTER1SAMPLES..............................................................................................................................337

    WordCnt.wbt................................................................................................................................337CHAPTER2SAMPLES..............................................................................................................................338

    HelloWorld.wbt...........................................................................................................................338CHAPTER3SAMPLES..............................................................................................................................338

    AskYesNo.wbt..............................................................................................................................338AskLine.wbt..................................................................................................................................339WILDialog.wbt..............................................................................................................................339PushButton.wbt...........................................................................................................................341RadioButton.wbt..........................................................................................................................343CheckBox.wbt...............................................................................................................................346EditBox.wbt..................................................................................................................................347Listbox.wbt...................................................................................................................................348FileListBox.wbt.............................................................................................................................349ComControl.wbt...........................................................................................................................350

    CHAPTER4SAMPLES..............................................................................................................................351StringTest.wbt..............................................................................................................................351ArrayTest.wbt...............................................................................................................................352HugeMath.wbt.............................................................................................................................355VariTest.wbt.................................................................................................................................355ListTest.wbt..................................................................................................................................356

    CHAPTER5SAMPLES..............................................................................................................................356MathTest.wbt...............................................................................................................................356SimpleCalculator.wbt...................................................................................................................361

    CHAPTER6SAMPLES..............................................................................................................................363SearchList.txt................................................................................................................................363SearchTest.wbt.............................................................................................................................363SearchTest2.wbt...........................................................................................................................364SearchTest3.wbt...........................................................................................................................365SearchTest4.wbt...........................................................................................................................366StrIndex.wbt.................................................................................................................................367Blake.txt.......................................................................................................................................367SearchReplace.wbt.......................................................................................................................367StrCmp.wbt..................................................................................................................................369RelationalOperators.wbt..............................................................................................................370Parts.lst.........................................................................................................................................371ListSelection.wbt..........................................................................................................................372ListSelection2.wbt........................................................................................................................374Password.wbt...............................................................................................................................376WaitForKey.wbt...........................................................................................................................378

    CHAPTER7SAMPLES..............................................................................................................................378Music.txt.......................................................................................................................................378

    viii

  • Table of Contents

    HyperLink.wbt..............................................................................................................................379GetData.wbt.................................................................................................................................382Parts.lst.........................................................................................................................................384ExternCall.wbt..............................................................................................................................384SortData.wbt................................................................................................................................384Run_EXE.wbt................................................................................................................................385

    CHAPTER8SAMPLES..............................................................................................................................385Logic.wbt......................................................................................................................................385Select1.wbt...................................................................................................................................387Select2.wbt...................................................................................................................................388Select3.wbt...................................................................................................................................390Prime.wbt.....................................................................................................................................391ForEach.wbt.................................................................................................................................391Prime2.wbt...................................................................................................................................392

    CHAPTER9SAMPLES..............................................................................................................................393Average.wbt.................................................................................................................................393Floor_Ceiling.wbt.........................................................................................................................393Decimals.wbt................................................................................................................................394Min_Max.wbt...............................................................................................................................394TestNumber.wbt..........................................................................................................................394Random.wbt.................................................................................................................................396Exponential.wbt...........................................................................................................................397LogE.wbt.......................................................................................................................................399Log10.wbt.....................................................................................................................................400SquareRoot.wbt...........................................................................................................................401Trig.wbt........................................................................................................................................402ArcSin.wbt....................................................................................................................................403ArcCosine.wbt..............................................................................................................................405ArcTangent.wbt............................................................................................................................406HyperTrig.wbt..............................................................................................................................407TimeCheck.wbt.............................................................................................................................409TimeCheck2.wbt...........................................................................................................................410TimeCheck3.wbt...........................................................................................................................411Mortgage.wbt..............................................................................................................................412FormatCurrency.wbt....................................................................................................................417

    CHAPTER10SAMPLES............................................................................................................................419CallFileList.wbt.............................................................................................................................419DirTest.wbt...................................................................................................................................421DirTest2.wbt.................................................................................................................................422FreeDiskSpace.wbt.....................................................................................................................422FormatNumber.wbt.....................................................................................................................424Phone.lst......................................................................................................................................425ShowList.wbt................................................................................................................................426PhoneList.wbt...............................................................................................................................426Phone.lst......................................................................................................................................431FileAttr.wbt..................................................................................................................................431Binary.wbt....................................................................................................................................433

    CHAPTER11SAMPLES............................................................................................................................434HelloWindows.wbt......................................................................................................................434Progress.wbt................................................................................................................................437TextFonts.wbt..............................................................................................................................445Colors.wbt....................................................................................................................................454Buttons.wbt..................................................................................................................................459

    ix

  • Introduction to Programming

    x

    Lines.wbt......................................................................................................................................461Shapes.wbt...................................................................................................................................469Phone.lst......................................................................................................................................476PhoneListBox.wbt.........................................................................................................................476

    CHAPTER12SAMPLES............................................................................................................................483Freehand.wbt...............................................................................................................................483

    CHAPTER13SAMPLES............................................................................................................................488SelfTest.wbt..................................................................................................................................488

    CHAPTER14SAMPLES............................................................................................................................489ExerciseA.wbt..............................................................................................................................489ExerciseB.wbt..............................................................................................................................494ExerciseC.wbt..............................................................................................................................498ExerciseD.wbt..............................................................................................................................503ExerciseE.wbt..............................................................................................................................508ExerciseF.wbt..............................................................................................................................513

    CHAPTER15SAMPLES............................................................................................................................519Debug01.wbt................................................................................................................................519Debug02.wbt................................................................................................................................520PartsList.lst..................................................................................................................................521ExternCall.wbt..............................................................................................................................521GetData.wbt.................................................................................................................................522SortData.wbt................................................................................................................................523Debug03a.wbt..............................................................................................................................523Debug03b.wbt..............................................................................................................................524Debug03c.wbt..............................................................................................................................525Debug03d.wbt..............................................................................................................................525

    CHAPTER16SAMPLES............................................................................................................................526PlatformInfo.wbt..........................................................................................................................526NetTest.wbt..................................................................................................................................527

  • Introduction : Becoming a Programmer

    INTRODUCTION : BECOMING A PROGRAMMER THERE WILL BE A TEST

    According to the popular myths, all programmers, commonly called geeks (even though the term itself applies to a certain type of performer in an old-style sideshow at the carnival) are strange individuals with eccentric habits. Programmers are solitary individuals who communicate better with computers than with other people, who work strange hours (usually in strange surroundings), and who are only happy when they are cracking into Pentagon or Kremlin computers and starting World War III.

    Obviously, this last assertion is patently untrue and is simply a rumor fostered by the Gnomes of Zurich and the Trilateral Commission after certain rogue programmers blocked their collective efforts to take over the world. (The rest of the rumors, however, hold some elements of truth.)

    This book is your invitation to join the ranks of those weird individuals who form the cyber-intelligencia comprising the true rulers of the world. As such, you will be expected to give up your three-piece suits, increase your intake of caffeinated beverages, and trade your usual 9-to-5 working hours for well, lets just say that programmers consider 9-to-5 to be slackers hours.

    However, as a reward, you will be allowed to mutter strange curses concerning devices and processes that the rest of the world has never heard of. You will be able to use such esoteric terms as FOOBAR, bytes, registers (which do not involve paper), bitmasks, parameters, and dwords; and to appear to be devoutly contemplating the soul of a silicon chip while others about you are devoting their time and energies to the mundanities of everyday business (including such tortures as conferences and committee meetings).

    In this book, Introduction to Programming, were going to cover a lot of ground. I hope that youll find the journey interesting and the destination rewarding. You are on your way to joining the elite of the new order (and assuming your proper position on the bleeding edge of technology). Your instructions are quite simple: Sit back, flex your typing fingers, and read on.

    The programming language we will use, WinBatch or WIL (Windows Interface Language), is a high-level language. This means that WinBatch allows you to perform tasks using relatively simple instructions that accomplish a great deal. And, perhaps more important, WinBatch allows you to write programs without needing to know all of the finer details of the Windows operating system.

    Since the assumption is that you, the reader, are not an experienced programmer (or, in any case, not experienced with WinBatch), this book will start with the basics. We begin by showing you how to use the tools in the form of the WinBatch IDE (Integrated Development Environment) and then how to write simple programs.

    xi

  • Introduction to Programming

    xii

    We will not, however, confine ourselves to only simple elements. In the course of this book, you will learn about a wide variety of programming capabilitiesor functions as they are commonly calledas well as how to create data-storage elements, how to manipulate data elements, how to present them, and a host of other matters.

    Along the way, youll learn how to manipulate strings, create lists of data, read and write files, play with numbers, create buttons and controls, draw images, paint fancy windows, and even how to debug your programs. And, naturally enough, given the prevalence of networks in todays world, youll learn how to access networks.

    In short, you will learn both the basics of programming and a fair measure of the tricks of the tradeenough to put you well on the road to becoming a competent programmer.

    Given this scope of material to be covered, it would be well to stop talking about it and to simply get started. Still, before proceeding, one word of warning:

    There will be a test

    And, that said, lets get on with the real topic of programming applications.

  • Chapter 1 : The Golem Principle

    CHAPTER 1 : THE GOLEM PRINCIPLE BASICS OF PROGRAMMING

    golem \g-lam\ n. [Yiddish goylem]: an artificial human being of Hebrew folklore endowed with life.

    In Hebrew folklore, a golem was a manufactured creature in the form of a human, constructed from clay and baked in an oven. The golem was sculpted with a cavity in its head. The constructor of the golem would place a script in the cavity. According to legend, this script was normally a holy scripture, and it was by the power of the words that the golem was brought to a semblance of life.

    Once activated, the golem was able to perform such tasks as the animations creator directed. From a religious standpoint, since a golem was a soulless creature, the construct was not subject to Levitical restrictions concerning the Sabbath and was not prohibited from working during the Sabbath.

    Likewise, not being flesh and blood, a golem was not subject to exhaustion; did not become bored; did not require rest, sleep, or sustenance; and was not injured by fire or other dangerous or debilitating conditions. In short, a golem was the equivalent of our contemporary concept of a robot.

    So, why are we talking about golems?

    The main reason is that the stories of golems can tell us a great deal about their modern counterparts, the computer.

    computer \kam-\ n. : one that computes; specif: an automatic electronic machine for performing calculations.

    Youll notice that this definition of a computer (taken from Websters Seventh New Collegiate Dictionary) doesnt have much in common with the definition of a golem. However, when you go beyond the mere dictionary definitions, you find that there are strong similarities.

    Both are constructed of similar materialsclay begins as a mixture of hydrous aluminum silicates; a computer chip is also silicon-based but uses aluminum circuitry. A golem is baked (to produce anhydrous silicates), and a computer chip is also created using heat (both to initially purify the silicon and then to add specific and highly controlled impurities, which give it functional capabilities).

    13

  • Introduction to Programming

    And, of course, like the golem, the computer is also a soulless machine. It is not subject to exhaustion, does not suffer from boredom, and is not governed by Levitical restrictions.

    But, for our purposes, the most important parallel is how they are both controlled by words. The golem is given life by the wordsthe script or scripture placed in its head. The computer chip also gains its life from the wordsthe instructions or machine code that tell the computer how to perform tasks.

    How Computer Applications Work

    Without getting into the details of CPUs and chips, file systems and memory allocation, or of bus speeds and duty cycles, what makes a computer application work is simply a series of instructionswords. These are not, however, words in English (or Russian, Yiddish, Thai, or Urdu). Instead, these instructions are in a binary language that the computer (or, more precisely, the computers CPU) can understand directly.

    The term word, as used in the computer and software industry, has a special meaning. It refers to a piece of data that consists of 16 bits (or binary digits, which are the smallest unit of computer information). For this reason, this chapter refers to instructions rather than words.

    Because what the computer can understand and what the programmer can readily understand are two quite different languages, programs are commonly written in what are called high-level languages, which are languages that humans can more easily comprehend. Note, however, that these high-level languages are not precisely English. It simply is not practical to tell the computer, Add up this column of figures and give me the total, the average value, and a breakdown of expenses by month.

    Lingua Cyber

    In order to talk to the computer and to create sets of instructions to produce your custom application, an initial requirement will be for you to learn to speak a lingua francaor, if you prefer, a lingua cyber. You need to know how to use a high-level language that you, as the programmer, can understand and that can be translated into instructions that the computer can recognize and execute.

    Remember, there is nothing sissy or unmanly/unwomanly about resorting to these high-level languages rather than struggling with the machine language instructions directly. The real point of developing any application is to write it in a reasonable length of time, to have it work when finished, and to have it accomplish the desired task.

    For example, would you prefer to program using assembly language (a low-level language) instructions such as:

    DISPLAY EQU 2H ; output function DOSCALL EQU 21H ; DOS interrupt number

    14

  • Chapter 1 : The Golem Principle

    COUNT EQU 12D ; string length DATASEG SEGMENT ; define data segment STRING DB 'Hello World!' DATASEG ENDS CODESEG SEGMENT ; define code segment MAIN PROC FAR ASSUME CS:CODESEG, DS:DATASEG START: ; starting execution address PUSH DS ; save old data segment XOR AX.AX ; ax = 0 PUSH AX ; save ax on stack MOV AX,DATASEG ; store data segment in DS register MOV DS,AX ; MOV CX,COUNT ; store string length in CS register MOV BX,OFFSET STRING ; address of string REPEAT: MOV DL,[BX] ; put one character in DL register MOV AH,DISPLAY ; display character function INT DOSCALL ; call DOS INC BX ; advance the pointer LOOP REPEAT ; loop until done RET ; return to DOS MAIN ENDP CODESEG ENDS MAIN END ; end of assembly Or would you find it easier to write: print Hello, World! Granted, this is a rhetorical question. We assume that your preference is a high-level language that allows simple instructions like those above to be used to accomplish relatively complex tasks.

    Both of these code fragments perform the same task: assigning values to two variables, then adding the two variables with the sum stored in a third variable. And, finally, the third variable is printed to the console (DOS) display.

    For programming applications, there are a wide variety of high-level languages, and these are commonly referred to as computer languages. BASIC, COBOL, FORTRAN, C/C++, and Java are just some of the multitude of computer languages.

    This book is about using a high-level language called WIL (Windows Interface Language) or simply WinBatch. Although this language is less powerful than some other languages, it is also much easier to learn and use than many other languages, such as C/C++ or BASIC.

    15

  • Introduction to Programming

    High-Level versus Low-Level Programming Languages

    In the next chapter, you will see how a single WinBatch instruction provides a window, a frame, a title bar, and a message display on the screen. In addition, behind the scenes, this same instruction provides a timer that will close the window after a specified interval. Compare this with the assembly language example shown in this chapter, and you can get an idea of the relative power supplied by a high-level language.

    Naturally, there is a trade-off. A low-level language like assembly allows the programmer to design anythingabsolutely anything. A high-level language like WinBatch, while granting a great deal of power in simple instructions, also constrains the developer to using the functions provided.

    Of course, learning to use a low-level language is considerably harder than learning to use a high-level language. Then, even after youve become familiar with the language, the work required to create even a simple application using a language like assembly is many, many times greater than creating a similar application using a high-level language like WinBatch.

    This is not to suggest that either high-level or low-level languages are preferable; each has different uses. However, high-level languages offer two important advantages: They are easier to learn, and they can be used for rapid application development.

    The Sorcerers Apprentice

    Computers are fast and accurate, but they are also complete idiots. Computers do not think! The only thing that a computer can do is to follow instructions. A computer can accomplish its tasks very rapidly, efficiently, and patiently. But the computer does not take any initiative; it does not possess even a modicum of common sense. A computer will do something totally stupid if this is what it has been instructed to do! If you saw Walt Disneys film Fantasia (and probably also if you watched the Disney show on TV), youve seen the story The Sorcerers Apprentice. In this story, Mickey plays the part of an apprentice whose job is to sweep out the sorcerers laboratory and to fill the cistern with water. While the sorcerer is away, Mickey decides to try out one of his magic spells to animate the broom and have it carry buckets of water. Then, Mickey falls asleep. The animated broom continues to carry water, repeating the task long after the cistern is filled to overflowing. Mickey finally awakens when the entire laboratory is underwater.

    Mickey, frantically trying to stop his creation, uses an ax to split the broom into a hundred pieces, each of which proceeds to carry more buckets of water into the structure. (This part of the story goes a bit beyond our immediate cautionan ax generally will stop your computer from executing its tasks.)

    16

  • Chapter 1 : The Golem Principle

    The point is that a computer applicationany computer applicationis very much like the broom animated by Mickey. Once an application is told to do a task, it will continue to do so until it is instructed otherwise. In computer applications, everything must be explicitly identified, and nothing can be assumed.

    For a simple example, suppose that weve included instructions in a program to break a sentence, called a string in computer terminology, into individual words (in the human sense). Were going to send each of these words to another process called dictionary.

    A subroutine is a block of code containing a set of instructions which may be called from any point in a program to perform a specific task. (Subroutines are discussed in Chapter 7.)

    To do this, we would create a loop, which is computer terminology for a group of instructions (called a block of code) that are repeated ad infinitum until a test condition is satisfied. (Loops and other control conditions are discussed in Chapter 8.)

    The term string is commonly used to refer to a string of characters, called chars, but remember that the spaces between words are also characters.

    Here are the instructions for the proposed process expressed as dummy code in plain language, with comments in italics (later, youll learn how to construct the same type of process in WinBatch): Let location equal 1. Repeat

    Is character at location in test_string equal to space? If NO Then

    Increase location by one. (to test the next character) Else Begin

    Copy location minus one number of characters (dont include spaces) from first of test_string into new_string. Send new_string to dictionary. Trim location number of characters from first of test_string.

    End. Until test_string is empty.

    In this example, the indentations are simply to group lines (blocks) visually to show which commands execute together. This type of formatting is not required by the computer but should be used simply because it makes it much easier for you to read your own code at a later timelike an hour or more after youve written it, not to mention next month when you find that you need to make a change (and this will happen!). Also note that the practice of writing dummy code in plain language like this is often useful when designing an application.

    17

  • Introduction to Programming

    Now, these instructions should parse (separate) our sentence (string of characters) into individual words, sending each one to the dictionary subroutine and finishing when no more words remain, correct?

    Does this question sound like it is loaded? Is it a trap?

    Well, yes it is. The process, as written, will never finish. This is routine will become what is called an infinite loop, because, once initiated, it will attempt to continue until the power is shut off or the computer is reset. Obviously, this is not a desirable condition in an application.

    In this example, the error is a simple one. Weve created a loop that is set to terminate when a specific condition is satisfied. Within this loop, we have also created a test that looks for a space character to identify individual words. The failure will occur when the last word in the sentence is reached unless, against all reasonable expectations, the sentence ends with a space character.

    In other words, as the routine is presently constructed, the final word in test_string will never be parsed unless there is a space following it to allow it to be identified as a word. And, unless this identification is made, test_string will never be empty, the test used to terminate the loop will never be satisfied, and the loop will never finish.

    WinBatch provides a function called ParseData that breaks a line into its individual items, similar to the example discussed here (without becoming embroiled in an infinite loop, of course). An example of the ParseData function is included in the WordCnt.wbt demo program.

    The moral of this example is a computer is only as intelligent as the application. And, of course, the application is only as intelligent as the instructions provided by the programmer.

    Does it seem as if the point is being belabored excessively; as if a sledgehammer were being used to drive a thumbtack or an elephant gun used to shoot a mosquito? Please believe that, if anything, we have been constrained in pressing this point home. Murphys Law is never more evident than in programming and never more annoying when it occurs.

    0 Murphys Law (short version): Mistakes will happen! Repeatedly! When a program doesnt run as planned (and, at some point or another, this will happen to you, just as surely as the sun rises), we use a process called debugging to locate the point where an error occurs and to discover why. In other words, we debug programs to find our mistakes. This topic will be covered in Chapter 15.

    For the moment, you may consider the lecture terminated. We will now move on to the subject of application design.

    18

  • Chapter 1 : The Golem Principle

    Principles of Designing Applications

    The one sure secret of success for a programmerwhether you are a professional software engineer or simply writing a few utility applications for your own useis attention to detail. While it is not the only requirement (otherwise, we could all be replaced by cats), this one factor greatly affects whether you are successful or only frustrated in your programming endeavors. Furthermore, attention to detail is never more important than at the start of your project, in the planning and designing stage.

    Therefore, before you learn how to create an application using a programming language, you need to know how to design the application. Application design is important no matter how simple your application is.

    There are seven major steps involved in the design process, as illustrated below and discussed in the following sections. (Note that in practice, the development steps are not always distinct; they frequently overlap.)

    The application development process

    Step One: Defining Objectives The first step, and the first principle, in designing any application is to decide what you want the application to do. This can be done formally, such as by writing a mission objective, or informally, as a series of notes or a paragraph or two of text. The exact form is unimportant; the content is important.

    19

  • Introduction to Programming

    Begin with a one-sentence description that is a broad overview of what the application is intended to accomplish. For example, suppose that we start with this stated objective for a simple application:

    Track the movements of the mouse. Once you have an overview, this broad statement should be expanded to encompass and further define the purposes to be served by your design. Our sample overview objective could be expanded to include these further objectives:

    Provide an explanation to the user. Display the mouse position in screen coordinates. Update the displayed coordinates at regular intervals. Provide an exit option.

    This represents a reasonable set of objectives. Later, perhaps well wish to revise this list. Typically, as we progress with developing