About Debug Mode

Transcription

About Debug Mode
WinTask Language Reference Manual
1
TABLE OF CONTENTS
#ActionTimeout................................................................14
Add$ ..................................................................................16
Allocate..............................................................................17
Alphabetical WinTask functions list and parameters ..18
AppendXMLNode............................................................24
Asc .....................................................................................26
Attribute............................................................................27
Beep ...................................................................................28
BeginDialog...EndDialog .................................................29
CallDialog .........................................................................33
CapsLock ..........................................................................34
Capture$ ...........................................................................35
Error codes for Capture functions .................................39
CaptureArea$...................................................................40
CaptureAreaOCR$ ..........................................................42
CaptureBitmap.................................................................44
CaptureHTML .................................................................45
CaptureIE$ .......................................................................46
CaptureOCR$ ..................................................................47
CaptureTableHTML .......................................................49
ChDir.................................................................................51
CheckedHTML ................................................................52
CheckedW.........................................................................53
ChooseItem .......................................................................55
2
ChooseMenu .....................................................................58
Chr$...................................................................................61
Click ..................................................................................62
ClickHTMLElement ........................................................64
ClickMouse .......................................................................66
ClickOnBitmap ................................................................67
ClickOnText .....................................................................69
ClickOnTextOCR ............................................................70
ClickScrollBar and WinScrollBar..................................72
ClickSpin...........................................................................73
CloseBrowser....................................................................74
CloseCom ..........................................................................75
CloseExcelCom.................................................................76
CloseWindow....................................................................78
CloseWindowRegEx ........................................................79
Command$........................................................................81
Comment...........................................................................83
CopyLink ..........................................................................84
Create ................................................................................85
CreateExcelFile ................................................................86
CreateUnicodeFile............................................................87
Curdir$..............................................................................88
#CurrentLine....................................................................89
CurrentPage$ ...................................................................90
CursorX, CursorY ...........................................................92
Data types .........................................................................93
3
Date$..................................................................................95
DateBetween .....................................................................96
DateToDate$.....................................................................97
Day$...................................................................................98
DbBof ................................................................................99
DbClose ...........................................................................100
DbConnect ......................................................................101
#DbDateFormat..............................................................102
DbDisconnect..................................................................103
DbEof ..............................................................................104
DbExecute.......................................................................105
DbGetFieldNumeric.......................................................106
DbGetFieldString...........................................................108
DbMove...........................................................................110
DbMoveFirst...................................................................111
DbMoveLast ...................................................................112
DbMoveNext...................................................................113
DbMovePrev...................................................................114
DbRecordCount .............................................................115
DbSelect ..........................................................................116
#DecimalSeparator$ ......................................................118
DeleteRegKey .................................................................119
DeleteRegValue ..............................................................120
DelTree............................................................................121
Dim ..................................................................................122
Dir....................................................................................123
4
DirTree............................................................................125
Disable.............................................................................127
DiskFree ..........................................................................129
Divide$ ............................................................................130
Enable..............................................................................131
EnabledW .......................................................................132
Encrypt............................................................................135
End ..................................................................................136
EnumXMLAttributes ....................................................137
EnumXMLChildren ......................................................139
Envir$..............................................................................142
Eof....................................................................................144
#ErrorCode.....................................................................145
#ErrorFunction$ ............................................................146
#ErrorLine$....................................................................147
#ErrorMsg$ ....................................................................148
#ErrorScript$ .................................................................149
ExecExcelMacro.............................................................150
#ExecTimeout.................................................................151
#ExecuteDelay ................................................................153
Exist.................................................................................154
ExistDir ...........................................................................155
ExistHTMLElement ......................................................156
ExistW.............................................................................158
ExitFunction ...................................................................160
ExitSub............................................................................161
5
External$.........................................................................162
External...........................................................................163
ExtractBetween$ ............................................................165
ExtractLink ....................................................................167
Error codes for File management functions................169
FileAttr$..........................................................................170
FileCopy ..........................................................................171
FileDate$ .........................................................................172
FileSize ............................................................................174
FileTime$ ........................................................................175
FileVersion$....................................................................176
Error codes for Flow control functions........................177
Focus$..............................................................................178
Error codes for FTP functions......................................179
FTPChDir .......................................................................180
FTPConnect....................................................................181
FTPCurrentDir ..............................................................183
FTPDisconnect ...............................................................184
FTPExistDir....................................................................185
FTPExistFile...................................................................186
FTPGetFile .....................................................................187
FTPKill............................................................................189
FTPMkDir ......................................................................190
FTPName ........................................................................191
FTPPutFile......................................................................192
FTPRmDir ......................................................................194
6
#FTPTimeout..................................................................195
Function...ExitFunction...EndFunction .......................197
GetClipboard$................................................................199
GetCpuLoad ...................................................................200
GetFocusWindowHandle ..............................................201
GetFrameSource$ ..........................................................202
GetHTMLEditText ........................................................203
GetMemUsage ................................................................205
GetPageSource$ .............................................................206
GetProcessCpuLoad ......................................................207
GetProcessList................................................................208
GetReadPos ....................................................................210
GetTopWindowHandle..................................................211
GetWindowHandle ........................................................212
GetWindowName$.........................................................215
GetWindowsList.............................................................216
GetXMLAttribute ..........................................................218
Goto or Go to..................................................................221
HardCopy .......................................................................222
#HideIcon........................................................................224
#HideTrayIcon ...............................................................225
Hour$ ..............................................................................226
#HTMLPosRetry............................................................227
Hundreds ........................................................................229
If...Then...Else...Endif ....................................................230
#IgnoreErrors.................................................................231
7
#IgnoreHTMLCase........................................................232
ImpersonateUser ............................................................233
Include.............................................................................234
InputBox$ .......................................................................235
InputBoxSecret$.............................................................236
Instr .................................................................................237
InstrRev ..........................................................................238
IsRunning .......................................................................239
IsServiceStarted .............................................................240
Kill ...................................................................................241
KillApp............................................................................242
KillAppChildren ............................................................244
KillProcess ......................................................................246
#LastErrorLine ..............................................................249
Lcase$..............................................................................250
Left$ ................................................................................251
Len...................................................................................252
ListHTMLItem$.............................................................253
ListItem$.........................................................................255
LockKbd .........................................................................257
LockMouse......................................................................258
LogFile ............................................................................259
Ltrim$ .............................................................................261
MaximizeWindow ..........................................................262
Mid$ ................................................................................263
Min$ ................................................................................264
8
MinimizeWindow...........................................................265
MkDir..............................................................................266
Month$ ............................................................................268
MouseShape....................................................................269
MouseX, MouseY ...........................................................271
MoveMouse.....................................................................272
MoveWindow..................................................................274
MsgBox............................................................................275
MsgFrame.......................................................................277
MsgFrameTitle...............................................................279
Multiply$.........................................................................281
Name................................................................................282
Navigate ..........................................................................283
NumLock ........................................................................284
Error codes for ODBC functions..................................285
OnAction...EndAction ...................................................286
OnAction Error..............................................................291
OpenCom ........................................................................294
OsVersion$......................................................................295
OverHTMLElement ......................................................297
Pause................................................................................298
#PauseTimeout ...............................................................303
PeekInteger.....................................................................304
PeekString$.....................................................................305
PokeInteger.....................................................................307
PokeString ......................................................................309
9
PostData ..........................................................................310
#Precision........................................................................311
Program structure .........................................................312
Random...........................................................................313
Read.................................................................................314
ReadCom ........................................................................318
ReadExcel .......................................................................321
ReadIni$..........................................................................323
ReadReg ..........................................................................324
Reboot .............................................................................325
Rem..................................................................................326
RemoveFrame ................................................................327
Repeat...until...................................................................328
Replace$ ..........................................................................329
ResetTimer......................................................................330
RestoreWindow ..............................................................331
RevertToSelf...................................................................332
Right$ ..............................................................................333
RmDir..............................................................................334
Rtrim$ .............................................................................335
Run ..................................................................................336
SavePictureAs.................................................................338
SaveTargetAs..................................................................340
#ScriptAfterTimeout$....................................................342
Sec$..................................................................................344
Select Case... EndSelect .................................................345
10
SelectDir$........................................................................347
SelectedHTMLItem$ .....................................................349
SelectedItem$..................................................................351
SelectFile .........................................................................352
SelectHTMLItem ...........................................................353
SelectMultipleFile ..........................................................355
SendEmail.......................................................................356
SendKeys.........................................................................357
#SendKeysDelay.............................................................359
SendKeysEncrypted.......................................................360
SetAttr.............................................................................362
SetClipboard...................................................................363
SetReadPos .....................................................................364
SetXMLAttribute...........................................................365
Shell .................................................................................368
ShellWait.........................................................................370
SizeWindow ....................................................................371
Sleep ................................................................................372
SplitIntoArray ................................................................374
StartBrowser ..................................................................375
StartService ....................................................................376
StartTimer ......................................................................377
Stop..................................................................................378
StopLog ...........................................................................379
StopService .....................................................................380
StopTimer .......................................................................381
11
Str$ ..................................................................................382
Sub...Exitsub...EndSub ..................................................383
Subtract$.........................................................................384
Error codes for Synchronization functions .................385
Syntax, general ...............................................................386
Error codes for System functions .................................387
#TextLookFrequency.....................................................388
Time$...............................................................................389
Timer...............................................................................390
Top$.................................................................................392
TopInstance ....................................................................393
Trim$...............................................................................394
Ucase$..............................................................................395
UnlockKbd......................................................................396
UnlockMouse ..................................................................397
#UseExact........................................................................398
UseOCREngine ..............................................................399
UsePage ...........................................................................400
#UsePageExact ...............................................................402
Error codes for User dialog functions..........................404
UseWindow.....................................................................405
UseWindowHandle ........................................................407
UseWindowRegEx..........................................................410
Val....................................................................................413
Error codes for Web functions .....................................414
WeekDay.........................................................................415
12
While...Wend ..................................................................416
WinDir$ ..........................................................................417
Error codes for Windows management functions ......418
Write................................................................................419
WriteCom .......................................................................421
WriteCombo ...................................................................423
WriteEdit ........................................................................424
WriteEditEncrypted ......................................................425
WriteExcel ......................................................................426
WriteHTML ...................................................................428
WriteHTMLEncrypted .................................................430
WriteIni...........................................................................431
WriteReg.........................................................................432
Year$ ...............................................................................434
13
#ActionTimeout
System variable - Windows management.
The #ActionTimeout system variable specifies the number of seconds which
WinTask should wait before reporting a runtime error when it tries to select a
window, a control, or an option in a menu.
Usage
Mainly used to increase the delay before an execution error is reported. For
example, a file download is finished when a new window is displayed - a
UseWindow statement in the script makes the synchronization which waits until
the new window is there ; but the wait is done by default for 30 seconds. If the
file download lasts more than 30 seconds, before the UseWindow, you have to
add a line #ActionTimeout=120 if you need to wait for 120 seconds.
Syntax
#ActionTimeout = n
Remarks
When n seconds have elapsed, if WinTask cannot find the object it must activate,
error management is launched. The default behavior (#IgnoreErrors=0) is that
an error message is displayed and the script execution stops.
The default value for #ActionTimeout is 30 seconds.
If this variable is set to 0, WinTask waits forever.
The functions affected by this system variable are :
CheckedHTML(), ChooseItem(), ChooseMenu(), Click(), ClickHTMLELement(),
ClickOnBitmap(), ClickOnText(), ClickOnTextOCR, ClickScrollBar(), ClickSpin(),
CloseWindow(), CopyLink(), MaximizeWindow(), MinimizeWindow(),
MoveWindow(), Navigate(), RestoreWindow(), SavePictureAs(), SaveTargetAs(),
SizeWindow(), StartBrowser(), UsePage(), UseWindow(), WinScrollBar(),
WriteCombo(), WriteEdit(), WriteHTML(), WriteHTMLEncrypted()
See also
#IgnoreErrors
Example
#ActionTimeout = 5
Example code
This script detects if the Notepad window is present or not.
#IgnoreErrors=1
' Error management is now active in the script
#ActionTimeout=10
' Maximum wait is 10 seconds
ret=UseWindow("NOTEPAD.EXE|Edit|Untitled - Notepad|1")
' We try to do actions on the Notepad window
' The return code is tested
14
if ret=0 then
msgbox("Notepad window is present")
else
msgbox("Notepad window is not present")
endif
#IgnoreErrors=0
' Error management is turned off
' The script stops if an error occurs
15
Add$
Floating point calculation function.
The Add$ function adds two strings representing floating point numbers.
Usage
As only integers are supported numbers in WinTask, calculation on floating point
numbers is done using their string representation.
Syntax
res$=ADD$(a$,b$[,rc])
Parameters
a$, b$ are the strings representing the two floating numbers to add.
rc, optional numeric return code.
Values are :
0 if successfull operation
1 invalid operation because parameters are incorrect (for instance, the string
can't be considered as a number)
2 if operation causes overflow
Return value
rcs$, string representing a$+b$.
Examples
Add$("13.56","145.789") 'gives "159.35"
Add$("-45.678","34.8976") 'gives "-10.78"
#Precision=3
Add$("567.34257","45.343") 'gives "612.686"
16
Allocate
System function.
The Allocate function reserves a memory area for data used by External DLL
functions within a script. Not available in WinTask Lite.
Syntax
address=Allocate(<num>)
Parameter
<num>, integer.
Return value
address, UNSIGNED type which must be declared beforehand. If the Allocate
function fails, address will be set to 0.
Example
dim MemPointer as unsigned
MemPointer=Allocate(80)
Example code
'declare a variable to hold the memory address
dim pointer as unsigned
'reserve a 64-byte memory space
pointer=allocate(64)
'prepare a string to place in memory
wdir$=" "
'writes the zero-terminated string to memory
ret=PokeString(pointer,wdir$,0)
'In Win32, an A must be added to function which return a string
a=External("kernel32","GetWindowsDirectoryA",pointer,64)
'read the string through its memory address
var$=peekString$(pointer)
msgbox(var$)
17
Alphabetical WinTask functions list and parameters
Below is the alphabetical list of all the functions available in WinTask.
res$=ADD$(a$,b$[,rc])
address=Allocate(<num>)
ret=AppendXMLNode(<filename>,<XML_path>,<tagname>)
var=Asc(string$)
Attribute("Frame",<frame_string>)
Beep(<frequency>)
BEGINDIALOG <dialog_name> <x>,<y>,<width>,<height>
CallDialog <dialog_name>[,title$]
CapsLock(ON|OFF)
a$=Capture$(<window_name>,<instance>,<mode>)
a$=CaptureArea$(<window_name>,<instance>,<x>,<y>,<height>,<width>)
a$=CaptureAreaOCR$(<window_name>,<instance>,<x>,<y>,<height>,<width
> [,<language>])
CaptureBitmap(<filename>[,InArea(<x>,<y>,<height>,<width>)])
ret=CaptureHTML(<html_descriptor>,var$)
a$=CaptureIE$(<window_name>,<x>,<y>,<height>,<width>)
a$=CaptureOCR$(<window_name>,<instance> [,<language>])
ret=CaptureTableHTML(<table_descriptor>,<range_descriptor>,tabcell$())
ChDir(<directory_name>)
ret=CheckedHTML(<html_descriptor>)
ret=CheckedW(<window_name>[,<item_name>])
ChooseItem(list,<id>,<item>,single[,<button>])
ChooseMenu(normal,<menu_item>[,on or off])
var$=Chr$(<ASCII_value>)
Click(Button,<button_name>)
ret=ClickHTMLElement(<html_descriptor>[,<x>,<y>])
ClickMouse(<Button>,<Action>,<x>,<y>[,absolute])
ClickOnBitmap(<filename.BMP>,<button>,<action>[,InArea(<x>,<y>,<height>
,<width>)[,<offset_x>,<offset_y>]]
ClickOnText(<text>,<offset_x>,<offset_y>,<action>,<button>)
ClickOnTextOCR(<text>,<action>,<button>,
InArea(<x>,<y>,<height>,<width>), <offset_x>,<offset_y>,)
ClickScrollBar(<Scrollbar_name>,<number>,LINE or PG or ABS)
ClickSpin(<spin_name>,<number>)
CloseBrowser()
Ret = CloseCom (<num_port>)
CloseExcelCom()
CloseWindow(<window_name>,<instance> [,forced|immediate])
CloseWindowRegEx(<window_name>,<instance>)
var$=command$(<number>)
Comment(<comment_text>)
ret=CopyLink(<html_descriptor> ,var$)
Create(<filename>)
CreateExcelFile(<filename>)
CreateUnicodeFile(<filename>)
var$=Curdir$()
page_title$=CurrentPage$()
x=CursorX()
y=CursorY()
date_day$=Date$([<format>])
val=DateBetween(<interval$>,<date1$>,<date2$>)
var$=DateToDate$(<interval$>,<number>,<date$>)
dateday$=Day$()
18
Ret = DbBof()
Ret=DbClose()
DbConnect("DSN=<database_ODBC>")
ret=DbDisconnect()
Ret = DbEof()
DbExecute("<SQL_command>")
DbGetFieldNumeric(<field_name>,<value>)
DbGetFieldString(<field_name>,<string>)
DbMove(<pos>)
Ret=DbMoveFirst()
Ret=DbMoveLast()
Ret=DbMoveNext()
Ret=DbMovePrev()
num=DbRecordCount()
DbSelect(<SQL_selection>[,DYNASET|SNAPSHOT])
DeleteRegKey(<path>)
DeleteRegValue(<path>)
ret=DelTree(<directory_name>)
Dim tab_integ(<size>)
Dir(<file_spec$>,tab1$(),tab2$(),tab3$(),"options")
DirTree(<file_spec$>,tablongname$(),tabshortname$(),tabpath$(),tabattrib$(),"
options")
Disable(<Action_Id>)
var=DiskFree(<resource_name>)
res$=Divide$(a$,b$[,rc])
Enable(<Id_action>)
ret=EnabledW(<window_name>)
ret=Encrypt(<Source_string>,<Encrypted_string>)
End[(<retcode>)]
ret=EnumXMLAttributes(<filename>,<XML_path>,<attribute_name_array>,<val
ue_array>)
ret=EnumXMLChildren(<filename>,<XML_path>,<child_node_array>)
var$=Envir$(<var_name$>)
var=Eof(<filename>)
ret=ExecExcelMacro (<workbook> ,<macro_name>)
ret=Exist(<filename>)
ret=ExistDir(<directoryname>)
ret=ExistHTMLElement(<html_descriptor>)
ret=ExistW(<window_name>[,<instance>])
var=External(<DLL_name$>,<function_name$>[, <param1>[,<param2>, ...]])
var$=External$(<DLL_name$>,<function_name$>[, <param1>[,<param2>,
...]])
var$=ExtractBetween$(<initial_string>,<start_string>,included|excluded,<end_s
tring$>,included|excluded)
ret=ExtractLink (<HTML_descriptor>, tablink$())
var$=FileAttr$(<filename>)
ret=FileCopy(<source_filename>,<target_filename>)
var$=FileDate$(<filename>)
a=FileSize(<filename>)
var$=FileTime$(<filename>)
var$=FileVersion$(<filename>)
window_name$=Focus$()
ret=FTPChDir(<target_folder>)
ret=FTPConnect(<FTP_servername>,<username>,<encrypted_password>
[,<FTP_portnumber>])
ret=FTPCurrentDir(<current_folder>)
ret=FTPDisconnect()
19
ret=FTPExistDir(<FTP_foldername>)
ret=FTPExistFile(<FTP_filename>)
ret=FTPGetFile(<spec_files>,<local_directory_name>, ,[<mode>
[,<local_filename>]])
ret=FTPKill(<filename>)
ret=FTPMkDir(<foldername>)
ret=FTPName(<old_filename>,<new_filename>)
ret=FTPPutFile(<spec_files>,<FTP_foldername>,[<mode> [,<FTP_filename>]])
ret=FTPRmDir(<foldername>)
Function <function_name>([<param1>[,<param2>]....]) [Local
<variable_name>]
a$=GetClipboard$()
Num=GetCpuLoad()
handle=GetFocusWindowHandle()
var$=GetFrameSource$(<src_framename>)
ret=GetHTMLEditText(<html_descriptor>,var$)
Num=GetMemUsage()
var$=GetPageSource$()
Num=GetProcessCpuLoad(<process_name>[,<instance_number>])
Ret=GetProcessList(<tab_name$>,<tab_PID>,<tab_CPU>,<tab_Mem>,<sort>)
var=GetReadPos(<filename>)
handle=GetTopWindowHandle(<window_name>)
handle=GetWindowHandle(<window_name>)
var$=GetWindowName$(<handle>)
Ret=GetWindowsList(<tab_namewin$>,<tab_instanc>,<tab_handl>,<tab_flag$
>)
ret=GetXMLAttribute(<filename>,<xml_path>,<attribute_name>,<result$>)
Goto <label>
ret=HardCopy(<filename>,<screenshot_type>[,<option>])
a$=Hour$()
n=Hundreds()
If <boolean_expression> Then <statements> [Else <statements>] EndIf
a = ImpersonateUser(<user>, <password>,[<domain>])
Include "<source_filename>"
var$=InputBox$(<Prompt> [, [<Title>][, [<Default_answer>][, [<X>],
[<Y>]]]])
var$=InputBoxSecret$(<Prompt> [, [<Title>][, [<Default_answer>][, [<X>],
[<Y>]]]])
pos=Instr(<target_string>,<search_string>)
pos=InstrRev(<target_string>,<search_string>)
a=IsRunning(<module_name>)
a = IsServiceStarted(<service_name>)
ret=Kill(<filename>)
ret=KillApp(<exe_name>,0|1)
ret=KillAppChildren(<exe_name>,0|1)
ret=KillProcess(<PID_name>,0|1)
var$=Lcase$(<string$>)
var$=Left$(<string$>,<nbchar>)
a=Len(<string$>)
var$=ListHTMLItem$(<HTML_descriptor>,<n>)
var$=ListItem$(<window_name>,<n>)
LockKbd
LockMouse
LogFile(<filename>,<type>,<mode>)
var$=Ltrim$(<string$>)
ret=MaximizeWindow(<window_name>)
20
var$=Mid$(<string$>,<start>,<length>)
a$=Min$()
ret=MinimizeWindow(<window_name>)
ret=MkDir(<directory_name>)
month_curr$=Month$()
current_val=MouseShape()
x=MouseX()
y=MouseY()
MoveMouse(<X>,<Y>[,Absolute])
ret=MoveWindow(<window_name>,<instance>,<X>,<Y>)
ret=MsgBox(<Message> [, [<Type>] [,<Title]])
ret=MsgFrame(<Text>,<Id>[,<x>,<y>,size>,<color>])
ret=MsgFrameTitle(<Frame_title>,<Text>,<Id>[,<x>,<y>,size>,<color>])
res$=Multiply$(a$,b$[,rc])
ret=Name(<old_filename>,<new_filename>)
Ret=Navigate(<url_address>[,<timeout>])
NumLock(ON|OFF)
OnAction <action_ident> Button(<Button>,<Type>) Dosub <sub_name>
EndAction
ret=OpenCom(<port_num>,<speed>,<parity$>,<databits>,<stopbits>,<flowctl
$>)
var$=OsVersion$()
ret=OverHTMLElement(<html_descriptor> [,<x>,<y>])
Pause x Secs|Mins|Ticks|Hours
var=PeekInteger(<address>,<number_of_bytes>)
var$=PeekString$(<address>)
ret=PokeInteger(<address>,<value>,<number_of_bytes>)
ret=PokeString(<address>,<string>[,<term>])
PostData(<field_name>,<value>)
ret=Random(<val>)
ret=Read(<filename>,<buffer>,<sep$>)
ret=ReadCom(<num_port>,<numbytes>,<char$>)
ret=ReadExcel(<workbook>,<range_descriptor>,<array_result$>[,<readPasswd
$>])
var$=Readini$(<filename>,<Section>,<Item>,<Default>)
ret=ReadReg(<path>,<type>,<returned value>)
ret=Reboot(<code>)
Rem <text_comment>
RemoveFrame(<Id>)
Repeat <statements> Until <boolean_expression>
var$=Replace$(<string>,<search_string>,<replacing_string>
[,<number_of_occurrences> [<start_position>,<end_position>]])
ResetTimer(<clock_number>)
ret=RestoreWindow(<window_name>)
RevertToSelf()
var$=Right$(<string$>,<numcar>)
ret=RmDir(<directory_name>)
var$=Rtrim$(<string$>)
Ret=Run( "Script_name[.rob] [<Arg_1> <Arg_2> ...<Arg_n>]")
ret=SavePictureAs(<html_descriptor>, <path>)
ret=SaveTargetAs(<html_descriptor>, <path>, <extension>)
a$=Sec$()
Select Case <tested_expression> [Case <expressions_1> <statements_1>] [...]
[Case Else <statements_3>] EndSelect
mydir$=SelectDir$(<text$>,<initial_directory$>,<flag>)
var$=SelectedHTMLItem$(<html_descriptor>)
var$=SelectedItem$(<window_name>)
21
ret=SelectFile(<title>,<directory>,<filter>,<selected_file>,<offset_name>,<offs
et_extension>)
ret=SelectHTMLItem(<html_descriptor>,item$)
a=SelectMultipleFile(<title>,<directory>,<filter>,<selected_directory>,<array>)
SendEmail(<From>,<To>,<Subject>,<Message_text>[,<Attachments>[,<Cc>]]
)
ret=SendKeys(<key_list> [,NoActivate])
ret=SendKeysEncrypted(<encrypted_keys> [,NoActivate])
ret=SetAttr(<filename>,<attribute_flags>)
SetClipboard(<string$>)
ret=SetReadPos(<filename>,<value>)
ret=SetXMLAttribute(<filename>,<XML_path>,<attribute_name>,<value>)
ret=Shell (<program_name> [,<param>])
ret=ShellWait
(<command$>,<mode>,<timeout>[,<processExitcode>[,output$]])
ret=SizeWindow(<window_name>,<instance>,<width>,<height>)
Sleep()
num=SplitIntoArray(<string$>,<array$> [,<delimiter$>])
Ret=StartBrowser(<browser_type>[,<start_page>[,<param>]])
ret=StartService(<service_name$>)
StartTimer(<clock_number>)
Stop
StopLog
ret=StopService(<service_name$>)
StopTimer(<clock_number>)
var$=Str$(<number>)
Sub <sub_name>([<param1>[,<param2>]....]) <statements> EndSub
res$=Subtract$(a$,b$[,rc])
hou$=Time$()
response_time=Timer(<clock_number>)
window_name$=Top$()
instance_num=TopInstance()
var$=Trim$(<string$>)
var$=Ucase$(<string$>)
UnlockKbd
UnlockMouse
ret=UseOCREngine(1|2)
ret=UsePage(<page_title>)
ret=UseWindow(<window_name>[,NoActivate])
ret=UseWindowHandle(<handle>)
ret=UseWindowRegEx(<window_name>[,NoActivate])
Number=Val(<string$>)
day=WeekDay()
While <boolean_expression> <statements> Wend
var$=WinDir$()
Ret=WinScrollBar(H or V,<number>,LINE or PG or ABS)
ret=Write(<filename>,<buffer>,<sep$>)
ret=WriteCom(<port_num>,<char$>)
ret=WriteCombo(<combo_name>,<text>)
ret=WriteEdit(<edit_field>,<text>)
ret=WriteEditEncrypted(<edit_field>,<encrypted_text>)
ret=WriteExcel(<workbook>,<range_descriptor>,<array$>[,<readPasswd$>][,<
editPasswd$])
ret=WriteHTML(<html_descriptor>,var$)
ret=WriteHTMLEncrypted(<html_descriptor>,<encrypted_text>)
ret=WriteIni(<filename>,<Section>,<Item>,<Value$>)
22
ret=WriteReg(<path>,<type>,<value>)
ye$=Year$()
23
AppendXMLNode
File management function.
The AppendXMLNode function adds a node in the specified XML file. Not
available in WinTask Lite.
Syntax
AppendXMLNode(<filename>,<XML_path>,<tagname>)
or
ret=AppendXMLNode(<filename>,<XML_path>,<tagname>)
Parameters
<filename>, string, name of the XML file where to add the node.
<XML_path>, string, list of node descriptors separated by the \ character for
adding the node after this list. The string is not case-sensitive. The structure of
such a path is:
tagname[attributename1='value']
The tagnames are strings without double quotes, they cannot contain spaces or
reserved characters. It can be an empty string to create the root node.
The attribute names are strings without double quotes, OR it can be the reserved
keyword <text> or the reserved keyword <index>. <text> is used to specify the
node inner text, <index> is used to specify the node index (first one starts at 1)
when more nodes with the same tag and attributes exist within the same parent.
Several attributes can be listed with the syntax
tagname[attributename1='value1', attributename2='value2']
Examples:
If the XML file contains:
<bookstore>
<book genre="autobiography" publicationdate="1981" ISBN="1-861003-110">
the <XML_path> can be "bookstore\book[genre='autobiography']" or
"bookstore\book[publicationdate='1981']" or
"bookstore\book[publicationdate='1981',genre='autobiography']"
<tagname>, string, value of the tag to be added.
Return value
Ret, numeric return code. When the node is successfully added to the XML file,
the function returns 0, otherwise use this return code for Error Handling. The
error codes are :
20
The XML file could not be saved
27
The XML file could not be opened
90
Internal error (COM error when invoking XML COM)
99
Invalid parameters
110
Invalid XML path
See also
GetXMLAttribute
SetXMLAttribute
EnumXMLAttributes
EnumXMLChildren
24
Example
This code will generate the XML file as below:
file$ = "c:\program files\wintask\scripts\test.xml"
create(file$)
appendxmlnode(file$, "", "root")
appendxmlnode(file$, "root", "book")
appendxmlnode(file$, "root", "book")
appendxmlnode(file$, "root\book", "Mark_Twain")
appendxmlnode(file$, "root\book", "Mark_Twain")
appendxmlnode(file$, "root\book[<index>=2]", "Portugalia")
setxmlattribute(file$, "root\book\Mark_Twain", "<text>", "Misc
description")
setxmlattribute(file$, "root\book\Mark_Twain[<index>=2]", "year", "1987")
setxmlattribute(file$, "root\book\Mark_Twain[year='1987']", "<text>",
"Another misc description")
Resulting XML file:
<root>
<book>
<Mark_Twain>Misc description</Mark_Twain>
<Mark_Twain year="1987">Another misc description</Mark_Twain>
</book>
<book>
<Portugalia />
</book>
</root>
25
Asc
String management function.
The Asc function returns the ASCII code of the first character in a specified
string.
Syntax
var=Asc(string$)
Parameter
string$, character string.
Return value
var, numeric value: ASCII code of the first character in string$. If string$ is
empty or an error occurs, the value 0 is returned.
See also
Chr$
Examples
a=Asc("{") 'returns 123
a=Asc("bcdef") 'returns 98 (ASCII code for "b")
26
Attribute
Not used anymore.
27
Beep
System function.
The Beep function plays a tone through the PC speaker.
Syntax
Beep(<frequency>)
Parameter
<frequency>, numeric (constant or variable), frequency of the tone to be played.
Examples
Beep(262)
or
a=262
Beep(a)
28
BeginDialog...EndDialog
User dialog function.
The BeginDialog...EndDialog function defines a dialog box with its controls. Not
available in WinTask Lite.
Usage
Used to ask the user multiple questions in a complex dialog box.
Syntax
BEGINDIALOG <dialog_name> <x>,<y>,<width>,<height>
CAPTION "Dialog Box Title"
PUSHBUTTON "Button_label",<button_namen>,<x>,<y>,<width>,<height>
DEFPUSHBUTTON "Button_label",<button_name>,<x>,<y>,<width>,<height>
EDITTEXT <Edit_namen$>,<x>,<y>,<width>,<height>[,protected]
TEXT "Text",<x>,<y>
COMBOBOX
<Combo_namen$()>,<x>,<y>,<width>,<height>,<SelCombon$>[,Sorted]
LISTBOX <List_namen$()>,<x>,<y>,<width>,<height>,<SelListn$>[,Sorted]
GROUPBOX ["Groupbox_label"],<x>,<y>,<width>,<height>
CHECK "check_label",<Check1>,<x>,<y>
RADIO "radio_label",<Radio1>,<x>,<y>
ICON "Type",<x>,<y>,<width>,<height>
ENDDIALOG
Parameters
<dialog_name>: name of the dialog box ; this name is used later in the script in
order to display the dialog box.
<x>,<y>,<width>,<height>: coordinates of the top-left point of the dialog box,
width and height of the dialog box.
On the CAPTION line, the title of the dialog box is specified.
Note that the first line of the lines defining the controls within the Dialog is the
control which has the focus at execution.
Example
BEGINDIALOG Box1 231, 130, 350, 413
CAPTION "Example"
...
...
ENDDIALOG
Different types of buttons can be displayed using the statements
PUSHBUTTON and DEFPUSHBUTTON.
DEFPUSHBUTTON defines the default button; only one default button is allowed.
"button_label" defines the label of the button (it can be a variable).
<button_namen> defines the result variable (set to 1 this button has been
clicked).
<x>,<y>,<width>,<height>: coordinates of the top-left point of the button,
width and height of the button.
Examples
BEGINDIALOG Box1 231, 130, 350, 413
29
CAPTION "Example"
DEFPUSHBUTTON "&OK", Button1, 50, 350, 65, 20
PUSHBUTTON "&Cancel", Button3, 137, 350, 65, 20
...
ENDDIALOG
Depending on which button is pressed, different actions are made:
BEGINDIALOG Dialog1 225, 176, 240, 153
CAPTION "Example"
DEFPUSHBUTTON "Button2", Button2, 57, 47, 59, 22
PUSHBUTTON "Button3", Button3, 143, 43, 47, 28
ENDDIALOG
CallDialog Dialog1
If button2=1 then
shell("my_program.exe")
endif
if button3=1 then
msgbox("button3 pressed")
endif
A Text control (static) can be added in the dialog box using the statement
TEXT.
"Text" specifies the text to be displayed.
<x>,<y>: coordinates of the top-left point of the text.
Example
BEGINDIALOG Box1 231, 130, 350, 413
CAPTION "Example"
TEXT "Type your name : ", 25, 30
...
ENDDIALOG
An Editbox can be added in the dialog box using the statement EDITTEXT.
<Edit_namen$>: string to be displayed or result string.
<x>,<y>,<width>,<height>: coordinates of the top-left point of the Editbox,
width and height of the Editbox.
Protected : optional parameter; hides the input by filling the field by *.
Example
BEGINDIALOG Box1 231, 130, 350, 413
CAPTION "Example"
EDITTEXT Edit1$, 30, 55, 193, 24
...
ENDDIALOG
A Combobox can be added in the dialog box using the statement COMBOBOX.
<Combo_namen$>: string array with all the strings to be displayed in the
combobox. You must define the array first using the DIM statement. Remember
that the first item of an array starts at 0.
<SelCombon$>: result string (the one selected by the user).
<x>,<y>,<width>,<height>: coordinates of the top-left point of the combobox,
width and height of the combobox.
Sorted: optional parameter, if used, the strings are sorted inside the combobox.
Example
DIM selec$(15)
selec$(0)="Choice 1"
selec$(1)="Choice 2"
choice$=selec$(1)
30
BEGINDIALOG Box1 231, 130, 350, 413
CAPTION "Example"
COMBOBOX selec$(), 180, 135, 125, 75, choice$,sorted
...
ENDDIALOG
A ListBox can be added in the dialog box using the statement LISTBOX.
<List_namen$>: string array with all the strings to be displayed in the list. You
must define the array first using the DIM statement.
<SelListn$>: result string (the one selected by the user).
<x>,<y>,<width>,<height>: coordinates of the top-left point of the listbox,
width and height of the listbox.
Sorted: optional parameter, if used, the strings are sorted inside the listbox.
Example
DIM List1$(10)
BEGINDIALOG Box1 231, 130, 350, 413
CAPTION "Example"
LISTBOX List1$(), 30, 135, 125, 75, SelList1$
...
ENDDIALOG
Radio Buttons and Checkboxes can be added in the dialog box using the
statements RADIO and CHECK.
"check_label": label of the radio button or checkbox, it can be a variable.
<Checkn>,<Radion>: integer; 1 if the button has been checked, or if you want
it checked at execution.
<x>,<y>: coordinates of the top-left point of the button.
Example
BEGINDIALOG Box1 231, 130, 350, 413
CAPTION "Example"
RADIO "Option 1", Radio1, 50, 263
CHECK "Check 1", Check1, 200, 263
...
ENDDIALOG
radio1=1
CallDialog Box1
A Groupbox can be added using the statement GROUPBOX.
"Groupbox_label": title of the group (optional).
<x>,<y>,<width>,<height>: coordinates of the top-left point of the frame,
width and height of the group frame.
The statement Groupbox must be just before the Radio statements defining the
radio buttons to be included in the group.
Within such a group, if you check a radio button, the radio button previously
checked becomes unchecked.
Example
BEGINDIALOG Box1 231, 130,
CAPTION "Example"
GROUPBOX "Options : ", 30,
RADIO "Option 1", Radio1,
RADIO "Option 2", Radio2,
...
ENDDIALOG
350, 413
233, 125, 100
50, 263
50, 283
An Icon can be added in the dialog box using the statement ICON.
31
"Type" can be:
"Stop": red cross icon.
"Info": I icon.
"Exclamation": ! icon.
"Question": ? icon.
"Winlogo": Windows logo icon.
<x>,<y>,<width>,<height>: coordinates of the top-left point of the icon, width
and height of the icon.
Example
BEGINDIALOG Box1 231, 130, 350, 413
CAPTION "Example"
ICON "Info", 260, 25, 50, 50
...
ENDDIALOG
32
CallDialog
User dialog function.
The CallDialog function displays a dialog box defined previously. Not available in
WinTask Lite.
Syntax
CallDialog <dialog_name>[,title$]
Parameters
<dialog_name>, name of the dialog box defined by the
BEGINDIALOG...ENDDIALOG function.
title$, optional string parameter: it contains the title of the dialog box (it replaces
the title specified by the CAPTION statement in the BEGINDIALOG function.)
Example
CallDialog Box1
33
CapsLock
System function.
The CapsLock function forces the capslock key to the specified state.
Syntax
CapsLock(ON|OFF)
Remarks
If ON, capslock key is activated.
See also
NumLock
Example
CapsLock(ON)
34
Capture$
Capture function.
The Capture$ function captures in text mode whatever appears in the specified
window.
Syntax
a$=Capture$(<window_name>,<instance>,<mode>)
Parameters
<window_name>, window name of the window to be captured, including its
<instance>, instance number of the window.
<mode>, integer (constant) corresponding to three bit flags. To obtain the value
of <mode>, you have to add the values of each bit set to 1.
Bit 0 (weight 1) specifies how the text is captured :
0
the text is captured as a long string without CRLF
1
each line of the text is captured and separated by CRLF
If this bit is set to 0, the two others are set to 0 (so mode=2, 4 and 6 are invalid
and an error is returned at compilation).
Bit 1 (weight 2) specifies the font and its size :
0
the font is not captured
1
the font and size are captured
Bit 2 (weight 4) specifies the underlined and color of the background attributes :
0
these attributes are not captured
1
these attributes are captured
So <mode> can be :
0
the text is captured as a long string without CRLF and attributes
1
the text is captured as several lines without attributes
3
the text is captured as several lines and the font size is
captured
5
the text is captured as several lines, the attributes and the color
of the background are captured
7
the text is captured as several lines, the fonts and the color of
the background are captured
9
special value : mode for capturing text inside an
emulator using non-proportional fonts. Use this mode if
you notice that the normal mode ignores some blank
fields.
Return value
a$, string containing the captured text. If <window_name> or <instance> are
not found, or if there is nothing to capture, an empty string is returned.
Remarks
Use the Insert/Statement menu and double click Capture$ in order to
automatically generate this statement.
Capture$ tries to capture the text in the order in which this text is displayed on
the screen.
Capture$ also works with multiline Editboxes, a single-line EditBox, an entire
DialogBox or a static control, if you specify the name of this static in the Capture$
parameters. Use it the same way for capturing the text of icons, buttons,
listboxes.
Capture$ does NOT capture the text which overflows the window.
If Capture$ returns an empty string whereas it's really text which is displayed, try
35
this hint:
in the script, copy the desired text to the Clipboard and retrieve after the content
of Clipboard - so the statements in the script would be:
'Text selection
SendKeys("<Ctrl a>",NoActivate)
Pause 5 ticks
'Copy the selection to the Clipboard
SendKeys("<Ctrl c>",NoActivate)
Pause 5 ticks
'Retrieve the content of the Clipboard
a$=GetClipboard$()
See also
CaptureArea$
CaptureIE$
Example
If you capture this window :
mode 0 returns :
"First line to be capturedSecond line to be capturedThird line to be
captured"
mode 1 returns :
"First line to be captured
Second line to be captured
Third line to be captured"
mode 3 returns :
|X20,Y4,Times New Roman,H15,L133|First line to be captured
|X20,Y19,Arial,H16,L62|Second
|X82,Y19,Arial,H16,L27|line
|X109,Y19,Arial,H16,L65| to be captured
|X20,Y35,Courier New,H17,L234|Third line to be captured
mode 5 returns :
|R0,G0,B0,U0|First line to be captured
|R0,G0,B0,U0|Second
|R0,G0,B0,U1|line
|R0,G0,B0,U0| to be captured
|R0,G0,B0,U0|Third line to be captured
36
mode 7 returns :
|X20,Y4,Times New Roman,H15,L133,R0,G0,B0,U0|First line to be captured
|X20,Y19,Arial,H16,L62,R0,G0,B0,U0|Second
|X82,Y19,Arial,H16,L27,R0,G0,B0,U1|line
|X109,Y19,Arial,H16,L65,R0,G0,B0,U0| to be captured
|X20,Y35,Courier New,H17,L234,R0,G0,B0,U0|Third line to be captured
Information about size, font and location are given below :
n is an integer.
Xn : n = X-axis of the starting point of the text (in pixels), relative to the left
edge of the window.
Yn : n = Y-axis of the starting point of the text (in pixels), relative to the top
edge of the window.
Hn : n = height of the font (in pixels).
Ln : n = length of the text on the line (in pixels).
With this information, you can find the line and column of the text. For instance,
if the first line starts at 4 with a font size of 15, the coordinate of the second
column will be 15+4=19. The third line will be at 19+16=35. You can also find
the X-axis (if the font is a fixed font) by dividing the length of the text on the line
(L) by the number of characters. It gives the width of a character (which is a
column).
Information about attributes :
n is an integer.
Un : n is 0 or 1 (not underlined or underlined).
Rn, Gn, Bn is for the background color (Red, Green, Blue). n ranges from 0 to
255.
White
255
255 255
Black
0
0
0
Red
255
0
0
Green
0
255 0
Blue
0
0
255
For a mode not equal to 0, if an attribute changes (size, underline, color), a line
feed is inserted in the result string.
Performance : Capture$ activates a complex analysis process (0,9 second). If you
need more performance, another way can be useful : select text then copy it in
the clipboard (via Ctrl+C) then get its content with GetClipboard$
Example code
This script captures the text in WordPad.
shell("wordpad")
Pause until 'wait until WordPad is opened
Text("For Help, press F1")
InWindow("WORDPAD.EXE|msctls_statusbar32|Document - WordPad|1",1)
PauseFalse
MsgBox("Pause at line " + #ErrorLine$ + " has failed !",16,"Runtime error")
End
EndPause
Msgbox("Write some text in WordPad and press F12")
Pause until
Key("<F12>")
PauseFalse
MsgBox("Pause at line " + #ErrorLine$ + " has failed !",16,"Runtime error")
End
37
EndPause
' captures your text in WordPad
text$=Capture$("WORDPAD.EXE|RICHEDIT|Document - WordPad",0,1)
msgbox("Your text is : "+text$)
38
Error codes for Capture functions
The error codes for the WinTask Capture functions on Web pages are listed at
Error codes for Web functions.
The error codes for the HardCopy function are listed at Error codes for File
management functions.
UseOCREngine returns 1 if the specified OCR engine cannot be used (typically not
installed).
The other Capture functions do not stop execution if the capture cannot be done,
either they return an empty string, or they return a return code which is given in
the help of the function.
39
CaptureArea$
Capture function.
The CaptureArea$ function captures in text mode whatever appears in the
specified area of a window.
Syntax
a$=CaptureArea$(<window_name>,<instance>,<x>,<y>,<height>,<width>)
Parameters
<window_name>, window name of the window to be captured, including its
<instance>, instance number of the window.
<x>,<y>, coordinates of the top-left corner of the rectangle to be captured
within the specified window.
<height>,<width>, integers specifying the height and the width of the rectangle
to capture.
Return value
a$, string containing the captured text. If <window_name> or <instance> are
not found, or if there is nothing to capture, an empty string is returned.
Remarks
Use the Insert/Statement menu and double click CaptureArea$ in order to
automatically generate this statement.
If the size of the specified area is greater than the size of the window
<window_name>, the captured area is limited to the entire window.
Performance : CaptureArea$ activates a complex analysis process (0,9 second).
If you need more performance, another way can be useful : select text then copy
it in the clipboard (via Ctrl+C) then get its content with GetClipboard$
See also
Capture$
Example code
This script searches for *.bat files on your C: hard drive and captures the number
of *.bat files.
UseWindow("EXPLORER.EXE|Shell_TrayWnd",1)
Click(Button,"Start")
ChooseMenu(Context,"&Find|&Files or Folders...")
Pause until
Text("Find Now")
InWindow("EXPLORER.EXE|Button|F&ind Now",1)
InArea(0,0,19,67)
PauseFalse
MsgBox("Pause at line " + #ErrorLine$ + " has failed !",16,"Runtime error")
End
EndPause
UseWindow("EXPLORER.EXE|#32770|Name && Location",1)
40
WriteCombo("1","*.bat")
UseWindow("EXPLORER.EXE|#32770|Find: All Files",1)
Click(Button,"F&ind Now")
Pause until
Text("file(s) found")
InWindow("EXPLORER.EXE|msctls_statusbar32",1)
PauseFalse
MsgBox("Pause at line " + #ErrorLine$ + " has failed !",16,"Runtime error")
End
EndPause
count$=CaptureArea$("EXPLORER.EXE|msctls_statusbar32",1,0,0,18,145)
msgbox(count$)
CloseWindow("EXPLORER.EXE|#32770|Find: Files named",1)
41
CaptureAreaOCR$
Capture function.
The CaptureAreaOCR$ function captures the text that appears in the specified
area of a window using OCR (not available in WinTask Lite).
Syntax
a$=CaptureAreaOCR$(<window_name>,<instance>,<x>,<y>,<height>,<width
> [,<language>])
Parameters
<window_name>, window name of the window to be captured, including its
<instance>, instance number of the window.
<x>,<y>, coordinates of the top-left corner of the rectangle to be captured
within the specified window.
<height>,<width>, integers specifying the height and the width of the rectangle
to capture.
<language>, optional string specifying which language must be used by the OCR
engine. If this parameter is not specified, the language used is the one defined in
Office settings. The WinTask OCR engine does not take into account this optional
parameter, it uses the default Windows language as defined in Regional settings.
Use CaptureAreaOCR$ wizard to generate the correct language string option.
Return value
a$, string containing the OCRized text seen in the window. If <window_name> or
<instance> are not found, if there is nothing to capture, if the OCR engine does
not return any character, or if the speficied OCR engine is not installed, an empty
string is returned.
Remarks
Use the Insert/Statement menu and double click CaptureAreaOCR$ in order
to automatically generate this statement.
CaptureAreaOCR$ takes a bitmap of the specified area of the window, submits
this bitmap to the OCR engine specified by last used UseOCREngine statement. If
no previous UseOCREngine statement is in the script, the WinTask OCR engine is
used (OCR engine per default).
The WinTask OCR engine keeps the line structure (the CRLF), the MODI OCR
engine does not keep it and so returns the OCRized text as a long string.
See also
CaptureOCR$
UseOCREngine
How to install MODI OCR engine
Examples
ret = UseOCREngine(2) 'Forces to use WinTask OCR engine
var$ = CaptureAreaOCR$("NOTEPAD.EXE|Edit|Untitled Notepad|1",1,275,107,30,139) 'OCRized the text within the specified
rectangle of window notepad.
ret = UseOCREngine(1) 'Forces to use MODI OCR engine
var$ = CaptureAreaOCR$("NOTEPAD.EXE|Edit|Untitled Notepad|1",1,275,107,30,139,"Japanese") 'OCRized the text within the
42
specified rectangle of window notepad. The MODI engine will use the Japanese
language to transform the bitmap to Japanese text.
Write in Excel a captured OCRized value:
Using CaptureAreaOCR$ wizard, you have captured a data displayed on a Web
page. And you need now to write that value to Excel.
'Declare at the beginning of the script the array which will be used for
WriteExcel function.
Dim data$(10)
UsePage("My page")
ret = UseOCREngine(2)
'Capture the data
var$ = CaptureAreaOCR$("IEXPLORE.EXE|Internet Explorer_Server|my page Microsoft Internet Explorer|1",1,160,592,43,238)
'Fill the first element of data$ array by var$
data$(0)=var$
'You can capture other values and store them in data$(1), data$(2), ...
'Then write this array in Excel
'tell where the Excel file is
fileexcel$="c:\program files\wintask\data\myexcel.xls"
'Fill the C1 to C10 column using WriteExcel function
WriteExcel(fileexcel$,"C1:C10",data$())
43
CaptureBitmap
Capture function.
The CaptureBitmap function captures an image or an image area in the active
window and saves this image in a .BMP file.
Syntax
CaptureBitmap(<filename>[,InArea(<x>,<y>,<height>,<width>)])
or
ret=CaptureBitmap(<filename>[,InArea(<x>,<y>,<height>,<width>)])
Parameters
<filename>, name of the file (extension .BMP) into which the captured image is
saved.
InArea : optional keyword if the capture must be done only in a specified area of
the active window.
<x>,<y> : coordinates of the top-left corner of the rectangle to be captured
inside the specified window.
<height>,<width> : integers specifying the height and the width of the rectangle
to capture.
Return value
Ret, numeric return code. When successful, the function returns 0, otherwise 1.
Remarks
Use the Insert/Statement menu and select CaptureBitmap in order to
automatically generate this statement.
See also
Capture$
HardCopy
Check functions
Examples
UseWindow( "NOTEPAD.EXE|Edit|Untitled - NotePad|1",1 )
CaptureBitmap("C:\save\image.bmp") 'captures the entire active window - note
that the UseWindow before is compulsory.
CaptureBitmap("C:\save\image.bmp",InArea(10,10,100,200)) 'captures only the
specified area
44
CaptureHTML
Capture function, Web function.
The CaptureHTML function captures the text of the specified HTML element
within a Web page.
Usage
Used for retrieving data from a Web page and paste them into another
application. A Capture wizard is available in Start/Capture wizard menu. For
retrieving data organized in Table, use CaptureTableHTML. A step by step capture
process is available at Web how to capture data.
Syntax
ret=CaptureHTML(<html_descriptor>,var$)
Parameters
<html_descriptor>, unique identifier for the block-level HTML element from which
the inner text is captured. See HTML descriptor for HTML tags identification. Spy
can be used for generating automatically the HTML descriptor. Only HTML
descriptors using CONTENT keyword are valid for the CaptureHTML function.
<var$>, string, captured text.
Return value
Ret, numeric return code. When successful, the function returns 0, otherwise use
this return code for Error Handling.
Remarks
Here is the list of HTML block-level text tags which can be captured using the
CaptureHTML function:
<address>, <blockquote>, <dd>, <div>, <dl>, <dt>, <h1> through <h6>,
<li>, <ol>, <p>, <ul>.
Use the Capture wizard (menu Start/Capture wizard) or use Spy for generating
automatically this statement.
CaptureHTML does not include any synchronization; a UsePage must be used
before to be sure that the object to capture is ready.
See also
CaptureTableHTML
GetHTMLEditText
Example
StartBrowser("IE","www.wintask.com")
UsePage("Macro and Data Extraction with WinTask - the automation software
for Windows and internet")
ret = CaptureHTML("LI[CONTENT='Eliminate']", var$)
Msgbox(var$)
CloseBrowser()
45
CaptureIE$
Capture function, Web function.
The CaptureIE$ function must not be used anymore since WinTask version 2.5.
It is kept only for compatibility with previous versions.
In order to capture some text within a Web page, use now CaptureHTML or
CaptureTableHTML functions. Below is an example :
Example
dim tabcell$(100)
StartBrowser("IE", "www.google.com")
UsePage("Google")
ClickHTMLElement("A[INNERTEXT= 'News']")
UsePage("Google News")
'Capture the HTML Table at the top left which column title is >Top
ret = CaptureTableHTML("TABLE[CONTENT='>Top']", "R1C2:R17C2",
tabcell$())'tabcell$(2) contains the first non-empty captured data
CloseWindow("IEXPLORE.EXE|IEFrame|Google News - Microsoft Internet
Explorer",1)
'The captured cells are stored in tabcell$
msgbox(tabcell$(2))
46
CaptureOCR$
Capture function.
The CaptureOCR$ function captures the text that is seen in the specified window
using OCR (not available in WinTask Lite).
Syntax
a$=CaptureOCR$(<window_name>,<instance> [,<language>])
Parameters
<window_name>, window name of the window to be captured, including its
<instance>, instance number of the window.
<language>, optional string specifying which language must be used by the OCR
engine. If this parameter is not specified, the language used is the one defined in
Regional settings. The WinTask OCR engine does not take into account this
optional parameter, it uses the default Windows language as defined in Regional
settings. Use CaptureOCR$ wizard to generate the correct language string option.
Return value
a$, string containing the OCRized text seen in the window. If <window_name> or
<instance> are not found, if there is nothing to capture, if the OCR engine does
not return any character, or if the specified OCR engine is not installed, an empty
string is returned.
Remarks
Use the Insert/Statement menu and double click CaptureOCR$ in order to
automatically generate this statement.
CaptureOCR$ takes a bitmap of the specified window, capturing only the window
part which is seen on the screen (it does not take the text which can be seen by
scrolling the window), submits this bitmap to the OCR engine specified by last
used UseOCREngine statement. If no previous UseOCREngine statement is in the
script, the WinTask OCR engine is used (OCR engine per default).
The WinTask OCR engine keeps the line structure (the CRLF), the MODI OCR
engine does not keep it and so returns the OCRized text as a long string.
See also
CaptureAreaOCR$
UseOCREngine
Examples
var$=CaptureOCR$("NOTEPAD.EXE|Edit|Untitled - Notepad|1",1) 'var$ returns
the OCRized text which is seen in the Notepad window.
'The OCRengine used is the WinTask one.
UseOCREngine(1)
var$=CaptureOCR$("NOTEPAD.EXE|Edit|Untitled - Notepad|1",1) 'var$ returns
the OCRized text which is seen in the Notepad window.
'The OCRengine used is the MODI one.
UseOCREngine(1)
var$=CaptureOCR$("NOTEPAD.EXE|Edit|Untitled - Notepad|1",1,"Japanese")
'var$ returns the OCRized text which is seen in an English Notepad window
using Japanese language for the text within the notepad window.
'The OCRengine used is the MODI one.
47
Example code
This script ocrizes the text that has been typed by the user in the notepad
window, using WinTask OCR engine.
shell("notepad")
Msgbox("Write some text in notepad and press F12")
Pause until
Key("<F12>")
PauseFalse
MsgBox("Pause at line " + #ErrorLine$ + " has failed !",16,"Runtime error")
End
EndPause
' captures your text in notepad
text$=CaptureOCR$("NOTEPAD.EXE|Edit|Untitled - Notepad|1",1)
msgbox("Your text is : "+text$)
This script ocrizes the text that has been typed by the user in the notepad
window, using MODI OCR engine.
shell("notepad")
Msgbox("Write some text in notepad and press F12")
Pause until
Key("<F12>")
PauseFalse
MsgBox("Pause at line " + #ErrorLine$ + " has failed !",16,"Runtime error")
End
EndPause
' captures your text in notepad using MODI OCR engine.
UseOCREngine(1)
text$=CaptureOCR$("NOTEPAD.EXE|Edit|Untitled - Notepad|1",1)
msgbox("Your text is : "+text$)
48
CaptureTableHTML
Capture function, Web function.
The CaptureTableHTML function captures the text of the specified range of cells
in an HTML table within a Web page.
Usage
Used for retrieving colums or lines of data from a Web page and insert them in an
Excel file for instance. You can retrieve prices from ebay, retrieve job positions,
capture phones from a yellow pages site, ... Capture wizard helps you for data
extraction : menu Start/Capture wizard. And a step by step capture process is
available at Web how to capture data.
Syntax
ret=CaptureTableHTML(<table_descriptor>,<range_descriptor>,tabcell$())
Parameters
<table_descriptor>, string, unique identifier for the HTML element TABLE from
which the inner text of the <range_descriptor> is captured in tabcell$(). Spy can
be used for generating automatically the <table_descriptor>. See HTML
descriptor for a detailed explanation. Only HTML descriptors using CONTENT
keyword are valid for the CaptureTableHTML function.
<range_descriptor>, string. It specifies the range of cells to capture, such as
R4C2:R4C6 for a row or R2C2:R5C2 for a column.
<tabcell$>, array of strings. The array must be declared at the beginning of the
script using Dim. The inner text of the cells specified in <range_descriptor> are
written to tabcell$(), beginning with index 0. If the array is smaller than the
range, only the number of cells which fit in the array are written.
Return value
Ret, numeric return code. When the capture is successful, the function returns
the number of cells captured, otherwise use this return code for Error Handling.
The return code is -1 if the capture could not be done or if the range is invalid.
Remarks
CaptureTableHTML does not include any synchronization; a UsePage must be
used before to be sure that the object to capture is ready.
Use the Capture wizard (menu Start/Capture wizard) to generate the needed
WinTask code for your extraction process.
See also
CaptureHTML
GetHTMLEditText
ExtractLink
Example
dim tabcell$(50)
StartBrowser("IE","www.wintask.com/faq.php")
UsePage("WinTask – FAQ")
49
ret=CaptureTableHTML("TABLE[CONTENT='Can']","R1C1:R15C1",tabcell$())
Msgbox(tabcell$(0))
CloseBrowser()
50
ChDir
System function.
The ChDir function sets the current working directory.
Usage
It is used to change the current working folder. This statement is automatically
generated in Recording mode when you start Recording mode by Launching an
application and you specify in Launching a program dialog box a working folder.
Syntax
ChDir(<directory_name>)
or
ret=ChDir(<directory_name>)
Parameters
<directory_name>, string, name of the new working directory file. Equivalent to
the DOS command CD; but whereas DOS CD cannot be used to change the drive
and directory simultaneously, ChDir can.
Return value
Ret, numeric return code. When successful, the function returns 0, otherwise use
this return code for Error Handling.
See also
CurDir$
Examples
ChDir("I:\docword")
or
direct$="c:\program files"
ChDir(direct$)
51
CheckedHTML
Web function.
The CheckedHTML function retrieves the state of the specified check box or
radio button in an HTML form. Not available in WinTask Lite.
Usage
Mainly used for testing purposes when you need to check that your Web site is
displayed as expected.
Syntax
ret=CheckedHTML(<html_descriptor>)
Parameters
<html_descriptor>, HTML descriptor of the check box or radio button to check in
the HTML form. See Remarks for finding this HTML descriptor.
Return value
Ret, numeric return code. When the specified check box or radio button is
checked, the function returns 1 ; otherwise it returns 0. If the HTML object to test
is not recognized as a check box or radio button, or the object is not there, or the
descriptor is invalid or no UsePage is done before, the return code is -1. You can
use ExistHTMLElement statement before in order to ensure that the object exists.
Remarks
For finding the <html_descriptor> for the checkbox/radio button, use Recording
mode and record the action of checking the box. Stop Recording mode, the
generated line ClickHTMLElement contains the html descriptor, copy and paste
the generated html descriptor within the CheckedHTML statement and delete the
ClickHTMLElement line.
CheckedHTML does not include any synchronization ; a UsePage must be used
before to be sure that the checkbox is ready.
Example
'On the form for downloading WinTask, we check the status of one check box
StartBrowser("IE", "www.wintask.com")
UsePage("Macro and Data Extraction with WinTask - the automation software
for Windows and internet")
ClickHTMLElement("A[INNERTEXT= 'DOWNLOAD your 30-day']")
UsePage("WinTask Download - Free Version 30 days")
'On the form, is the checkbox Quick Start Guide checked ?
ret=CheckedHTML("INPUT CHECKBOX[NAME= 'quickstartguide']")
msgbox(ret)
52
CheckedW
Windows management function.
The CheckedW function retrieves the state of the specified check box or radio
button. Not available in WinTask Lite.
Syntax
ret=CheckedW(<window_name> [,<item_name>])
Parameters
<window_name>, window name of the check box or radio button. If all the
buttons are within a unique window, then <window_name> is the name of this
unique window, and you specify <item_name>.
<item_name>, string, optional parameter, text of the check box or radio button
to check ; it has to be used if the check box or radio button is not a window by
itself, and so window_name does not specify uniquely the item to test. WinTask is
case sensitive for finding the <item_name> at replay, so a good way to be sure
to type it properly, you can use Recording mode for checking the item, it will
generate a ChooseItem statement with the exact <item_name> and you can
then paste that name in the CheckedW statement.
Return value
Ret, numeric return code. When the specified check box or radio button is
checked, the function returns 1 ; otherwise it returns 0. If the item to test is not
recognized as a check box or radio button, or the window name does not exist,
the return code is -1.
Remarks
When you have to use the <item_name> parameter, it's easy to make a spelling
error ; to avoid that, use Recording mode and check/uncheck the checkbox item
that you want to test - stop Recording mode, two lines are generated, a
UseWindow that you have to delete, and a ChooseItem which gives you the exact
<item_name>. Then you can write manually the CheckedW line where you use
Spy for finding the <window_name> and you copy/paste the <item_name>. At
the end delete the ChooseItem line.
CheckedW does not include a synchronization mechanism, so you have to wait
that the window <window_name> is really displayed before running the
CheckedW.
CheckedW truncates the <window_name> and tries to find an approaching
window. To force an exact recognition of the window, use #UseExact=1 (see the
examples below).
As a check box or a radio button can have three states (Checked, Enabled,
Hidden), the table below gives the return code of the three WinTask functions
which deal with this kind of window, ExistW, EnabledW and CheckedW :
Checked
Enabled
Hidden
ExistW
EnabledW
CheckedW
0
0
0
1
0
0
0
0
1
0
0
-1
0
1
0
1
1
0
0
1
1
0
0
-1
1
0
0
1
0
1
1
0
1
0
0
-1
1
1
0
1
1
1
1
1
1
0
0
-1
Example code
This example tests a checkbox status in the window Find of WordPad.
53
Shell("wordpad",1)
UseWindow("WORDPAD.EXE|RICHEDIT50W|Document - WordPad|1",1)
SendKeys("Hello")
UseWindow("WORDPAD.EXE|WordPadClass|Document - WordPad",1)
ChooseMenu(Normal,"&Edit|&Find... Ctrl+F")
'Force the exact recognition
#UseExact=1
'Is Match case checkbox checked ?
ret=CheckedW("WORDPAD.EXE|Button|Match &case")
msgbox(ret)
This example tests a checkbox status in the window Internet options, Advanced
Tab of Internet Explorer.
StartBrowser("IE")
UseWindow("IEXPLORE.EXE|ReBarWindow32|about:blank - Microsoft Internet
Explorer|1",1)
ChooseItem(ToolBar, "|4", "&Tools", dropdown, left )
UseWindow("IEXPLORE.EXE|IEFrame|about:blank - Microsoft Internet
Explorer",1)
ChooseMenu(Context,"Internet &Options...")
UseWindow("IEXPLORE.EXE|#32770|Internet Options",1)
Click(Tab,"Advanced")
'Force the exact recognition
#UseExact=1
'As all the checkboxes are within the same window, we specify the checkbox
text in CheckedW function.
ret=CheckedW("IEXPLORE.EXE|SysTreeView32|Settings","Disable script
debugging")
msgbox(ret)
54
ChooseItem
Windows management function.
The ChooseItem function selects an item in a listbox or combobox.
Usage
Used to select an item from a listbox, a combobox, a tree view, a list view or a
toolbar. If the Windows control is not a standard one, ChooseItem will not work.
In such a case, you can try ClickOnText function or ClickOnTextOCR function or
use multiple SendKeys("<Down>") and a last SendKeys("<Enter>") for selecting
the desired item.
Syntax
ChooseItem(list,<id>,<item>,single[,<button>][,shift|ctrl])
ChooseItem(combo,<id>,<item>,single[,<button>])
ChooseItem(treeview,<id>,<item>,single or expand[,<button>])
ChooseItem(listview,<id>,<item>,single[,<button>][,shift|ctrl])
ChooseItem(toolbar,<id>,<item>,dropdown[,<button>])
or
ret=ChooseItem(list,<id>,<item>,single[,<button>])
ret=ChooseItem(combo,<id>,<item>,single[,<button>])
ret=ChooseItem(treeview,<id>,<item>,single or expand[,<button>])
ret=ChooseItem(listview,<id>,<item>,single[,<button>])
ret=ChooseItem(toolbar,<id>,<item>,dropdown[,<button>])
Parameters
list, combo, treeview, listview,toolbar : keywords defining the list type. Toolbar
and dropdown keywords are used to navigate in special menus of Explorer or IE
as below :
UseWindow("EXPLORER.EXE|SysPage|Explorer - C:\|2",1)
ChooseItem(ToolBar,"|1","&Display",dropdown,left)
UseWindow("EXPLORER.EXE|ExploreWClass|Exploring - C:\",1)
ChooseMenu(Context,"&List")
<id>, identifier of the list ; it can be a variable.
<item>, item to be selected in the list ; it can be a variable.
single (or double) : keyword for either a selection by a single click or a double
click.
expand : keyword to expand a branch (for instance, clicking the + icon in
Explorer).
<button>, mouse button used for the action (left or right). If this parameter is
not present, left is assumed.
shift or ctrl : in a list/listview, when a multiple selection is done, the shift
keyword is used for the last item selected, or the ctrl keyword is used for each
individual item selected.
Return value
Ret, numeric return code. When successful, the function returns 0, otherwise use
this return code for Error Handling.
Remarks
If you need to choose an item in systray (the notification area on the right part of
taskbar), the WinTask icons in the systray interfere with the generated
55
chooseitem. Use the code below instead of ChooseItem for selecting an icon in
systray:
#HideTrayIcon=1
pause 2
UseWindow("EXPLORER.EXE|TrayNotifyWnd")
pause 10 ticks
SendKeys("<Tab>",NoActivate)
Example code
This script shows the different uses of the statement ChooseItem in Explorer or in
Windows control panel.
'ChooseItem(Treeview, )
shell("explorer.exe")
'click on Recycle Bin
msgbox("WinTask simulates a click on Recycle Bin")
UseWindow("EXPLORER.EXE|ReBarWindow32|My Documents|2",1)
ChooseItem(TreeView, "1", "Recycle Bin", single, left )
pause 3
CloseWindow("EXPLORER.EXE|ExploreWClass|Recycle Bin",1)
'ChooseItem(Listview, ) and ChooseItem(Combo, )
pause 2
shell("control.exe")
UseWindow("EXPLORER.EXE|SHELLDLL_DefView|Control Panel|1",1)
MsgBox("WinTask simulates a click on Date and Time")
ChooseItem(ListView,"1","Date and Time",double,left)
pause 1
UseWindow("RUNDLL32.EXE|#32770|Date && Time",1)
MsgBox("WinTask simulates the selection of November in a Combobox")
ChooseItem(Combo,"1","November",single,left)
pause 1
UseWindow("RUNDLL32.EXE|#32770|Date and Time Properties",1)
Click(Button,"Cancel")
'ChooseItem(Toolbar, )
UseWindow("EXPLORER.EXE|ReBarWindow32|Control Panel|1",1)
ChooseItem(ToolBar, "|2", "&Tools", dropdown, left )
UseWindow("EXPLORER.EXE|CabinetWClass|Control Panel",1)
ChooseMenu(Context,"Folder &Options...")
UseWindow("EXPLORER.EXE|#32770|Folder Options",1)
56
Click(Button,"Cancel")
CloseWindow("EXPLORER.EXE|CabinetWClass|Control Panel",1)
57
ChooseMenu
Windows management function.
The ChooseMenu function selects a menu item.
Syntax
ChooseMenu(normal,<menu_item>[,on or off])
ChooseMenu(system,<menu_item>[,on or off])
ChooseMenu(context,<menu_item>[,on or off])
or
ret=ChooseMenu(normal,<menu_item>[,on or off])
ret=ChooseMenu(system,<menu_item>[,on or off])
ret=ChooseMenu(context,<menu_item>[,on or off])
Parameters
normal, system, context : keywords defining the menu type, normal for menus
inside applications, system for system menus, context for pop-up context menus.
<menu_item>, string, text of the menu item to be selected. During the time
delay specified by #ActionTimeout, WinTask tries to find this item in the window
specified by the last UseWindow statement and activates it. If the menu item is
not found, an error is generated and the script is stopped. <menu_item> is a one
string whatever special characters are in it - just use Recording mode for
recording properly a menu selection.
on, off : keywords to check or uncheck the menu item ; this additional parameter
is not generated by the Recording mode ; it must be added manually if needed.
Return value
Ret, numeric return code. When successful, the function returns 0, otherwise use
this return code for error management.
Remarks
The variable #SendKeysDelay (0 as default value) slows down the selection.
Some Windows applications do not implement menu design using the standard
Windows API functions, and then WinTask Recording mode is not able to record in
an object-oriented way your menu selections, see the example below : menu
selection by keyboard shortcut.
Context menus opened by right clicking the desktop are special too. See the
example code below : context menu selection.
Example code - general
This script shows the different uses of the statement ChooseMenu in the
application WordPad.
'Launch wordpad
shell("wordpad.exe")
UseWindow("WORDPAD.EXE|RICHEDIT|Document - WordPad|1",1)
SendKeys("test CHOOSEMENU<Enter>")
'ChooseMenu(Normal, )
UseWindow("WORDPAD.EXE|WordPadClass|Document - WordPad",1)
MsgBox("WinTask simulates the selection of the option Format|Font inside an
58
application")
pause 2
ChooseMenu(Normal,"F&ormat|&Font...")
UseWindow("WORDPAD.EXE|#32770|Font",1)
Click(Button,"Cancel")
'ChooseMenu(Context, )
UseWindow("WORDPAD.EXE|WordPadClass|Document - WordPad",1)
MsgBox("WinTask simulates a text selection, a right click and Copy
selection")
UseWindow("WORDPAD.EXE|RichEdit20A|Document - WordPad",1)
ClickMouse(Left,Down,13,17)
ClickMouse(Left,Up,13,17)
ClickMouse(Right,Down,89,19)
ClickMouse(Right,Up,89,19)
UseWindow("WORDPAD.EXE|WordPadClass|Document - WordPad",1)
ChooseMenu(Context,"&Copy")
'ChooseMenu(System, )
MsgBox("WinTask simulates the selection of the option Close in a system
menu")
UseWindow("WORDPAD.EXE|WordPadClass|Document - WordPad",1)
ChooseMenu(System,"&Close Alt+F4")
UseWindow("WORDPAD.EXE|#32770|WordPad",1)
Click(Button,"&No")
Example code - menu selection by keyboard shortcut
Shell("notepad",1)
UseWindow("NOTEPAD.EXE|Notepad|Untitled - Notepad",1)
'The usual mode - selecting File/exit would be
'ChooseMenu(Normal,"&File|E&xit")
'Using shortcuts, the same action can be done with the lines below
SendKeys("<Alt f>")
'a small pause to give the system some relief
pause 3 ticks
Sendkeys("x")
Example code - context menu selection
'A first UseWindow to attach to the desktop
UseWindow("EXPLORER.EXE|SysListView32|FolderView",1)
'Click somewhere on the desktop
ClickMouse(Right,Down,682,514)
59
ClickMouse(Right,Up,682,514)
'The context menu is displayed
pause 3
'Press Down to select first option in the context menu ;
'We send the keys with option NoActivate for sending the keys where the
cursor is
'whatever window is there.
Sendkeys("<Down>",Noactivate)
pause 5
Sendkeys("<Right>",Noactivate)
pause 3
60
Chr$
String management function.
The Chr$ function converts an <ASCII_value> into its equivalent ASCII
character.
Syntax
var$=Chr$(<ASCII_value>)
Parameter
<ASCII_value>: number between 0 and 255. If an invalid value is passed, the
script stops at execution with a runtime error.
Return value
var$, the number is converted to a character, so other functions can manipulate
non-displayable characters (for instance : a$=Chr$(13), a$ returns CRLF).
See also
Asc
Examples
var$=chr$(123) 'returns "{"
x=34
var$=chr$(x)
61
Click
Windows management function.
The Click function simulates a click on a button, a checkbox, a radiobutton or a
tab.
Usage
Used to click a control on a Windows application. The Click function is objectoriented (compared to ClickMouse function) and will replay correctly even if the
control has been moved. Only standard Windows controls work with Click function
; many applications use images or non-standard controls. In such case, use
ClickOnBitmap function or ClickMouse.
Syntax
Click(Button,<button_name>)
Click(Radio,<radio_name>)
Click(Check,<check_name>[,On or Off])
Click(Tab,<tab_name>)
or
ret=Click(Button,<button_name>)
ret=Click(Radio,<radio_name>)
ret=Click(Check,<check_name>[,On or Off])
ret=Click(Tab,<tab_name>)
Parameters
Button, Radio, Check, Tab : keywords defining the control type. During the time
delay specified by #ActionTimeout, WinTask tries to find this item in the window
specified by the last UseWindow statement and selects it. If the item is not found,
an error is generated and the script is stopped.
Return value
Ret, numeric return code. When successful, the function returns 0, otherwise use
this return code for Error Handling.
Example code
This script shows the different uses of the Click statement in the Windows control
panel.
'Launch control panel
shell("control.exe")
'Click(Tab, )
UseWindow("EXPLORER.EXE|SHELLDLL_DefView|Control Panel|1",1)
ChooseItem(ListView,"1","Date and Time",double)
UseWindow("RUNDLL32.EXE|#32770|Date/Time Properties",1)
MsgBox("Wintask simulates a click on Time Zone tab")
Click(Tab,"Time Zone")
62
'Click(Check, )
UseWindow("RUNDLL32.EXE|#32770|Time Zone",1)
MsgBox("Wintask simulates a click on the checkbutton Automatically adjust
clock...")
Click(Check,"Automatically adjust clock for &daylight saving changes",OFF)
'Click(Button, )
UseWindow("RUNDLL32.EXE|#32770|Date/Time Properties",1)
MsgBox("Wintask simulates a click on the button Cancel")
Click(Button,"Cancel")
'Close Control panel
CloseWindow("EXPLORER.EXE|CabinetWClass|Control Panel",1)
63
ClickHTMLElement
Web function.
The ClickHTMLElement function clicks a specified html element in the current
Web page.
Usage
Used to click a Web control on a Web page. The ClickHTMLElement function is
object-oriented (compared to ClickMouse function) and will replay correctly even
if the control has been moved within the Web page. Using the "right" parameter,
you can open the context menu for the specified Web control. For a very small
Web control, if you see at replay that the click is not done on the exact small
control, you can add mouse coordinates to ClickHTMLElement function.
Syntax
ret=ClickHTMLElement(<html_descriptor> [,left|right[,<x>,<y>]])
Parameters
<html_descriptor>, unique identifier for the HTML element to click within the
current Web page specified by the last UsePage. See HTML descriptor for each
HTML objects identification. Use Recording mode for generating automatically the
ClickHTMLElement syntax, you can use too Spy for finding the HTML descriptor
for block-text objects.
left|right, optional mouse button ; if not specified, a left click is used.
<x>,<y>, optional, mouse coordinates relative to the clicked element : it can be
used for clicking slightly besides the element.
Return value
Ret, numeric return code. If the specified HTML element has been successfully
clicked within 30 seconds (this default value can be changed using
#ActionTimeout), the function returns 0. Otherwise use this return code for Error
Handling.
List of negative error codes
-1
No browser in use (no previous UsePage or StartBrowser)
-3
Bad descriptor, invalid syntax
-4
The browser has been lost (for instance because of a Closewindow)
-5
Page not found
-8
Specified element not found
-11
Any other error
-404,405
Usual http error codes (requires IE 6 or above)
Remarks
ClickHTMLElement function does not return the actual link which is behind the
clicked link. Use CopyLink function if you need the actual link.
At replay, the function waits for the specified HTML element to be loaded before
clicking it. The timeout is the value of #ActionTimeout, so 30 secs by default.
You can use a variable for <html_descriptor> parameter : for example, to replace
the words between the single quotes in
ClickHTMLELement("A[INNERTEXT='Pacific Media']") with a variable, the code is:
a$="Pacific Media"
ClickHTMLElement("A[INNERTEXT= '"+a$+"']")
'The "+a$+" are used to concatenate the first part of the html descriptor
64
(A[INNERTEXT= ) with the last part ']"
When you write a script for capturing data, you usually use a loop for clicking
each individual elements in order to go to the next page where the details for the
clicked element has to be captured. Your list of elements to be clicked is usually
stored in an array, and you build the clickhtmlelement line using array$(0),
array$(1), ..., array$(i), ....
If array$(i) contains the ' character, the clickhtmlelement will fail as the single
quote is a separator for the clickhtmlelement syntax. So you need to replace the '
by the \' string (with the \ character in front of the ', the ' is not anymore
understood as the separator). Below are a couple of lines demonstrating how to
replace:
array$(i)="The O'Conors of Connacht and the O'Briens"
'Replace all the ' by \'
array$(i)=replace$(array$(i), "'","\'")
'Use now in the clickhtmlelement the correct HTML descriptor
ClickHtmlElement("A[INNERTEXT='"+array$(i)+"']")
Example
On WinTask Web site, we click the "Download your 30-day trial now!" link below
the product picture:
StartBrowser("IE","www.wintask.com")
UsePage("Macro and Data Extraction with WinTask - the automation software
for Windows and internet")
ClickHTMLElement("A[INNERTEXT= 'DOWNLOAD your 30-day']")
CloseBrowser()
65
ClickMouse
Windows management function.
The ClickMouse function simulates a mouse button click in the specified window.
Usage
ClickMouse should be used only if an object within the application cannot be
clicked using Click function or SendKeys function (for sending accelerator keys or
hot-keys). ClickMouse function is pixel related and dependant on screen
resolution.
Syntax
ClickMouse(<Button>,<Action>,<x>,<y>[,absolute])
Parameters
<Button>, mouse button used, the keywords are Left or Right (or Middle, but this
keyword is not recorded in Recording mode).
<Action> : Down, Up or Double for a double click.
<x>,<y>, coordinates of the mouse click in pixels
absolute : optional keyword ; the <x>,<y> coordinates are not against the
upper-left corner of the window but against the upper-left hand of the screen
(this option is added automatically when Recording in Low level mode).
Remarks
The mouse action is executed in the window specified by the last statement
UseWindow.
When a single click is recorded, two statements are generated :
ClickMouse(left,down,X,Y)
ClickMouse(left,up,X,Y)
If no window were specified previously by a UseWindow statement, an error
message is displayed and all the scripts are stopped (unless #IgnoreErrors=1)
Examples
ClickMouse(Right, Down, 100, 200)
ClickMouse(Left, Double, var_x, var_y)
66
ClickOnBitmap
Windows management function.
The ClickOnBitmap function simulates a click on the specified image (or near
the specified image).
Usage
Mainly used to click icons which are images and not standard Windows icons. For
example, a Cancel button is not a standard Cancel button as in any notepad
dialog boxes, but a nice Cancel button with a cross. For such a button which is in
fact a bitmap, use ClickOnBitmap function and its wizard for automatizing the
click.
Syntax
ClickOnBitmap(<filename.BMP>,<button>,<action>[,InArea(<x>,<y>,<height>
,<width>)[,<offset_x>,<offset_y>]]
or
ret=ClickOnBitmap(<filename.BMP>,<button>,<action>[,InArea(<x>,<y>,<hei
ght>,<width>)[,<offset_x>,<offset_y>]]
Parameters
<filename.BMP>, the mouse click is executed using the image stored in the
specified file (extension .BMP). During the time delay specified by
#ActionTimeout, WinTask tries to find and click this image within the window
specified by the last UseWindow statement. You must specify the UseWindow
function just before the ClickOnBitmap. If the image is not found, no error is
generated and the script continues.
<Button>, mouse button used to click the image, the keywords are Left or Right.
<Action> : single or double click.
InArea : optional keyword to indicate that the image must be searched for only
within the specified area.
<x>,<y> : coordinates of the top-left corner of the area in which to look for the
image.
<height>,<width> : integers specifying the height and the width of the area in
which to look for the image.
<offset_x>,<offset_y>, optional parameters : coordinates of the click offset from
the middle of the specified image. If these values are 0, the click occurs in the
middle of the image.
Return value
Ret, numeric return code. When successful, the function returns 0. Return code is
1 if the .BMP is not present on disk, 5 if the bitmap is in wrong color depth and 8
if the matching bitmap is not found on the screen. Error 22 means that the
window where the bitmap has to be clicked is not there anymore at execution of
ClickOnBitmap line.
Script execution does NOT stop in case of an error while executing
ClickOnBitmap.
Remarks
This function can be used when standard functions (such as ChooseItem) cannot
click the proper item (non-standard Windows applications).
Use the Insert/Statement menu and select ClickOnBitmap in order to
automatically generate this statement.
67
Be aware that the generated .BMP file depends on how many colors have been
configured in the video settings.
See also
Is there a new mail, this script example shows how to use ClickOnBitmap for
testing if a bitmap is present or not.
Example
UseWindow(...)
ClickOnBitmap("C:\save\image.bmp",Left,Single,-10,50)
68
ClickOnText
Windows management function.
The ClickOnText function simulates a click on the specified text or near the
specified text.
Syntax
ClickOnText(<text>,<offset_x>,<offset_y>,<action>,<button>)
or
ret=ClickOnText(<text>,<offset_x>,<offset_y>,<action>,<button>)
Parameters
<text>, string (variable or constant) : the mouse click is made on that <text>.
During the time delay specified by #ActionTimeout, WinTask tries to find this
<text> in the window specified by the last statement UseWindow and clicks. Such
a function UseWindow must be just before the ClickOnText. If the text is not
found, no error is generated and the script continues.
<offset_x>,<offset_y> : coordinates of the click offset from the middle of the
specified text. If these values are 0, the click occurs in the middle of the text.
These offsets allow you, for example, to click an icon just above the specified
text.
<Action> : single or double click.
<Button>, mouse button used to click the text, the keywords are Left or Right.
Return value
Ret, numeric return code. When the text is found, the function returns 0,
otherwise this return code has a value different from 0 (1 if the text is not found).
Remarks
This function can be used when standard functions (ChooseItem,…) cannot click
the proper icon (non-standard Windows applications).
Use the Insert/Statement menu and select ClickOnText in order to
automatically generate this statement.
Script execution does NOT stop in case of an error while executing ClickOnText
Examples
UseWindow(...)
ClickOnText("Demonstration",0,0,Single,Left)
69
ClickOnTextOCR
Windows management and Capture function.
The ClickOnTextOCR function clicks the specified text recognized by the OCR
engine (or clicks near it). Not available in WinTask Lite.
Usage
Sometimes, a text to click on is a "graphic" text and the only way to
record/replay a click on it is either to use ClickOnBitmap function or
ClickOnTextOCR function. ALWAYS use the ClickOnTextOCR wizard to generate
the parameters for this function, it is the only way to check that the OCR engine
will recognize correctly the specified text at replay.
Syntax
ClickOnTextOCR(<text>,<action>,<button>,
InArea(<x>,<y>,<height>,<width>), <offset_x>,<offset_y> [,<language>])
or
ret=ClickOnTextOCR(<text>,<action>,<button>,
InArea(<x>,<y>,<height>,<width>), <offset_x>,<offset_y> [,<language>])
Parameters
<text>, string (variable or constant) : the mouse click is made on that <text>.
During the time delay specified by #ActionTimeout, the OCR engine captures the
screen portion specified in InArea, converts the image in text and tries to find this
<text> in the window specified by the last statement UseWindow and clicks. Such
a function UseWindow must be just before the ClickOnTextOCR. If the text is not
found by the OCR engine in the specified area, a return code of 8 is setup but no
execution error is reported and the script continues.
<Action>: single or double click.
<Button>: mouse button used to click the text, the keywords are Left or Right or
Middle.
InArea(<x>,<y>,<height>,<width>): screen portion to capture and then where
to look for the <text>.
<offset_x>,<offset_y> : coordinates of the click offset from the middle of the
specified text. If these values are 0, the click occurs in the middle of the text.
These offsets allow you, for example, to click an icon just above the specified
text.
<language>, optional string specifying which language must be used by the OCR
engine. If this parameter is not specified, the language used is the one defined in
Regional settings. The WinTask OCR engine does not take into account this
optional parameter, it uses the default Windows language as defined in Regional
settings. Use ClickOnTextOCR wizard to generate the correct language string
option.
Return value
Ret, numeric return code. When the text is found, the function returns 0,
otherwise this return code has a value different from 0 (1 if the text is not found).
Remarks
ClickOnTextOCR can use two different OCR engines, the default one is the
WinTask OCR engine. If WinTask OCR engine is used, the click at replay is done
in the middle of the rectangle specified in the ClickOnTextOCR function. If MODI
70
OCR engine is used, the click at replay is done on the exact word as specified in
<text> parameter. You can force the use of MODI OCR engine by adding the line
UseOCREngine(1) before the ClickOnTextOCR call (the ClickOnTextOCR wizard
generates this line automatically). Of course, if the MODI OCR engine is not
installed, script execution will return an error.
ALWAYS use the ClickOnTextOCR wizard (Insert/Statement menu and select
ClickOnTextOCR function) to generate the ClickOnTextOCR parameters, the
wizard allows to check that the specified text will be correctly recognized by the
OCR engine at replay. NEVER change manually the <text> parameter.
In the wizard dialog box, click Capture. The mouse pointer changes shape ; draw
a rectangle around the text WinTask must click on. Release the mouse.
The captured bitmap transformed by the OCR engine is now in the "Text" field. If
the results do not give a readable text, Capture a new area.
The "Window" field is for information only. It displays the window name where
the text must be captured.
From the text as transformed by the OCR engine (field "Text"), copy a small
correctly transformed part of the text and paste it in the field "From the text seen
by OCR engine field, copy and paste below the text you want to click on:". Click
Check button to check that at replay, the text that you have pasted in that field
will be recognized correctly by the OCR engine. This Check process makes a
mouse move on the text which will be recognized at replay.
Click Paste into the script to paste the ClickOnTextOCR statement into the
script.
Examples
'A ClickOnTextOCT for clicking combination word in the sentence Automate any
combination of tasks
StartBrowser("IE", "www.wintask.com")
UseWindow( "IEXPLORE.EXE|Internet Explorer_Server|Macro and Data Extraction
with WinTask",1 )
ClickOnTextOCR("combi", left, single, InArea(183, 386, 95, 22))
'Using MODI OCR engine, those lines click the Download your 30-day trial now!
button at the "your" word.
StartBrowser("IE", "www.wintask.com")
UseOCREngine(1)
UseWindow("IEXPLORE.EXE|Internet Explorer_Server|Macro and Data Extraction
with WinTask",1 )
ClickOnTextOCR("your", left, single, InArea(729, 563, 172, 18))
71
ClickScrollBar and WinScrollBar
Windows management function.
The ClickScrollBar and WinScrollBar functions simulate the movement of a
scroll bar.
Syntax
ClickScrollBar(<Scrollbar_name>,<number>,LINE or PG or ABS)
WinScrollBar(H or V,<number>,LINE or PG or ABS)
or
Ret=ClickScrollBar(<Scrollbar_name>,<number>,LINE or PG or ABS)
Ret=WinScrollBar(H or V,<number>,LINE or PG or ABS)
Parameters
<Scrollbar_name>, string, ID of the scrollbar. During the time delay specified by
#ActionTimeout, WinTask tries to find this scrollbar in the window specified by
the last UseWindow statement and simulates a scroll. If the scrollbar is not found,
an error is generated and the script is stopped.
<number>, number of scrolls. If the next parameter is ABS, <number> is
positive starting at 0, if the next parameter equals PG or LINE, <number>
simulates relative scrolls and can be negative or positive.
Use LINE for scrolling by lines, PG for scrolling by pages, and ABS for absolute
positioning.
H or V : keywords for Horizontal or Vertical scrolling.
Return value
Ret, numeric return code. When successful, the function returns 0, otherwise use
this return code for error management.
Remarks
If the scrollbar is a separate control within the last window specified by the most
recent UseWindow, ClickScrollBar is used.
If the scrollbar is part of the last window specified by the most recent
UseWindow, WinScrollBar is used.
Examples
UseWindow("WINWORD.EXE|OpusMwd|SYNTAX.DOC",1)
ClickScrollBar( "1", 1, Line)
UseWindow("NOTEPAD.EXE|Edit|Untitled",1)
WinScrollBar(V, -1, Line)
72
ClickSpin
Windows management function.
The ClickSpin function simulates a click on a spin control.
Syntax
ClickSpin(<spin_name>,<number>)
or
Ret=ClickSpin(<spin_name>,<number>)
Parameters
<spin_name>, string, name of the spin control.
<number>, numeric, number of times WinTask must click on the spin arrow in
order to decrement or increment the spin control.
Return value
Ret, numeric return code. When successful, the function returns 0, otherwise use
this return code for error management.
Example
ClickSpin("spin1",-2)
73
CloseBrowser
Web function.
The CloseBrowser function closes the previous open instance of the browser.
Usage
CloseBrowser closes only the previous instance of the browser. To close all the
browser windows, use KillApp("IEXPLORE.EXE",1)
Syntax
CloseBrowser()
or
Ret=CloseBrowser()
Parameter
None
Return value
Ret, numeric return code. When the browser has been closed correctly, the
function returns 0. The return code is -1 if no browser has been opened with the
StartBrowser function - use this return code for Error Handling.
See also
StartBrowser
Example
CloseBrowser()
74
CloseCom
Com port management function. Function not available anymore since Windows
XP.
The CloseCom function closes the specified Com port. Not available in WinTask
Lite.
Syntax
Ret = CloseCom (<num_port>)
Parameter
<num_port>: Com port number to close (from 1 to 8, Com1 to Com8).
Return value
Ret, numeric return code. If the specified Com port has been closed correctly, the
function returns 0, otherwise use this return code for error management.
See also
OpenCom, WriteCom, ReadCom
Example
ret=CloseCom(1) ' Closes the serial port Com1.
75
CloseExcelCom
File management function.
The CloseExcelCom function closes the background Excel instance loaded by
WriteExcel or ReadExcel.
Usage
If you need to automate directly the Excel interface after having used
WriteExcel/ReadExcel functions, use CloseExcelCom function before using the
Shell function to launch Excel.
Syntax
CloseExcelCom()
or
ret=CloseExcelCom()
Parameters
None
Return value
Ret, numeric return code. When the background Excel application has been
closed successfully, the function returns 0, otherwise the function returns -1.
Example
This script example captures the market indices on yahoo finances, writes them
into Excel, opens the resulting Excel file and prints it.
'The 3 arrays for capturing the columns
Dim tabcell_2$(100)
Dim tabcell_1$(100)
Dim tabcell_0$(100)
StartBrowser("IE", "http://finance.yahoo.com")
'Capture the finances data and write them in c:\finance.xls
UsePage("Yahoo! Finance - Get stock quotes, market news, mortgage rates &
currency info.")
ret = CaptureTableHTML("TABLE[CONTENT='Symbol']", "R1C1:R7C1",
tabcell_0$())
ret = WriteExcel("c:\finance.xls", "Sheet1!A1:A7", tabcell_0$())
ret = CaptureTableHTML("TABLE[CONTENT='Symbol']", "R1C2:R7C2",
tabcell_1$())
ret = WriteExcel("c:\finance.xls", "Sheet1!B1:B7", tabcell_1$())
ret = CaptureTableHTML("TABLE[CONTENT='Symbol']", "R1C3:R7C3",
tabcell_2$())
ret = WriteExcel("c:\finance.xls", "Sheet1!C1:C7", tabcell_2$())
'As Excel is launched after a WriteExcel, CloseExcelCom line is mandatory.
CloseExcelCom()
Shell(Chr$(34)+"C:\Program Files\Microsoft
Office\Office\EXCEL.EXE"+Chr$(34)+" c:\finance.xls",1)
'Print the Excel file - always use the keyboard shortcuts in Excel
automation
UseWindow("EXCEL.EXE|MsoCommandBar|Worksheet Menu Bar")
SendKeys("<Alt F>")
76
pause 10 ticks
SendKeys("P")
UseWindow("EXCEL.EXE|bosa_sdm_XL9|Print",1)
SendKeys("<Enter>")
77
CloseWindow
Windows management function.
The CloseWindow function closes the specified window.
Usage
Generally used to close an application or a dialog box. KillApp function is better to
use if a Save dialog box is displayed when ending the application, and you do not
want to save.
Syntax
CloseWindow(<window_name>[[,<instance>],forced|Immediate])
or
ret=CloseWindow(<window_name>[[,<instance>],forced|Immediate])
Parameters
<window_name>, window name of the window to close. The window name can
be truncated in order to close any window starting by the characters specified in
<window_name> (see the truncation algorithm at window name help topic).
<instance>,optional parameter, instance number of the window to close.
forced or Immediate, optional keyword. If forced is used, if the window cannot be
closed due to a still opened dialog box, the close is forced after 30 seconds. If
Immediate is used, the close is made immediately.
Return value
Ret, numeric return code. When successful, the function returns 0, otherwise use
this return code for Error Handling.
See also
CloseWindowRegEx
Examples
CloseWindow("NOTEPAD.EXE|Notepad|Untitled")
CloseWindow("NOTEPAD.EXE|Notepad|Untitled",1)
CloseWindow("NOTEPAD.EXE|Notepad|Untitled",1,forced)
78
CloseWindowRegEx
Windows management function.
The CloseWindowRegEx function closes the specified window, using Regular
Expressions to specify the window title part of the window name. Not available in
WinTask Lite.
Usage
Used usually to close a child window within a parent one, when the window name
of the child window changes from one execution to another.
Syntax
CloseWindowRegEx(<window_name> [[,<instance>], forced])
or
ret=CloseWindowRegEx(<window_name> [[,<instance>], forced])
Parameters
<window_name>, string. window name (see this topic) of the window to close.
You can use the SPY tool to manually determine the caption of a window. During
Recording mode they will be inserted automatically. The Regular expressions can
be used to specify the title part of the window name, for example if in
"NOTEPAD.EXE|Edit|20.txt - Notepad" 20 is a day number which changes every
day, CloseWindowRegEx("NOTEPAD.EXE|Edit|[0-9][0-9].* - Notepad") triggers
on a window title whatever day number in it.
<instance>, optional parameter, instance number of the window.
forced : optional keyword. If specified, the window is closed after 30 seconds
even if a dialog box prompts for an answer.
WinTask will try to close the window defined by CloseWindowRegEx for a period
of time defined by the system variable #ActionTimeout.
Return value
Ret, numeric return code. When the <window_name> has been found and can be
closed, the function returns 0, otherwise use this return code for Error Handling.
Remarks
We describe below the most common cases for Regular Expressions:
Charac Description
Examples
ter
.
Matches a single character
a.r matches a0r, air, a£r,...
*
Repeats the previous character abc* matches ab, abc, abcc, abccc, ...
zero or several times
+
Repeats the previous character abc+ matches abc, abcc, abccc, ...
one or several times
?
Makes the preceding character
abc? matches ab or abc
optional
|
Alternation, regular expression 200[6|7] matches 2006 or 2007
equivalent of OR
[]
Matches one out of several
gr[ae]y matches gray, grey but not
characters
graey
{n}
Repeats n times the previous
a{3} matches aaa
character
{n,m} Repeats the previous character a{2,4} matches aa, aaa, aaaa
79
between n and m times
Matches one out of a range of
several characters
[ ^ - ] Excludes the range of several
characters
^
Outside a [, matches at the start
of the string
$
Matches at the end of the string
\chara A backslash escapes special
ct.
characters above their meaning
[-]
gr[0-9]y matches gr0y, gr1y, ... gr9y
but not gr19y
gr[^0-9]y matches gray, grby, grcy, ...
grzy but not gr0y, gr1y,... gr9y
^begin matches begin, beginning, begin
with
end$ matches end, will end, at the end
\+ matches + (and so the + sign does
not have its special meaning)
See also
UseWindowRegEx
Examples
We list below the most common cases
Single character
Closes the notepad window whatever character is after Doc
CloseWindowRegEx("NOTEPAD.EXE|Notepad|Doc. - Notepad|1")
Triggers for any window Doca, Docb, ..., Doc0, Doc1, ....
Single character in a list
Closes the notepad window if, after Doc, the year is 2005, 2006 or 2007
CloseWindowRegEx("NOTEPAD.EXE|Edit|Doc200[567] - Notepad|1")
Triggers for any window Doc2005, Doc2006, or Doc2007
Single character NOT in a list
Closes the notepad window if, after Doc, the year is NOT 2005, 2006 or 2007
CloseWindowRegEx("NOTEPAD.EXE|Edit|Doc200[^567] - Notepad|1")
Triggers for any window Doc2000, Doc2001, Doc2002, Doc2003, Doc2004,
Doc2008, Doc2009 and Doc200a, Doc200b, ...
Single character within a range
Closes the notepad window if, after Doc, it can be any year in the 1990s
CloseWindowRegEx("NOTEPAD.EXE|Edit|Doc199[0-9] - Notepad|1")
Triggers for any window Doc1990, Doc1991,..., Doc1999
80
Command$
Program flow control function.
The Command$ function allows a calling script to use the parameters from the
called script.
Syntax
var$=command$(<number>)
Parameter
<number>, numeric: the number of the parameter on the command line used to
launch the script. Number 0 is the name of the script itself (including its path). So
command$(0) will always return the full name of the running script. Parameters
are strings separated by blanks.
Return value
var$ gives the <number> parameter on the command line used to launch the
script. If the parameter <number> does not exist, an empty string is returned.
See also
Parameters passed from one script to another
Example
Script 1
Run("script2 param1 param2")
Script 2
msgbox(command$(1)) ' displays param1
msgbox(command$(2)) 'displays param2
Example code
Script 1 (calling.src) :
Parm1$="Param1"
Parm2$="Param2"
Script_Path$="c:\taskware\scripts\"
Program$=Script_Patht$+"called.rob "+Parm1$+" "+Parm2$
run(Program$)
Script 2 (called.src) :
Rem Displays the program name
a$=command$(0)
Message$="Program name : " + a$
msgbox(a$)
Rem Displays the first parameter
a$=command$(1)
81
Message$="Parameter 1 : " + a$
msgbox(a$)
Rem Displays the second parameter
a$=command$(2)
Message$="Parameter 2 : " + a$
msgbox(a$)
82
Comment
Logfile management function.
The Comment function writes a comment to the log file. Not available in WinTask
Lite. If you want to write a comment within a script in Editor, use the ' character
in front of the text to comment (see WinTask Editor).
Syntax
Comment(<comment_text>)
Parameter
<comment_text>: string to write to the log file.
Remarks
You must have already opened a log file before writing comments; you can use
the LogFile function or the TASKEDIT menu Configure|Run.
To write a complex string in the log file, you can concatenate multiple strings
using the + operator and you can use str$ function to transform an integer in a
string. For example:
Comment("The result for i index is: "+ str$(i))
Example
Shell("notepad")
UseWindow("NOTEPAD.EXE|Edit|Untitled",1)
SendKeys("Hello<Enter>")
Comment("Hello was sent! ")
83
CopyLink
Web function.
The CopyLink function returns the link associated at the specified html element.
Not available in WinTask Lite.
Usage
It's the same usage as a right click on a link and then in the context menu, the
selection of Copy shortcut option.
Syntax
ret=CopyLink(<html_descriptor> ,result$)
Parameters
<html_descriptor>, unique identifier for the HTML element to look for its link.
result$, string, returns the link.
Return value
Ret, numeric return code. If the specified HTML element has been successfully
found within 30 seconds (this default value can be changed using
#ActionTimeout), the function returns 0. Otherwise use this return code for Error
Handling.
List of negative error codes
-1
No browser in use (no previous UsePage or StartBrowser)
-3
Bad descriptor, invalid syntax
-4
The browser has been lost (for instance because of a Closewindow)
-5
Page not found
-8
Specified element not found
-11
Any other error
-404,405
Usual http error codes (requires IE 6 or above)
Remarks
CopyLink function returns the actual link which is behind a clickable link. It
simulates a right click on the specified html element, and in the context menu
takes the option Copy shortcut.
Example
On WinTask Web site, we click the Download your 30-day trial now! link below
the product picture:
StartBrowser("IE","www.wintask.com")
UsePage("Macro and Data Extraction with WinTask - the automation software
for Windows and internet")
CopyLink("A[INNERTEXT= 'DOWNLOAD your 30-day']",link$)
msgbox(link$)
'link$ contains http://www.wintask.com/download-wintask.php
CloseBrowser()
84
Create
File management function.
The Create function creates a file.
Syntax
Create(<filename>)
or
ret=Create(<filename>)
Parameters
<filename>, string, name of the file to be created. If the file already exists, it is
deleted and recreated.
Return value
Ret, numeric return code. When the file is created successfully, the function
returns 0, otherwise use this return code for Error Handling.
Example
var = Create("\\Server\C\my directory\my file.txt")
85
CreateExcelFile
File management function.
The CreateExcelFile function creates an Excel worksheet.
Usage
Mainly used to create an Excel file before you populate it using WriteExcel
function.
Syntax
CreateExcelFile(<filename>)
or
ret=CreateExcelFile(<filename>)
Parameters
<filename>, string, name of the Excel file to be created. If the file already exists,
it is deleted and recreated.
Return value
Ret, numeric return code. When the Excel file is created successfully, the function
returns 0, otherwise use this return code for Error Handling.
Example
var = CreateExcelFile("C:\my_Sheet_Excel.xls")
86
CreateUnicodeFile
File management function.
The CreateUnicodeFile function creates a file using Unicode encoding.
Usage
Used to force WinTask Write function to write in a new file using Unicode
encoding.
Syntax
CreateUnicodeFile(<filename>)
or
ret=CreateUnicodeFile(<filename>)
Parameters
<filename>, string, name of the file to be created. If the file already exists, it is
deleted and recreated. The Byte-Order Mark (BOM) is written at the beginning of
the empty file, this byte is then detected by Write function for writing data in this
new file using Unicode encoding.
Return value
Ret, numeric return code. When the file is created successfully, the function
returns 0, otherwise use this return code for Error Handling.
Example
var = CreateUnicodeFile("\\Server\C\my directory\my file.txt")
87
Curdir$
System function.
The Curdir$ function returns the current working directory.
Syntax
var$=Curdir$()
Return value
var$, string containing the current working directory.
See also
ChDir
Example
directory$ = Curdir$() 'directory$ contains "c:\winword" if the current working
directory is c:\ winword.
88
#CurrentLine
System variable - Logfile management.
The #CurrentLine system variable returns the current line number within the
currently running script.
Syntax
var=#CurrentLine
Return value
var, integer, current line number within this script.
Example
var = #CurrentLine
var$=str$(var)
msgbox(var$)
89
CurrentPage$
Web function.
The CurrentPage$ function returns the title of the current Web page.
Usage
Some Web sites have dynamic page titles (the title changes at each display),
CurrentPage$ will retrieve the correct page title.
Syntax
page_title$=CurrentPage$()
Return value
page_title$, string. It gives the title of the current Web page as seen by WinTask
processing Web pages. So a StartBrowser or a UsePage must be in the script
before, or an empty string will be returned.
Remarks
CurrentPage$ returns the current Web page without any synchronization, so the
page must have finished to load.
Examples
StartBrowser("IE","www.wintask.com",2)
'Note that StartBrowser makes the automatic synchronization and waits until
the page is loaded.
a$=currentpage$()
msgbox(a$)
Error sub-routine returning the non-expected page loaded after a link has been
clicked and the page after that click is not the expected one:
sub iferror()
local page$
page$=currentpage$()
'page$ contains the page displayed just before the call to that function.
msgbox(page$)
usepage(page$)
'To come back to a known web page, we click Home in the error Sub
ClickHTMLElement("A[INNERTEXT= 'Home']")
endsub
'Use example on www.wintask.com
startbrowser("ie","www.wintask.com")
UsePage("Macro and Data Extraction with WinTask - the automation software
for Windows and internet")
'This clickhtmlelement loads a page which makes fail the next OCR
synchronization.
ClickHTMLElement("A[INNERTEXT= 'DOWNLOAD your 30-day']")
ret = UseOCREngine(1)
ret=0
Pause 30 until
TextOCR("on the recording ")
InWindow("IEXPLORE.EXE|Internet Explorer_Server||1",1)
PauseOK
ret=1
PauseFalse
90
ret=0
EndPause
if ret=0 then
'The pause OCR failed if ret=0, so we call the Error Sub to know which page
title is currently displayed
iferror()
endif
91
CursorX, CursorY
Windows management function.
The CursorX, CursorY functions return the X or Y position of the Windows caret
(text insert position).
Syntax
x=CursorX()
y=CursorY()
Return value
x,y : numeric in pixels ; it gives the coordinates of the current text caret relative
to the top-left corner of the window. If no caret is present or if no window is
found, 0 is returned.
Examples
x=CursorX()
y=CursorY()
92
Data types
Four data types are available. Note that floating numerics (reals) are supported
through strings (see Add$ Subtract$ Multiply$ and Divide$ to know how to deal
with floating point numbers).
Integers
Integers are 32-bit numbers (between -2 147 483 648 and +2 147 483 647).
An integer variable name can be up to 32 alphanumeric characters long. The first
character must be a letter and the last one must NOT be the character $. The
language is not case sensitive.
Integer variables are initialized with the value 0.
Examples :
a=12
qwerty =3567
Strings
A string variable name can be up to 32 alphanumeric characters long. The first
character must be a letter and the last one MUST BE the character $. The
language is not case sensitive.
(see Add$ Subtract$ Multiply$ and Divide$ to know how to deal with floating
point numbers)
String variables are initialized with an empty string.
Examples :
a$="Hello"
Name$="Here is a string variable name"
Arrays
Arrays are unidimensional and can contain up to 65,535 elements. There are two
types of arrays :
Array of integers
Array of strings
An array variable name can be up to 32 alphanumeric characters long. The first
character must be a letter. The language is not case sensitive.
A name for an array of strings must end with the character $. A name for an
array of integers must not end with the character $.
The array variables must be declared using the DIM function at the beginning of
the script. (See Program Structure)
The first element of an array starts at 0.
Examples :
Dim Tab(10) ' Definition of an array with 11 integers (0 to 10)
Dim Tab$(20) ' Definition of an array with 21 strings (0 to 20)
Tab(1)=3
Tab$(2)= "Hello"
See also operators on arrays.
Unsigned
The type UNSIGNED is for unsigned 32-bit integers used for specifying a memory
address (designed for API calls for example).
An UNSIGNED variable must be declared using the statement DIM at the
beginning of the script. (See Program Structure)
Example :
Dim Addr as Unsigned
System Variables
93
Specific variables used by WinTask. Their name starts with the character # and
their use is explained in this help system.
94
Date$
Date/Time function.
The Date$ function returns the current date.
Syntax
date_day$=Date$([<format>])
Parameters
<format>, numeric; either 0 (default value) or 1.
Return value
date_day$, date returned as a string in the short format (such as 09/07/08) if
<format> equals 0, in the long format if <format> equals 1 (as Sunday,
September 7, 2008). The returned date is as specified in the Windows regional
settings.
Example
date_day$=Date$()
95
DateBetween
Date/Time function.
The DateBetween function returns the number of specified time intervals
between two dates.
Usage
It can return the number of days between two dates, the number of weeks
between today and the end of the year, ...
Syntax
val=DateBetween(<interval$>,<date1$>,<date2$>)
Parameters
<interval$>, string specifying the time interval you want to use as the unit of
difference between <date1$> and <date2$>.
<interval$>
Unit of time difference
value
d
Day
w
Weekday
ww
Week (number of weeks), same as w
y
Day of the year, same as d
yyyy
Year (number of years)
q
Quarter (number of quarters)
m
Month (number of months)
h
Hours (number of hours)
n
Minutes (number of minutes)
s
Seconds (number of seconds)
<date1$>, string, first date value to use in the calculation. The date format must
be the one as in Regional settings (05/01/2007 for 1st of May in US format,
01/05/2007 in European format).
<date2$>, string, second date value to use in the calculation
Return value
Returns the number of time intervals as an integer. If one of the parameter is
incorrect (invalid date for example) and if #IgnoreErrors=1, the function returns
0. A negative number is returned if <date2$> is before <date1$>.
Remarks
If the year is not included in <date$>, the current year is added automatically.
If <interval$> is "w" and <date1$> is a Monday, the function returns the number
of Mondays between <date1$> and <date2$> without taking the first Monday
<date1$> (see second example).
Examples
val=DateBetween( "d","12/01/2007","12/31/2007") 'returns 30
val=DateBetween( "w","12/24/2007","12/30/2007") 'returns 0 as 24 December
2007 is a Monday
ret=DateBetween("s","01/12/2007 07:05:00","01/12/2007 08:05:10") 'returns
70 for 70 secs between 7:05 and 8:05:10
96
DateToDate$
Date/Time function.
The DateToDate$ function returns a new datetime value based on adding an
interval to the specified date.
Usage
It can return a date at 30 days from today, a time at 1h45 from now, ...
Syntax
var$=DateToDate$(<interval$>,<number>,<date$>)
Parameters
<interval$>, string specifying the time interval you want to add to <date$>.
<interval$>
Unit of time difference
value
d
Day
w
Weekday
ww
Week (number of weeks)
y
Day of the year
yyyy
Year (number of years)
q
Quarter (number of quarters)
m
Month (number of months)
h
Hours (number of hours)
n
Minutes (number of minutes)
s
Seconds (number of seconds)
<number>, integer, number of interval you want to add. Can be positive, for
dates in the future or negative, for dates in the past.
<date$>, string, date to which <interval$> is added
Return value
Returns a string, the date to which the specified datetime interval has been
added.
Remarks
The returned date always uses the Regional Settings date/time format.
To add days to the specified date, "y", "d" or "w" give all the same result.
Examples
var$=DateToDate$( "d",30,"12/01/2007") 'returns 12/31/2007
var$=DateToDate$( "y",2,"12/30/2007") 'returns 12/30/2009
var$=DateToDate$( "d",30,date$()) 'returns the date 30 days after today
var$=DateToDate$( "d",-30,date$()) 'returns the date 30 days before today
97
Day$
Date/Time function
The Day$ function returns the day number of the current month as a string.
Syntax
dateday$=Day$()
Return value
dateday$, day number returned as a string; if the day is less then 10, a leading 0
is included.
Example
dateday$=Day$() 'for instance, dateday$ contains "09"
98
DbBof
ODBC function.
The DbBof function tests whether the read pointer is at the beginning of the
dataset or not. Not available in WinTask Lite.
Syntax
Ret = DbBof()
Return value
Ret, numeric return code. Ret equals 1 if the pointer is before the first record of
the dataset, 0 if not.
Example
DbConnect("DSN=gpao;PWD=SILOG") ' connection to ODBC database called gpao
DbSelect("SELECT * FROM Business",DYNASET) ' select all records in table
Business.
If DbBof=1 then ' no record in the selection.
stop ' then stop the script.
else ' if records are in selection, continue.
'other statements
endif
99
DbClose
ODBC function.
The DbClose function closes the dataset created by the DbSelect function. Not
available in WinTask Lite.
Syntax
DbClose()
or
Ret=DbClose()
Return value
Ret, numeric return code. Ret is set to 0 if the close was successful, 1 if not.
Example
DbConnect("DSN=gpao;PWD=SILOG") ' connection to ODBC database called gpao
DbSelect("SELECT * FROM Business",DYNASET) ' select all records in table
Business.
DbMoveLast() ' move to last record.
total=DbRecordCount() ' count the number of records.
MsgBox(str$(total)) ' display the record count.
DbClose() ' close dataset Business
100
DbConnect
ODBC function.
The DbConnect function makes a connection to an ODBC database. Not available
in WinTask Lite.
Syntax
DbConnect("DSN=<database_ODBC>")
or
ret=DbConnect("DSN=<database_ODBC>")
Parameter
<database_ODBC> : exact name of the ODBC database as declared in the ODBC
(double check the configuration of this) . The
icon from Contro Panel
keyword DSN is mandatory as only ODBC databases can be accessed using
WinTask. The database name can be followed by other parameters required to
open it, such as userid and password.
Return value
Ret, numeric return code. If the specified database has been opened successfully,
the function returns 0, otherwise use this return code for error management.
Examples
DbConnect("DSN=gpao;PWD=SILOG") ' connection to an ODBC database called gpao
DbConnect("DSN=SQLTEST ;UID=MICHEL ;PWD=ABC") ' connection to an ODBC
database called SQLTEST for the user Michel using the password ABC.
101
#DbDateFormat
System variable - ODBC.
The #DbDateFormat system variable controls the format for displaying a Date
field. Not available in WinTask Lite.
Syntax
#DbDateFormat=1
Remarks
Default value is 0 meaning that Date fields are displayed in the Windows short
format (as defined in Regional settings).
If this variable is set to 1, Date fields are displayed in the Windows long format.
102
DbDisconnect
ODBC function.
The DbDisconnect function disconnects the last connected ODBC database. Not
available in WinTask Lite.
Syntax
DbDisconnect()
or
ret=DbDisconnect()
Return value
Ret, numeric return code. If the database has been disconnected successfully, the
function returns 0, otherwise use this return code for error management.
Example
DbDisconnect()
103
DbEof
ODBC function.
The DbEof function tests whether the read pointer is at the end of the dataset or
not. Not available in WinTask Lite.
Syntax
Ret = DbEof()
Return value
Ret, numeric return code. Ret is set to 1 if the pointer is after the last record of
the dataset, or if there are no records to read; otherwise, Ret is set to 0.
Example
DbConnect("DSN=gpao;PWD=SILOG") ' connection to ODBC database named gpao
DbSelect("SELECT * FROM Business",DYNASET) ' select all records in table
Business.
While not DbEof() ' while there are still records to read
Err=DbGetFieldString("CompanyNum",a$) ' a$ contains the field CompanyNum ;
' return code can be tested.
MsgBox(a$) ' display the result.
Err=DbMovenext() ' move to next record.
Wend
104
DbExecute
ODBC function.
The DbExecute function executes a SQL command on the current dataset. Not
available in WinTask Lite.
Syntax
DbExecute("<SQL_command>")
or
Ret = DbExecute("<SQL_command>")
Parameter
<SQL_command> : any valid SQL command to be executed on the current
dataset.
Return value
Ret, numeric return code. If the SQL command has been performed successfully,
the function returns 0, otherwise use this return code for error management.
Examples
DbConnect("DSN=gpao;PWD=SILOG") ' connection to ODBC database named gpao
DbExecute("UPDATE Article SET Price=Price+100") ' updates the table Article
DbDisconnect()
DbConnect("DSN=gpao;PWD=SILOG") ' connection to ODBC database named gpao
DbExecute("INSERT into Article (article,label) VALUES ('WinTaskDP','Development pack')") ' inserts new values in the table Article
DbDisconnect()
DbConnect("DSN=gpao;PWD=SILOG") ' connection to ODBC database named gpao
DbExecute("DELETE from Article WHERE Price<50") ' deletes selected records in
the table Article
DbDisconnect()
105
DbGetFieldNumeric
ODBC function.
The DbGetFieldNumeric function retrieves the value of a numeric field (integer)
within the current record for the dataset in use. Not available in WinTask Lite.
Syntax
DbGetFieldNumeric(<field_name>,<value>)
or
Ret=DbGetFieldNumeric(<field_name>,<value>)
Parameters
<field_name>, string, name of the field to retrieve.
<value>, numeric, a variable which will contain the value of the field.
Return value
Ret, numeric return code. If the retrieval has been done, the function returns 0,
otherwise use this return code for error management.
Example
DbConnect("DSN=gpao;PWD=SILOG") ' connection to ODBC database called gpao
DbSelect("SELECT * FROM Business",DYNASET) ' select all records in table
Business.
#Ignorerrors=0 ' error management inside the script.
While not DbEof() ' while there are still records to read.
Err=DbGetFieldNumeric("Value",num) ' num contains the numeric value in field
Value.
If err<>0 then ' if an error occurs during retrieval.
Goto gesterr ' call an error routine.
endif
msgbox(str$(num)) ' display the value of the field.
DbMovenext() ' move to next record.
Wend
Example code
'Declare first in system configuration, ODBC databases, your target ODBC
database
'in this script, we have called it DBASE
sub display_enreg()
'It displays in one long string the retrieved fields.
mes$="ID : "+str$(id)
mes$=mes$+"\n\"+"SiteCode : "+sitecode$
mes$=mes$+"\n\"+"RequestNumber : "+requestnumber$
mes$=mes$+"\n\"+"Notes : "+notes$
mes$=mes$+"\n\"+"Address : "+address$
mes$=mes$+"\n\"+"City : "+city$
106
mes$=mes$+"\n\"+"State : "+state$
mes$=mes$+"\n\"+"Zip : "+zip$
msgbox(mes$,64,"Record "+str$(i+1))&#9;&#9;
endsub
'-----------------------------------------sub extract()
nbenreg=DbRecordCount() 'get total records
if nbenreg > 0 then
msgbox(str$(nbenreg)+ " records(s) to process")
DbMoveFirst()
i=0
repeat
DbGetFieldNumeric("ID",id)
DbGetFieldString("SiteCode",sitecode$)
DbGetFieldString("RequestNumber",requestnumber$)
DbGetFieldString("Notes",notes$)
DbGetFieldString("Address",address$)
DbGetFieldString("City",city$)
DbGetFieldString("State",state$)
DbGetFieldString("Zip",zip$)
display_enreg()
DbMoveNext()
i=i+1
until i=nbenreg
else
msgbox("No record to process")
endif
endsub
'************************************
res=dbconnect("DSN=DBASE")
res=dbselect("SELECT * FROM Table1",DYNASET)
extract()
107
DbGetFieldString
ODBC function.
The DbGetFieldString function retrieves the contents of any non-numeric field
within the current record for the dataset in use. Not available in WinTask Lite.
Syntax
DbGetFieldString(<field_name>,<string>)
or
Ret=DbGetFieldString(<field_name>,<string>)
Parameters
<field_name>, string, name of the field to retrieve.
<string>, string, a variable which will contain the contents of the field.
Return value
Ret, numeric return code. If the retrieval has been done, the function returns 0,
otherwise use this return code for error management.
Example
DbConnect("DSN=gpao;PWD=SILOG") ' connection to ODBC database called gpao
DbSelect("SELECT * FROM Business",DYNASET) ' select all records in table
Business.
#IgnoreErrors=0 ' error management inside the script.
While not DbEof() ' while there are still records to read.
Err=DbGetFieldString("Value",val$) ' val$ will be set to the contents of the
' Value field (it is returned as a string).
If err<>0 then ' if an error occurs during retrieval.
Goto gesterr ' call an error routine.
endif
msgbox(val$) ' display the extracted field.
DbMovenext() ' move to next record.
Wend
Example code
'Declare first in system configuration, ODBC databases, your target ODBC
database
'in this script, we have called it DBASE
sub display_enreg()
'It displays in one long string the retrieved fields.
mes$="ID : "+str$(id)
mes$=mes$+"\n\"+"SiteCode : "+sitecode$
mes$=mes$+"\n\"+"RequestNumber : "+requestnumber$
mes$=mes$+"\n\"+"Notes : "+notes$
mes$=mes$+"\n\"+"Address : "+address$
mes$=mes$+"\n\"+"City : "+city$
108
mes$=mes$+"\n\"+"State : "+state$
mes$=mes$+"\n\"+"Zip : "+zip$
msgbox(mes$,64,"Record "+str$(i+1))&#9;&#9;
endsub
'-----------------------------------------sub extract()
nbenreg=DbRecordCount() 'get total records
if nbenreg > 0 then
msgbox(str$(nbenreg)+ " records(s) to process")
DbMoveFirst()
i=0
repeat
DbGetFieldNumeric("ID",id)
DbGetFieldString("SiteCode",sitecode$)
DbGetFieldString("RequestNumber",requestnumber$)
DbGetFieldString("Notes",notes$)
DbGetFieldString("Address",address$)
DbGetFieldString("City",city$)
DbGetFieldString("State",state$)
DbGetFieldString("Zip",zip$)
display_enreg()
DbMoveNext()
i=i+1
until i=nbenreg
else
msgbox("No record to process")
endif
endsub
'************************************
res=dbconnect("DSN=DBASE")
res=dbselect("SELECT * FROM Table1",DYNASET)
extract()
109
DbMove
ODBC function.
The DbMove function moves the read pointer to the specified record for the
dataset in use. Not available in WinTask Lite.
Syntax
DbMove(<pos>)
or
Ret=DbMove(<pos>)
Parameter
<pos>, mumeric, indicates how many records the read pointer must move to get
to the desired record. A positive value moves the pointer toward the end of the
dataset, a negative value moves the pointer toward the beginning of the dataset.
Return value
Ret, numeric return code. If the move has been performed successfully, the
function returns 0, otherwise use this return code for error management.
Example
DbConnect("DSN=gpao;PWD=SILOG") ' connection to ODBC database called gpao
DbSelect("SELECT * FROM Business",DYNASET) ' select all records in table
Business.
DbMove(5) ' move read pointer to the 5th record.
110
DbMoveFirst
ODBC function.
The DbMoveFirst function moves the read pointer to the first record of the
dataset in use. Not available in WinTask Lite.
Syntax
DbMoveFirst()
or
Ret=DbMoveFirst()
Return value
Ret, numeric return code. If the move has been performed successfully, the
function returns 0, otherwise use this return code for error management.
Example
DbConnect("DSN=gpao;PWD=SILOG") ' connection to ODBC database called gpao
DbSelect("SELECT * FROM Business",DYNASET) ' select all records in table
Business.
DbMoveFirst() ' move read pointer to the first record.
111
DbMoveLast
ODBC function.
The DbMoveLast function moves the read pointer to the last record of the
dataset in use. Not available in WinTask Lite.
Syntax
DbMoveLast()
or
Ret=DbMoveLast()
Return value
Ret, numeric return code. If the move has been performed successfully, the
function returns 0, otherwise use this return code for error management.
Example
DbConnect("DSN=gpao;PWD=SILOG") ' connection to ODBC database called gpao
DbSelect("SELECT * FROM Business",DYNASET) ' select all records in table
Business.
DbMoveLast() ' move read pointer to the last record.
112
DbMoveNext
ODBC function.
The DbMoveNext function moves the read pointer to the next record of the
dataset in use. Not available in WinTask Lite.
Syntax
DbMoveNext()
or
Ret=DbMoveNext()
Return value
Ret, numeric return code. If the move has been performed successfully, the
function returns 0, otherwise use this return code for error management.
Example
DbConnect("DSN=gpao;PWD=SILOG") ' connection to ODBC database called gpao
DbSelect("SELECT * FROM Business",DYNASET) ' select all records in table
Business.
DbMoveNext() ' move read pointer to the next record, (the 2nd record).
113
DbMovePrev
ODBC function.
The DbMovePrev function moves the read pointer to the previous record of the
dataset in use. Not available in WinTask Lite.
Syntax
DbMovePrev()
or
Ret=DbMovePrev()
Return value
Ret, numeric return code. If the move has been performed successfully, the
function returns 0, otherwise use this return code for error management.
Example
DbConnect("DSN=gpao;PWD=SILOG") ' connection to ODBC database called gpao
DbSelect("SELECT * FROM Business",DYNASET) ' select all records in table
Business.
DbMoveLast() ' move read pointer to the last record.
DbMovePrev() ' move read pointer to the next to last record.
114
DbRecordCount
ODBC function.
The DbRecordCount function returns the number of records in the dataset in
use. Not available in WinTask Lite.
Syntax
num=DbRecordCount()
Return value
Num, number of records.
Example
DbConnect("DSN=gpao;PWD=SILOG") ' connection to ODBC database called gpao
DbSelect("SELECT * FROM Business",DYNASET) ' select all records in table
Business.
counter=DbRecordCount() ' count the number of records present in dataset.
msgbox(str$(counter)) 'display result
115
DbSelect
ODBC function.
The DbSelect function creates the dataset by selecting the desired records in the
ODBC database. Not available in WinTask Lite.
Syntax
DbSelect(<SQL_selection>[,DYNASET|SNAPSHOT])
or
Ret=DbSelect(<SQL_selection>[,DYNASET|SNAPSHOT])
Parameters
<SQL_selection>, string, SQL request which specifies the records to select in the
ODBC database previously connected using the DbConnect function. In case
<SQL_selection> is a complex one, it is recommended to create it as a string, to
display it for checking using msgbox statement, and then to use it in DbSelect
statement - see the example below.
DYNASET or SNAPSHOT, optional keywords. It specifies how the database must
be read, SNAPSHOT (default value) for ODBC static mode, DYNASET for ODBC
dynamic mode.
If your ODBC driver displays error messages, try to add the DYNASET keyword.
Return value
Ret, numeric return code. If the selection has been performed successfully, the
function returns 0, otherwise use this return code for error management.
Remarks
The selection is a Unicode string, so instead of such a selection:
sql$ = "select 'XYZ' as typeref"
use:
sql$ = "select Cast('XYZ' as nvarchar) as typeref"
Examples
DbConnect("DSN=gpao;PWD=SILOG") ' connection to ODBC database called gpao
DbSelect("SELECT * FROM Business",DYNASET) ' select all records in table
Business.
With a complex SQL syntax :
DbConnect("DSN=gpao;USER=SILOG")
my_request$="SELECT CodeArticle.ARTICLE,Designation1.ARTICLE FROM
LCTC,ARTICLE WHERE CodeRubrique.LCTC=CodeArticle.ARTICLE AND
CodeLancement.LCTC='10000' AND TypeRubrique.LCTC='A'"
msgbox(my_request$)
lct$="10000"
my_request1$="SELECT CodeArticle.ARTICLE,Designation1.ARTICLE FROM
LCTC,ARTICLE WHERE CodeRubrique.LCTC=CodeArticle.ARTICLE AND
CodeLancement.LCTC= '"+lct$+"' AND TypeRubrique.LCTC='A'"
msgbox(my_request1$)
DbSelect("SELECT CodeArticle.ARTICLE,Designation1.ARTICLE FROM LCTC,ARTICLE
WHERE CodeRubrique.LCTC=CodeArticle.ARTICLE AND CodeLancement.LCTC='10000'
AND TypeRubrique.LCTC='A'",DYNASET)
116
117
#DecimalSeparator$
System variable - Floating point calculation functions.
The #DecimalSeparator$ system variable specifies the decimal separator
character used for floating point numbers.
Syntax
#DecimalSeparator$ = "<separator_string>"
Remarks
If this system variable is not specified, the decimal symbol specified in the
Windows Regional Settings is used.
Example
#DecimalSeparator$ = "."
118
DeleteRegKey
System function.
The DeleteRegKey function deletes the specified key in the Registry. Not
available in WinTask Lite.
Syntax
DeleteRegKey(<path>)
or
ret=DeleteRegKey(<path>)
Parameter
<path>, string, path for the key to delete in the Registry (it's the path for the key
to be deleted, not the key itself).
Return value
Ret, numeric return code. If deletion is successful, the function returns 0,
otherwise use this return code for error management.
Example
res=DeleteRegKey("HKEY_CURRENT_USER\Software\Taskware\WinTask
1.0\TASKEDIT\Recent File List")
119
DeleteRegValue
System function.
The DeleteRegValue function deletes the specified value in the Registry. Not
available in WinTask Lite.
Syntax
DeleteRegValue(<path>)
or
ret=DeleteRegValue(<path>)
Parameter
<path>, string, path for the value to delete in the Registry (it's the path for the
value to be deleted, not the value itself).
Return value
Ret, numeric return code. If the deletion is successful, the function returns 0,
otherwise use this return code for error management.
Example
res=DeleteRegValue("HKEY_CURRENT_USER\Software\Taskware\WinTask
1.0\TaskEdit\Recent File list\File1")
120
DelTree
System function.
The DelTree function deletes all the files and sub-directories below the specified
directory.
Syntax
DelTree(<directory_name>)
or
ret=DelTree(<directory_name>)
Parameters
<directory_name>, string, name of the directory under which all files and subdirectories have to be deleted.
Return value
Ret, numeric return code. When the deletion is successful, the function returns 0,
otherwise use this return code for Error Handling.
Remarks
Use RmDir function to delete the directory name itself after having deleted its
files and sub-directories using DelTree.
The function works as the old DelTree Dos function under Windows 98, so note
that if the specified directory does not exist, no error is reported.
See also
RmDir
Examples
DelTree("c:\bmp")
RmDir("c:\bmp")
DelTree(direct$)
RmDir(direct$)
121
Dim
Compilation
The Dim keyword is used to declare arrays or Unsigned integers at the beginning
of a script.
Syntax
Dim tab_integ(<size>)
or
Dim tab_string$(<size>)
or
Dim unsigned_int As Unsigned
Parameters
<size>, numeric, size of the array starting at 0. Arrays are limited to one
dimension and 65535 elements.
Remarks
Array variables MUST BE DECLARED AT THE VERY BEGINNING OF THE SCRIPT
before being used. Functions/Subs declaration must be written after arrays
declaration. If Included scripts are used, the structure of the full long script with
the inclusions must follow the same order, first arrays, second functions/subs,
third main program.
See also
Program Structure
Data types
Example
dim my_array$(5) 'declares an array with 6 string elements.
my_array$(1)="test"
my_array$(2)="hello"
msgbox("1="+my_array$(1))
msgbox ("2="+my_array$(2))
dim my_array(100) 'declares an array with 100 integer elements (first element is
my_array(0)).
dim my_pointer as unsigned
122
Dir
System function.
The Dir function puts file names from a directory into arrays.
Usage
In an automation task, you often have to repeat the same actions for all the files
within a directory, or for all the files with a specific extension. Dir function gives
the needed list of files to process. We recommend to use DirTree instead of Dir.
Syntax
Dir(<file_spec$>,tab1$(),tab2$(),tab3$(),"options")
or
ret=Dir(<file_spec$>,tab1$(),tab2$(),tab3$(),"options")
Parameters
<file_spec$>: string such as "c:\mydir\*.txt" or "\\serv\home\dir 1\as??.*", list
of files to put in a array. If the path is omitted, the search is performed in the
current directory. If option "R" is specified, the files are searched in the current
directory and all its subdirectories.
Tab1$(), tab2$(), tab3$() are result arrays. They must have been declared at the
beginning of the script with the DIM statement.
Tab1$() returns the long file names of the files found (including hidden or system
files), without their paths.
Tab2$() returns the short file names (DOS 8.3 format) of the files found with
their paths.
Tab3$() returns the attributes of the files found:
D
directory
R
read only
H
hidden
A
archive
S
system
"options" is a string, modifying the search and sort order of the arrays. It may
contain one or more of the following letters:
N
sort by name
S
sort by size
E
sort by type (extension)
D
sort by date
G
put directories first
R
include subdirectories
A
sort by last access date (this is different from last modification
date)
Ex : if option = "AN", the list will be sorted by last access date. For identical
access dates, files will be sorted by name.
Return value
ret, integer, number of files found. If no items are found, 0 is returned. If an
error is detected in an argument (for instance, an invalid path), a return code of 1 is returned; unless #IgnoreErrors=1, all the scripts are stopped.
Remarks
If file_spec$ ends with "*.*", the first 2 items in the arrays tab1$() and tab2$()
123
will be "." and ".." as in a DOS DIR command listing. In tab3$, they will appear
with the "D" attribute (directory).
If Dir() is used with the R option, file names appear in the specified order,
without regard to the directory in which they are found. If the R option is used in
a search for "*.*", tab1$() and tab2$() will contain "." and ".." several times (see
above).
See also
DirTree
FileAttr$
Example
Dim tab1$(100)
Dim tab2$(100)
Dim tab3$(100)
spec$="*.lst"
'Returns all the *.LST filenames within the current directory and its subdirectories.
num=dir(spec$,tab1$(),tab2$(),tab3$(),"R")
if num=0 then stop endif
i=0
repeat
msgbox(tab1$(i))
i=i+1
until i>=num
124
DirTree
System function.
The DirTree function puts file names and directory names into arrays.
Usage
In an automation task, you often have to repeat the same actions for all the files
within a directory, or for all the files with a specific extension. DirTree function
gives the needed list of files to process. Look at a script example Process and
Rename all the files with a specific extension.
Syntax
DirTree(<file_spec$>,tablongname$(),tabshortname$(),tabpath$(),tabattrib$(),"
options")
or
ret=DirTree(<file_spec$>,tablongname$(),tabshortname$(),tabpath$(),tabattrib
$(),"options")
Parameters
<file_spec$>: string such as "c:\mydir\*.txt" or "\\serv\home\dir 1\as??.*", list
of files to put in a array. If the path is omitted, the search is performed in the
current directory. If option "R" is specified, the files are searched in the current
directory and all its subdirectories.
Tablongname$(), tabshortname$(), tabpath$(), tabattrib$() are result arrays.
They must have been declared at the beginning of the script with the DIM
statement.
Tablongname$() returns the long file names of the files found (including hidden
or system files), without their paths.
Tabshortname$() returns the short file names (DOS 8.3 format) of the files found
without their paths.
Tabpath$() returns the path (without the \ at the end) of the files found.
Tabattrib$() returns the attributes of the files found:
R
read only
H
hidden
A
archive
S
system
"options" is a string, modifying the search and sort order of the arrays. It may
contain one or more of the following letters:
N
sort by name
S
sort by size
E
sort by type (extension)
D
sort by date
R
include subdirectories
A
sort by last access date (this is different from last modification
date)
Ex : if option = "AN", the list will be sorted by last access date. For identical
access dates, files will be sorted by name.
Return value
ret, integer, number of files found. If no items are found, 0 is returned. If an
error is detected in an argument (for instance, an invalid path), a return code of 1 is returned ; unless #IgnoreErrors=1, all the scripts are stopped.
125
See also
Dir
FileAttr$
Process and Rename all the files with a specific extension
Example
With such a tree :
ivodbc
header
odbcinst.h
sql.h
sqlext.h
sqltypes.h
sqlucode.h
jdbcodbc
brdgread.me
jsjob.exe
msjob.exe
oleodbc
msdadll.exe
msdahelp.exe
msdainst.bat
regsvr32.exe
translat
libmain.c
readme.trn
translat.c
winnt.mak
ivsetup.inf
prodlist.ini
qprofile.dll
read.me
uninst.isu
Statement
ret=Dirtree("c:\ivodbc\*.*",tablong$(),tabshort$(),tabpath$(),tabattrib$(),"
GR")
returns 25 and arrays have contents as below :
tablong$()
header
jdbcodbc
oleodbc
translat
ivsetup.inf
prodlist.ini
qprofile.dll
read.me
uninst.isu
odbcinst.h
........
126
tabshort$()
header
jdbcodbc
oleodbc
translat
ivsetup.inf
prodlist.ini
qprofile.dll
read.me
uninst.isu
odbcinst.h
tabpath$()
c:\ivodbc
c:\ivodbc
c:\ivodbc
c:\ivodbc
c:\ivodbc
c:\ivodbc
c:\ivodbc
c:\ivodbc
c:\ivodbc
c:\ivodbc
tabattrib$()
D
D
D
D
A
A
A
A
A
A
Disable
Synchronization function.
The Disable function disables the management of a specified event. Not available
in WinTask Lite.
Syntax
Disable(<Action_Id>)
or
Disable()
Parameter
<Action_Id>, event to be disabled. This event is taken out of the list of events
that WinTask manages.
Disable(): when no parameters are specified, all events are disabled.
Remarks
The compiler checks if <Id_action> has been defined.
The Disable function can only be used in the script after the event has been
activated.
The Disable function can be inserted in the procedure managing the <Id_action>;
the event is then taken out of the list of events to be managed and execution
continues.
See also
OnAction, Sleep
Example code
This example shows how an event can be disabled using the Disable command;
the event is defined by the OnAction command, this event is the selection of the
option Close in the Explorer menu.
Sub close()
Disable(wait_for_close_menu)
res=msgbox("Would you like to close the message box? ",4,"EXAMPLE")
if res=6 then
' if res=6 WinTask closes Explorer and stops the script
CloseWindow("EXPLORER.EXE|ExploreWClass|My Documents",2)
stop
endif
Enable(wait_for_close_menu)
EndSub
OnAction wait_for_close_menu
_Menu("File|&Close")
_InWindow("EXPLORER.EXE|ExploreWClass|My Documents",2)
_DoSub close
EndAction
shell("explorer")
' Definition of the event, each time the user selects the option Close in
the Explorer menu File,
127
' the script runs the procedure close().
sleep()
'leaves the management of the random events active.
128
DiskFree
System function.
The DiskFree function returns the available space on the specified resource.
Syntax
var=DiskFree(<resource_name>)
Parameter
<resource_name>, string constant or variable. It's a disk letter (it can't be a UNC
path).
Return value
var, numeric, available space (in Kbytes) on the resource; 0 if <resource_name>
is not found or if there is no more space on the disk. If the disk does not exist, an
error message is displayed and all the scripts are stopped if #IgnoreErrors=0
(value by default). If #IgnoreErrors=1, the returned value is at 0 when an error
is detected at execution.
Example
var = DiskFree("F:") 'returns the available space on the disk F
129
Divide$
Floating point calculation function.
The Divide$ function divides two strings representing floating point numbers.
Usage
As only integers are supported numbers in WinTask, calculation on floating point
numbers is done using their string representation.
Syntax
res$=Divide$(a$,b$[,rc])
Parameters
a$, b$ are the strings representing the two floating numbers to be divided.
rc, optional numeric return code.
Values are :
0 if the division is successful
1 invalid operation because the parameters are incorrect (for instance, the string
can't be considered a number)
2 if operation causes and overflow
3 if division by zero is attempted
Return value
res$, string representing a$/b$.
Examples
Divide$("13.56","145.789") 'gives "0.09"
Divide$("-45.678","34.8976") 'gives "-1.31"
#Precision=3
Divide$("567.34257","45.343") 'gives "12.512"
130
Enable
Synchronization function.
The Enable function reactivates the management of a specified event. Not
available in WinTask Lite.
Syntax
Enable(<Id_action>)
Parameter
<Id-action>, event to be reactivated.
See also
OnAction, Sleep, Disable
Example code
This example shows how an event can be enabled using the Enable command;
the event is defined by the OnAction command, this event is the selection of the
option Close in the Explorer menu.
Sub close()
Disable(wait_for_close_menu)
res=msgbox("Would you like to close the message box? ",4,"EXAMPLE")
if res=6 then
' if res=6 WinTask closes Explorer and stops the script
CloseWindow("EXPLORER.EXE|ExploreWClass|My Documents",2)
stop
endif
Enable(wait_for_close_menu)
EndSub
OnAction wait_for_close_menu
Menu("File|&Close")
InWindow("EXPLORER.EXE|ExploreWClass|My Documents",2)
DoSub close
EndAction
shell("explorer")
' Definition of the event, each time the user selects the option Close in
the Explorer menu File,
' the script runs the procedure close().
sleep()
'leaves the management of the random events active.'leaves the management of
the random events active.
131
EnabledW
Windows management function.
The EnabledW function verifies that the specified window is enabled and can
receive actions.
Syntax
ret=EnabledW(<window_name> [,<instance>])
Parameters
<window_name>, window name of the window to check.
<instance>, optional parameter, instance number of the window to check.
Return value
Ret, numeric return code. When the specified window is enabled, the function
returns 1 ; if the window cannot receive any mouse/keyboard actions, the
function returns 0.
Remarks
This statement can be used to test if a button is grayed or not. Buttons within a
toolbar cannot be tested with EnabledW function because the only window seen
by WinTask is the Toolbar window : the second script example listed below shows
how to test if a button in a toolbar is active or not.
This statement can be used for testing if a window is active when you receive the
error message Unable to activate window (see the first example below).
EnabledW does not include a synchronization mechanism, so you have to wait
that the window <window_name> is really displayed before running the
EnabledW.
See also
CheckedW for interaction with EnabledW in case of a check box or a radio button.
Example code
This example tests a button status in the window Display properties of the
Control panel.
Function Button_test(win$,name$)
ret=ExistW(win$)
if ret=0 then
msgbox("There is no button "+name$,16,"")
stop
else
ret=EnabledW(win$)
if ret=0 then
msg$="Disabled"
else
msg$="Enabled"
endif
endif
132
Msgframe("The button "+name$+" is "+msg$,1,0,0,12,255)
pause 4
removeframe(1)
EndFunction
Shell("Control")
pause 2
UseWindow("EXPLORER.EXE|SHELLDLL_DefView|Control Panel|1",1)
ChooseItem(ListView,"1","Display",double)
UseWindow("RUNDLL32.EXE|#32770|Display Properties",1)
button_win$="RUNDLL32.EXE|Button|&Apply"
button_name$="Apply"
Button_test(button_win$,button_name$)
'Change button status
UseWindow("RUNDLL32.EXE|#32770|Background",1)
sendkeys("<Down>")
Button_test(button_win$,button_name$)
CloseWindow("RUNDLL32.EXE|#32770|Display Properties",1)
CloseWindow("EXPLORER.EXE|CabinetWClass|Control Panel",1)
This second example shows how to test if a button in a Toolbar is active or not,
without clicking this button.
'Function testing if the bitmap specified in file_bmp$ is found within the
window win$.
'after timeout seconds, if file_bmp$ is not found, the function returns 0.
'file_bmp$ contains the bitmap file for the button to be checked, when this
one is active ;
'use Capturebitmap to create this file
Function is_control_enable(file_bmp$,win$,timeout)
local buffer,res
buffer=#Pausetimeout
#Pausetimeout=Timeout
res=0
Pause until
bitmap(file_bmp$)
inWindow(win$)
PauseOK
res=1
PauseFalse
res=0
EndPause
133
#Pausetimeout=buffer
is_control_enable=res
EndFunction
'Main program on a specific window toolbar
result=is_control_enable("C:\program
files\wintask\scripts\button_toolbar.bmp","KODAKIMG.EXE|ToolbarWindow32|Imag
ing",10)
msgbox(result)
134
Encrypt
String management function
The Encrypt function encrypts the specified string (not available in WinTask
Lite).
Syntax
Encrypt(<Source_string>,<Encrypted_string>)
or
ret=Encrypt(<Source_string>,<Encrypted_string>)
Parameters
<Source_string>, string, constant or variable. String to be encrypted.
<Encrypted_string>, string, variable only. Result of the encryption.
ret, optional numeric return code. The return code is 0 if the encryption has been
done successfully, 1 if not. If #IgnoreErrors=0, and the encryption could not be
done, the script execution stops and an error message is returned.
Example
a$=InputBoxSecret$("Enter your password:")
Encrypt(a$,encr$)
msgbox("Your encrypted password is: "+encr$)
135
End
Program flow control function.
The End function stops the currently running script.
Syntax
End[(<retcode>)]
Parameters
<retcode>: optional return code which can be tested by the calling script in the
case of nested scripts. If no return code is specified, 0 is returned.
See also
Stop
Parameters passed from one script to another
Examples
End(2)
End
For a full example, see the Run function.
136
EnumXMLAttributes
File management function.
The EnumXMLAttributes function retrieves the attribute names and attribute
values for the specified XML node. Not available in WinTask Lite.
Syntax
EnumXMLAttributes(<filename>,<XML_path>,<attribute_name_array>,<value_a
rray>)
or
ret=EnumXMLAttributes(<filename>,<XML_path>,<attribute_name_array>,<val
ue_array>)
Parameters
<filename>, string, name of the XML file where to add/modify the attribute.
<XML_path>, string, list of node descriptors separated by the \ character to go
where the attribute is. The string is not case-sensitive.The structure of such a
path is:
tagname[attributename1='value']
The tagnames are strings without double quotes, they cannot contain spaces or
reserved characters.
The attribute names are strings without double quotes, OR it can be the reserved
keyword <text> or the reserved keyword <index>. <text> is used to specify the
node inner text, <index> is used to specify the node index (first one starts at 1)
when more nodes with the same tag and attributes exist within the same parent.
Several attributes can be listed with the syntax
tagname[attributename1='value1', attributename2='value2']
Examples:
If the XML file contains:
<bookstore>
<book genre="autobiography" publicationdate="1981" ISBN="1-861003-110">
the <XML_path> can be "bookstore\book[genre='autobiography']" or
"bookstore\book[publicationdate='1981']" or
"bookstore\book[publicationdate='1981',genre='autobiography']"
<attribute_name_array>, array of strings. The content of the cells beginning with
element 0 returns each attribute name under the specified XML node.
<value_array>, array of strings. The content of the cells beginning with element
0 returns the value for the corresponding attribute.
Return value
Ret, numeric return code. When the function is successfully executed, ret returns
the number of attributes for the specified XML path, otherwise use this return
code for Error Handling. The error codes are :
-27
The XML file could not be opened
-90
Internal error (COM error when invoking XML COM)
-99
Invalid parameters
-110
Invalid XML path
-112
Index too big
See also
137
AppendXMLNode
GetXMLAttribute
EnumXMLChildren
SetXMLAttribute
Example
XML file:
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
dim children$(100)
dim name$(100)
dim value$(100)
file$ = "c:\program files\wintask\scripts\sample.xml"
ret = EnumXMLAttributes(file$, "bookstore\book[<index>=2]", name$(),
value$())
'ret returns the number of attributes under bookstore\book\[<index>=2] XML
node
msgbox(ret)
' Displays the first attribute name and its value
msgbox(name$(0) + "=" + value$(0))
138
EnumXMLChildren
File management function.
The EnumXMLChildren function enumerates the child node descriptors for the
specified XML node. Not available in WinTask Lite.
Syntax
EnumXMLChildren(<filename>,<XML_path>,<child_node_array>)
or
ret=EnumXMLChildren(<filename>,<XML_path>,<child_node_array>)
Parameters
<filename>, string, name of the XML file where to add/modify the attribute.
<XML_path>, string, list of node descriptors separated by the \ character to go
where the attribute is. The string is not case-sensitive.The structure of such a
path is:
tagname[attributename1='value']
The tagnames are strings without double quotes, they cannot contain spaces or
reserved characters.
The attribute names are strings without double quotes, OR it can be the reserved
keyword <text> or the reserved keyword <index>. <text> is used to specify the
node inner text, <index> is used to specify the node index (first one starts at 1)
when more nodes with the same tag and attributes exist within the same parent.
Several attributes can be listed with the syntax
tagname[attributename1='value1', attributename2='value2']
Examples:
If the XML file contains:
<bookstore>
<book genre="autobiography" publicationdate="1981" ISBN="1-861003-110">
the <XML_path> can be "bookstore\book[genre='autobiography']" or
"bookstore\book[publicationdate='1981']" or
"bookstore\book[publicationdate='1981',genre='autobiography']"
<child_node_array>, array of strings. The content of the cells beginning with
element 0 returns each child node under the specified XML node.
Return value
Ret, numeric return code. When the attribute value is successfully inserted in the
XML file, the function returns 0, otherwise use this return code for Error Handling.
The error codes are :
27
The XML file could not be opened
90
Internal error (COM error when invoking XML COM)
99
Invalid parameters
110
Invalid XML path
112
Index too big
See also
AppendXMLNode
GetXMLAttribute
SetXMLAttribute
EnumXMLAttributes
Example
139
XML file:
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
dim children$(100)
dim name$(100)
dim value$(100)
file$ = "c:\program files\wintask\scripts\sample.xml"
ret = EnumXMLAttributes(file$, "bookstore\book[<index>=2]", name$(),
value$())
'ret returns the number of attributes under bookstore\book\[<index>=2] XML
node
msgbox(ret)
' Displays the first attribute name and its value
msgbox(name$(0) + "=" + value$(0))
'children$(0) returns the first child node of
bookstore\book[category='CHILDREN']
ret = enumxmlchildren(file$, "bookstore\book[category='children']",
children$())
'the array children$() can then be used to loop on each child node and
retrieve their attribute values
i=0
while i < ret
getxmlattribute(file$, children$(i), "<text>", val$)
msgbox(val$)
i = i+1
wend
On the same file, the script below returns the text titles for the books in category
WEB:
dim children$(100)
file$ = "c:\program files\wintask\scripts\sample.xml"
ret = enumxmlchildren(file$, "bookstore", children$())
140
i=0
while i < ret
getxmlattribute(file$, children$(i), "category", val$)
if val$ = "WEB" then
getxmlattribute(file$, children$(i)+"\title[lang='en']", "<text>", val$)
msgbox(val$)
endif
i = i+1
wend
141
Envir$
System function.
The Envir$ function returns the value of an environment variable.
Syntax
var$=Envir$(<var_name$>)
Parameters
<var_name$>, string, name of an environment variable.
Return value
var$, string, value of the specified environment variable.
Remarks
envir$ can retrieve any Windows environment variables, but for the variables
defined by the SET command, the SET command must have been done by
WinTask in the actual session (see script example below).
Example
var$ = Envir$("mydir")
'returns in var$ "c:\test" if the statement " SET mydir = c:\test " has been
executed
Example showing that envir$ can retrieve Windows environment variables plus
only the variables which has been SET by the WinTask script :
shell("cmd")
var$="MYVARIABLE"
'The script sets up an environment variable
usewindow("CMD.EXE|ConsoleWindowClass|")
sendkeys("set "+var$+" = VALUE")
sendkeys("<Enter>")
pause 1
sendkeys("cls<Enter>")
sendkeys("set "+var$)
sendkeys("<Enter>")
a$=capture$("CMD.EXE|ConsoleWindowClass|", 0, 1)
pos1=instr(a$,var$+" = ")
res$=mid$(a$,pos1,80)
msgbox(res$,64,"Capture in the Dos box")
'As you can see var$ is present in SET environment
'var$ is empty
a$=envir$(var$)
msgbox(var$+" : "+a$,64,"Variable retrieved using envir$ statement")
'Username is correct
142
a$=envir$("username")
msgbox("username : "+a$)
sendkeys("exit<Enter>")
pause 1
shell("cmd")
usewindow("CMD.EXE|ConsoleWindowClass|")
sendkeys("set "+var$)
sendkeys("<Enter>")
'As you can see, Var$ is not anymore in set environment as it's a new Dos
box but username is still present
sendkeys("set username")
sendkeys("<Enter>")
143
Eof
File management function.
The Eof function determines if the end of the specified file has been reached.
Usage
Eof is used in loop constructions to detect the end of the file which is processed.
Syntax
Eof(<filename>)
or
var=Eof(<filename>)
Parameters
<filename>, string, name of the file to test.
Return value
var, numeric return code; if the end of the file has been reached, the return code
is set to 1, otherwise 0. If <filename> is not open for reading or does not exist, 0
is returned (see statement Read).
Example
var = Eof("C:\my directory\my file.txt")
144
#ErrorCode
System variable - Synchronization, File management, Program flow control,
System, Com management.
The #ErrorCode system variable gives the return code of the WinTask function
that triggered the OnAction Error procedure. Not available in WinTask Lite.
Usage
When a script is replayed with #IgnoreErrors=1, and if the script fails, the error
code is not displayed. You can use #ErrorCode system variable to know the error
code which explains why the script failed.
Syntax
msgbox(#ErrorCode)
145
#ErrorFunction$
System variable - Synchronization, File management, Program flow control,
System, Com management.
The #ErrorFunction$ system variable gives the WinTask sub or function name
where the error triggering the OnAction Error procedure occurred. Not available in
WinTask Lite.
Usage
When a script is replayed with #IgnoreErrors=1, and if the script fails, the name
of the function in error is not displayed. You can use #ErrorFunction$ system
variable to know which function triggered the error.
Syntax
msgbox(#ErrorFunction$)
146
#ErrorLine$
System variable - Synchronization, File management, Program flow control,
System, Com management.
The #ErrorLine$ system variable indicates the script line where a timeout has
occurred during the execution of a Pause Until ... EndPause statement.
Syntax
a$=#ErrorLine$
See statement Pause
147
#ErrorMsg$
System variable - Synchronization, File management, Program flow control,
System, Com management.
The #ErrorMsg$ system variable returns the WinTask error message for the
error that triggered the OnAction Error procedure. Not available in WinTask Lite.
Usage
When a script is replayed with #IgnoreErrors=1, and if the script fails, the error
message is not displayed. You can use #ErrorMsg$ system variable to know the
error message which explains why the script failed.
Syntax
msgbox(#ErrorMsg$)
148
#ErrorScript$
System variable - Synchronization, File management, Program flow control,
System, Com management.
The #ErrorScript$ system variable gives name of the script where the error
trigerring the OnAction Error procedure occurred. Not available in WinTask Lite.
Usage
When a script is replayed with #IgnoreErrors=1, and if the script fails, the script
name is not displayed. You can use #ErrorScript$ system variable to know in
which script the error occurred.
Syntax
msgbox(#ErrorScript$)
Remarks
If the executed script uses included scripts, #ErrorScript$ returns the name of
the main script, not the name of the included script even if the OnAction Error
triggered in this included script.
149
ExecExcelMacro
System function.
The ExecExcelMacro function executes an Excel macro in the specified Excel
book.
Usage
Use ExecExcelMacro function to run a macro in Excel in just one line without
opening Excel. The macro execution is done silently and the Excel file is saved.
Syntax
ExecExcelMacro (<workbook> ,<macro_name>,<timeout>)
or
ret=ExecExcelMacro (<workbook> ,<macro_name>,<timeout>)
Parameters
<workbook>, string, name of the Excel workbook to read from. It is a string
which can be a constant or a variable. Long names and UNC names are accepted,
such as \\Server\c\my_directory\my_file.xls. If the path is not specified, the file
is searched in the current directory.
<macro_name>, string, name of the macro to execute. At the end of the macro
execution, the Excel workbook is automatically saved.
If after <timeout> seconds, the macro has not finished its execution, an error is
reported (if #IgnoreErrors=1, default value) . If <timeout> is set to 0, there is
no limitation for execution duration.
Return value
Ret, numeric return code. When the macro execution has ended successfully, the
function returns 0. If the macro did not finish within the <timeout> the return
code is set to -1 and you can use this return code for Error Handling. The return
code is 2 if the specified Excel file does not exist. The return code is 107 if the
specified macro does not exist in the workbook.
Examples
ExecExcelMacro("c:\my documents\my_excel_file.xls", "my_macro",0)
ExecExcelMacro("c:\my documents\my_excel_file.xls",
"PERSONAL.XLS!my_macro",30)
excelfile$="c:\my documents\my_excel_file.xls"
macro$="my_macro"
ExecExcelMacro(excelfile$,macro$,10)
150
#ExecTimeout
System variable - Program flow management.
The #ExecTimeout system variable specifies the maximum number of seconds
that WinTask will wait before killing the current script. Not available in WinTask
Lite.
Usage
If you need to run a script at regular interval whatever error is reported,
#ExecTimeout used in conjunction with #ScriptAfterTimeout$ allow to rerun
within a clean desktop whatever happened during previous execution.
Syntax
#ExecTimeout = n
Remarks
When n seconds have elapsed, if the script is not finished, the script is killed and
the execution stopped. If the system variable #ScriptAfterTimeout$ is filled with
a value, the script named in this variable is then launched.
The use of this system variable along with #ScriptAfterTimeout$ allows to
recreate a "clean" environment if the script fails for any reason and so you can
rerun the same script exactly in the same state than if it was the first time; see
below the example code.
#ExecTimeout set to 0 means that there is no timeout.
If #ExecTimeout is set to a value lower than the execution time so far,
#ExecTimeout is forced to 0.
See also
#ScriptAfterTimeout$
Example
#ExecTimeout = 20
Example code
This script launches Notepad and the Web page www.wintask.com. After
#ExecTimeout seconds (here at 10), the script is killed and the script
killprocesses is launched. This last script kills the two processes Notepad and
Iexplore, so the environment before launching the first script is restored.
#ExecTimeout=10
#ScriptAfterTimeout$="killprocesses"
Shell("notepad")
StartBrowser("IE", "www.wintask.com")
UsePage("Macro and Data Extraction with WinTask - the automation software
for Windows and internet")
ClickHTMLElement("A[INNERTEXT= 'DOWNLOAD your 30-day']")
UseWindow("IEXPLORE.EXE|TravelBand|WinTask Download - Free Version 30 days Windows Internet Explorer|1",1)
151
ChooseItem(ToolBar, "|1", "Back", single, left )
pause 20
' Script killprocesses------------------------------------------------KillApp("notepad.exe",1)
killApp("iexplore.exe",1)
This other example shows how to take a screenshot of the desktop after
#ExecTimeout.
'If the script does not finish after 30 secs (#ExecTimeout), the execution
is stopped
'and the script called AfterTimeout is executed (the file AfterTimeout.rob
must exist).
#ScriptAftertimeout$="AfterTimeout"
#Exectimeout=30
#Actiontimeout=15
Shell("notepad")
'The window does not exist and so the script fails.
UseWindow("toto")
And the script called after this first script is killed has just one line:
ret=Hardcopy("C:\program files\wintask\scripts\error.jpg",1,1)
152
#ExecuteDelay
System variable - Windows management.
The #ExecuteDelay system variable slows down a running script by inserting a
wait for n ticks between every statement.
Syntax
#ExecuteDelay=val
The default value is 0. A tick is around 1/100 second.
See also
#SendKeysDelay
Example
' Delay 10 ticks between each statement
#ExecuteDelay=10
153
Exist
File management function.
The Exist function checks for the existence of the specified file.
Usage
Before processing actions on a file, it is a good practise to test first if the file
exists. You will not get an error if in some circumstances, the file does not exist.
Syntax
ret=Exist(<filename>)
Parameters
<filename>, string, name of the file to test. If no path is included in <filename>,
the current directory is searched.
Return value
ret, numeric return code; if the file exists, the return code is set to 1, otherwise
0.
See also
ExistDir
Example
a=Exist(WinDir$()+"\sol.exe").
If a=1 then
' if sol.exe exists in Windows directory, run it.
shell("sol.exe")
endif
154
ExistDir
File management function.
The ExistDir function checks for the existence of the specified directory.
Syntax
ret=ExistDir(<directoryname>)
Parameters
<filename>, string, name of the directory to test. A path can be included in
<directoryname>.
Return value
ret, numeric return code; if the directory exists, the return code is set to 1,
otherwise 0. If the path specified in <directoryname> is not valid, return code is
0. If <directoryname> is in fact a filename, return code is 0.
See also
Exist
Examples
ret=ExistDir(WinDir$())
msgbox(ret)
ret=ExistDir("C:\program files\wintas")
msgbox(ret)
155
ExistHTMLElement
Web function.
The ExistHTMLElement function checks for the existence of the specified html
element. Not available in WinTask Lite.
Usage
For advanced users, it allows to check first if an HTML element is there before
trying to use it.
Syntax
ret=ExistHTMLElement(<html_descriptor>)
Parameters
<html_descriptor>, identifier of the HTML element to check within the current
Web page specified by the last UsePage. Use Recording mode for generating
automatically the html descriptor.
Return value
Ret, numeric return code. If the specified HTML element is found, the function
returns 1, if not it returns 0. If there is no previous UsePage or StartBrowser line,
the function returns 0.
Remarks
ExistHTMLELement function does not check if a UsePage has been done before, or
if the element to test has finished to load. So always write a UsePage before
using ExistHTMLElement: the UsePage makes the automatic synchronization and
so the line after the UsePage will be executed only when all the elements on the
page are loaded.
Example
Check if the html element WinTask is on the first page of the WinTask website.
StartBrowser("IE", "www.wintask.com")
UsePage("Macro and Data Extraction with WinTask - the automation software
for Windows and internet")
ret=ExistHTMLElement("A[INNERTEXT= 'WinTask']")
msgbox(ret) 'returns 1
The function is case sensitive for the HTML descriptor unless you use
#IgnoreHTMLCase = 1
StartBrowser("IE", "www.wintask.com")
UsePage("Macro and Data Extraction with WinTask - the automation software
for Windows and internet")
ret=ExistHTMLElement("A[INNERTEXT= 'winTask']")
msgbox(ret) 'returns 0
but
StartBrowser("IE", "www.wintask.com")
UsePage("Macro and Data Extraction with WinTask - the automation software
for Windows and internet")
#IgnoreHTMLCase=1
ret=ExistHTMLElement("A[INNERTEXT= 'winTask']")
msgbox(ret) 'returns 1
156
157
ExistW
Windows management function.
The ExistW function checks for the existence of the specified window.
Usage
If a window appears only in some circumstances, you can test if it is there using
ExistW function. For example, when you save a document, depending if the
document already exists or not, you get or you do not get a window prompting to
replace it.
Syntax
ret=ExistW(<window_name>[,<instance>])
Parameters
<window_name>, window name of the window to test.
<instance>, optional, instance number of the window.
Return value
ret, numeric return code ; if the window exists and is displayed, the return code
is set to 1, otherwise 0.
Remarks
To know if a script (.rob) is running, use
ExistW("TASKEXEC.EXE|TaskExec|my_script.rob",1)
which returns 1 if the script's icon exists (this does not work if #HideIcon = 1).
ExistW function used in conjunction with an If structure can be used for testing if
a window appears during a task.
ExistW never truncates the specified window name, so if you want to check the
existence of a window which title changes at replay, truncate its window name.
See also
CheckedW for interaction with ExistW in case of a check box or a radio button.
Examples
a = ExistW("NOTEPAD.EXE|Edit|Untitled")
a = ExistW("NOTEPAD.EXE|Edit|Untitled",1)
'Click Yes button for replacing a document if it already exists
Shell("notepad",1)
UseWindow("NOTEPAD.EXE|Edit|Untitled - Notepad|1",1)
SendKeys("Hello")
CloseWindow("NOTEPAD.EXE|Notepad|Untitled - Notepad",1)
UseWindow("NOTEPAD.EXE|#32770|Notepad",1)
Click(Button,"&Yes")
UseWindow("NOTEPAD.EXE|SHELLDLL_DefView|Save As|1",1)
ChooseItem(ListView, "1", "test.txt", single, left )
158
UseWindow("NOTEPAD.EXE|#32770|Save As",1)
Click(Button,"&Save")
If ExistW("NOTEPAD.EXE|#32770|Save As") = 1 then
Click(Button,"&Yes")
Endif
ExistW function can be used to write a Function which waits for one window to
appear OR a second window to appear:
function wait_for_two_window(name1$,name2$, Timeout)
'The function returns 0 if none of the 2 specified window names have been
found within timeout
local ret, t
repeat
ret=existw(name1$)
if ret=0 then
ret=existw(name2$)
if ret=0 then
pause 1
t=t+1
else
ret=2
endif
endif
until ret > 0 or t > timeout
wait_for_two_window=ret
EndFunction
'CALL example
res=wait_for_two_window("NOTEPAD.EXE|Notepad|","CALC.EXE|#32770|Calc", 10)
msgbox(res)
159
ExitFunction
Program flow control function.
See
Function...EndFunction
160
ExitSub
Program flow control function.
See
Sub...EndSub
161
External$
System function.
The External$ function calls a Windows DLL and returns a string. Not available in
WinTask Lite.
Syntax
var$=External$(<DLL_name$>,<function_name$>[, <param1>[,<param2>,
...]])
Parameter
<DLL_name$>, string, name of the Windows DLL.
<function_name$>, string, name of the DLL function.
<param1>, <param2>: optional parameters, type integer or unsigned or string.
Return value
var, return value, string type.
Remarks
In order to use External$, the calling convention for the exported function must
be _stdcall and the function must return char*. External is more powerful as it
does not have those limitations.
Example code
See External
See a full script example at How to call API Windows functions
162
External
System function.
The External function calls an external DLL. Not available in WinTask Lite.
Syntax
var=External(<DLL_name$>,<function_name$>[, <param1>[,<param2>, ...]])
Parameter
<DLL_name$>, string, name of the Windows DLL.
<function_name$>, string, name of the DLL function.
<param1>, <param2>: optional parameters, type integer or unsigned or string.
If <paramx> is an output string, its maximum length is 1023 characters. If you
need an output string longer, use External$.
Return value
var, return value, either a 32-bit integer or an address type UNSIGNED.
See also
How to call API Windows functions
External$
In WinTask\Advanced_script_examples\Windows_API_Functions_Call folder,
some scripts using External are listed.
A WinTask customer has written many scripts using Windows API functions, you
can view them at http://www.sqablogs.com/jstrazzere/WinTask
Example code
This example shows the use of the GetWindowsDirectory function to get the
name of the directory where Windows is installed.
wdir$=" "
a=External("kernel32","GetWindowsDirectoryA",wdir$,145)
msgbox(wdir$)
This more complex example gives the name of the computer
Dim compName as unsigned 'Space for the computer name string
Dim bufferLen as unsigned 'Space for the length of the string
'Initialization
compName = Allocate(255)
bufferLen = Allocate(4)
PokeInteger(bufferLen, 255, 4) 'Initialize the length of the buffer
' According to MSDN the second parameter of GetComputerName is a pointer to
a dword, not a dword.
'BOOL GetComputerName( LPTSTR lpBuffer, // computer name
' LPDWORD lpnSize // size of name buffer);
ret=External("kernel32.dll", "GetComputerNameA", compName, bufferLen)
name$=PeekString$(compName)
MsgBox(name$)
163
This more complex example gives the mouse position on the screen
'It calls the Windows API GetCursorPos
'External, structure, allocate, peekinteger, pokeinteger are used.
'When you call Windows API functions, data is often written in
'structures (memory areas). A structure can contain various data (integer,
'string, etc ...). The only way to access this data is to use the WinTask
'Peek... and Poke.. functions
'The Windows API GetCursorPos function gives the mouse cursor position.
'It requires as a parameter an address of a "point" structure.
'The structure is composed of 2 integers of 4 bytes each (LONG)
'with consecutive addresses. The first address contains the X coordinate.
'The second address contains the Y coordinate.
'Define memory address
dim addx as unsigned
dim addy as unsigned
'allocate memory starting at addx for the coordinates
'addx will contain the X coordinate
addx=allocate(8)
'addy will contain the Y coordinate
addy=addx+4
'Call the function in a loop
repeat
'address for structure addx is a parameter for GetCursorPos
a=External("user32.dll","GetCursorPos",addx)
if a <>0 then
'Read 4 bytes from memory at address addx (x position)
pos_x=PeekInteger(addx,4)
'Read 4 bytes from memory at address addy (y position)
pos_y=PeekInteger(addy,4)
'Display result
mes$="Cursor X is at : "+str$(pos_x)+"\n\Cursor Y is at : "+str$(pos_y)
msgframe(mes$,1)
pause 1
endif
until i=100
'the function loops for 100 seconds
164
ExtractBetween$
String management function.
The ExtractBetween$ function extracts a string between two strings.
Usage
Used to extract a string from a long captured string. You can capture data from a
window or a web page using the Capture wizard (menu Start/Capture wizard)
and take from the captured data only a part of it.
Syntax
var$=ExtractBetween$(<initial_string>,<start_string>,included|excluded,<end_s
tring$>,included|excluded)
Parameters
<initial_string>, string from which extraction is done
<start_string>, string where the extraction starts ; the extracted result includes
the <start_string> if the keyword Included is specified, it excludes it if the
keyword Excluded is specified. If <start_string> is an empty string ("") or is not
found, the extraction starts from the beginning of <initial_string>.
<end_string>, string where the extraction finishes ; the extracted result includes
the <end_string> if the keyword Included is specified, it excludes it if the
keyword Excluded is specified. If <end_string> is an empty string ("") or is not
found, the extraction goes to the end of <initial_string>.
Note that the extraction process is case sensitive. The extraction is done between
the first occurrence of <start_string> and the first occurrence of <end_string>.
If <start_string> and <end_string> are the same, the extracted result is the
string between the first and the second occurrence of <start_string>.
Return value
var$ returns the extracted string. If the extraction is not successfull for any
reason, var$ is empty (an empty string is "").
See also
Extract name, directory and extension from a full filename
Examples
Initialstring$="Automate any combination of tasks, whether Web or Windows
applications"
Startstring$="any"
Endstring$="Web"
a$=ExtractBetween$(initialstring$,startstring$,included,endstring$,included)
' a$ contains : "any combination of tasks, whether Web"
a$=ExtractBetween$(initialstring$,startstring$,included,endstring$,excluded)
' a$ contains : "any combination of tasks, whether"
a$=ExtractBetween$(initialstring$,startstring$,excluded,endstring$,included)
' a$ contains : " combination of tasks, whether Web"
165
Initialstring$="Automate any combination of tasks, whether Web or Windows
applications"
Startstring$=""
Endstring$="Web"
a$=ExtractBetween$(initialstring$,startstring$,included,endstring$,included)
' a$ contains : "Automate any combination of tasks, whether Web"
Initialstring$="Automate any combination of tasks, whether Web or Windows
applications"
Startstring$="any"
Endstring$="nothing"
a$=ExtractBetween$(initialstring$,startstring$,included,endstring$,included)
' a$ contains : "any combination of tasks, whether Web or Windows applications"
' Some examples at boundaries
a$=ExtractBetween$("abc def ghi £test abc
>test","£",included,"£test",included)
' a$ contains : "£test abc >test"
a$=ExtractBetween$("abcabctt","abc",excluded,"abc",included)
' a$ contains : "abc"
a$=ExtractBetween$("abcabctt","",excluded,"abc",excluded)
' a$ contains : "" (empty string)
a$=ExtractBetween$("ttabcabc uu","abc",excluded,"",excluded)
' a$ contains : "abc uu"
166
ExtractLink
Web function.
The ExtractLink function returns all the links (HREF properties) of the child
elements of the specified HTML element. Not available in WinTask Lite.
Usage
A Web table often contains elements that you need to click in order to display and
capture the details of each item in the table. As the elements displayed within the
table are dynamic, you cannot know by advance the link name for each link to
click. ExtractLink function returns each link name listed under the specified
element and then you can use the link name as the argument for Navigate
function and so navigate to the detailed page for each child element.
Syntax
ret=ExtractLink (<HTML_descriptor>, tablink$())
Parameters
<HTML_descriptor>, string, HTML descriptor of the element from which all the
links for its child elements are extracted.
tablink$(), array of strings. The array must be declared at the beginning of the
script using Dim. The link (HREF property) for each child element is returned in
this array, beginning with index 0. If the array is smaller than the range, only the
number of links which fit in the array are written.
Return value
Ret, numeric return code. When the extraction is successful, the function returns
the number of links found, otherwise use this return code for Error Handling. The
return code is -1 if the extraction could not be done.
Remarks
ExtractLink does not include any synchronization; a UsePage must be used before
to be sure that the element from which extract the links is ready.
Use Spy tool to generate the HTML descriptor.
See also
CaptureTableHTML
Example
'On a web page displaying a list of companies,
'we need to click each company name and capture some data on the detailed
page of each company
'Declare the array for the capture process
Dim contact$(10)
'Declare the array for ExtractLink function
Dim link$(100)
'Start the website
StartBrowser("IE","http://www.actuary.com/actuarial-recruiters/")
UsePage("Actuarial Recruiters Directory from Actuary.com - Actuary
167
Recruiters and Actuarial Recruiters for Actuarial Jobs in Actuarial
Directory")
'Extract all the links which are under the TABLE titled Directory of
Actuarial Recruiters
ret = ExtractLink("TABLE[CONTENT='Directory of Actuarial Recruiters']",
link$())
'display how many links have been found
msgbox(ret)
'loop to navigate to each page listed in link$() array.
i=0
repeat
Navigate(link$(i))
UsePage("Actuarial Recruiter Directory Listing of Actuarial Careers, Inc.®
from Actuary.com")
'On the new page, capture some data
ret = CaptureTableHTML("TABLE[CONTENT='Contact:']", "R3C1:R3C1",
contact$())
'display them for a check. The data can be written to an Excel file.
msgbox(contact$(0))
i=i+1
'We stop the loop at ret-1 because the last link retrieved by ExtractLink
is the link
'Click here to see how to list your company (this link is part of the
TABLE).
until i=ret-1
CloseBrowser()
168
Error codes for File management functions
The table below lists the possible error codes for the WinTask File management
functions, for the errors stopping script execution (unless #IgnoreErrors=1).
-2
-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
90
99
110
111
112
Index too big when running WinTask Excel functions (the array is
smaller than the number of cells)
ColeDispatch Exception : Error returned by Excel when an invalid
operation is attempted by WinTask Excel functions
File empty
File not found
Path not found
Too many files open
Path empty
Directory already exists
File already exists
Not enough memory
File or path not found (TaskExec could not find if it's the file or the
path which is not found)
Incorrect disk
Error in current directory
Write protected
Unable to copy files
Unable to delete files
Unable to name files
Unable to move directory
Unable to create directory
Unable to delete directory
Unable to change directory
Unable to write (or save)
Directory full
Bad sector
Error IO
Violation error
Disk full
Unable to create file
Unable to open file
Unable to readi file
Invalid file
Unable to close file
Invalid length
Unable to change attributes
Internal XML COM error
Invalid parameters
Invalid XML path
Invalid XML attribute or XML attribute not found
Index too big (return code only for the XML functions)
169
FileAttr$
File management function.
The FileAttr$ function retrieves the attributes of the specified file name.
Syntax
var$=FileAttr$(<filename>)
Parameters
<filename>: string, file name or directory name of the object whose attributes
will be retrieved. UNC names are accepted (such as "\\serv\home\dir 1\as3.txt").
Return value
var$, string, contains the attributes of the object:
N
No attribute
D
directory
R
read only
H
hidden
A
archive
S
system
Remarks
If an error occurs at execution (object not found, ...), standard error
management is used; if #IgnoreErrors=1, an empty string is returned in case of
an error.
See also
DirTree
Example
filename$="c:\program files\wintask\logs\untitled1.log"
attr$=FileAttr$(filename$)
msgbox(attr$)
170
FileCopy
File management function.
The FileCopy function copies the specified source file to the specified target file.
Usage
Do not copy files using Drag and Drop in Explorer; drag and drop automation is
not reliable as the way to display files in Explorer depends on Windows settings
for each user. Use instead FileCopy function. Wildcards (* or ? characters) are
allowed in the file names.
Syntax
FileCopy(<source_filename>,<target_filename> [,forced])
or
ret=FileCopy(<source_filename>,<target_filename> [,forced])
Parameters
<source_filename>, string, name of the file to copy.
<target_filename>, string, name of the destination file.
forced: optional keyword. It is used when a locked file must be replaced (for
instance, a file can be locked because it is in use). In that case, it will be replaced
at the next Windows restart.
Return value
Ret, numeric return code. When the copy is successful, the function returns 0,
otherwise use this return code for Error Handling.
Remarks
The function works like the DOS statement COPY. If you need a more complex
COPY, use the Dos command xcopy with ShellWait function. Here is an example:
shellwait("xcopy c:\*.* d:\save /S",1,1000)
Examples
Ret = FileCopy("c:\*.txt", "i:\text\*.txt")
FileCopy(File1$, File2$)
171
FileDate$
File management function.
The FileDate$ function returns the modification date of the specified file.
Syntax
var$=FileDate$(<filename>)
Parameters
<filename>, string, name of the file.
Return value
var$, string, modification date (format dd/mm/yyyy). If <filename> is empty or
the file does not exist, an empty string is returned. To transform the date format
in a US format (mm/dd/yyyy), see example code below.
Example
a$=FileDate$("myfile.txt")
Example code
Date$() returns a date with the format specified in Windows.
Filedate$() returns the file creation date always with format dd/mm/yyyy.
The two next functions transform from one format to the other
'************************************************************
'Conversion of file creation date to format mm/dd/yyyy
'ARGUMENT of this function is the name of the file
function american_filedate_date$(file$)
local da$, mon$, yea$, date_file$
date_file$=filedate$(file$)
da$=left$(date_file$,2)
mon$=mid$(date_file$,4,2)
yea$=right$(date_file$,4)
american_filedate_date$=mon$+"/"+da$+"/"+yea$
endfunction
'------------------------------------------------------------------'Function which gives always the current date at format dd/mm/yyyy
function european_date$()
local da$, mon$, yea$, date_file$
da$=day$()
mon$=month$()
yea$=year$()
european_date$=da$+"/"+mon$+"/"+yea$
endfunction
172
'------------------------------------------------------------------------'Example
mes$="Current date at format dd/mm/yyyy is : "+european_date$()
msgbox(mes$)
create("c:\bidon.txt")
mes$="File date created today at format mm/dd/yyyy is :
"+american_filedate_date$("c:\bidon.txt")
msgbox(mes$)
173
FileSize
File management function.
The FileSize function returns the size of the specified file.
Syntax
a=FileSize(<filename>)
Parameters
<filename>, string, name of the file.
Return value
a, numeric value, integer which gives the number of bytes. If the file name is
empty or the file does not exist, -1 is returned.
Example
a=FileSize("myfile.txt")
174
FileTime$
File management function.
The FileTime$ function returns the modification time of the specified file.
Syntax
var$=FileTime$(<filename>)
Parameters
<filename>, string, name of the file.
Return value
var$, string, modification time (format hh:mm:ss). If <filename> is empty or the
file does not exist, an empty string is returned.
Example
a$=FileTime$("myfile.txt")
175
FileVersion$
File management function.
The FileVersion$ function returns the version number of the specified file.
Syntax
var$=FileVersion$(<filename>)
Parameters
<filename>, string, name of the file.
Return value
var$, string, version number of the specified file. Using Windows interface, you
can see the version of a file by right clicking it in Explorer, select Properties and
take Version Tab - if the Version Tab is not available, FileVersion$ returns an
empty string. If <filename> is empty or the file does not exist, an empty string is
returned too.
Example
a$=FileVersion$("myfile.txt")
176
Error codes for Flow control functions
The table below lists the possible error codes for the WinTask Flow control
functions, for the errors stopping script execution (unless #IgnoreErrors=1). Only
the Shell or the Run function return such error codes.
34
35
36
37
38
39
40
DDE failure
No association
Access denied
DLL not found
Sharing violation
Empty Shell name
Empty Run name
177
Focus$
Windows management function.
The Focus$ function returns the name of the window which has the input focus.
Syntax
window_name$=Focus$()
Parameters
None.
Return value
A string which gives the window name of the window which has the input focus.
See also
Top$
Example
Shell("sysedit")
'wait until sysedit is loaded
pause 3
'display the name of the window which has the focus
windows_name$=Focus$()
Msgbox("The command Focus$ returns : "+windows_name$)
pause 1
'window commutation
usewindow(top$())
sendkeys("<Ctrl <tab>>")
pause 1
'display the name of the new window which has the focus
windows_name$=Focus$()
Msgbox("The command Focus$ returns : "+windows_name$)
pause 1
'close sysedit
CloseWindow(top$())
178
Error codes for FTP functions
The table below lists the possible error codes for the WinTask FTP functions, for
the errors stopping script execution (unless #IgnoreErrors=1).
9
80
550
553
12001
12002
12003
12004
12005
12006
12007
12008
12012
12013
12014
12015
12016
12017
12020
12021
12022
12023
12026
12028
12029
12030
12037
12038
12039
12040
12110
12111
12156
File or path does not exist
The file already exists
Requested action not taken. File unavailable (e.g., file not found, no
access)
Requested action not taken. File name not allowed
No more handles could be generated at this time
The request has timed out
An extended error was returned from the server
An internal error has occurred
The URL is invalid
The URL scheme could not be recognized or is not supported
The server name could not be resolved
The requested protocol could not be located
Internet function support is being shut down or unloaded
The request to connect and log on to an FTP server could not be
completed because the supplied user name is incorrect
The request to connect and log on to an FTP server could not be
completed because the supplied password is incorrect
The request to connect to and log on to an FTP server failed
The requested operation is invalid
The operation was canceled
The request cannot be made via a proxy
A required registry value could not be located
A required registry value was located but is an incorrect type or has
an invalid value
Direct network access cannot be made at this time
The required operation could not be completed because one or more
requests are pending
The requested item could not be located
The attempt to connect to the server failed
The connection with the server has been terminated
SSL certificate date that was received from the server is bad. The
certificate is expired
SSL certificate common name (host name field) is incorrect
The application is moving from a non-SSL to an SSL connection
because of a redirect
The application is moving from an SSL to an non-SSL connection
because of a redirect
The requested operation cannot be made on the FTP session handle
because an operation is already in progress
The FTP operation was not completed because the session was
aborted
The redirection failed because either the scheme changed (for
example, HTTP to FTP) or all attempts made to redirect failed
(default is five attempts)
179
FTPChDir
FTP function.
The FTPChDir function specifies the new FTP current folder.
Syntax
FTPChDir(<target_folder>)
or
ret=FTPChDir(<target_folder>)
Parameter
<target_folder> : string, name of the new current folder in use on the already
connected FTP server.
Return value
Ret, numeric return code. The return code is 0 when the current folder has been
successfully changed. The non zero possible error codes for FTP errros are listed
in FTP functions error codes topic. During #FTPTimeout seconds, the function
tries to change the name of the current folder and after this timeout, the
standard error management is used.
Example
FtpConnect("www.wintask.com","ftp","MX/WH05CZE3h") ' connection to the FTP
server www.wintask.com (fake credentials!)
FtpCurrentDir(var$) ' var$ contains /
FtpChDir("upgrades") ' change the current folder to /upgrades
FtpCurrentDir(var$) ' var$ contains /upgrades
FtpDisconnect() ' Terminates the FTP connection
180
FTPConnect
FTP function.
The FTPConnect function makes a connection to the specified FTP server.
Usage
Establishes the connection with the FTP server where subsequent FTP actions
have to be done.
Syntax
FTPConnect(<FTP_servername>,<username>,<encrypted_password>
[,<FTP_portnumber>])
or
ret=FTPConnect(<FTP_servername>,<username>,<encrypted_password>
[,<FTP_portnumber>])
Parameters
<FTP_servername> : string, url or IP address of the FTP server.
<username> : string, user name of the FTP server. If the connection can be
anonymous, the parameter <username> must be "Anonymous" and the next
field <paswword> is left at blank.
<encrypted_password> : string, password for the specified user name. The string
is encryped. To encrypt the password, use either the Insert/Encrypted string
menu option in WinTask Editor window or use the FTPConnect wizard (in the
Language window, press F4 if the Language window is not displayed, check Show
wizard checkbox and double click FTPConnect in the list). If there is no password,
<encrypted_password> is " ".
<FTP_portnumber> : integer, port number used by the FTP connection, optional
parameter. The default value is 21 when this parameter is not specified.
Return value
Ret, numeric return code. The return code is 0 when the connection has been
successfully established. The non zero possible error codes are listed in FTP
functions error codes topic. During #FTPTimeout seconds, the function tries to
establish the connection and after this timeout, the standard error management
is used.
Remarks
Before invoking any FTP function, a FTPConnect has to be done.
Only one FTP connection can be established.
See also
FTPDisconnect
Examples
FtpConnect("www.wintask.com","ftp","MX/WH05CZE3h") ' connection to the FTP
server www.wintask.com (fake credentials)
FtpConnect("192.135.90.5","Anonymous"," ") ' connection to the anonymous FTP
server specified by its IP address
FtpConnect("www.wintask.com","ftp","MX/WH05CZE3h",35) ' connection to the FTP
181
server www.wintask.com using port 35
182
FTPCurrentDir
FTP function.
The FTPCurrentDir function returns the FTP current folder.
Syntax
FTPCurrentDir(<current_folder>)
or
ret=FTPCurrentDir(<current_folder>)
Parameter
<current_folder> : string, returns the name of the current folder in use on the
already connected FTP server.
Return value
Ret, numeric return code. The return code is 0 when the current folder has been
successfully retrieved. The non zero possible error codes for FTP errors are listed
in FTP functions error codes topic. During #FTPTimeout seconds, the function
tries to retrieve the name of the current folder and after this timeout, the
standard error management is used.
See also
FTPChDir, FTPMkDir, FTPRmDir, FTPExistDir
Example
FtpConnect("www.wintask.com","ftp","MX/WH05CZE3h") ' connection to the FTP
server www.wintask.com (fake credentials!)
FtpCurrentDir(var$) ' var$ contains /
FtpDisconnect() ' Terminates the FTP connection
183
FTPDisconnect
FTP function.
The FTPDisconnect function terminates the connection to a FTP server.
Syntax
FTPDisconnect()
or
ret=FTPDisconnect()
Return value
Ret, numeric return code. If the FTP connection has been successfully ended, the
function returns 0, otherwise use this return code for error management.
Example
FTPDisconnect()
184
FTPExistDir
FTP function.
The FTPExistDir function checks if the specified FTP foldername exists or not.
Syntax
ret=FTPExistDir(<FTP_foldername>)
Parameter
<FTP_foldername> : string, name of the folder to check the existence.
Return value
Ret, numeric return code. The return code is 1 if <FTP_foldername> exists, 0 if
not. During #FTPTimeout seconds, the function tries to check the existence of the
specified folder. After this timeout, the script executes the next line whatever
value for #IgnoreErrors (script execution does not stop even if a FTP error is
returned).
See also
FTPCurrentDir, FTPChDir, FTPRmDir, FTPExistFile
Example
FtpConnect("www.wintask.com","ftp","MX/WH05CZE3h") ' connection to the FTP
server www.wintask.com (fake credentials!)
ret=FTPExistDir("/todelete") ' if ret returns 1, the FTP folder /todelete exists.
If ret = 1 then
FTPRmDir("/todelete") 'Delete the folder if it exists.
EndIf
FtpDisconnect() ' Terminates the FTP connection
185
FTPExistFile
FTP function.
The FTPExistFile function checks if the specified FTP filename exists or not.
Syntax
ret=FTPExistFile(<FTP_filename>)
Parameter
<FTP_filename> : string, name of the FTP file to check the existence.
Return value
Ret, numeric return code. The return code is 1 if <FTP_filename> exists, 0 if not.
During #FTPTimeout seconds, the function tries to check the existence of the
specified file. After this timeout, the script executes the next line whatever value
for #IgnoreErrors (script execution does not stop even if a FTP error is returned).
See also
FTPKill
Example
FtpConnect("www.wintask.com","ftp","MX/WH05CZE3h") ' connection to the FTP
server www.wintask.com (fake credentials!)
ret=FtpExistFile("/todelete/test.jpg") ' ret returns 1 if the file test.jpg exists in
the FTP folder /todelete
If ret = 1 then
FtpKill("/todelete/test.jpg") ' deletes the FTP file if it exists
EndIf
FtpDisconnect() ' Terminates the FTP connection
186
FTPGetFile
FTP function.
The FTPGetFile function downloads one or several files to the local PC from the
FTP server.
Syntax
FTPGetFile(<spec_files>,<local_directory_name> [,<Ascii|Binary>
[,<local_filename>]])
or
ret=FTPGetFile(<spec_files>,<local_directory_name> [,<Ascii|Binary>
[,<local_filename>]])
Parameters
<spec_files>, string, name of the file(s) to download. Wildcard characters are
permitted for downloading multiple files.
<local_directory_name>, string, name of the local directory where the
downloaded files are written. If the directory does not exist, it is created.
<Ascii|Binary>, optional keyword. The default is Binary. See Remarks section
below.
<local_filename>, optional parameter, string. If only one file is downloaded from
the FTP server, this optional parameter specifies a new name under which the
downloaded file is stored on <local_directory_name>. If this parameter is not
specified or if multiple files are downloaded (and in this last case, even if
<local_filename> is specified), the filenames on the local PC are the same as on
the FTP server. If <local_filename> includes by mistake a path, it is not taken
into account, the file will be written in <local_directory_name>.
Return value
Ret, numeric return code. The return code is 0 when the file(s) has been
successfully downloaded. The non zero possible error codes for FTP errors are
listed in FTP functions error codes topic. The non zero possible error codes due to
a file error on the PC are listed in File management functions error codes topic.
During #FTPTimeout seconds, the function tries to download the file(s) and after
this timeout, the standard error management is used.
Remarks
When files are transferred in ASCII mode, the transferred data is considered to
contain only ASCII formatted text. The party that is receiving the transferred data
is responsible for translating the format of the received text to one that is
compatible with their operating system. The most common example of how this is
applied pertains to the way Windows and UNIX handle newlines. On a Windows
computer, pressing the "enter" key inserts two characters in an ASCII text
document - a carriage return (which places the cursor at the beginning of the
line) and a line feed (which places the cursor on the line below the current one).
On UNIX systems, only a line feed is used. ASCII text formatted for use on UNIX
systems does not display properly when viewed on a Windows system and vice
versa.
Binary mode refers to transferring files as a binary stream of data. Where ASCII
mode may use special control characters to format data, binary mode transmits
the raw bytes of the file being transferred. In this way, the file is transferred in its
exact original form.
IMPORTANT: increase the value of #FTPTimeout if you download big files to
avoid a script timeout during the download.
187
See also
FTPPutFile
Examples
FtpConnect("www.wintask.com","ftp","MX/WH05CZE3h") ' connection to the FTP
server www.wintask.com (fake credentials!)
FtpGetFile("/upgrades/todelete/*.jpg","C:\test") ' downloads all the *.jpg files
stored in upgrades/todelete folder to the local directory c:\test.
FtpDisconnect() ' Terminates the FTP connection
FtpConnect("www.wintask.com","ftp","MX/WH05CZE3h") ' connection to the FTP
server www.wintask.com (fake credentials!)
FtpGetFile("/upgrades/todelete/myimage.jpg","C:\test",,"c:\test\newimage.jpg
") ' downloads myimage.jpg stored in upgrades/todelete folder to the local
directory c:\test and saves it under the name newimage.jpg.
FtpDisconnect() ' Terminates the FTP connection
FtpConnect("www.wintask.com","ftp","MX/WH05CZE3h") ' connection to the FTP
server www.wintask.com (fake credentials!)
FtpGetFile("/upgrades/todelete/myimage.jpg","C:\test","ASCII","c:\test\newim
age.jpg") ' downloads myimage.jpg stored in upgrades/todelete folder to the
local directory c:\test and saves it under the name newimage.jpg. The data are
tansferred using ASCII mode.
FtpDisconnect() ' Terminates the FTP connection
188
FTPKill
FTP function.
The FTPKill function deletes one or several files from the FTP server.
Syntax
FTPKill(<filename>)
or
ret=FTPKill(<filename>)
Parameter
<filename> : string, name of the file/files to delete. Multiple files are specified
using wildcards (myfile.*, my???.e*, ...).
Return value
Ret, numeric return code. The return code is 0 when the file(s) have been
successfully deleted. The non zero possible error codes due to an FTP error are
listed in FTP functions error codes topic. During #FTPTimeout seconds, the
function tries to delete the file(s), and after this timeout, the standard error
management is used.
Remarks
If <filename> does not exist, FTPKill reports an error and script execution stops
(if #IgnoreErrors is at its default value : #IgnoreErrors=0). So use FTPExistFile
function to be sure that the file exists before deleting it.
See also
FTPRmDir
FTPExistFile
Example
FtpConnect("www.wintask.com","ftp","MX/WH05CZE3h") ' connection to the FTP
server www.wintask.com (fake credentials!)
FtpKill("/upgrades/todelete/*.jpg") ' deletes all the files with the jpg extension
from the folder /upgrades/todelete
FtpCurrentDir(var$) ' var$ contains /upgrades/todelete
FtpDisconnect() ' Terminates the FTP connection
189
FTPMkDir
FTP function.
The FTPMkDir function creates a folder on the FTP server.
Syntax
FTPMkDir(<FTP_foldername>)
or
ret=FTPMkDir(<FTP_foldername>)
Parameter
<FTP_foldername> : string, name of the new folder to create on the already
connected FTP server.
Return value
Ret, numeric return code. The return code is 0 when the new folder has been
successfully created. The non zero possible error codes for FTP errors are listed in
FTP functions error codes topic. During #FTPTimeout seconds, the function tries
to create the new folder and after this timeout, the standard error management is
used.
See also
FTPCurrentDir, FTPChDir, FTPRmDir, FTPExistDir
Example
FtpConnect("www.wintask.com","ftp","MX/WH05CZE3h") ' connection to the FTP
server www.wintask.com (fake credentials!)
FtpMkDir("/upgrades/todelete") ' creates the subfolder todelete under the
upgrades folder
FtpChDir("/upgrades/todelete") ' change the current folder to /upgrades/todelete
FtpCurrentDir(var$) ' var$ contains /upgrades/todelete
FtpDisconnect() ' Terminates the FTP connection
190
FTPName
FTP function.
The FTPName function renames one or several files in the FTP server.
Syntax
FTPName(<old_filename>,<new_filename>)
or
ret=FTPName(<old_filename>,<new_filename>)
Parameters
<old_filename>, string, name of the file(s) to be renamed. Wildcard characters
are permitted.
<new_filename>, string, new name of the file(s). Wildcard characters are
permitted.
Return value
Ret, numeric return code. The return code is 0 when the file(s) has been
successfully renamed. The non zero possible error codes for FTP errors are listed
in FTP functions error codes topic. The non zero possible error codes due to a file
error on the PC (file not found for example) are listed in File management
functions error codes topic. During #FTPTimeout seconds, the function tries to
rename the file(s) and after this timeout, the standard error management is
used.
Remarks
FTPName can be used to move a file within a folder, for example
Name("\todelete\file1.txt","\todelete\file2.txt").
Example
FtpConnect("www.wintask.com","ftp","MX/WH05CZE3h") ' connection to the FTP
server www.wintask.com (fake credentials!)
FtpName("/upgrades/todelete/*.jpg","/upgrades/images/*.gif") ' renames all the
*.jpg files stored in upgrades/todelete folder.
FtpDisconnect() ' Terminates the FTP connection
191
FTPPutFile
FTP function.
The FTPPutFile function uploads one or several files from the local PC to a FTP
folder.
Syntax
FTPPutFile(<spec_files>,<FTP_foldername> [,<Ascii|Binary>
[,<FTP_filename>]])
or
ret=FTPPutFile(<spec_files>,<FTP_foldername> [,<Ascii|Binary>
[,<FTP_filename>]])
Parameters
<spec_files>, string, name of the file(s) to upload. Wildcard characters are
permitted for uploading multiple files.
<FTP_foldername>, string, name of the FTP folder where the files have to be
uploaded. If the folder does not exist, it is created. If the files already exist on
the FTP folder, they are replaced.
<Ascii|Binary>, optional keyword. The default is Binary. See Remarks section
below.
<FTP_filename>, optional parameter, string. Used only if just one file is
uploaded. In that case, <FTP_filename> specifies the name under which the file
is written on the FTP server. If several files are uploaded, the file names on FTP
server are the ones on the local machine. If several files are uploaded and this
parameter is given, this parameter is not used. If <FTP_filename> includes by
mistake a path, it is not taken into account, the file will be uploaded in
<FTP_foldername>.
Return value
Ret, numeric return code. The return code is 0 when the file(s) has been
successfully uploaded. The non zero possible error codes for FTP errors are listed
in FTP functions error codes topic. The non zero possible error codes due to a file
error on the PC are listed in File management functions error codes topic. During
#FTPTimeout seconds, the function tries to upload the file(s) and after this
timeout, the standard error management is used.
Remarks
When files are transferred in ASCII mode, the transferred data is considered to
contain only ASCII formatted text. The party that is receiving the transferred data
is responsible for translating the format of the received text to one that is
compatible with their operating system. The most common example of how this is
applied pertains to the way Windows and UNIX handle newlines. On a Windows
computer, pressing the "enter" key inserts two characters in an ASCII text
document - a carriage return (which places the cursor at the beginning of the
line) and a line feed (which places the cursor on the line below the current one).
On UNIX systems, only a line feed is used. ASCII text formatted for use on UNIX
systems does not display properly when viewed on a Windows system and vice
versa.
Binary mode refers to transferring files as a binary stream of data. Where ASCII
mode may use special control characters to format data, binary mode transmits
the raw bytes of the file being transferred. In this way, the file is transferred in its
exact original form.
IMPORTANT: increase the value of #FTPTimeout if you upload big files to avoid
192
a script timeout during the download.
See also
FTPGetFile
Examples
FtpConnect("www.wintask.com","ftp","MX/WH05CZE3h") ' connection to the FTP
server www.wintask.com (fake credentials!)
FtpPutFile("c:\test\*.jpg","/upgrades/todelete") ' uploads all the *.jpg files
stored in local directory c:\test to the FTP folder /upgrades/todelete
FtpDisconnect() ' Terminates the FTP connection
FtpConnect("www.wintask.com","ftp","MX/WH05CZE3h") ' connection to the FTP
server www.wintask.com (fake credentials!)
FtpPutFile("C:\test\myimage.jpg","/upgrades/todelete","newimage.jpg") '
uploads myimage.jpg stored in local directory c:\test to FTP folder
/upgrades/todelete and saves it under the name newimage.jpg.
FtpDisconnect() ' Terminates the FTP connection
FtpConnect("www.wintask.com","ftp","MX/WH05CZE3h") ' connection to the FTP
server www.wintask.com (fake credentials!)
FtpPutFile("C:\test\myimage.jpg","/upgrades/todelete","ASCII","newimage.jpg"
) ' uploads myimage.jpg stored in local directory c:\test to FTP folder
/upgrades/todelete and saves it under the name newimage.jpg. The data are
tansferred using ASCII mode.
FtpDisconnect() ' Terminates the FTP connection
193
FTPRmDir
FTP function.
The FTPRmDir function deletes a folder and its contents on the FTP server.
WARNING : this function deletes the specified folder without prompting
for a confirmation. It deletes too all the sub-folders if any, and all the
files stored in this folder.
Syntax
FTPRmDir(<FTP_foldername>)
or
ret=FTPRmDir(<FTP_foldername>)
Parameter
<FTP_foldername> : string, name of the folder to delete (and its contents) on the
already connected FTP server.
Return value
Ret, numeric return code. The return code is 0 when the folder has been
successfully deleted. The non zero possible error codes for FTP errros are listed in
FTP functions error codes topic. During #FTPTimeout seconds, the function tries
to delete the folder and its contents, and after this timeout, the standard error
management is used.
Remarks
If <FTP_foldername> does not exist, FTPRmDir reports an error and script
execution stops (if #IgnoreErrors is at its default value : #IgnoreErrors=0). So
use FTPExistDir function to be sure that the folder exists before deleting it.
See also
FTPCurrentDir, FTPChDir, FTPMkDir, FTPExistDir, FTPKill
Example
FtpConnect("www.wintask.com","ftp","MX/WH05CZE3h") ' connection to the FTP
server www.wintask.com (fake credentials!)
FtpMkDir("/upgrades/todelete") ' creates the subfolder todelete under the
upgrades folder
FtpChDir("/upgrades/todelete") ' change the current folder to /upgrades/todelete
FtpCurrentDir(var$) ' var$ contains /upgrades/todelete
FtpRmDir(var$) ' deletes the folder specified in var$ (so "/upgrades/todelete")
FtpCurrentDir(var$) ' var$ contains /upgrades
FtpDisconnect() ' Terminates the FTP connection
194
#FTPTimeout
System variable - FTP function.
The #FTPTimeout system variable specifies the number of seconds which
WinTask should wait before reporting a runtime error when it tries to execute a
FTP function.
Usage
Mainly used to increase the delay before an execution error is reported. For
example, if a big file is downloaded from the FTP server to the local machine, the
default timeout of 30 secs will stop the transfer. So before invoking the
FTPGetFile function, add a line #FTPTimeout=120 if the file downloads in less
than 120 seconds.
Syntax
#FTPTimeout = n
Remarks
When the n seconds have elapsed, if a FTP function execution is not finished,
error management is launched. The default behavior (#IgnoreErrors=0) is that
an error message is displayed and the script execution stops.
The default value for #FTPTimeout is 30 seconds.
If this variable is set to 0, WinTask waits forever.
See also
#IgnoreErrors
Example
#FTPTimeout = 5
Example code
This script downloads wintaskdemo.exe from www.wintask.com FTP server (the
password is not correct on purpose!).
#IgnoreErrors=1
' Error management is now active in the script
#FTPTimeout=120
' Maximum wait is 10 seconds
FtpConnect(("www.wintask.com","ftp","PMJN1563hSWHXFj/CD")
' Connect to the FTP server
ret=FTPGetFile("c:\test","/wintaskdemo.exe")
' Download wintaskdemo.exe from the FTP server and save it under c:\test
' The return code is tested
if ret=0 then
msgbox("Download done")
195
else
msgbox("Increase the timeout")
endif
#IgnoreErrors=0
' Error management is turned off
FtpDisconnect() ' Terminates the FTP connection
196
Function...ExitFunction...EndFunction
Program flow management function.
The Function...EndFunction structure defines a function in order to make
scripts more modular.
Syntax
Function <function_name>([<param1>[,<param2>]....])
[Local <variable_name>]
<statements>
...
<function_name>=<value>
...
EndFunction
Parameters
<function_name>, name of the function. The maximum length of the name is 32
characters.
<param1>, <param2> optional parameters.
The keyword LOCAL allows the declaration of local variables.
ExitFunction is used to quit the function within the function.
Remarks
NOTE : all functions must be declared at the beginning of the script, just after the
DIM statements (if any are needed).
If the function returns a string, its name must end with a $, see the example
below.
Parameters cannot be arrays. See below an example code demonstrating how to
pass arrays in a function using a global variable.
See also
Sub
Program Structure
Global and local variables
Example code
Function value_absolute_dif(int1, int2)
if int1 > int2 then
value_absolute_dif = int1 - int2
else
if int1 = int2 then
value_absolute_dif = 0
else
value_absolute_dif = int2 - int1
endif
endif
Endfunction
res = value_absolute_dif(my_number,123)
With a function returning a string:
197
Function concat$(string1$,string2$)
local result$
result$=string1$+string2$
concat$=result$
EndFunction
'Call example
msgbox(concat$("Hello"," WinTask"))
Example code - use of an array
Dim buffer$(100)
dim k1$(100)
dim k2$(100)
function insert_values(nb_row)
i=0
repeat
setclipboard(buffer$(i))
i=i+1
until i=nb_row
endfunction
'Call the function, but first fill the global variable buffer$ by the data
you want.
buffer$()=k1$()
insert_values(10)
buffer$()=k2$()
insert_values(30)
198
GetClipboard$
Clipboard management function.
The GetClipboard$ function returns the text contained in the Windows
Clipboard.
Usage
The main use is to retrieve data from one application and then send them to
another application using SendKeys.
Syntax
a$=GetClipboard$()
Parameters
None.
Return value
A string which holds the text contained in the Clipboard. If the Clipboard is empty
or contains non-textual data, an empty string is returned. The returned string
does not include any information about the text type, font size or attributes.
See also
SetClipboard
Example
a$=GetClipboard$()
199
GetCpuLoad
System function.
The GetCpuLoad function returns the CPU load percentage (from 0 to 100). Not
available in WinTask Lite.
Syntax
Num=GetCpuLoad()
Parameters
None.
Return value
Num, integer, CPU load percentage.
Num= -3 if the statistical function has failed.
Num= -4 if WinTaskAdmin Service is not started.
Example
a=GetCpuLoad()
200
GetFocusWindowHandle
Windows management function.
The GetFocusWindowHandle function returns the handle of the window which
has focus; this handle can then be used in Windows API functions or with
UseWindowHandle (gives title independence).
Syntax
handle=GetFocusWindowHandle()
Parameters
None
Return value
handle : integer, handle of the window which has the focus.
See also
GetTopWindowHandle, UseWindowHandle, GetWindowName$
Example
shell("wordpad.exe")
pause 2
a=GetFocusWindowhandle()
msgbox(a)
UseWindowHandle(a)
SendKeys("Hello")
a returns WordPad window's handle and this handle can be used in
UseWindowHandle and then SendKeys sends the specifed keys to that handled
window.
201
GetFrameSource$
Web function.
The GetFrameSource$ function returns the source code of the specified frame
in the current Web page. Not available in WinTask Lite.
Usage
It gives the same results as the View/Source option in the context menu when
you right click somewhere in the frame. To be sure that the page is loaded before
invoking the function, you can include a UsePage line before.
Syntax
var$=GetFrameSource$(<src_framename>)
Parameters
<src_framename>, string, SRC property of the frame as seen in View/Source of
the main page
Return value
var$, string, long string with all the source code of the specified frame. If the
source code could not be returned for any reason, the string is empty (an empty
string is "").
Remarks
Before invoking this function, a UsePage call must specify on which page the
frame has to be found. If you want to be sure that the frame is loaded before
calling GetFrameSource$, you can force this synchronization by adding a UsePage
line if the previous UsePage is a couple of lines above the GetFrameSource$ call.
Example
UsePage("WinTask Frames")
'The page includes a frame which loads the frame7.htm file
a$=getframesource$("frame7.htm")
msgbox(a$)
202
GetHTMLEditText
Capture function, Web function.
The GetHTMLEditText function captures the content of an HTML Edit field within
a Web form.
Usage
Used for retrieving data displayed in a field of a Web form. To know the HTML
descriptor of the field where the data has to be captured, use Recording mode
and record some typing in this field.
Syntax
ret=GetHTMLEditText(<html_descriptor>,var$)
Parameters
<html_descriptor>, unique identifier for the HTML element INPUT field from
which the text has to be captured. See HTML descriptor for HTML tags
identification. Use Recording mode to generate automatically this HTML descriptor
by just typing some data in the field.
<var$>, string, captured text.
Return value
Ret, numeric return code. When successful, the function returns 0, otherwise use
this return code for Error Handling.
Remarks
GetHTMLEditText does not include any synchronization; a UsePage must be used
before to be sure that the content of the field to capture is already displayed.
Examples
StartBrowser("IE", "www.yahoo.com")
UsePage("Yahoo!")
WriteHTML("INPUT TEXT[NAME= 'p']", "WinTask")
pause 2
UsePage("Yahoo!")
ret = GetHTMLEditText("INPUT TEXT[NAME= 'p']",var$)
msgbox(var$) 'var$ contains the data typed in the Search field of yahoo
page, so var$ contains WinTask
CloseBrowser()
'A second example on the demonstration pages of wintask web site, note the
capture of the content of a TextArea field
StartBrowser("IE", "www.wintask.com/demos")
UsePage("WinTask Demonstration Pages")
ClickHTMLElement("A[INNERTEXT= 'Form']")
UsePage("Form")
WriteHTML("TEXTAREA[NAME= 'message']", "bla bla bli")
SelectHTMLItem("SELECT[NAME= 'subject']", "Web site")
ret=gethtmledittext("TEXTAREA[NAME= 'message']",var$)
msgbox(var$)
WriteHTML("INPUT TEXT[NAME= 'name']", "Test")
WriteHTML("INPUT TEXT[NAME= 'email']", "[email protected]")
ret=gethtmledittext("INPUT TEXT[NAME= 'email']",var$)
203
msgbox(var$)
ClickHTMLElement("INPUT RESET[VALUE= 'Clear']")
CloseBrowser()
204
GetMemUsage
System function.
The GetMemUsage function returns the percentage memory use (from 0 to
100). Not available in WinTask Lite.
Syntax
Num=GetMemUsage()
Parameters
None.
Return value
Num, integer, percentage memory used.
Num= -3 if the statistical function has failed.
Example
a=GetMemUsage()
205
GetPageSource$
Web function.
The GetPageSource$ function returns the source code of the current Web page.
Not available in WinTask Lite.
Usage
It gives the same results as the View/Source option in Internet Explorer. To be
sure that the page is loaded before invoking the function, check that a UsePage
has been done before.
Syntax
var$=GetPageSource$()
Return value
var$, string, long string with all the source code of the HTML Web page. If the
source code could not be returned for any reason, the string is empty (an empty
string is "").
Remarks
Before invoking this function, you must ensure that the page is fully loaded. You
can for example force such a synchronization by using UsePage function.
GetPageSource$ calls directly the Innertext property of Internet Explorer. Due to
the way notepad displays this same information, there can be some differences
between what you see in notepad using View/Source option and the result of
GetPageSource$ function.
See also
GetFrameSource$
Example
On WinTask Web site, we display the source code of the main page:
StartBrowser("IE","www.wintask.com")
UsePage("Macro and Data Extraction with WinTask - the automation software
for Windows and internet")
a$=GetPageSource$()
CloseBrowser()
msgbox(a$)
206
GetProcessCpuLoad
System function.
The GetProcessCpuLoad function returns the percentage CPU used by the
specified process. Not available in WinTask Lite.
Syntax
Num=GetProcessCpuLoad(<process_name>[,<instance_number>])
Parameters
<process_name>, string, name of the process to measure.
<instance_number>, optional instance number; to be used if several instances of
the same process are running.
Return value
Num, integer, CPU percentage used by the process <process_name>.
Num= -3 if the statistical function has failed (for example because the specified
process does not exist)
Num= -4 if WinTaskAdmin Service is not started (under Vista).
Example
a=GetProcessCpuLoad("TASKEXEC.EXE")
207
GetProcessList
System function.
The GetProcessList function returns the list of active processes and their
attributes. Not available in WinTask Lite.
Syntax
GetProcessList(<tab_name$>,<tab_PID>,<tab_CPU>,<tab_Mem>,<sort>)
or
Ret=GetProcessList(<tab_name$>,<tab_PID>,<tab_CPU>,<tab_Mem>,<sort>)
Parameters
<tab_name$>: alphanumeric array, list of the active processes and attributes
(the list displayed by the Process Tab of Task manager).
<tab_PID>: integer array, list of the PIDs for each process.
<tab_CPU>: integer array ; contains the cumulative CPU used (in seconds) by
each individual active process.
<tab_Mem>: integer array ; contains the memory (in Kbytes) used by each
individual process.
<sort>: integer which indicates how the result array should be sorted :
0
result array not sorted
1
result array sorted by process name
2
result array sorted by PID
3
result array sorted by CPU usage (from the highest to the lowest)
4
result array sorted by memory usage (from the highest to the
lowest)
Return value
Ret, integer, return code which gives the number of processes found. If any of
the arrays is too small, ret contains -1, but the arrays will still contain the first n
processes found (if #IgnoreErrors=1). If Ret=-1 and if #IgnoreErrors=0, the
script is stopped.
Example code
dim name$(210)
dim pid(210)
dim cputime(210)
dim memuse(210)
proc$="process.txt"
create(proc$)
p=GetProcessList(name$(),pid(),cputime(),memuse(),1)
write(proc$,str$(p),CRLF)
i=0
repeat
'The list is written to the file
write(proc$,name$(i)+","+str$(pid(i))+","+str$(cputime(i))+","+str$(memuse(i
)),CRLF)
i=i+1
208
until i=p
pause 1
'The list is displayed
shell("notepad "+proc$)
209
GetReadPos
File management function.
The GetReadPos function returns the value of the read pointer for the specified
file.
Syntax
GetReadPos(<filename>)
or
var=GetReadPos(<filename>)
Parameters
<filename>, string, name of the file which is being read.
Return value
var, numeric, value for the read pointer, which gives the position for the next
read. GetReadPos allows you to know this value (in bytes from the beginning of
the file). The value of this pointer is 0 when the file is read for the first time, then
WinTask increments it automatically. If <filename> is not currently being read,
GetReadPos returns 0. If <filename> is empty or the file does not exist, an error
message is displayed and all the scripts are stopped.
It is sometimes interesting to know the value of this pointer in order to force the
next Read at a specific position.
Examples
var = GetReadPos("\\Server\C\my directory\my file.txt")
For a full example, see the Read statement.
210
GetTopWindowHandle
Windows management function.
The GetTopWindowHandle function returns the handle of the window which is
on top; this handle can then be used in Windows API functions or with
UseWindowHandle (gives title independence).
Syntax
handle=GetTopWindowHandle()
Parameters
None
Return value
handle : integer, handle of the window which is on top.
See also
GetFocusWindowHandle, UseWindowHandle, GetWindowName$
Examples
shell("wordpad.exe")
pause 2
a=GetTopWindowhandle()
msgbox(a)
a returns WordPad top window's handle.
211
GetWindowHandle
Windows management function.
The GetWindowHandle function returns the handle of specified window ; this
handle can then be used in Windows API functions or with UseWindowHandle
(gives title independence).
Syntax
handle=GetWindowHandle(<window_name> [,<instance>])
Parameters
<window_name>, string. window name of the window we want to find the
handle. You can use the SPY tool to manually determine the caption of a window
or use Recording mode.
<instance>, optional parameter, instance number of the window we want to find
the handle.
Return value
handle : integer, handle of the window <window_name>. If window
<window_name> is not found, there are no errors but handle is set to 0. If
#UseExact is at 0 (its default value), a window with nearly the same name will
return the handle of that window.
See also
#UseExact, UseWindowHandle, GetWindowName$
Examples
shell("wordpad.exe")
a=GetWindowhandle("WORDPAD.EXE|RichEdit20A|Document - WordPad|1")
msgbox(a)
a returns WordPad window's handle.
shell("wordpad.exe")
a=GetWindowhandle("WORDPAD.EXE|RichEdit20A|Doc - WordPad|1")
msgbox(a)
a returns WordPad window's handle as a window name with nearly the same
name is found (Document instead of Doc).
#UseExact=1
shell("wordpad.exe")
a=GetWindowhandle("WORDPAD.EXE|RichEdit20A|Doc - WordPad|1")
msgbox(a)
a returns 0 as the WordPad window contains Document whereas
GetWindowhandle's argument contains Doc and system variable #UseExact is set
to 1.
Example code
The script below installs Acrobat ; two functions are defined for testing if the
button we want to click is ready for being clicked ; GetWindowHandle and
212
UseWindowHandle are used (instead of UseWindow) as window names varies
from one installation to another.
'Function waits for object objet$ to have focus for Tmax seconds
function wait_focus(objet$,Tmax)
local i, exitr, a$
i=0
exitr=0
repeat
a$=focus$()
if instr(a$,objet$)=0 then
pause 1
i=i+1
if i > Tmax then
msgbox("wait too long for "+objet$)
stop
endif
else
exitr=1
endif
until exitr=1
endfunction
'-------------------------------------------'Function waits for object objet$ to be on top for Tmax seconds
function wait_top(objet$,Tmax)
local i, exitr, a$
i=0
exitr=0
repeat
a$=top$()
if instr(a$,objet$)=0 then
pause 1
i=i+1
if i > Tmax then
msgbox("wait too long for "+objet$)
stop
endif
else
exitr=1
endif
until exitr=1
endfunction
'----------------------------------------------#ActionTimeout=10
213
'Start Acrobat setup from CDROM
Shell("f:\Acrobat4\Setup.exe",1)
'License window
wait_focus("License",10)
a=getwindowhandle(top$())
usewindowhandle(a)
Click(Button,"&Accept")
'Installation choice
wait_focus("Button|Typical",10)
a=getwindowhandle(top$())
usewindowhandle(a)
Click(Button,"&Next >")
'User information window
wait_top("User information",10)
a=getwindowhandle(top$())
usewindowhandle(a)
Click(Button,"&Next >")
'Confirmation window
wait_focus("Button|&Yes",10)
a=getwindowhandle(top$())
usewindowhandle(a)
Click(Button,"&Yes")
'Last validation
wait_focus("Button|&Next",10)
a=getwindowhandle(top$())
usewindowhandle(a)
Click(Button,"&Next >")
214
GetWindowName$
Windows management function.
The GetWindowName$ function returns the name of the window specified by its
handle.
Syntax
var$=GetWindowName$(<handle>)
Parameters
<handle>, numeric. Handle of the window we are looking for its name.
Return value
var$ : string, window name, including its instance, of the window specified by its
<handle>. If no window is found, an empty string is returned.
See also
GetWindowHandle
Examples
shell("wordpad.exe")
a=GetWindowhandle("WORDPAD.EXE|RichEdit20A|document - WordPad|1")
ret=UseWindowhandle(a)
msgbox(ret)
a$=getwindowname$(a)
msgbox(a$)
a$ contains the window name of WordPad window.
215
GetWindowsList
System function.
The GetWindowsList function returns the list of parent window names present
on Windows desktop. Not available in WinTask Lite.
Syntax
GetWindowsList(<tab_namewin$>,<tab_instanc>,<tab_handl>,<tab_flag$>)
or
Ret=GetWindowsList(<tab_namewin$>,<tab_instanc>,<tab_handl>,<tab_flag$
>)
Parameters
<tab_namewin$>, alphanumeric array; it lists the names of the parent windows
present on the desktop. These names use the syntax as described in the
UseWindow statement.
<tab_instanc>: integer array; lists the instance numbers of each parent window
present on the desktop.
<tab_handl>: integer array; lists the handle of each parent window present on
the desktop.
<tab_flag$>: alphanumeric array; two characters containing the status of the
application or of the window. The first character is 1 if the status is " running ", 0
if not. The second character is 1 if the application is enabled (it can receive
actions), 0 if disabled.
Return value
Ret, integer, return code which gives the number of found windows. If any of the
arrays is too small, ret contains -1, but the arrays will still contain the first n
windows found (if #IgnoreErrors=1). If Ret=-1 and if #IgnoreErrors=0, the script
is stopped.
Example code
dim namewin$(210)
dim numinst(210)
dim handlewin(210)
dim winflag$(210)
proc$="namewin.txt"
create(proc$)
p=GetWindowsList(namewin$(),numinst(),handlewin(),winflag$())
write(proc$,str$(p),CRLF)
i=0
repeat
'The list is written to the file
write(proc$,namewin$(i)+","+str$(numinst(i))+","+str$(handlewin(i)) +","
+winflag$(i),CRLF)
i=i+1
until i=p
216
pause 1
' the list is displayed
shell("notepad "+proc$)
See also the script example, Close all Internet Explorer windows.
217
GetXMLAttribute
File management function.
The GetXMLAttribute function retrieves the content of an attribute in the
specified XML file. Not available in WinTask Lite
Syntax
GetXMLAttribute(<filename>,<xml_path>,<attribute_name>,<result$>)
or
ret=GetXMLAttribute(<filename>,<xml_path>,<attribute_name>,<result$>)
Parameters
<filename>, string, name of the XML file where to add/modify the attribute.
<XML_path>, string, list of node descriptors separated by the \ character to go
where the attribute is. The string is not case-sensitive.The structure of such a
path is:
tagname[attributename1='value']
The tagnames are strings without double quotes, they cannot contain spaces or
reserved characters.
The attribute names are strings without double quotes, OR it can be the reserved
keyword <text> or the reserved keyword <index>. <text> is used to specify the
node inner text, <index> is used to specify the node index (first one starts at 1)
when more nodes with the same tag and attributes exist within the same parent.
Several attributes can be listed with the syntax
tagname[attributename1='value1', attributename2='value2']
Examples:
If the XML file contains:
<bookstore>
<book genre="autobiography" publicationdate="1981" ISBN="1-861003-110">
the <XML_path> can be "bookstore\book[genre='autobiography']" or
"bookstore\book[publicationdate='1981']" or
"bookstore\book[publicationdate='1981',genre='autobiography']"
<attribute_name>, string, name of the attribute (surrounded by double quotes as
it is a string), OR keyword <text> surrounded by double quotes to retrieve the
content of the text between the starting tag and the ending tag of the tag
specified in <xml_path>.
<result$>, string, retrieved content for the specified attribute
Return value
Ret, numeric return code. When the content of the specified attribute is
successfully retrieved from the XML file, the function returns 0, otherwise use this
return code for Error Handling. The possible error codes are:
27
The XML file cannot be open
90
Internal error (COM error when invoking XML COM)
99
Invalid parameters
110
Invalid XML path
111
Invalid XML attribute or attribute not found
See also
AppendXMLNode
SetXMLAttribute
218
EnumXMLAttributes
EnumXMLChildren
Examples
This code generates a XML file and GetXMLAttribute is used to retrieve the
content of 2 attribute names just created.
file$ = "c:\program files\wintask\scripts\test.xml"
create(file$)
appendxmlnode(file$, "", "root")
appendxmlnode(file$, "root", "book")
appendxmlnode(file$, "root", "book")
appendxmlnode(file$, "root\book", "Mark_Twain")
appendxmlnode(file$, "root\book", "Mark_Twain")
appendxmlnode(file$, "root\book[<index>=2]", "Portugalia")
setxmlattribute(file$, "root\book\Mark_Twain", "<text>", "Misc
description")
setxmlattribute(file$, "root\book\Mark_Twain[<index>=2]", "year", "1987")
setxmlattribute(file$, "root\book\Mark_Twain[year='1987']", "<text>",
"Another misc description")
getxmlattribute(file$, "root\book\Mark_Twain[<index>=2]", "year", val$)
msgbox(val$) 'val$ contains 1987
getxmlattribute(file$, "root\book\Mark_Twain[year='1987']", "<text>", val$)
msgbox(val$) 'val$ contains Another misc description
With this XML file:
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
the script below returns the text titles for the books in category WEB:
dim children$(100)
file$ = "c:\program files\wintask\scripts\sample.xml"
ret = enumxmlchildren(file$, "bookstore", children$())
i=0
while i < ret
219
getxmlattribute(file$, children$(i), "category", val$)
if val$ = "WEB" then
getxmlattribute(file$, children$(i)+"\title[lang='en']", "<text>", val$)
msgbox(val$)
endif
i = i+1
wend
220
Goto or Go to
Program flow management function.
The Goto function causes the execution of the script to jump to another line.
Usage
Even if Goto is an easy way to make a jump to another section of the script, it
makes scripts unreadable and difficult to debug. Use instead Sub to call a subprogram which executes the section you want.
Syntax
Goto <label>
Go to <label>
Parameters
<label>, the script continues execution directly after this label. In the GoTo
statement, <label> is not followed by a semicolon (:) but the definition of this
label in the program must be followed by : (no blank).
The compiler detects errors such as <label> not defined, or multiple definitions
of the same <label>.
Example code
next:
ret=msgbox("Would you like to continue ?",4,"EXAMPLE")
if ret=7 then
stop
endif
'the loop is repeated until you click " No " in the message box
goto next
'How to replace the goto by a better structure using Sub
Sub continue()
ret=msgbox("Would you like to continue ?",4,"EXAMPLE")
EndSub
ret=0
While ret<>7
continue()
WEnd
221
HardCopy
Capture function.
The HardCopy function takes a screenshot of the entire screen or of the active
window and saves is as a .BMP or .JPG file. Not available in WinTask Lite.
Usage
HardCopy function can be used for debugging purposes : you can capture the
entire screen at some points during execution of the script. Use HardCopy wizard
to generate the function easily (to access the wizard, press F4 to display the
Language window and in Capture Instructions chapter, double click the HardCopy
function). See the script example below to take a screenshot if an execution error
happens
Syntax
HardCopy(<filename>,<screenshot_type>[,<option>])
or
ret=HardCopy(<filename>,<screenshot_type>[,<option>])
Parameters
<filename>, name of the file (extension .BMP or .JPG) into which the captured
image is saved. If no extension is specified, .BMP is added.
<screenshot_type> : integer, 1 to capture the entire screen, 2 to capture only
the active window.
<option>, optional integer, specifying some options. <option> cannot be a
variable. It is the sum of those values:
0
The file is generated without any option
1
A time stamp is added to the filename ; the timestamp format is
hhmmss (for example, if filename is "screenshot.jpg" and the
hardcopy is done at 3:45:34 pm, the hardcopy function will generate
this filename : "screenshot154534.jpg")
2
The filename is incremented at each execution
4
The image is captured in black and white
So for example, if <option> is at 3, the filename will include a timestamp and will
increment when the capture is done.
Return value
Ret, numeric return code. When successful, the function returns 0, otherwise use
this return code for error management.
Example
HardCopy("C:\program files\wintask\scripts\screenshot.jpg",1,2) 'captures the
entire screen and increments at each execution the filename (screenshot1.jpg,
screenshot2.jpg, ... will be created).
Example code
'Definition of the proc to call if an error is detected.
Sub Process_Error()
local buffer$
222
'If within this proc, an error occurs too, it generates an infinite loop as
'the call to the error proce causes an error. To avoid that, we disable
OnAction Error within this proc.
disable(Error)
'Take a screenshot of the desktop
ret=Hardcopy("C:\program files\wintask\scripts\error.jpg",1,1)
'Here a part for writing in a txt file where we were in the script, the
error code, the error message when the error occurred.
buffer$="Error in : "+#ErrorScript$
write("C:\program files\wintask\scripts\error.txt",buffer$,crlf)
buffer$="Error line : "+str$(#LastErrorLine)
write("C:\program files\wintask\scripts\error.txt",buffer$,crlf)
buffer$="Error Code : "+str$(#Errorcode)
write("C:\program files\wintask\scripts\error.txt",buffer$,crlf)
buffer$="Error Function : "+#ErrorFunction$
write("C:\program files\wintask\scripts\error.txt",buffer$,crlf)
buffer$="Error message : "+#ErrorMsg$
write("C:\program files\wintask\scripts\error.txt",buffer$,crlf)
'Add here other lines for what to do in case of an error.
'......
Endsub
OnAction error
dosub Process_Error
endaction
#Actiontimeout=15
'The window is not found, so OnAction error triggers.
UseWindow("toto")
223
#HideIcon
System variable - System.
The #HideIcon system variable specifies if an icon is present or not in the
taskbar during execution of scripts.
Syntax
#HideIcon = 0
or
#HideIcon = 1
Remarks
The default value is 0: an icon is present in the Windows taskbar.
Example
#HideIcon = 1
224
#HideTrayIcon
System variable - System.
The #HideTrayIcon system variable specifies if an icon is present or not in the
system tray during execution of scripts.
Syntax
#HideTrayIcon = 0
or
#HideTrayIcon = 1
Remarks
The default value is 0: an icon is present in the Windows system tray.
Example
#HideTrayIcon = 1
225
Hour$
Date/Time function
The Hour$ function returns the current hour as a two-character string.
Syntax
a$=Hour$()
Return value
a$, hour number returned as a string; if current hour is less than 10, a leading 0
is included. a$ is always two characters long.
Example
a$=Hour$() 'if it is 9:00 AM, a$ contains "09"
226
#HTMLPosRetry
System variable - Web function
The #HTMLPosRetry system variable controls how many times the coordinates
of an HTML element have to be the same before WinTask can use them. The
default value is 0, which means that the coordinates rendered by IE are
considered as the correct ones and no coordinates retry is done.
Usage
ClickHTMLElement and WriteHTML functions calculate the coordinates of the
specified HTML element before clicking it or writing into it. On some web sites or
very fast PCs, the element is first displayed at some coordinates and when all the
page is loaded, the element is at a different place. By using #HTMLPosRetry with
a default value not equal to 0, before using the element, the script checks that its
coordinates rendered by IE are #HTMLPosRetry times the same. Be aware that it
slows down script execution, so use this variable only when a web field is not
typed correctly by WriteHTML.
Syntax
#HTMLPosRetry = 0
or
#HTMLPosRetry = n
Remarks
If #HTMLPosRetry=0 (default value), at execution of a ClickHTMLElement or
WriteHTML function, WinTask gets the coordinates of the HTML element specified
by its HTML descriptor and uses them directly for clicking it or writing into it.
If #HTMLPosRetry=n (n integer different from 0), WinTask gets the coordinates
of the HTML object, pause half a second, retrieves again the coordinates and
checks that they are still the same. When they are #HTMLPosRetry times the
same, the object is used by the script.
If after #ActionTimeout, the HTML element is not found (either the coordinates
could not be retrieved, or it was not possible to get the same coordinates for
#HTMLPosRetry+1 times), the error "HTML Element not found" is displayed
(unless #IgnoreErrors=1)
Example
'Note the speed typing difference depending on #HTMLPosRetry value.
StartBrowser("IE", "www.wintask.com/demos")
UsePage("WinTask Demonstration Pages")
ClickHTMLElement("A[INNERTEXT= 'Form']")
#HTMLPosRetry=3
UsePage("Form")
'The typing in the Company field takes a while as it checks that the
coordinates
'of the field are 3 times the same.
WriteHTML("INPUT TEXT[NAME= 'company']", "My Company")
pause 1
ClickHTMLElement("INPUT RESET[VALUE= 'Clear']")
#HTMLPosRetry=0
'The same typing is fast as it writes immediately as soon as the
coordinates of the field are rendered by IE.
WriteHTML("INPUT TEXT[NAME= 'company']", "My Company")
pause 1
227
CloseBrowser()
228
Hundreds
Date/Time function
The Hundreds function returns hundredth seconds of sytem time as an integer
from 0 to 99.
Syntaxe
n=Hundreds()
Return value
n, integer from 0 to 99, hundredth seconds of system time.
Example
n=Hundreds() 'if it is 9:08:05:50, n contains "50"
229
If...Then...Else...Endif
Program flow management function.
The If...EndIf structure defines a conditional statement.
Usage
It allows decisions to be made during the execution of the script depending on
the result of a condition (true or false). If the result is True, WinTask executes
the block of steps following the If line up until an EndIf is encountered, otherwise
the block is skipped (if an Else line is encountered, the Else block is executed).
Syntax
If <boolean_expression> Then
<statements>
[Else
<statements>]
EndIf
Parameters
<boolean_expression>, if the expression evaluates to TRUE, the <statements>
after the THEN are executed; if the expression evaluates to FALSE, the
<statements> after the ELSE are executed. The ELSE statement is optional.
See also
Logical operators
Example
If a=1 Then
beep(100)
Else
beep(200)
EndIf
If b=3 Then
beep(100)
EndIf
230
#IgnoreErrors
System variable - Windows management, File management, Program flow
management, System, Com management.
The #IgnoreErrors system variable controls the way Error Handling is done.
Usage
Used to change the default way execution errors are reported. By setting
#IgnoreErrors=1, the lines in the script are executed sequentially without
stopping if an error occurs. Be aware that with #IgnoreErrors=1, it's not possible
any more to see why a script execution fails. So when you debug a script, you
should temporarily come back to the default settings (#IgnoreErrors=0).
Syntax
#IgnoreErrors = 0
or
#IgnoreErrors = 1
Remarks
If this variable is set to 0, when an execution error occurs, an error message is
displayed and all the scripts are stopped.
If this variable is set to 1, the script goes on and the return code of the function
which gave the error can be tested.
For the file management functions, the possible return codes are:
0 No error
2 or 9 File not found
3 Path not found
4 Too many files opened
8 Not enough memory
15 Incorrect disk
16 Error on the current disk
19 Error write protection
26 Specific to Vista, Error in file creation
The default value for #IgnoreErrors is 0.
All the statements which simulate an action by WinTask return a return code
(except ClickMouse and MoveMouse). This return code can be tested ; it's always
0 if the action has been successfully completed. If #IgnoreErrors=1, all the errors
generated by these statements are ignored. The programmer can then test the
return code of each individual statement. If the return code is not 0, the
programmer must manage the error situation.
If OnAction Error construction is used (not available in WinTask lite), as soon as
an error is seen, it's the procedure defined in the OnAction Error which is
launched, whatever value has #IgnoreErrors.
See also
Error Management
#ErrorCode, #ErrorFunction$, #ErrorMsg$, #ErrorScript$, #LastErrorLine,
#LastErrorLine$
231
#IgnoreHTMLCase
System variable - Web functions.
The #IgnoreHTMLCase system variable enables/disables character case in
HTML descriptors.
Syntax
#IgnoreHTMLCase = 0
or
#IgnoreHTMLCase = 1
Remarks
If this variable is set to 0, at execution, HTML descriptors are found only if the
case is the same as when recorded. It's the default value.
If this variable is set to 1, at execution, an HTML descriptor with some letters
with a different case that when recorded is found.
Example
In Recording mode, on main WinTask Web page, clicking the link DOWNLOAD
your 30-day trial now! below the product picture:
StartBrowser("IE", "www.wintask.com")
UsePage("Macro and Data Extraction with WinTask - the automation software
for Windows and internet")
ClickHTMLElement("A[INNERTEXT= 'DOWNLOAD your 30-day']")
If we change the case of the HTML descriptor DOWNLOAD in Download, at replay
the script fails with the error HTML element not found, but the script below runs:
#IgnoreHTMLCase=1
StartBrowser("IE", "www.wintask.com")
UsePage("Macro and Data Extraction with WinTask - the automation software
for Windows and internet")
ClickHTMLElement("A[INNERTEXT= 'Download your 30-day']")
232
ImpersonateUser
System function.
The ImpersonateUser function allows WinTask to temporarily assume the rights
of another user. This allows WinTask to execute administrator tasks, for example.
Not available in WinTask Lite. Not available under Windows XP and 2003.
Syntax
a=ImpersonateUser()
or
a = ImpersonateUser(<user>, <password>,[<domain>])
Parameters
When the parameters are omitted, the function will use the default account
specified in WinTask Scheduler.
When parameters are included, the impersonation is done using the account
specified by <user> and <password>. If <domain> is not specified, the current
user domain will be used.
Return value
a, integer, return code which indicates if the impersonation has failed or
succeeded.
Remarks
ImpersonateUser can be cancelled by the RevertToSelf function. ImpersonateUser
cannot give admin rights to a .EXE, so you can't use it to run a file which needs
admin rights for its execution. It can be used for changing file attributes just
when the script is running.
Example code
This example explains how a script can acquire administrator privileges in order
to change the default user name for the machine. Note that it's better to put
another script in the Start Group which can complete the desired actions and
delete the AutoAdminLogon from the Registry.
ImpersonateUser("administrator", "master1", "taskware")
auto$="1"
WriteReg("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows
NT\CurrentVersion\Winlogon\AutoAdminLogon",1,auto$)
user$= "administrator"
password$="master1"
dom$= "taskware"
WriteReg("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows
NT\CurrentVersion\Winlogon\DefaultUserName",1,user$)
WriteReg("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows
NT\CurrentVersion\Winlogon\DefaultPassword",1,password$)
WriteReg("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows
NT\CurrentVersion\Winlogon\DefaultDomainName",1,dom$)
flag=4 ' force new NT logon
lg = External("user32.dll", "ExitWindowsEx", flag, 0)
233
Include
Compilation
The Include function includes the specified source file into the current script
Syntax
Include "<source_filename>"
Parameters
<source_filename>, the source script to be included into the main script at
compilation. If the included script is in the same directory than the main script,
the full path is not necessary ; if not, you must specify the full path for the
included script (for instance, "C:\program files\my_scripts\my_script.src").
Relative paths are allowed : Include ".\sub1\sub1script1.src".
Remarks
If you use multiple Include lines, you have to ensure that the full long script with
those inclusions keep the correct program structure, first the Dim lines, second
the Functions and Subs definitions and last the main program. Yo need too to
ensure that all the Subs/Functions are declared before using them in another
Function/Sub. You have to ensure that there are not duplicate names. And for
maintenance ease, we recommend that you use different parameters names
within the different Functions/Subs.
See also
Program Structure
Example
include "script1.src"
234
InputBox$
User dialog function.
The InputBox$ function displays a dialog box for accepting user input.
Usage
Used for asking the user a question. The text value is populated into a variable. If
his answer must be hidden, use InputBoxSecret$ function.
Syntax
var$=InputBox$(<Prompt> [, [<Title>][, [<Default_answer>][, [<X>],
[<Y>]]]])
Parameters
<Prompt>, string, prompt in the dialog box above the edit box where the user
can enter input. At execution, the script is paused, waiting the user to click a
button.
<Title>, optional string, title of the dialog box.
<Default_answer>, optional default answer inserted into the edit box.
<X>,<Y>, optional integers, coordinates of the top-left point of the Inputbox.
Return value
If the button OK is selected, var$ contains whatever was entered in the edit box.
If the button Cancel is selected, var$ contains "ID_CANCEL".
See also
InputBoxSecret$
Examples
Var$ = InputBox$("Hello : ","Title :", "Today")
Var$ = InputBox$( prompt$, title$, default$, var_x, var_y)
Var$ = InputBox$( prompt$)
Var$ = InputBox$( prompt$, , , 100, 100)
235
InputBoxSecret$
User dialog function.
The InputBoxSecret$ function displays a dialog box for accepting a hidden user
input (for typing a password for instance). Not available in WinTask Lite.
Usage
Mainly used for requesting user passwords.
Syntax
var$=InputBoxSecret$(<Prompt> [, [<Title>][, [<Default_answer>][, [<X>],
[<Y>]]]])
Parameters
<Prompt>, string, prompt in the dialog box above the edit box where the user
can enter input. At execution, the script is paused, waiting the user to click a
button. When the user types in the Edit field, the content is hiddent with stars.
<Title>, optional string, title of the dialog box.
<Default_answer>, optional default answer inserted into the edit box.
<X>,<Y>, optional integers, coordinates of the top-left point of the Inputbox.
Return value
If the button OK is selected, var$ contains whatever was entered in the edit box.
If the button Cancel is selected, var$ contains "ID_CANCEL".
Examples
Var$ = InputBoxSecret$("Type your password: ","Title :", "Today")
Var$ = InputBoxSecret$( prompt$, title$, default$, var_x, var_y)
Var$ = InputBoxSecret$( prompt$)
Var$ = InputBoxSecret$( prompt$, , , 100, 100)
236
Instr
String management function.
The Instr function returns the position of one string within another.
Usage
Mainly used to extract a substring from one string. For example, Instr function
can be used to extract only the filename from a long filename including the path,
or only the filename without the extension. See the script example Extract name,
directory and extension from a full filename.
Syntax
pos=Instr(<target_string>,<search_string>)
Parameters
<target_string>, string to be searched
<search_string>, string to search for
Return value
Pos returns the position where the search string was found. If the search string is
not found in the target string, 0 is returned; if <target_string> or
<search_string> are empty, 0 is also returned.
See also
InstrRev
Extract the first and second word from a string
Extract name, directory and extension from a full filename
ExtractBetween$
Examples
pos = Instr("abcdefg","de") ' returns 4
pos = Instr("abcdefg","dz") ' returns 0
237
InstrRev
String management function.
The InstrRev function returns the position of a substring within the specified
string, searching backward through the string.
Usage
Mainly used to extract a substring from one string. For example, InstrRev
function can be used to extract the path from a long filename. See the example
below.
Syntax
pos=InstrRev(<target_string>,<search_string>)
Parameters
<target_string>, string to be searched
<search_string>, string to search for, searching backward
Return value
Pos returns the position where the search string was found, starting from the
beginning, with a backward search through the string. If the search string is not
found in the target string, 0 is returned; if <target_string> or <search_string>
are empty, 0 is also returned.
See also
Instr
Examples
a$="Hello WinTask, Hellobis"
pos=InstrRev(a$,"Hello")
msgbox(pos) ' returns 16
'Path extraction of a long filename including its path
pos=InstrRev("c:\program files\wintask\scripts\my_script.rob","\")
msgbox(pos)
path$=left$("c:\program files\wintask\scripts\my_script.rob",pos)
msgbox(path$)
238
IsRunning
System function.
The IsRunning function indicates whether a program is loaded in memory or
not.
Usage
Depending if a process is running or not, you take the appropriate action, for
example, you kill it.
Syntax
a=IsRunning(<module_name>)
Parameters
<module_name>, string which defines the name of the program ; if an extension
is not included, .EXE is assumed. It can be a constant or a variable; a path can be
included in <module_name> which can be in upper/lower case.
Return value
a = 1 if the program is loaded, 0 otherwise.
Examples
a = IsRunning("Wordpad") ' 1 if Wordpad.exe is loaded.
a = IsRunning("Comdlg32.dll") ' 1 if Comdlg32.dll is loaded.
prog$ = "c:\taskware\mfc42.dll"
a = IsRunning(prog$) ' 1 if mfc42.dll is loaded (the one in c:\taskware)
'Kills the application if it is running
Shell("notepad",1)
If IsRunning("notepad") then
KillApp("notepad",1)
Endif
239
IsServiceStarted
System function.
The IsServiceStarted function indicates if the specified Windows
2000/XP/2003/Vista Service is started or not. Not available in WinTask Lite.
Syntax
a = IsServiceStarted(<service_name>)
Parameters
<service_name>, string, name of the service.
Return value
a, integer, return value: 1 if the service <service_name> is started, 0 otherwise.
The return code is 109 if WinTaskAdmin Service is not started. The return code is
5 if the access is denied.
Example
a = IsServiceStarted("WTScheduler") ' Returns 1 if the WTScheduler service (the
WinTask Scheduler) is started.
240
Kill
File management function.
The Kill function deletes one or more files.
Usage
Do not kill files using Del key in Explorer; the selection of the file to kill is not
reliable as the way to display files in Explorer depends on Windows settings for
each user. Use instead Kill function. Wildcards (* or ? characters) are allowed in
the file names. As Kill returns an error if you try to delete a file which does not
exist, you can first check that the file exists using Exist function.
Syntax
Kill(<filename>)
or
ret=Kill(<filename>)
Parameters
<filename>, string, name of the file(s) to be deleted. Wildcard characters can be
included in the file name parameter.
Return value
Ret, numeric return code. When the deletion is successful, the function returns 0,
otherwise use this return code for Error Handling.
Remarks
The function works the same as the DOS statement DEL.
Examples
Kill("c:\*.txt")
Result = Kill(file$)
241
KillApp
System function.
The KillApp function kills the specified application. Not available in WinTask Lite.
Usage
Used to force an application (a program file or EXE) to close. KillApp function is
more powerful than CloseWindow function as it closes the application even if it is
not responding or if a Save dialog prevents from closing.
Syntax
KillApp(<exe_name>,0|1 [,<user_name>])
or
ret=KillApp(<exe_name>,0|1 [,<user_name>])
Parameters
<exe_name>, string, name of the application to kill. The name of the application
is not case sensitive and the extension is not compulsory (for instance,
Notepad.exe or Notepad or NOTEPAD are valid <exe_name>). All the instances of
the application are killed.
If the second parameter is 1, the application is killed immediately. If the second
parameter is 0 and if the application cannot be killed after 60 secs, a confirmation
dialog box is displayed. If the user does not click OK within 60 secs, the
application is killed.
<user_name>, string, optional parameter. If specified, KillApp kills only the
instances of the specified application which have been started by the user
<user_name>.
Return value
Ret, numeric return code. 0 if the specified application has been killed
successfully, 1 if the application has been killed after user confirmation.A
negative value is returned if the application could not be killed and script
execution stops (unless #IgnoreErrors=1). The possible negative return codes
are -3 if the Kill has been cancelled by the user, -4 if the application could not be
killed due to an denied access, -1 if the application could not be killed for any
other reason.
Remarks
If you use KillApp to kill all the instances of Internet Explorer, the next time you
open IE, you will get the message "Your last browsing session closed
unexpectedly". To avoid this message, in the Tools menu of Internet Explorer,
select Internet options and click the Advanced Tab. Under Browsing session,
uncheck "Enable automatic crash recovery".
Example code
The script below launches Notepad, types some text and exits. A dialog box is
displayed asking if the document has to be saved. As KillApp is used with the 1
flag, the application Notepad is killed immediately.
Shell("notepad",1)
UseWindow("NOTEPAD.EXE|Edit||1",1)
242
SendKeys("Hello")
UseWindow("NOTEPAD.EXE|Notepad|",1)
SendKeys("<Alt <F4>>")
KillApp("notepad",1)
243
KillAppChildren
System function.
The KillAppChildren function kills the specified application and its associated
children. Not available in WinTask Lite.
Usage
Used to force an application (a program file or EXE) to close; it closes too the
children processes started by the parent application.
Syntax
KillAppChildren(<exe_name>,0|1 [,<user_name>])
or
ret=KillAppChildren(<exe_name>,0|1 [,<user_name>])
Parameters
<exe_name>, string, name of the application to kill with its associated children.
The name of the application is not case sensitive and the extension is not
compulsory (for instance, Notepad.exe or Notepad or NOTEPAD are valid
<exe_name>). All the instances of the application and its associated children are
killed. Note that if the application A calls B, which calls C, if for any reason, B is
killed, a KillAppChildren of A won't be able to kill the child C.
If the second parameter is 1, the application is killed immediately. If the second
parameter is 0 and if the application cannot be killed after 60 secs, a confirmation
dialog box is displayed. If the user does not click OK within 60 secs, the
application is killed.
<user_name>, string, optional parameter. If specified, KillAppChildren kills only
the instances of the specified application which have been started by the user
<user_name>.
Return value
Ret, numeric return code. 0 if the specified application has been killed
successfully, 1 if the application has been killed after user confirmation.A
negative value is returned if the application could not be killed and script
execution stops (unless #IgnoreErrors=1). The possible negative return codes
are -3 if the Kill has been cancelled by the user, -4 if the application could not be
killed due to an denied access, -1 if the application could not be killed for any
other reason.
See also
KillApp
Example code
The script below launches Notepad, types some text and exits. A dialog box is
displayed asking if the document has to be saved. As KillAppChildren is used with
the 1 flag, the application Notepad is killed immediately.
Shell("notepad",1)
UseWindow("NOTEPAD.EXE|Edit||1",1)
SendKeys("Hello")
244
UseWindow("NOTEPAD.EXE|Notepad|",1)
SendKeys("<Alt <F4>>")
KillAppChildren("notepad",1)
245
KillProcess
System function.
The KillProcess function kills the specified process. Not available in WinTask
Lite.
Usage
Used to kill a process specified by its internal Windows PID. It should be used
only in advanced system scripts as KillApp function is much easier to use if you
need to kill an application.
Syntax
KillProcess(<PID_name>,0|1)
or
ret=KillProcess(<PID_name>,0|1)
Parameters
<PID_name>, numeric, PID of the process.
If the second parameter is 1, the process is stopped immediately. If the second
parameter is 0 and if the process is not stopped after 60 secs, a confirmation
dialog box is displayed. If the user does not click OK, the process is then stopped.
Return value
Ret, numeric return code. 0 if the process has been stopped successfully, 1 if the
process has been stopped after user confirmation; a negative value is returned if
the process has not been stopped. The possible negative error codes are -2 if the
<PID_name> is incorrect, -3 if the function has been cancelled by the user, -4 if
the access is denied, -1 for any other reason.
Depending on the setting of #IgnoreErrors, a negative return code stops the
script and an error message is displayed or the return code can be tested in order
to continue executing the script. See Error Handling.
Example code
This complete example displays a dialog box with a list of all active windows and
their associated process IDs. With this dialog box, the user can kill (forced or not)
the process chosen.
'arrays for window information
Dim name$ ( 50 )
Dim instance( 50 )
Dim handles ( 50 )
Dim flags$ (50)
'----------------------------------------------------'arrays for processes
Dim name_proc$ ( 50 )
Dim pid ( 50 )
Dim times ( 50 )
Dim memory ( 50 )
'----------------------------------------------------BEGINDIALOG liste 79, 70, 467, 326
CAPTION "Window list"
246
TEXT label$, 93, 16
LISTBOX name$(), 28, 45, 403, 156, win$
PUSHBUTTON "&Quit", canc, 359, 243, 76, 24
DEFPUSHBUTTON "&Activate App", activat, 29, 243, 76, 24
PUSHBUTTON "&Close App", clos, 115, 243, 75, 24
PUSHBUTTON "Kill(&forced) App", killed, 196, 243, 90, 24
PUSHBUTTON "&Refresh", refresh, 292, 243, 60, 24
ENDDIALOG
'----------------------------------------------------sub kill_process(name_win$,param)
local pos,i, find
pos=instr(name_win$,"|")
name_exe$=left$(name_win$,pos-1)
'msgbox(name_exe$)
size = GetProcessList(name_proc$(),pid(),times(),memory(), 1 )
i=0
name_exe$=ucase$(name_exe$)
repeat
if ucase$(name_proc$(i))=name_exe$ then
'msgbox("compared with : "+name_proc$(i))
proc_id=pid(i)
find=1
else
i=i+1
endif
until i=size or find=1
if find=1 then
if killed=1 then
ret=KillProcess(proc_id, 1)
else
ret=KillProcess(proc_id, 0)
endif
msgbox("Return code from KillProcess : "+str$(ret))
else
msgbox("No corresponding process for : "+name_exe$)
endif
endsub
'-----------------------------------------------------sub displayed()
killed=0
CallDialog liste
if canc=1 then
stop
else
#IgnoreErrors=1
'msgframe("<"+win$+">",1,0,0,8)
'pause 1
if activat=1 then
247
usewindow(win$)
else
if killed=1 then
kill_process(win$,1)
else
if refresh<>1 then
kill_process(win$,0)
endif
endif
endif
#IgnoreErrors=1
endif
endsub
'------------------------------------------------------sub terminate()
stop
endsub
'------------------------------------------------------OnAction end_process
'If the user presses Alt+F1, the script stops.
key("<Alt <F1>>")
dosub terminate
EndAction
'********************************************************
' MAIN PROGRAM
'********************************************************
#IgnoreErrors=1
repeat
name$()=""
instance()=0
handles()=0
flags$()=""
size=GetwindowsList(name$(),instance(),handles(),flags$())
if size <> -1 then
label$="Total of active windows : "+str$(size)
displayed()
else
msgbox("Array too small")
label$="Total of active windows : "
displayed()
endif
until 1=2
248
#LastErrorLine
System variable - Synchronization, File management, Program flow control,
System, Com management.
The #LastErrorLine system variable gives the line number in the script where
the error triggering the OnAction Error procedure occurred. Not available in
WinTask Lite.
Usage
When a script is replayed with #IgnoreErrors=1, and if the script fails, the error
line is not displayed. You can use #LastErrorLine system variable to know at
which line in the script the error occurred.
Syntax
msgbox(#LastErrorLine)
or
msgbox(#LastErrorLine$)
Remarks
The returned script line number takes into account the number of lines of
included scripts.
#LastErrorLine$ is similar to #LastErrorLine but returns the script line number as
a string.
249
Lcase$
String management function.
The Lcase$ function converts all characters in the specified string to lowercase.
Syntax
var$=Lcase$(<string$>)
Parameters
<string$>, string to be converted.
Return value
var$, string with all characters converted to lowercase.
Examples
a$ = Lcase$("bCdeF/G") ' Returns bcdef/g
a$ = Lcase$(a$)
250
Left$
String management function.
The Left$ function returns the specified number of characters from the the
specified string starting from the left.
Syntax
var$=Left$(<string$>,<nbchar>)
Parameters
<string$>, string from which to extract characters.
<nbchar>, numeric, the number of characters to extract.
Return value
var$, string, return value containing the first <nbchar> characters from
<string$>. If <nbchar> is negative or 0, the returned string is empty.
See also
Right$, Mid$
ExtractBetween$
Examples
a$ = Left$("toto",2) ' Returns "to" in a$
a$ = Left$("toto",0) ' Returns "" in a$
b$ = Left$(a$,2) ' Returns the first 2 characters of a$ and puts them in b$
b$ = Left$(a$,i) ' Returns the first i characters of a$ and puts them in b$
251
Len
String management function.
The Len function returns the length of the specified string.
Syntax
a=Len(<string$>)
Parameters
<string$>, string.
Return value
a, numeric, return value containing the length of <string$>.
See also
Extract the first and second word from a string
ExtractBetween$
Examples
a = Len("bcdefg") ' Returns 6
a = Len(var$)
252
ListHTMLItem$
Web function.
The ListHTMLItem$ function returns the specified item from the specified HTML
listbox or combobox.
Usage
Extracts the text contents of an item in a listbox or combobox displayed on a Web
page. If the list/combo is a non-HTML plugin, ListHTMLItem$ function will not
recognize the list, and you can use Clipboard:
SendKeys("<Ctrl C">) to copy the text to Clipboard (use Down key if you need
to select a different item than the one selected), and GetClipboard$ function to
retrieve the content of Clipboard.
Syntax
var$=ListHTMLItem$(<HTML_descriptor>,<n>)
Parameters
<HTML_descriptor>, string, HTML descriptor of the listbox or combobox in which
to find the <n>th item. First item starts at 0.
Return value
var$, string, return value which contains the <n>th item from the listbox or
combobox. If the item does not exist, an empty string is returned.
Remarks
ListHTMLItem$ does not include any synchronization; a UsePage must be used
before to be sure that the list to capture is ready.
Example
StartBrowser("IE", "www.wintask.com/demos")
'Click Form link.
UsePage("WinTask Demonstration Pages")
ClickHTMLElement("A[INNERTEXT= 'Form']")
UsePage("Form")
a$=ListHTMLItem$("SELECT[NAME= 'subject']", 3)
msgbox(a$)
Example code
This example demonstrates how ListHTMLItem can be used for retrieving all the
items of an HTML list.
'The script launches google.com
'On the main page, it clicks the Advanced Search link,
'and on the next page extracts all the items for the list in the Language
listitem.
dim tab_element$(1000)
startbrowser("IE","www.google.com")
253
UsePage("Google")
ClickHTMLElement("A[INNERTEXT= 'Advanced Search']")
UsePage("Google Advanced Search")
i=0
repeat
a$=ListHTMLItem$("SELECT[NAME= 'lr']", i)
if ltrim$(rtrim$(a$))="" then
quit=1
else
tab_element$(i)=a$
i=i+1
endif
until quit=1
nb_item=i
i=0
repeat
mes$=mes$+"\n\"+tab_element$(i)
i=i+1
until i=nb_item
msgbox(mes$,64,"Number of items : "+str$(nb_item))
254
ListItem$
Windows management function.
The ListItem$ function returns an item from the specified listbox or combobox.
Usage
Retrieves the text content of an item in a listbox or combobox. Only standard
Windows list/combo will work with ListItem$. With a non-standard list/combo,
you can use Clipboard :
SendKeys("<Ctrl c">) to copy the text to Clipboard, and GetClipboard$ function
to retrieve the content of Clipboard.
Syntax
var$=ListItem$(<window_name>,<n>)
Parameters
<window_name>, string, window name of the listbox or combobox in which to
find the <n>th item. First item starts at 0.
Return value
var$, string, return value which contains the <n>th item from the listbox or
combobox. If the item does not exist, an empty string is returned.
See also
VB and Sheridan controls not recognized by ListItem$
Example
var$=ListItem$("EXPLORER.EXE|ComboBox|Run|1",1)
Example code
This script displays all the items displayed in the Combobox Font style within the
dialog box Font in Notepad application.
function display_list(list_name$)
local i,msg$,s_exit
i=0
msg$=""
s_exit=0
repeat
var$=ListItem$(list_name$,i)
if var$="" then
if i=0 then
msgbox("ListBox or ComboBox not found",48,"ERROR")
stop
else
s_exit=1
endif
else
255
msg$=msg$+var$+"\n\"
i=i+1
endif
until s_exit=1 or i>40
msgbox(msg$,64,"The list contains : ")
endfunction
'launch notepad
Shell("notepad",1)
'Select menu Edit, option Set Font
UseWindow("NOTEPAD.EXE|Notepad|Untitled - Notepad",1)
ChooseMenu(Normal,"F&ormat|&Font...")
'function call for listing all the items for the Combobox named Font style.
'Combobox name is found using Spy.
display_list("NOTEPAD.EXE|ComboLBox|Font|2")
'close the dialog box and close Notepad
UseWindow("NOTEPAD.EXE|#32770|Font",1)
Click(Button,"Cancel")
CloseWindow("NOTEPAD.EXE|Notepad|Untitled - Notepad",1)
256
LockKbd
System function.
The LockKbd function locks the keyboard.
Usage
Even if LockKbd can be useful for preventing user interference while a script is
running, we do not recommend to use it as if something goes wrong, the only
way to enable again the keyboard will be to power off!
Syntax
LockKbd
Remarks
Keystrokes are not transmitted during the execution of scripts. If you want to
lock keyboard and still be able to transmit keystrokes, see example code below.
The special combinations, such as <Ctrl <Alt <Del>>> or <Ctrl <Esc>> are still
active. When the last script finishes, the entire keyboard is reactivated.
Example
LockKbd
Example code
Under Windows 2000/XP/2003, it is possible to call a Windows API function
locking the keyboard using WinTask External statement (not available in WinTask
Lite). Below is a sample:
Shell("notepad",1)
False=0
True=1
'Lock keyboard and mouse for 10 seconds
external("user32","BlockInput",True)
pause 5
'The script can still type
UseWindow("NOTEPAD.EXE|Edit|Untitled - Notepad|1",1)
SendKeys("aa")
pause 5
'unlock keyboard and mouse - when the script ends,
'keyboard and mouse are unlocked even if an external call is not done.
external("user32","BlockInput",False)
'check during 5 secs that you can now use mouse
pause 5
257
LockMouse
System function.
The LockMouse function locks the mouse.
Usage
Even if LockMouse can be useful for preventing user interference while a script is
running, we do not recommend to use it as if something goes wrong, the only
way to enable again the mouse will be to power off!
Syntax
LockMouse
Remarks
The mouse actions are not transmitted during the execution of the script. When
the last script finishes, the mouse is reactivated.
Example
LockMouse
Example code
Under Windows 2000/XP/2003, it is possible to call a Windows API function
locking the keyboard using WinTask External statement (not available in WinTask
Lite). Below is a sample:
Shell("notepad",1)
False=0
True=1
'Lock keyboard and mouse for 10 seconds
external("user32","BlockInput",True)
pause 5
'The script can still type
UseWindow("NOTEPAD.EXE|Edit|Untitled - Notepad|1",1)
SendKeys("aa")
pause 5
'unlock keyboard and mouse - when the script ends,
'keyboard and mouse are unlocked even if an external call is not done.
external("user32","BlockInput",False)
'check during 5 secs that you can now use mouse
pause 5
258
LogFile
Logfile management function.
The LogFile function forces the script to log each statement executed into the
specified logfile. Not available in WinTask Lite.
Usage
Mainly used to trace in a text file all the statements executed by the script.
Syntax
LogFile(<filename>,<type>,<mode>)
Parameters
<filename>: name of the file where the statements executed after this function
are written. The extension must be .LOG if you want to be able to open the logfile
using File/Open Log menu. If the full path is not included in <filename>, the
file is created in the scripts current directory.
<type>: 1 for a full logfile, 0 for a limited logfile (only statements Comment are
written into the logfile).
<mode>: 1 to delete the logfile before writing, 0 to add the new statements at
the end of the logfile.
Remarks
This statement redefines the setting specified in TaskEdit (menu
Configure|Run).
Example
Script : Untitled1.src
Shell("notepad")
LogFile("c:\Program Files\WinTask\Logs\history.log",1,1)
UseWindow("NOTEPAD.EXE|Edit|Untitled - Notepad|1",1)
SendKeys("Hello<Enter>")
UseWindow("NOTEPAD.EXE|Notepad|Untitled - Notepad",1)
ChooseMenu(Normal,"&File|E&xit")
UseWindow("NOTEPAD.EXE|#32770|Notepad",1)
Click(Button,"&No")
If you have specified a logfile using the Configure Run dialog, two files are
created in the Logs subdirectory: " Untitled1.log " and " History.log "; the second
log is created by the LogFile function.
Those two files can be opened with a text editor like WordPad or in WinTask
Editor, select menu File|Open Log.
File Untitled1.log:
2009/02/0 15 :43:10 Untitled1
1
2009/02/0 15 :43:11 Untitled1 1
1
Started
Shell
notepad
259
2009/02/0 15 :43:11 Untitled1 2
1
LogFile
c :\Program
Files\WinTask\Logs\history.log,1,
1
File History.log:
2009/02/0 15 :43:12 Untitled1 3
1
2009/02/0 15 :43:14 Untitled1 4
1
2009/02/0 15 :43:15 Untitled1 5
1
UseWindow
2009/02/0 15 :43:16 Untitled1 6
1
2009/02/0 15 :43:16 Untitled1 7
1
ChooseMenu Normal,&File|E&xit
UseWindow
NOTEPAD.EXE|#32770Notep
ad,1
2009/02/0 15 :43:17 Untitled1 8
1
2009/02/0 15 :43:17 Untitled1 8
1
Click
Button,&No
260
SendKeys
UseWindow
Ended
NOTEPAD.EXE|Edit|Untitled Notepad|1,1
Hello<Enter>
NOTEPAD.EXE|Edit|Untitled Notepad,1
Ltrim$
String management function.
The Ltrim$ function removes leading spaces/tabulations from a string.
Usage
Used to take spaces and tabulations off the beginning of a text. To avoid spaces
added by mistake during data-entry, use this function.
Syntax
var$=Ltrim$(<string$>)
Parameters
<string$>, string from which to remove leading spaces.
Return value
var$, string, the string from which the leading spaces and tabulations of
<string$> have been removed.
See also
Rtrim$
Trim$
Examples
a$ = Ltrim$(" bcde") ' Returns "bcde" in a$
a$ = Ltrim$(a$) ' Deletes the leading spaces from a$
261
MaximizeWindow
Windows management function.
The MaximizeWindow function maximizes the specified window.
Syntax
MaximizeWindow(<window_name> [,<instance>])
or
ret=MaximizeWindow(<window_name> [,<instance>])
Parameter
<window_name>, window name of the window to maximize.
<instance>, optional parameter, instance number of the window to maximize.
Return value
Ret, numeric return code. When successful, the function returns 0, otherwise use
this return code for Error Handling.
Examples
MaximizeWindow("NOTEPAD.EXE|Notepad|Untitled - Notepad")
MaximizeWindow("NOTEPAD.EXE|Notepad|Untitled - Notepad",1)
Result = MaximizeWindow(win$)
262
Mid$
String management function.
The Mid$ function returns the specified portion of a string.
Syntax
var$=Mid$(<string$>,<start>,<length>)
Parameters
<string$>, string from which to extract.
<start>, numeric, position in <string$> from which to extract. The first character
position is 1. If <start> is greater than the number of characters in <string$>,
var$ is set to an empty string. If <start> is negative, the extraction start at
position 1.
<length>: numeric, number of characters to be extracted. If <number> is
negative or 0, var$ is set to an empty string.
Return value
var$, string, return value containing the substring. If the length of <string$>
(including the character starting at <start>) is less than <length>, all the
characters from <start> to the end of <string$> are returned in var$.
See also
Left$, Right$, ExtractBetween$
Examples
a$ = Mid$("bcdefg",2,2) ' Returns "cd" in a$
a$ = Mid$("bcdefg",2,0) ' Returns "" in a$
a$ = Mid$("bcdefg",0,2) ' Returns "bc" in a$
263
Min$
Date/Time function
The Min$ function returns the minutes portion of the current time as a two
character string.
Syntax
a$=Min$()
Return value
a$, minutes number returned as a string; if the value is less than 10, a leading 0
is added. a$ is always two characters long.
Example
a$=Min$() 'if its 9:08 am, a$ contains "08"
264
MinimizeWindow
Windows management function.
The MinimizeWindow function minimizes the specified window.
Syntax
MinimizeWindow(<window_name> [,<instance>])
or
ret=MinimizeWindow(<window_name> [,<instance>])
Parameter
<window_name>, window name of the window to minimize.
<instance>, optional parameter, instance number of the window to minimize.
Return value
Ret, numeric return code. When successful, the function returns 0 and the
window icon is displayed in the taskbar, otherwise use this return code for Error
Handling.
Examples
Res=MinimizeWindow("NOTEPAD.EXE|Notepad|Untitled - Notepad")
Res=MinimizeWindow("NOTEPAD.EXE|Notepad|Untitled - Notepad", 1)
MinimizeWindow(win$)
265
MkDir
System function.
The MkDir function creates a directory.
Syntax
MkDir(<directory_name>)
or
ret=MkDir(<directory_name>)
Parameters
<directory_name>, string, name of the directory to create.
Return value
Ret, numeric return code. When the directory is successfully created, the function
returns 0, otherwise use this return code for Error Handling.
Remarks
The function works the same as the DOS statement MKDIR, except it can create
only one directory level at a time (see the examples).
See also
RmDir
Examples
MkDir("c:\docs")
MkDir(dir$)
MkDir("c:\topdir")
MkDir("c:\topdir\subdir")
Example code
The script below creates a directory based on date/hour
'On C:\, we suppose that the directory paul is there.
'And four sub-directories AA, BB, CC, DD are under C:\paul.
'As an example, we retrieve the AA subdirectory name and under AA, we create
a subdirectory
'c:\paul\AA\AA-date-hour
dim tablongname$(10)
dim tabshortname$(10)
dim tabpath$(10)
dim tabattrib$(10)
number_of_files=DirTree("c:\paul\*.*",tablongname$(),tabshortname$(),tabpath
$(),tabattrib$(),"N")
cdate$=month$()+day$()+"03"
ctime$=hour$()+min$()
266
i=0
mkdir("c:\paul\"+tablongname$(i)+"\"+tablongname$(i)+"-"+cdate$+"-"+ctime$)
267
Month$
Date/Time function
The Month$ function returns the number of the current month as a string.
Syntax
month_curr$=Month$()
Return value
month_curr$, number of the current month returned as a string; if the value is
less than 10, a leading 0 is added (the string is always two characters long).
Example
a$=Month$() 'if current month is March, a$ contains "03"
268
MouseShape
Windows management function.
The MouseShape function returns the shape of the mouse pointer as an integer.
Usage
Mainly used for inserting an advanced synchronization method. For example, if a
text refresh within a window can only be dectected by the mouse shape changing
from the hourglass to the standard arrow, MouseShape function allows to insert
the correct synchronization (see example code below).
Syntax
MouseShape()
or
current_val=MouseShape()
Return value
current_val, integer corresponding to the shape of the mouse as below (standard
Windows values) :
Standard arrow and small
1
hourglass
Normal arrow pointer
2
I-beam pointer
4
Hourglass
14
Cross
3
4-direction arrow
8
NW-SE arrow
11
NE-SW arrow
9
East-West arrow
12
North-South arrow
10
Remarks
This statement can be used to synchronize WinTask with the application, for
instance, to wait until the hourglass disappears.
Example
Cursor_Val=MouseShape()
Example code
This script includes a synchronization function which waits until the hourglass has
disappeared ; this function can then be used to wait the mouse shape change
before executing next line.
function wait_cursor()
local sortie
sortie=0
repeat
if mouseshape()=14 then
pause 1
else
269
sortie=1
endif
until sortie=1
endfunction
'Example how to use it when a program loads many windows and so a simple
UseWindow
'is not enough to be sure that all the windows are loaded.
Shell(Chr$(34)+"C:\Program Files\Norton AntiVirus\Navw32.exe"+Chr$(34),1)
'Test that the application is totally loaded.
wait_cursor()
This script displays some cursor values in NotePad.
msg$="Cursor value is : "
shell ("notepad.exe")
SizeWindow("NOTEPAD.EXE|Notepad|Untitled - Notepad",0,596,427)
MoveWindow("NOTEPAD.EXE|Notepad|Untitled - Notepad",0,65,78)
UseWindow("NOTEPAD.EXE|Notepad|Untitled - Notepad",0)
ChooseMenu(System,"&Move")
pause 2
a=MouseShape()
sendkeys("<Esc>")
Rem display the value returned by MouseShape
msgframe (msg$+str$(a),1,0,0,12,255)
pause 2
RemoveFrame(1)
MoveMouse(594,100)
pause 2
a=MouseShape()
msgframe (msg$+str$(a),1,0,0,12,255)
pause 2
RemoveFrame(1)
UseWindow("NOTEPAD.EXE|Notepad|Untitled - Notepad",1)
ChooseMenu(Normal,"&File|E&xit")
270
MouseX, MouseY
Windows management function.
The MouseX, MouseY functions return the X or Y position of the mouse.
Syntax
x=MouseX()
y=MouseY()
Return value
x,y : numeric in pixels ; it gives the coordinates of the mouse relative to the topleft corner of the screen.
Examples
x=MouseX()
y=MouseY()
271
MoveMouse
Windows management function.
The MoveMouse function moves the mouse pointer.
Usage
Used for highlighting text selections or in drawing software. Low level Recording
mode generates a lot of MoveMouse lines as recording is done at pixel level
instead of Windows level object.
Syntax
MoveMouse(<X>,<Y>[,Absolute])
Parameters
<X>,<Y>, numeric in pixels ; coordinates of the new mouse pointer position
(relative to the upper-left hand corner of the current window). MoveMouse
statements are recorded in the script only if one of the mouse buttons is pressed.
Absolute : optional keyword indicating that the coordinates are relative to the
upper-left hand of the screen instead of the upper-left corner of the window.
If no window was previously specified by a UseWindow statement, an error
message is displayed and all the scripts are stopped.
Examples
MoveMouse(100, 200)
MoveMouse(var_x, var_y)
Example code
This script launches MsPaint and draws a rectangle.
Rem Open Mspaint
shell("mspaint")
Rem Select the Rectangle tool
UseWindow("MSPAINT.EXE|AfxWnd42u|Tools",1)
ClickMouse(Left,Down,15,160)
ClickMouse(Left,Up,15,160)
Rem Draw the rectangle
UseWindow("MSPAINT.EXE|Afx:1990000:8|untitled - Paint|1",1)
ClickMouse(Left,Down,14,19)
MoveMouse(15,19)
MoveMouse(17,19)
MoveMouse(20,19)
MoveMouse(23,18)
MoveMouse(25,18)
MoveMouse(26,18)
MoveMouse(30,18)
MoveMouse(33,18)
MoveMouse(36,19)
272
MoveMouse(38,20)
MoveMouse(42,22)
MoveMouse(46,25)
MoveMouse(50,27)
MoveMouse(51,27)
MoveMouse(52,28)
MoveMouse(55,29)
MoveMouse(56,29)
MoveMouse(58,30)
MoveMouse(60,32)
MoveMouse(64,35)
MoveMouse(67,38)
MoveMouse(68,39)
MoveMouse(68,40)
MoveMouse(70,42)
MoveMouse(75,45)
MoveMouse(76,46)
MoveMouse(76,47)
MoveMouse(77,47)
MoveMouse(77,48)
MoveMouse(78,48)
MoveMouse(78,49)
MoveMouse(81,50)
MoveMouse(81,51)
MoveMouse(82,51)
MoveMouse(84,52)
MoveMouse(84,53)
MoveMouse(85,53)
MoveMouse(86,53)
MoveMouse(87,53)
ClickMouse(Left,Up,87,53)
Pause 4
UseWindow("MSPAINT.EXE|MSPaintApp|untitled - Paint",1)
ChooseMenu(Normal,"&File|E&xit;Alt+F4")
UseWindow("MSPAINT.EXE|#32770|Paint",1)
Click(Button,"&No")
273
MoveWindow
Windows management function.
The MoveWindow function moves the specified window without changing its
size.
Syntax
MoveWindow(<window_name>,<instance>,<X>,<Y>)
or
ret=MoveWindow(<window_name>,<instance>,<X>,<Y>)
Parameters
<window_name>, window name of the window to move, it must include
<instance>, instance number of the window to move.
<X>,<Y>, numeric in pixels ; coordinates of the point where the window is to be
moved. These are the coordinates of the upper-left corner of the window, relative
to the upper-left corner of the screen. These coordinates can be negative ; the
size of the window is not changed.
Return value
Ret, numeric return code. When the move is successful, the function returns 0,
otherwise use this return code for Error Handling.
Examples
MoveWindow("NOTEPAD.EXE|Notepad|Untitled - Notepad",1, 100, 120)
Ret = MoveWindow(win$, 0, var_x, var_y)
274
MsgBox
User dialog function.
The MsgBox function displays a standard Windows dialog box.
Usage
Used to provide information feedback to the user. If you prefer to display
information without any user interaction, use MsgFrame function.
Syntax
MsgBox(<Message> [, [<Type>] [,<Title>] [,<timeout>]]])
or
ret=MsgBox(<Message> [, [<Type>] [,<Title] [,<timeout>]]])
Parameters
<Message>, string or integer to be displayed in the dialog box. In order to
display numeric and string variables together, you must first convert numbers to
a string (using the Str$ function - see the examples below). You can force a line
feed by including \n\ in your <Message>.
<Type>, optional integer, sum of the values below used for specifying buttons
and icons in the dialog box. The default value is 0 (only an OK button). <Type>
cannot be a variable. If <Type> is omitted, you must include the field separator
(,), see the example.
Type of buttons:
0
OK button only
1
OK and Cancel
2
Cancel, Retry and Ignore
3
Yes, No and Cancel
4
Yes and No
5
Retry and Cancel
Type of icons:
16
Critical message
32
Confirmation
48
Warning
64
Information
Default button:
0
First button
256
Second button
512
Third button
<Title>, optional string, title of the dialog box.
<timeout>, optional integer. If after <timeout> in seconds, no button has been
clicked, the message box vanishes, and a return code of 128 is returned (if the
message box has only an OK button, the return code when the message box
vanishes after <timeout> is 1).
Return value
Return value for the corresponding selected button:
1
OK
2
Cancel
3
Quit
4
Retry
5
Ignore
6
Yes
275
7
No
If the dialog box displays a Cancel button, pressing Escape is the same as clicking
Cancel.
Examples
Ret = MsgBox("Hello", 65, "Title") ' Box with 2 buttons (OK and Cancel, plus
the Information icon)
MsgBox("Hello") ' Box with no title and one OK button
MsgBox(msg$, x, title$)
Msgbox(number)
Msgbox("You found " + str$(number) + " occurrences") 'As number is an
integer, it must be first converted to a string using str$ function, and
then str$(number) can be concatenated to other strings using the + operator.
MsgBox("Hello", , "Title")
MsgBox("Hello", , "Title",10)
276
MsgFrame
User dialog function.
The MsgFrame function displays a message.
Usage
Used to provide information feedback to the user without he needs to click any
Yes/No/Cancel button.
Syntax
MsgFrame(<Text>,<Id>,[<x>],[<y>],[<size>][,<color>])
or
ret=MsgFrame(<Text>,[<x>],[<y>],[<size>][,<color>])
Parameters
<Text>, string to be displayed, constant or variable. The current font and size
are used to display the <text>. The <text> is automatically displayed in the
middle of the frame. If the <text> is too long, it's displayed on several lines
unless no spaces are included in <text>. You can force a line feed by including
\n\ in your <text>. If a number has to be displayed, it must be first converted to
a string using Str$ function (see the example below).
<Id>, integer, identifier of this specific message. It can be a constant or a
variable.
<x>,<y>, optional coordinates of the left-top point of the rectangle containing
the message; if these parameters are not specified, the message is displayed in
the middle of the screen. If these parameters would cause part of the rectangle
to be displayed off-screen, the rectangle is automatically displayed at the top-left.
Instead of specifying coordinates, those keywords can be used:
<x> can be replaced by Left, Center or Right keyword
<y> can be replaced by Top, Center or Bottom keyword
<size>, optional integer, size of the font used to display the message (default
value : 12).
<color>, optional integer, color of the text; the default value is black. Red is:
255, green is 65280, blue is 255 x 65536, white (sum of these three colors): 255
+ (255x256) + (255x65536) = 16,777,215. If red, green and blue are the index
of each color from 0 to 255, <color> is:
red+(green*256) + (blue*65536).
Return value
Ret, numeric return code. When the message frame is display successfully, the
function returns 0, otherwise use this return code for Error Handling.
Remarks
When the script ends, all the messages are removed.
You can also remove them by using the RemoveFrame function.
If you want to display the & character, you need to double it: msgframe("A &&
B")
Examples
MsgFrame("Please wait",1) ' Displays the text "Please wait"
MsgFrame("Please wait",1,Center,Center) ' Displays the text "Please wait" in the
277
middle of the screen
MsgFrame("The index is: "+str$(index),1) ' Displays the text "The index is: 3"
if the index value is 3
278
MsgFrameTitle
User dialog function.
The MsgFrameTitle function displays a message in a frame with a title.
Syntax
MsgFrameTitle (<frame_title>,<Text>,<Id>,[<x>],[<y>],[<size>][,<color>])
or
ret=MsgFrameTitle
(<frame_title>,<Text>,<Id>,[<x>],[<y>],[<size>][,<color>])
Parameters
<frame_title>, string to be displayed as the title of the frame. It can be a
constant or a variable.
<Text>, string to be displayed, constant or variable. The current font and size
are used to display the <text>. The <text> is automatically displayed in the
middle of the frame. If the <text> is too long, it's displayed on several lines
unless no spaces are included in <text>. You can force a line feed by including
\n\ in your <text>.
<Id>, integer, identifier of this specific message. It can be a constant or a
variable.
<x>,<y>, optional coordinates of the left-top point of the rectangle containing
the message; if these parameters are not specified, the message is displayed in
the middle of the screen. If these parameters would cause part of the rectangle
to be displayed off-screen, the rectangle is automatically displayed at the top-left.
Instead of specifying coordinates, those keywords can be used:
<x> can be replaced by Left, Center or Right keyword
<y> can be replaced by Top, Center or Bottom keyword
<size>, optional integer, size of the font used to display the message (default
value : 12).
<color>, optional integer, color of the text; the default value is black. Red is:
255, green is 65280, blue is 255 x 65536, white (sum of these three colors): 255
+ (255x256) + (255x65536) = 16,777,215. If red, green and blue are the index
of each color from 0 to 255, <color> is:
red+(green*256) + (blue*65536).
Return value
Ret, numeric return code. When the message frame is display successfully, the
function returns 0, otherwise use this return code for Error Handling.
Remarks
When the script ends, all the messages are removed.
You can also remove them by using the RemoveFrame function.
If you want to display the & character, you need to double it: msgframetitle("Title
frame","A && B",1)
Examples
MsgFrameTitle("Login","Please wait",1) ' Displays the text "Please wait" in the
frame with the title "Login"
MsgFrameTitle("Login","Please wait",1,Center,Center) ' Displays the text
"Please wait" in the frame with the title "Login" in the middle of the screen
279
MsgFrameTitle("Your userid is: "+name$,"Please wait",1,Center,Center) '
Displays the text "Your userid: " concatenated with the content of name$.
280
Multiply$
Floating point calculation function.
The Multiply$ function multiplies two strings representing floating point
numbers.
Usage
As only integers are supported numbers in WinTask, calculation on floating point
numbers is done using their string representation.
Syntax
res$=Multiply$(a$,b$[,rc])
Parameters
a$, b$ are the strings representing the two floating numbers to multiply.
rc, optional numeric return code.
Values are :
0 if the operation was successful
1 invalid operation because parameters are incorrect (for instance, the string
can't be considered a number)
2 if an overflow occurred
Return value
res$, string representing a$ * b$.
See also
#Precision
Examples
Multiply$("13.56","145.789") 'gives "1976.90"
Multiply$("-45.678","34.8976") 'gives "-1594.05"
#Precision=3
Multiply$("567.34257","45.343") 'gives "25725.014"
281
Name
File management function.
The Name function renames or moves one or more files.
Usage
Do not move files using Drag and Drop in Explorer; drag and drop automation is
not reliable as the way to display files in Explorer depends on Windows settings
for each user. Use instead Name function. Wildcards (* or ? characters) are
allowed in the file names.
Syntax
Name(<old_filename>,<new_filename>)
or
ret=Name(<old_filename>,<new_filename>)
Parameters
<old_filename>, string, name of the file(s) to be renamed. Wildcard characters
are permitted.
<new_filename>, string, new name of the file. If the path of <new_filename>
exists and is different from the path of <old_filename>, the Name function
moves the file to the new directory and renames it. If <old_filename> and
<new_filename> have different paths but the same filename, Name moves the
file to the new directory but doesn't change the filename. The file <old_filename>
must exist and the file <new_filename> must not exist. They must both be on
the same drive.
Return value
Ret, numeric return code. When the rename is successful, the function returns 0,
otherwise use this return code for Error Handling.
Remarks
The function works like the DOS statement RENAME. Name can also modify the
name of a directory. Name cannot rename a file within the same directory, for
example Name("c:\test\name1.txt","c:\test\name2.txt") returns an error. Use
FileCopy instead and then Kill the original file.
Examples
Name("c:\mytext\toto.*", "c:\mytext\titi.*") ' Renames files c:\mytext\toto.*
to c:\mytext\titi.*
Name("c:\mytext\toto.txt", "c:\docs\toto.txt") ' Moves the file toto.txt from
c:\mytext\ to c:\docs\
Result = Name(Fi1e1$, File2$)
282
Navigate
Web function.
The Navigate function causes the browser to open the specified url address.
Usage
Mainly used to go directly to a page instead of using the Web site navigation
through its menus and links.
Syntax
Navigate(<url_address>[,<timeout>])
or
Ret=Navigate(<url_address>[,<timeout>])
Parameters
<url_address>, string, url address to open.
<timeout>, numeric in seconds, optional parameter which specifies the maximum
delay to wait for the page to be loaded.
If the optional parameter is not present, the #ActionTimeout system variable is
used to specify the maximum wait for the page to be loaded.
Return value
Ret, numeric return code. When the navigation completes within the timeout
period, the function returns the time it took for the page to be loaded in tenths of
a second, otherwise use this return code for Error Handling. The return code is -1
if the browser has not been started (using StartBrowser function), or -5 if a
navigation timeout occurs. If the IE browser object cannot "navigate" the
specified address, the return code is -10. If Internet Explorer returns an error
code (such as 404, 405), the return code is this Internet Explorer error code with
the negative sign (-404, -405).
Remarks
Navigate is not generated automatically by Recording mode. Add this function in
the script for navigating directly to an URL.
If a StartBrowser is done loading a blank page, the automatic synchronization on
the page loaded cannot be done, so the Navigate function fails if an absolute
Pause (Pause 2 secs for example) is not added between the StartBrowser line and
the Navigate line. Under Vista, a StartBrowser with a blank page followed by a
Navigate is rejected by IE if UAC is on. So we recommend to always use a
StartBrowser to an url before using the Navigate function.
Example
StartBrowser("IE","www.wintask.com")
UsePage("Macro and Data Extraction with WinTask - the automation software
for Windows and internet")
Navigate("http://www.wintask.com/top-10-uses.php")
283
NumLock
System function.
The NumLock function forces the numlock key to the specified state.
Syntax
NumLock(ON|OFF)
Remarks
If ON, numlock key is activated.
See also
CapsLock
Example
NumLock(ON)
284
Error codes for ODBC functions
The table below lists the possible error codes for the WinTask ODBC functions, for
the errors stopping script execution (unless #IgnoreErrors=1).
-5
-4
-3
-2
-1
Close the record set first
Connection cancelled
No numeric field
No connection available
No record set
285
OnAction...EndAction
Synchronization function.
The OnAction...EndAction function handles events. Not available in WinTask
Lite. Its syntax is similar to Pause function.
See also
OnAction Error if you want to do specific actions whenever an error occurs at
execution.
Syntax
OnAction <action_ident>
Button(<Button>,<Type>)
or
Key(<key_list>)
or
Menu(<menu_item>)
or
Text(<text>)
or
WinStatus(Exists|NotExists|Active|NotActive[,Exact|Near])
inWindow(<window_name>,<instance>)
or
WinStatus(Exists|NotExists|Active|NotActive[,Exact|Near])
InWindowAnyInstance(<window_name>)
or
Date(<Date>)
Time(<Hour>)
or
Pause x seconds
DoSub <sub_name>
EndAction
Parameters
<action_ident>, name of the event to be handled. It is a constant unique for this
event. This identifier can be used to deactivate this particular event.
An event can be a:
Button: <button>, name of the button to be pressed to activate the event.
Key: <key_list>, key(s) to be typed to activate the event ; the wizard list of
keys can be used if you want to define a key combination, such as Alt+F1. Note
that the PrintScreen key cannot be used to trigger a keyboard event.
Menu: <menu_item>, menu item to select in order to activate the event.
Text: <text>, text to be found in order to activate the event. The frequency with
which text is checked is determined by the variable #TextLookFrequency.
Window: <window_name>, name of the window which activates the event.
Date: <Date>, date which will activate the event.
Time: <Hour>, time which will activate the event.
<sub_name>, subroutine to be executed as soon as the event occurs.
Remarks
Such an event can happen at any time. But its nature is known - keyboard event,
mouse event, menu event, date/time event, duration event. All these events are
external - if WinTask simulates the action the event is not fired.
For every event, an entry is created in a table of events. During execution,
286
WinTask continually checks to see if one of the events listed in the table has
occured.
If an event occurs during execution of the script, the procedure <sub_name> is
immediately executed, then the script continues. This <sub_name> is a
subroutine without any parameters.
This event handler mechanism is reentrant : during the execution of
<sub_name>, if the same event or another event in the table occurs,
<sub_name> is suspended and the new subroutine for this new event is
launched. When the second event handler is complete, execution continues in the
previous event handler.
Activation of the an event handler:
An event handler (and the execution of the associated subroutine) is activated as
soon as the statement OnAction has been interpreted in the script. It stays active
until the script ends. At the end of the script, all the events handled by that script
are removed from the table of events, unless you use the SLEEP function (see the
full example below). If a script launches another script (using the RUN
statement), the event handler in the parent script remains active during
execution of the child scripts (the table of events is shared by all the scripts
currently running).
It is possible to deactivate the one event handler by the DISABLE function, but
this function must be inserted in the script in which the event was defined (not in
a parent/child script).
When an event handler is re-triggered:
For keyboard/mouse/menu events, each time the event occurs.
For text events, the text which has been handled must have disappeared before
it can be triggered again.
Examples
Every time the user presses <Alt <F10>>, the script executes <name_sub> :
OnAction Active_Alt_F10
Key("<Alt <F10>>")
DoSub <name_sub>
EndAction
Script which uses an OnAction on Window for clicking OK button each time a
Security Alert window is displayed on a Web page.
Sub ClickOK()
UseWindow("IEXPLORE.EXE|#32770|Security Alert",1)
Click(Button,"OK")
EndSub
OnAction WindowAction
WinStatus(Exists, Exact)
InWindow("IEXPLORE.EXE|#32770|Security Alert",1)
DoSub ClickOK
EndAction
Sleep()
The same script which uses an OnAction on Window for clicking OK button each
time a Security Alert window, whatever instance of Internet Explorer is used, is
displayed on a Web page.
Sub ClickOK()
UseWindow("IEXPLORE.EXE|#32770|Security Alert")
287
Click(Button,"OK")
EndSub
OnAction WindowAction
WinStatus(Exists, Exact)
InWindowAnyInstance("IEXPLORE.EXE|#32770|Security Alert")
DoSub ClickOK
EndAction
Sleep()
Every time the user clicks the right mouse button inside Word, the script runs
<name_sub> :
OnAction Right_Mouse_Word
Button(Right,Down)
InModule("WINWORD.EXE")
DoSub <name_sub>
EndAction
Every time the user selects Goto from the Edit menu of Word, the script runs
<name_sub> :
OnAction Menu_Edit_Goto
Menu("&Edit|&Goto... Ctrl+G")
InWindow("WINWORD.EXE|OpusApp|Microsoft Word - TEST.DOC",1)
DoSub <name_sub>
EndAction
Examples code
This example shows how an event is defined by the OnAction command; this
event occurs when the user selects Close from the Explorer menu.
Sub close()
Disable(wait_for_close_menu)
res=msgbox("Would you like to close the message box? ",4,"EXAMPLE")
if res=6 then
' if res=6 WinTask closes Explorer and stops the script
CloseWindow("EXPLORER.EXE|ExploreWClass|My Documents",2)
stop
endif
Enable(wait_for_close_menu)
EndSub
OnAction wait_for_close_menu
Menu("File|&Close")
InWindow("EXPLORER.EXE|ExploreWClass|My Documents",2)
DoSub close
EndAction
shell("explorer")
' Definition of the event, each time the user selects the option Close in
the Explorer menu File,
' the script runs the procedure close().
288
sleep()
'leaves the management of the random events active.
This script shows the use of OnAction for doing some actions when user
presses some keys.
The structure is :
OnAction touche (touche is the onaction identifier)
Key("<Alt <F2>>") 'the key will be Alt+F2
'DoSub appuie_touche (when the user press the specified key, Alt+F2, the
subroutine appuie_touche is launched)
REMARK : The compiler needs that the subroutine appuie_touche has been
defined BEFORE the OnAction using it
EndAction
'********************************************************************
'example
'Definition of the subroutine which will be launched when "<Alt <F2>>" will
be pressed
sub appuie_touche()
'here you can do what you want
msgframe("Key displayed",1)
pause 1
removeframe(1)
endsub
'-------------------------------------'Definition of the subroutine to stop the script if you press "<Alt <F1>>"
sub termine()
msgframe("Script ended",1)
pause 1
removeframe(1)
stop
endsub
'--------------------------------------'OnAction definition for "<Alt <F2>>"
OnAction touche
Key("<Alt <F2>>")
DoSub appuie_touche
EndAction
'--------------------------------------'OnAction definition for "<Alt <F1>>"
OnAction Fin
Key("<Alt <F1>>")
DoSub termine
EndAction
289
'---------------------------------------'The OnAction is active until the end of the script
'If the script has a SLEEP instruction, all the OnAction stay active
'SLEEP
sleep()
290
OnAction Error
Synchronization function.
The OnAction Error...EndAction function handles error events. Not available in
WinTask Lite. It's a specific OnAction for managing execution errors.
Usage
Used for calling an error procedure whatever unexpected error occurs during
script execution. You can for example take a screenshot of the desktop when an
execution error occurs.
Syntax
OnAction Error
DoSub <sub_name>
EndAction
Parameters
<sub_name>, subroutine to be executed as soon as a runtime error occurs.
Remarks
If an error occurs during execution of the script, the procedure <sub_name> is
immediately executed, then the script continues. This <sub_name> is a
subroutine without any parameters.
Only one error handler is active at a time: so if a new one is defined in the script,
it's the latest one which is used when an error occurs after the definition of this
new OnAction Error.
The error handler (and the execution of the associated subroutine) is activated as
soon as the statement OnAction Error has been interpreted in the script. It stays
active until the script ends OR until a new statement OnAction Error is
encountered in the script.
If a script launches another script (using the RUN statement), the error handler in
the parent script is not active anymore during execution of the child scripts.
It is possible to deactivate the error handler by inserting a Disable(Error)
function, but this function must be inserted in the script in which the error
handler was defined (not in a parent/child script). It can be activated again by
inserting a Enable(Error) function.
See also
#ErrorCode, #ErrorFunction$, #ErrorMsg$, #ErrorScript$, #LastErrorLine,
#LastErrorLine$
Examples
'General error procedure which is called when an error occurs.
'In this proc, we just log the error and execution goes on.
Sub error_proc()
Comment(#ErrorFunction$+" at line "+#LastErrorLine$+" : "+#ErrorMsg$)
EndSub
'As soon as an error occurs, the procedure defined there is called.
OnAction Error
291
DoSub error_proc
EndAction
#ActionTimeout=10
LogFile("c:\my_log.txt",0,1)
Shell("wordpad",1)
UseWindow("WORDPA.EXE|RichEdit20W|Document - WordPad|1",1)
SendKeys("aaaaaa")
UseWindow("WORDPAD.EXE|WordPadClass|Document - WordPad",1)
ChooseMenu(Normal,"&File|E&xit")
UseWindow("WORDPAD.EXE|#32770|WordPad",1)
Click(Button,"&No")
A full script which in case of any execution error captures the desktop, so if the
script runs unattended, you will know how was the entire desktop when the error
occurred.
'Definition of the proc to call if an error is detected.
Sub Process_Error()
local buffer$
'If within this proc, an error occurs too, it generates an infinite loop as
'the call to the error proc causes an error. To avoid that, we disable
OnAction Error within this proc.
disable(Error)
'Take a screenshot of the desktop
ret=Hardcopy("C:\program files\wintask\scripts\error.jpg",1,1)
'Here a part for writing in a txt file where we were in the script, the
error code, the error message when the error occurred.
buffer$="Error in : "+#ErrorScript$
write("C:\program files\wintask\scripts\error.txt",buffer$,crlf)
buffer$="Error line : "+str$(#LastErrorLine)
write("C:\program files\wintask\scripts\error.txt",buffer$,crlf)
buffer$="Error Code : "+str$(#Errorcode)
write("C:\program files\wintask\scripts\error.txt",buffer$,crlf)
buffer$="Error Function : "+#ErrorFunction$
write("C:\program files\wintask\scripts\error.txt",buffer$,crlf)
buffer$="Error message : "+#ErrorMsg$
write("C:\program files\wintask\scripts\error.txt",buffer$,crlf)
'Add here other lines for what to do in case of an error.
'......
Endsub
OnAction error
292
dosub Process_Error
endaction
#Actiontimeout=15
'The window is not found, so OnAction error triggers.
UseWindow("toto")
293
OpenCom
Com port management function. Function not available anymore since Windows
XP.
The OpenCom function opens the specified Com port. Not available in WinTask
Lite.
Syntax
ret=OpenCom(<port_num>,<speed>,<parity$>,<databits>,<stopbits>,<flowctl
$>)
Parameters
<port_numt>: Com port number to open (from 1 to 8, Com1 to Com8).
<speed>: port speed, integer with the following possible values:
75, 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 56000,
57600
<parity$>: one character for the parity ; possible values are :
N
none (no parity)
E
even (even parity)
O
odd (odd parity)
M
mark
S
space
<databits>: data bits, integer with the following possible values:
4, 5, 6, 7, 8.
<stopbits>: stop bits, integer with the following possible values:
1, 2 or 3 (3 is the code for a stopbit with a value of 1.5) .
<flowctl$>: one character for the flow control ; possible values are:
N
none
R
RTS/CTS
X
Xon/Xoff
Return value
Ret, numeric return code. If the specified Com port has been opened correctly,
the function returns 0, otherwise use this return code for Error Handling.
Remarks
Parameters can be in uppercase or lowercase.
WinTask allocates a 1024-byte buffer for receiving characters from the com port.
This buffer can be read by the ReadCom function.
See also
CloseCom, WriteCom, ReadCom
Example
ret=OpenCom(1,9600,"n",8,1,"n")
Opens the serial port Com1 for 9600 bits per second, no parity, 8 databits, 1
stop bit and no flow control.
294
OsVersion$
System function.
The OsVersion$ function returns the Windows version.
Syntax
var$=OsVersion$()
Return value
var$, string, Windows version.
Example
OsVersion$()
Example code
This script shows a function which returns a string containing OS version.
'Function donne_Os$ returns a string containing OS version :
'95 Windows 95
'98 Windows 96
'Me Windows Millenium Edition
'nt Windows NT
'2000 Windows 2000
'XP Windows XP
'2003 Windows 2003 Server
'Vista
function donne_Os$()
local os$
os$=left$(OsVersion$(),4)
Select Case os$
Case "4.10"
os$="98"
Case "4.00"
'to know if it's 95 or nt, you must read the OS environment variable
osvar$=envir$("OS")
if osvar$="Windows_NT" then
os$="nt"
else
os$="95"
endif
Case "4.90"
os$="Me"
Case "5.00"
os$="2000"
295
Case "5.01"
os$="XP"
Case "5.02"
os$="2003"
Case "6.00"
os$="Vista"
Case Else
os$="Unknown Version"
EndSelect
donne_os$=os$
endfunction
'--------------------------------------------------a$=donne_os$()
msgbox("Windows "+a$)
296
OverHTMLElement
Web function.
The OverHTMLElement function puts the mouse on a specified html element
and opens the options under it.
Usage
On some Websites, menus are displayed dynamically : it's only when you move
the mouse on a menu option that the sub-menu is displayed. OverHTMLElement
function deals with this case. You can generate automatically the proper
OverHTMLElement line in Recording mode by recording a mouse move on the text
of the menu option, then press Shift key, then record the next action.
Syntax
ret=OverHTMLElement(<html_descriptor> [,<x>,<y>])
Parameters
<html_descriptor>, unique identifier for the HTML element to move the mouse on
within the current Web page specified by the last UsePage. See HTML descriptor
for each HTML objects identification. Use Recording mode for generating
automatically the OverHTMLElement syntax : in Recording mode, move manually
the mouse on the text of the menu option, press once Shift key, and then record
the next action.
<x>,<y>, optional, mouse coordinates relative to the element : it can be used
for moving the mouse slightly besides the element.
Return value
Ret, numeric return code. If the specified HTML element at replay is found within
30 seconds (this default value can be changed using #ActionTimeout), the
function returns 0. Otherwise use this return code for Error Handling.
Example
StartBrowser("IE","www.wintask.com")
UsePage("Macro and Data Extraction with WinTask - the automation software
for Windows and internet")
OverHTMLElement("A[INNERTEXT= 'Overview']")
ClickHTMLElement("A[INNERTEXT= 'Features']")
At replay, the OverHTMLElement moves the mouse to the top menu Overview,
which opens the Overview menu. In this menu, there is a Features option which
is clicked by the ClickHTMLElement line.
297
Pause
Synchronization function.
The Pause function waits for an action or for a specified amount of time.
Usage
Used to pause execution of the script until a process has completed. If the
process completion time is variable, instead of using an "absolute" pause, prefer
to use a wait for a window to appear, a text or a bitmap to be displayed.
For example, the line:
pause 10 ticks
pauses script execution for 10 ticks. A tick is approximately 0.01 seconds
Syntax
Wait for a specified amount of time
Pause x Secs|Mins|Ticks|Hours ' a tick is approximately 0.01 sec
[EndPause]
Wait for a user action
Pause [x secs] until
Button(<Button>,<Type>) 'wait for a mouse click
or
Key(<key_list>) ' wait for a keyboard action
or
Menu(<menu_item>) ' wait for a selection in a menu
InWindow(<window_name>)
or
InModule("xxx.EXE") ' the keyword "InModule" allows you to synchronize with
several windows of the same application.
[PauseOK|PauseTrue]
' after the pause condition is met, these statements are executed
[PauseFalse]
' If after the specified x secs or if not specified, after #PauseTimeout system
variable, the pause condition is not met, the PauseFalse statement is executed
MsgBox("Pause at line "+ #ErrorLine$ +" has failed !",16,"Runtime error")
End
EndPause
Synchronizations
Synchronization on Text:
Pause [x secs|ticks] until
Text(<Text>)
InWindow(<window_name>,<instance>)|InWindowAnyInstance((<window_nam
e>)
[InArea(<x>,<y>,<height>,<width>)]
[PauseOK|PauseTrue]
'pause condition was met
[PauseFalse]
' If after the specified x secs or x ticks, or if not specified, after #PauseTimeout
system variable, the pause condition is not met, the PauseFalse statement is
executed
MsgBox("Pause at line "+ #ErrorLine$ +" has failed !",16,"Runtime error")
End
EndPause
298
The optional keyword "InArea" specifies that <Text> must be in a specific area of
window <window_name> for the pause to be activated.
If InWindowAnyInstance keyword is used, the <Text> is searched in any
instance of <window_name>
Synchronization on OCR Text:
(See Remarks section for a proper usage of this Pause)
Pause [x secs] until
TextOCR(<Text> [,<language>])
InWindow(<window_name>)
[InArea(<x>,<y>,<height>,<width>)]
[PauseOK|PauseTrue]
'pause condition was met
[PauseFalse]
' If after the specified x secs or if not specified, after #PauseTimeout system
variable, the pause condition is not met, the PauseFalse statement is executed
MsgBox("Pause at line "+ #ErrorLine$ +" has failed !",16,"Runtime error")
End
EndPause
The optional keyword "InArea" specifies that <Text> must be in a specific area of
window <window_name> for the pause to be activated.
At execution, a bitmap capture is done for capturing the specified area within the
specified window. The captured bitmap is then submitted at the OCR engine
which transforms the bitmap in text. Then the text specified in the TextOCR line
is compared to the captured and transformed text at execution. If the same text
is found, the Pause triggers. The OCR engine uses the default language of
Windows. If <language> is specified in TextOCR line, this language is used
(applies only to MODI OCR engine).
Synchronization on an Image:
Pause [x secs|ticks] until
Bitmap(<filename.BMP>)
InWindow(<window_name>)
[InArea(<x>,<y>,<height>,<width>)]
[PauseOK|PauseTrue]
'pause condition was met
[PauseFalse]
' If after the specified x secs or x ticks, or if not specified, after #PauseTimeout
system variable, the pause condition is not met, the PauseFalse statement is
executed
MsgBox("Pause at line "+ #ErrorLine$ +" has failed !",16,"Runtime error")
End
EndPause
The optional keyword "InArea" specifies that the bitmap must be in a specific
area of window <window_name> for the pause to be activated.
Synchronization on a Window:
Pause [x secs] until
WinStatus(Exists|NotExists|Active|NotActive [,Exact|Near])
InWindow(<window_name>,<instance>)|InWindowAnyInstance(<window_name
>)
[PauseOK|PauseTrue]
'pause condition was met
[PauseFalse]
299
' If after the specified x secs, or if not specified, after #PauseTimeout system
variable, the pause condition is not met, the PauseFalse statement is executed
MsgBox("Pause at line "+ #ErrorLine$ +" has failed !",16,"Runtime error")
End
EndPause
Keyword "WinStatus" specifies the window status which will activate the pause.
If none of keyword "Exact" or "Near" is specified, keyword "Near" is used by
default, which means pause will be activated if a window with a name
approaching <window_name> is found. If "Exact" is specified, the exact
<window_name> must be found in order to activate the pause. You can truncate
the window name and still use "Exact" keyword : it will detect a window which
window name has the same beginning as the one specified in the InWindow line.
InWindow specifies the <window_name> with its <instance> to look for. If
InWindowAnyInstance is used instead of InWindow, the <window_name>
whatever its instance is used.
Synchronization on a Date/Time:
Pause until
Date(<date_definition>)
Time(<hour_definition>)
EndPause
( Note: the '[x secs|ticks] until' clause is not used with Date or Time definitions)
Parameters
x secs or x ticks is optional ; if not specified, the #PauseTimeout system variable
is used. Pause 10 is the same as Pause 10 secs. A tick is around 0.01 second.
The structure :
PauseFalse
MsgBox("Pause at line "+ #ErrorLine$ +" has failed !",16,"Runtime error")
End
displays a dialog box and stops the script execution if the delay x seconds (or
#PauseTimeout) has elapsed. If x secs is not specified and if #PauseTimeout=0,
the wait is infinite. The structure PauseFalse ... End can be omitted or the
statements can be changed as in the example below :
Pause until
Button(left,down)
PauseFalse
If stopimmediate=1 then
stop
else
comment("we write just this message in the logfile "+#ErrorLine$)
endif
EndPause
PauseOK (PauseTrue has the same meaning than PauseOK) and PauseFalse are
optional.
Mouse :
<button> : Right or Left
<type> : Up or Down or Double
Menu :
<menu_item>, for instance &Edit|&Copy
<day_definition> : the day (ex : Tuesday) or date in DD-MM-YYYY format (for
example : 21-04-2001)
300
<hour_definition> : time in 24-hour HH:MM format (for example : 13:30)
Remarks
NOTE : If a PAUSE n SECS or n TICKS is the last line just before an UNTIL, the
compiler gives an error, so insert the EndPause statement just before the Until.
Pause TextOCR compared to Pause Bitmap : both addresses the case where
the text displayed within the window cannot be recognized as pure text. We
explain here the advantages and drawbacks of each Pause. A pause TextOCR
captures the defined area, submits the image to the OCR engine and the Pause
triggers if the OCRerized text is seen - then if the text is not seen, the Pause
waits around 1 sec before starting again the recognition attempt. So the main
drawback of the Pause TextOCR is that it takes a while, the OCR engine can take
up to 3-4 secs. There are 3 advantages compared to a Pause bitmap : no extra
file for the captured image, a more readable Pause block as the text is seen in the
script and the Pause will work even when you distribute the script on other PCs as
the bitmap capture is done at execution.
Pause bitmap at execution captures the defined area and compares it to the
specified bmp file. If ticks unit is used in the Pause bitmap, as soon as TaskExec
sees that it does not trigger, it captures again and compares again, and so on. So
with ticks unit, the Pause bitmap can take up to 100% of CPU but will be very
fast to execute. If secs unit is used, when the image is not found, the Pause
bitmap waits around 1 sec before starting again to capture the defined area. So
whatever ticks or secs unit used, a Pause Bitmap will be always faster than a
Pause TextOCR.
Examples
Pause until
Date(20-1-2007)
Time(10:16)
EndPause
a$="19-1-2007"
b$="21:06"
Pause until
Date(a$)
Time(b$)
EndPause
Example code
This example shows how to use a wait_text Function to synchronize repeatedly in
a script.
Function wait_text(timeout)
local res
res=1
pause timeout seconds until
Text("toto")
InWindow("NOTEPAD.EXE|Edit|Untitled - Notepad|1",1)
PauseFalse
Res=0
EndPause
301
wait_text=res
Endfunction
' the function is called as follows :
If wait_text(10)=0 then
...
Else
...
Endif
This example shows how to use a pause_on_two_bmp Function to wait until one
of the two specified bmp appears.
function pause_on_two_bmp(win1$,bmp1$,win2$,bmp2$)
local sortie, ret, t
repeat
Pause 1 until
Bitmap(bmp1$)
InWindow(win1$)
PauseOk
ret=1
EndPause
pause 1 until
Bitmap(bmp2$)
InWindow(win2$)
PauseOk
ret=2
EndPause
if ret=0 then
t=t+1
endif
until ret<>0 or t > #PauseTimeout
pause_on_two_bmp_bmp=ret
Endfunction
'Call example
win1$="AD-AWARE.EXE|TACimage|Ad-Aware SE Personal|16"
win2$="AD-AWARE.EXE|TACimage|Ad-Aware SE Personal|16"
bmp1$="C:\Program Files\WinTask\Scripts\aaw_next.bmp"
bmp2$="C:\Program Files\WinTask\Scripts\aaw_finish.bmp"
'Maximum timeout before pause on the 2 bmp fails.
#PauseTimeout=400
pause_on_two_bmp(win1$,bmp1$,win2$,bmp2$)
If pause_on_two_bmp=0 then
msgbox("None of the two specified bmp has been found")
End
Endif
302
#PauseTimeout
System variable - Synchronization
The #PauseTimeout system variable specifies the maximum delay for a Pause
statement before an error occurs.
Usage
As soon as a #PauseTimeout= a value (for example #PauseTimeout=300) is
encountered in the script, the Pause statements use this new value instead of the
120 seconds default value to wait before a Pause fails.
Syntax
#PauseTimeout = <integer>
Parameters
<integer>, numeric in seconds (default value is 120 seconds); if after <integer>
seconds, the Text or the image have not been seen by the Pause function, the
statements following the PauseFalse keyword in the Pause function are executed:
a dialog box is displayed and the script is stopped.
If this system variable is set to 0, the pause is infinite.
Example
#PauseTimeout=20
303
PeekInteger
System function.
The PeekInteger function reads one or more bytes in memory and returns an
integer. Not available in WinTask Lite.
Syntax
var=PeekInteger(<address>,<number_of_bytes>)
Parameters
<address>: UNSIGNED variable, memory is read starting at this address. The
variable must be declared beforehand.
<number_of_bytes>: 1, 2 or 4 bytes to be read
Return value
var, return value, integer or UNSIGNED. If an error occurs during execution, no
matter what the setting of #IgnoreErrors, an error message is displayed and the
script is stopped.
Example
DIM ahandle as UNSIGNED
...
handle=PeekInteger(ahandle,2)
304
PeekString$
System function.
The PeekString$ function reads a string in memory. Not available in WinTask
Lite.
Syntax
var$=PeekString$(<address> [, Unicode])
Parameters
<address>: UNSIGNED, memory is read starting at this address until the end of
string character (binary zero) is found.
Unicode is an optional parameter, keyword which tells that the returned string
uses Unicode encoding.
Return value
var$, return value, string. If an error occurs during execution, no matter what the
setting of #IgnoreErrors, an error message is displayed and the script is stopped.
Example
message$=PeekString$(address_string)
Example code
'memory address
dim pointer as unsigned
'memory allocation
pointer=allocate(64)
'prepare a variable for the return value
wdir$=" "
'write the blank string to memory
ret=PokeString(pointer,wdir$,0)
'In Win32, an A must be added to functions returning an ASCII string
a=External("kernel32","GetWindowsDirectoryA",pointer,64)
'read the string at the given memory address
var$=peekString$(pointer)
msgbox(var$)
Example code using Unicode
'memory address
305
dim pointer as unsigned
'memory allocation
pointer=allocate(64)
'prepare a variable for the return value
wdir$=" "
'write the blank string to memory
ret=PokeString(pointer,wdir$,0)
'In Win32, an W must be added to functions returning a Unicode string
a=External("kernel32","GetWindowsDirectoryW",pointer,64)
'read the string at the given memory address
var$=peekString$(pointer,Unicode)
msgbox(var$)
306
PokeInteger
System function.
The PokeInteger function writes a value of type Integer or Unsigned to memory.
Not available in WinTask Lite.
Syntax
PokeInteger(<address>,<value>,<number_of_bytes>)
or
ret=PokeInteger(<address>,<value>,<number_of_bytes>)
Parameters
<address>: integer or UNSIGNED, address to which <value> is written.
<number_of_bytes>: 1, 2 or 4.
Return value
ret, numeric return code. When <value> has been written successfully, the
function returns 0, otherwise use this return code for Error Handling.
Example
dim Myvalue as unsigned
Myvalue=32500
ret=PokeInteger(MemPtr,myvalue,4)
Example code
'ASCII code
'77 121 32 115 116 114 105 110 103
'M y s t r i n g
dim pointer as unsigned
dim address as unsigned
'Writes a string to memory
pointer=allocate(32)
ret=PokeString(pointer,"My string",1)
'reads the string as integers (ASCII codes)
i=0
repeat
address=pointer+i
var=PeekInteger(address,1)
mes$=mes$+"Byte "+str$(1+i)+" : "+str$(var)+"\n\"
i=i+1
until i=8
msgbox(mes$,64,"Reads in memory")
307
'--------------------------------------------------------------'Writes integer in memory (ASCII codes)
pointer=allocate(32)
address=pointer
ret=PokeInteger(pointer,77,1)
pointer=pointer+1
ret=PokeInteger(pointer,121,1)
pointer=pointer+1
ret=PokeInteger(pointer,32,1)
pointer=pointer+1
ret=PokeInteger(pointer,115,1)
pointer=pointer+1
ret=PokeInteger(pointer,116,1)
pointer=pointer+1
ret=PokeInteger(pointer,114,1)
pointer=pointer+1
ret=PokeInteger(pointer,105,1)
pointer=pointer+1
ret=PokeInteger(pointer,110,1)
pointer=pointer+1
ret=PokeInteger(pointer,103,1)
'0 binary for end of string
pointer=pointer+1
ret=PokeInteger(pointer,0,1)
var$=PeekString$(address)
msgbox("String read : "+var$,64,"Memory read")
308
PokeString
System function.
The PokeString function writes a string to memory. Not available in WinTask
Lite.
Syntax
PokeString(<address>,<string>[,<term> [,Unicode]])
or
ret=PokeString(<address>,<string>[,<term> [,Unicode]])
Parameters
<address>: UNSIGNED, address to which <string> is written.
<term>: number, to indicate if an end of string character must be added. 0: no
character is added, 1: a binary zero is added (default value), 2: two binary
zeroes are added.
Unicode: optional keyword. It tells that the string to write to memory is written
using Unicode encoding.
Return value
ret, numeric return code. When <string> has been written successfully, the
function returns 0, otherwise use this return code for Error Handling.
Example
dim Memptr as unsigned
Memptr=32500
ret=PokeString(MemPtr,"My string",1)
Example code
'memory address
dim pointer as unsigned
'memory allocation
pointer=allocate(64)
'prepare a variable for the return value
wdir$=" "
'write the blank string to memory
ret=PokeString(pointer,wdir$,0)
'In Win32, an A must be added to functions returning an ASCII string
a=External("kernel32","GetWindowsDirectoryA",pointer,64)
'read the string at the given memory address
var$=peekString$(pointer)
309
PostData
Web function.
The PostData function fills the fields of a Web form just before the next Navigate
submits it.
The PostData function must not be used anymore since WinTask version 2.5. It
is kept only for compatibility with previous versions.
You fill now a Web form by using the WriteHTML function which is generated
automatically by the Recording mode.
310
#Precision
System variable - Floating point calculation functions.
The #Precision system variable specifies the number of decimal places for
floating point calculation functions.
Syntax
#Precision = n
Remarks
The default value is 2.
Example
#Precision = 3
311
Program structure
The program structure must be :
1. declarations with DIM
2. Functions and Subs, in the correct order. That is : if sub a() calls
sub b(), then the definition of b must precede the definition of a.
3. main program and other code
If INCLUDE is used, the entire program with all the inclusions must conform to
this structure.
312
Random
System function.
The Random function returns a random integer between 0 and the specified
value.
Syntax
Random(<val>)
or
ret=Random(<val>)
Parameters
<val>, integer (at least 1)
Return value
Ret, random integer between 0 and <val>.
Example
a=Random(5000)
MsgBox(str$(a))
313
Read
File management function.
The Read function reads data from the specified file.
Usage
You read data from an external souce, a text file. For example, in a loop, you
read each record stored in a text file, send the data to another application and
the loop ends when the end of file is reached.
Syntax
Read(<filename>,<buffer>)
Read(<filename>,<buffer>,<n>)
Read(<filename>,<buffer>,<sep$>)
Read(<filename>,<buffer>,CRLF)
or
ret=Read(<filename>,<buffer>)
ret=Read(<filename>,<buffer>,<n>)
ret=Read(<filename>,<buffer>,<sep$>)
ret=Read(<filename>,<buffer>,CRLF)
Parameters
<filename>, string, name of the file to read. It is a string which can be a constant
or a variable. Long names and UNC names are accepted, such as
\\Server\c\my_directory\my_file.txt. If the path is not specified, the file is
searched in the current directory.
<buffer>, string ; it must be a variable. The maximum size is 32K. The variable is
filled with the result of the Read function.
The Read is done sequentially starting at the read pointer associated with the file.
After a Read, the pointer is automatically moved to the next byte not already
read. Between two Reads, you can move the pointer by using the
SetReadPos(<filename>) statement. If a Read encounters the end of file, then
EOF(<filename>) is set to 1.
If the length of <filename> is less than 32K (maximum size of a string variable),
the entire file is copied into the variable <buffer>, and EOF(<filename>) is set to
1; if the length is more than 32K, <buffer> contains the first 32K of the file and
the read pointer is set for reading the next 32K.
<n>, integer, number of bytes to read. If the length of <filename> is less than n,
the entire files is copied into the variable <buffer> and EOF(<filename>) is set to
1, if the length is more than n, <buffer> contains the first n bytes and the read
pointer is set for reading the following n bytes.
<sep$>, string (variable or constant). The Read is performed until the next
occurrence of <sep$>. <buffer> contains the bytes read between the initial
position until sep$ (sep$ is not placed in <buffer>). The read pointer is set to the
next character following sep$.
If sep$ is not found during a Read:
end of file has been reached; <buffer> contains the bytes between the
read pointer and the end of file. EOF(<filename>) is set to 1.
or end of file has not been reached and <buffer> contains the 32K
following the pointer.
314
CRLF : carriage-return-line-feed keyword (chr$(13)+chr$(10)). The file is read
line by line.
Return value
Ret, numeric return code. When the read is successful, the function returns 0,
otherwise use this return code for Error Handling.
Examples
Read(file$,var$)
Read("c:\sample.txt", var$)
Read(file$,var$,80) ' puts the next 80 characters in var$
Read(file$,var$,n) ' puts the next n characters in var$
Read(file$,var$,CRLF) ' puts the next line of file$ in var$
Read(file$,var$,"mark") ' puts the characters between the pointer and "mark" in
var$, but var$ does not include "mark"
Example code
This script reads the autoexec.bat file.
msgbox(OsVersion$())
FileName$="c:\autoexec.bat"
repeat
Read(FileName$,result$,CRLF)
display$=display$+"\n\"+result$
until eof(FileName$)=1
msgbox(display$,0,"Autoexec.bat File")
This script reads two files simultaneously. It explains the use of the two
commands GetReadPos and SetReadPos. It creates, writes and reads files
FileName1$="c:\file1.txt"
FileName2$="c:\file2.txt"
create(FileName1$)
create(FileName2$)
'write into file1.txt "File 1 Line 1")
Write(FileName1$,"File 1 Line 1",CRLF)
'write into file1.txt "File 1 Line 2"
delim$="Line 2"+CRLF
Write(FileName1$,"File 1 ",delim$)
'write into file1.txt "File 1 Line 3"
delim$=CRLF
Write(FileName1$,"File 1 ")
315
Write(FileName1$,"Line 3",Delim$)
'write 4 different lines into file2.txt
awrite$="File 2 Line 1"+CRLF+"File 2 Line 2"+CRLF+"File 2 Line 3"+CRLF+"File
2 Line 4"
write(Filename2$,awrite$)
'loop reading the files File1.txt and File2.txt
display1$="Sequential reading of the file File1.txt : "+"\n\"
display2$="Sequential reading of the file File2.txt : "+"\n\"
i=0
repeat
result$=""
if eof(FileName1$)<>1 then 'if we are not at the end of the file
read(FileName1$,Result$,CRLF)
endif
'after having read the last record, eof is positioned to 1
display1$=display1$+"\n\"+result$
result$=""
if eof(FileName2$)<>1 then 'if we are not at the end of the file
read(FileName2$,Result$,CRLF)
endif
'after having read the last record, eof is positioned to 1
display2$=display2$+"\n\"+result$
pause 1
MsgFrame(display1$,1,5,10,8)
MsgFrame(display2$,2,230,10,8)
i=i+1
if i=1 then 'if we have just read the first record
FilePos1=GetReadPos(FileName1$)
'we remember the position of the pointer of the file 1
endif
if i=3 then 'if we have just read the fourth record
FilePos2=GetReadPos(FileName2$)
316
'we remember the position of the pointer of the file 2
endif
until eof(FileName1$)=1 and eof(FileName2$)=1
SetReadPos(FileName1$,0)
'this is how to reposition to the beginning of file 1
SetReadPos(FileName2$,0)
'this is how to reposition to the beginning of file 2
'management of the pointers of files
MsgFrame("** Reading of the files by using SetReadPos **",9,40,160,8)
FileRead1$="Reading record 2 in file 1"+"\n\\n\"
FileRead2$="Reading record 4 in file 2"+"\n\\n\"
'we go back to the second record (previously saved)
SetReadPos(FileName1$,FilePos1)
read(FileName1$,result$,CRLF) 'to read second line
FileRead1$=FileRead1$+"\n\"+result$
MsgFrame(FileRead1$,3,5,220,8)
pause 4
SetReadPos(FileName2$,FilePos2)
read(FileName2$,result$,CRLF) 'to read second line
FileRead2$=FileRead2$+"\n\"+result$
MsgFrame(FileRead2$,3,5,220,8)
pause 4
317
ReadCom
Com port management function. Function not available anymore since Windows
XP.
The ReadCom function reads the specified number of characters from the FIFO
buffer of the specified Com port. Not available in WinTask Lite.
Syntax
ret=ReadCom(<num_port>,<numbytes>,<char$>)
Parameters
<num_port>: Com port number from which to read (from 1 to 8, Com1 to
Com8).
<numbytes>: number of bytes to be read from the Com port buffer.
<char$>: character string variable used to receive the characters.
Return value
Ret, numeric return code. If the specified Com port has not yet been opened, the
function returns 8; you can use this return code for Error Handling.
If <numbytes> is 0 or is equal to the number of characters available in the
buffer, all the characters in the buffer are read and the buffer is emptied. The
return code is then 0.
If no characters are in the buffer or if less than <numbytes> characters are
available in the buffer, the return code is 13.
If numbytes < number of characters available in the buffer, return code is 12.
See also
OpenCom, WriteCom, CloseCom
Example
result$=""
Ret=OpenCom(1,9600,"n",8,1,"n")
Ret=ReadCom(1,3,result$) ' Reads the first 3 characters of Com1 buffer
Example code
For this example, you must connect two PCs with a NULL MODEM cable (using
COM1).
The sending program installed on one of the PCs sends a 20 character string. The
receiving program installed on the other PC waits until the sender sends a 20character string to it.
Settings for the Com port are :
No flow control, COM1, Speed 9600, no parity, 8 data bits, 1 stop bit.
'******************************************************
'**************** Sending program *********************
'******************************************************
res=OpenCom(1,9600, "n",8,1, "n" )
SendVar$="SERIAL PORT TEST"
318
' the string SendVar$ will be sent to the serial port.
res=WriteCom(portnum, SendVar $)
res=CloseCom(1)
'******************************************************
'************* Receiving program **********************
'******************************************************
sub main(ByteNb)
var$=""
res = ReadCom(1, ByteNb,var$)
Select Case res
Case 0
' we emptied the buffer, we received the 20 characters
message$=message$+var$
out=1
Case 13
'it there are not 20 characters in the buffer, it is necessary to make
another
' read but with the number of characters equal to the number of characters
still
' in the buffer
message$=message$+var$
i=i-len(var$)
Case Else
msgbox("unexpected characters"+str$(res))
stop
EndSelect
Endsub
res=OpenCom(1,9600, "n",8,1, "n" )
i=20
out=0
message$=""
repeat
main(i)
until out=1
res=CloseCom(1)
msgbox(message$,32,"Received")
319
320
ReadExcel
File management function.
The ReadExcel function reads a cell, a row or a column from an Excel workbook.
Microsoft Excel must be installed on the PC, but does not have to be open. The
workbook itself can be already open or not in Excel at the time of the ReadExcel.
Usage
You read data from an external souce, an Excel file. For example, you populate 3
arrays reading three columns in an Excel file, first one is First name, second is
Last name, third is Town, and in a loop, you submit to a yellow pages Web site
those three data for capturing phone numbers.
Syntax
ReadExcel(<workbook>,<range_descriptor>,<array_result$>[,<readPasswd$>])
or
ret=ReadExcel(<workbook>,<range_descriptor>,<array_result$>[,<readPasswd
$>])
Parameters
<workbook>, string, name of the Excel workbook to read from. It is a string
which can be a constant or a variable. Long names and UNC names are accepted,
such as \\Server\c\my_directory\my_file.xls. If the path is not specified, the file
is searched in the current directory.
<range_descriptor>, string. If only one sheet exists in the workbook, only the
range of cells must be specified, such as A4:F4 for a row or A2:A12 for a column.
If multiple sheets exist in the workbook, the required syntax is
"sheet_name!range_of_cells" ; for example, TOOLS!A9:F9
Other range examples: mycell1 (a named cell), A1, A3:B3, tools!$b$2:$b$4
<array_result$>, array of strings. The array must be declared at the beginning of
the script using Dim. The contents of the cells specified in <range_descriptor> is
placed into this array, beginning with element 0.
<readPasswd$>, optional string parameter; password for reading the
<workbook> if needed.
Return value
Ret, numeric return code. When the read is successful, the function returns the
number of cells read, otherwise use this return code for Error Handling. The
return code is -1 if an error is reported by Excel or the range is not a single cell, a
column or a row, the return code is -2 if the array is smaller than the number of
cells read.
See also
WriteExcel
CloseExcelCom
Excel, useful functions
How to read all the lines of an Excel worksheet until the cell in the first column is
empty
Capture data from a web site and write them in an Excel file
321
Example
dim array$(20)
ret=ReadExcel("C:\My documents\myexcel_file.xls","TOOLS!A9:F9",array$())
msgbox(ret,,"number of cells read")
Example code
The script below reads all the lines from an Excel file from A column to C column
and writes them in another Excel file.
dim arrayline$(10)
fileexcel$="c:\example1.xls"
filetowritein$="c:\test.xls"
j=1
repeat
' The complex string "sheet1!"+"a"+str$(j)+":c"+str$(j) means if j=1
' "Sheet1!a1:c1"
readexcel(fileexcel$,"sheet1!"+"a"+str$(j)+":c"+str$(j),arrayline$())
WriteExcel(filetowritein$,"sheet1!"+"a"+str$(j)+":c"+str$(j),arrayline$())
j=j+1
until arrayline$(0)=""
322
ReadIni$
System function.
The ReadIni$ function reads a parameter in the specified INI file. Not available
in WinTask Lite.
Usage
An INI file is easy to manage when external data have to be shared with one or
several scripts. Data are organized properly and ReadIni$ function accesses
directly the desired data without dealing with read pointers, End Of File character,
record separator character, ...
Syntax
var$=Readini$(<filename>,<Section>,<Item>,<Default>)
Parameters
<filename>: string; INI file to be read. It is a string which can be a constant or a
variable. UNC names are accepted. If the path is not specified, the file is searched
in the Windows directory.
<Section>: string, section to be read from the INI file.
<Item>: string, item to be read from the INI file.
Return value
Var$: return value, string containing the desired parameter from the INI file.
If the file <filename> or the section <Section> or the item <Item> do not exist,
the value <Default> is returned.
See also
WriteIni
Example
Assume SAMPLE.INI contains:
[Section1]
Item1 = 123
Item2 =
var$=ReadIni$("sample.ini", "Section1","Item1","Default")
Returns "123" in var$
var$=ReadIni$("sample.ini", "Section1","Item2","Default")
Returns an empty string ("") in var$
var$=ReadIni$("sample.ini", "Section2","Item2","Default")
Returns "Default" in var$
323
ReadReg
System function.
The ReadReg function reads a string or an integer from the Windows Registry.
Not available in WinTask Lite.
Syntax
ReadReg(<path>,<type>,<returned value>)
or
ret=ReadReg(<path>,<type>,<returned value>)
Parameters
<path>: entire path before the value (not the key).
For example :
"HKEY_LOCAL_MACHINE\SOFTWARE\TaskWare\WinTask\1.0\Name"
To read the default value of a key (named Default), use the entire path of the key
and end with the character \
<type> can be :
1
string
2
string expand
3
binary
4
integer or dword
7
string multiple
If <type> is 1 or 2, a string is returned; if it is 7, a string is also returned but the
binary zeroes separating the multiple strings are changed to \n\ and the ending
double binary 0 is not returned. If <type> is 3 (binary), a string is returned
containing a hexadecimal conversion of the binary value. A <type> of 4 returns
an integer.
Return value
Ret, numeric return code. When the read is successful, the function returns 0,
otherwise use this return code for Error Handling. If the return code is not zero,
an empty or null value is returned in <returned value>.
Remarks
If there is an inconsistency between the specified <type> and the type of the
returned value, a compilation error is generated.
Example
ReadReg("HKEY_LOCAL_MACHINE\SOFTWARE\TaskWare\WinTask\1.0\Name",1,name$)
324
Reboot
System function.
The Reboot function reboots the PC or restarts Windows.
Syntax
Reboot(<code>)
or
ret=Reboot(<code>)
Parameters
<code>, numeric according to:
0
Restarts Windows
2
Restarts Windows and the PC (warmboot)
4
Puts the PC in suspend mode (only NT and 2000)
8
Stops the PC
If an application cannot be closed, the system is not rebooted (for instance, when
a document has not been saved and a dialog box appears).
Return value
Ret, numeric return code. When the reboot is successful, the function returns 0,
otherwise use this return code for error management.
Example
Reboot(0)
325
Rem
Compilation.
The Rem statement inserts a comment in the script.
Syntax
Rem <text_comment>
or
' <text_comment>
Parameters
<text_comment>, any text. Any text following the keyword Rem or the character
' is not executed when running the script.
Remarks
You can comment a full block of lines inserting the characters /* at the beginning
of the first line of the block and putting the characters */ at the end of the last
line of the block.
Examples
Rem text blabla
'text blabla
Reboot(0) ' restarts Windows
/* All the lines are comments
A second line
A third line
*/
Msgbox("end of the comments")
326
RemoveFrame
User dialog function.
The RemoveFrame function removes the message displayed by MsgFrame.
Syntax
RemoveFrame(<Id>)
Parameter
<Id>, integer, identifier of this message as defined by MsgFrame.
See also
MsgFrame
MsgFrameTitle
Example
RemoveFrame(1) ' Removes the message displayed by MsgFrame("Wait",1)
327
Repeat...until...
Program flow management function.
The Repeat...until structure defines a loop with a completion check at the end of
the loop.
Usage
Used to repeat the same steps a certain number of times or until a condition is
true.
Syntax
Repeat
<statements>
Until <boolean_expression>
Parameters
<statements>: statements to be executed until <boolean_expression> becomes
true.
Remarks
In a REPEAT statement (unlike a While statement), <statements> are always
executed at least once.
If PAUSE n SECS or PAUSE n TICKS is the last line before UNTIL, use the
statement EndPause to close this Pause block, or the compiler will generate the
error message Invalid Pause ... Until.
See also
Logical operators
Example
a = 0
Repeat
beep (100)
a = a + 1
pause 300 ticks ' same as 3 seconds
EndPause
Until a = 5
328
Replace$
String management function.
The Replace$ function finds and replaces some or all occurrences of a substring
within the specified string.
Usage
Same usage as the Replace option in an Edit menu.
Syntax
var$=Replace$(<string>,<search_string>,<replacing_string>
[,<number_of_occurrences> [<start_position>,<end_position>]])
Parameters
<string>, string in which to find and replace
<search_string>, string to search for within <string>
<replacing_string>, string replacing <search_string> when this substring is
found
<number_of_occurrences>, numeric, optional parameter to specify how many
times the find/replace must be done. If this parameter is omitted or is at 0, the
find/replace is done on all the occurrences.
<start_position>, numeric, optional parameter. If specified, the find/replace is
done starting at the <start_position> character of <string>.
<end_position>, numeric, optional parameter. If specified, the find/replace is
done starting at the <start_position> character of <string> and ending at
<end_position> character of <string>.
Return value
var$, string with the replaced substrings.
Remarks
The find/replace is case sensitive.
Examples
a$="Hello WinTask, Hellobis"
var$=replace$(a$,"Hello","Hi")
msgbox(var$) ' displays Hi WinTask, Hibis
a$="Hello WinTask, Hellobis"
var$=replace$(a$,"Hello","Hi",1)
msgbox(var$) ' displays Hi WinTask, Hellobis
a$="Hello WinTask, Hellobis"
var$=replace$(a$,"Hello","Hi",0,2,8)
msgbox(var$) ' displays Hello WinTask, Hellobis - no changes as the Hello word is
not found between the 2nd and 8th character.
329
ResetTimer
Response time function.
The ResetTimer function resets the specified clock. Not available in WinTask
Lite.
Syntax
ResetTimer(<clock_number>)
Parameters
<clock_number>: number of the clock to be reseted; valid values go from 1 to
10.
Even if the specified clock is not stopped, the function resets the clock to zero.
If <clock_number> is an invalid number, Error Handling rules are used.
See also
StartTimer, StopTimer, Timer
Examples
This script measures a connection time: connection is supposed achieved when
the text "connected" is displayed in the emulator window (window name :
my_emulator$).
ResetTimer(1)
'After having reset clock number 1, start clock number 1
StartTimer(1)
Pause until
Text("connected")
InWindow(my_emulator$)
EndPause
'Stop the timer
StopTimer(1)
'Timer function returns the result as a number in 1/100 sec.
Comment("connection made in : "+str$(Timer(1)/10))
This script measures how long it takes for a page on www.wintask.com to load
ResetTimer(1)
StartBrowser("IE", "www.wintask.com/demos")
UsePage("WinTask Demonstration Pages")
StartTimer(1)
ClickHTMLElement("A[INNERTEXT= 'Form']")
UsePage("Form")
'Stop the timer
StopTimer(1)
'Timer function returns the result as a number in 1/100 sec.
msgbox("Page How it works loaded in : "+str$(Timer(1))+" hundreds of a sec")
330
RestoreWindow
Windows management function.
The RestoreWindow function restores the specified window to its previous size.
Syntax
RestoreWindow(<window_name> [,<instance>])
or
ret=RestoreWindow(<window_name> [,<instance>])
Parameters
<window_name>, window name of the window to be restored.
<instance>, optional parameter, instance number of the window to be restored.
Return value
Ret, numeric return code. When the restore is successful, the function returns 0,
otherwise use this return code for Error Handling.
Examples
Result = RestoreWindow("NOTEPAD.EXE|Notepad|Untitled",1)
RestoreWindow(win$)
331
RevertToSelf
System function.
The RevertToSelf function cancels an impersonation made by ImpersonateUser.
Not available in WinTask Lite.
Syntax
RevertToSelf()
Parameters
None
See also
ImpersonateUser
Example
RevertToSelf()
332
Right$
String management function.
The Right$ function returns the specified number of characters in a string
starting from the right.
Syntax
var$=Right$(<string$>,<numcar>)
Parameters
<string$>, string from which to extract characters.
<numcar>, numeric, number of characters to extract from <string$>.
Return value
var$, string, return value containing the extracted characters. If <numcar> is
negative or 0, an empty string is returned. If <numcar> is greater than or equal
to the number of characters of <string$>, the entire string is returned.
See also
ExtractBetween$
Left$, Mid$
Examples
a$ = Right$("example",3) ' Returns "ple" in a$
a$ = Right$("example",0) ' Returns "" in a$
333
RmDir
System function.
The RmDir function deletes a directory.
Syntax
RmDir(<directory_name>)
or
ret=RmDir(<directory_name>)
Parameters
<directory_name>, string, name of the directory to delete.
Return value
Ret, numeric return code. When the deletion is successful, the function returns 0,
otherwise use this return code for Error Handling.
Remarks
The function works like the DOS statement RMDIR.
See also
MkDir
Examples
RmDir("c:\text")
RmDir(direct$)
334
Rtrim$
String management function.
The Rtrim$ function removes the trailing spaces/tabulations from a string.
Usage
Used to take spaces, tabulations and CRLF off the end of a text. To avoid spaces
added by mistake during data-entry, use this function.
Syntax
var$=Rtrim$(<string$>)
Parameters
<string$>, string to be trimmed.
Return value
var$, string, return value containing the trimmed string.
See also
Ltrim$
Trim$
Examples
a$ = Rtrim$("bcde ") ' Returns "bcde" in a$
a$ = Rtrim$(a$) ' Deletes the spaces at the end of a$
335
Run
Program flow control function.
The Run function launches a compiled script as a sub-program.
Syntax
Run( "Script_name[.rob] [<Arg_1> <Arg_2> ...<Arg_n>]")
or
Ret=Run( "Script_name[.rob] [<Arg_1> <Arg_2> ...<Arg_n>]")
Parameters
"script_name", string, compiled script to be executed.
If the script name contains spaces, you must surround the name by CHR$(34):
Run(chr$(34)+"C:\program files\WinTask\scripts\my_script"+chr$(34))
The statement Run("script2"+""param1 param2"") would cause a compilation
error since the character " is reserved for string definition ; you must replace the
character " by its ASCII equivalent, so the correct statement is:
Run("script2"+chr$(34)+"param1 param2"+chr$(34)).
You can also see an example in the Shell function.
<Arg_n>: optional parameters for the compiled script; these parameters can be
read by the Command$ function.
Return value
RetCode : numeric return code; 0 if the compiled script finishes correctly; or the
value defined by the programmer using the End function. If "script_name" is
empty, an error occurs at execution time (retcode=40). If the .ROB does not
exist, no matter how #IgnoreErrors is set, an error message is displayed and the
script is stopped.
Remarks
The values of system variables are valid only inside the script; so if a parent
script calls a child script through Run, the values of system variables set up in the
parent are not passed to the child script.
If you want to run an external program (a .EXE, a .BAT), use Shell function.
See also
Parameters passed from one script to another
Example
Result = Run("My_script userid pswd")
a$="my_script"
b$=a$ + " " + usrid$ + " " + pswd$
Result = Run(b$)
Example code
This example shows how to use the return code (End function)
Script1
File_to_find$="c:\program files\wintask\scripts\*.src"
336
Ret=Run("script2"+" "+chr$(34)+file_to_find$+chr$(34))
If Ret=-1 then
Mes$="Could not determine file count for "+file_to_find$
Else
Mes$="Number of file(s) "+File_to_find$+" : "+str$(Ret)
Endif
Msgbox(mes$)
Script2
Dim tab_name$(100)
Dim short_name$(100)
Dim att$(100)
#IgnoreErrors=1
Res=dir(command$(1), tab_name$(), short_name$(), att$(), "N")
' script2 return code is the return code of the Dir function
' Script1 can test for it
End(Res)
337
SavePictureAs
Web function.
The SavePictureAs function saves an HTML element referring to a picture.
Usage
It simulates a right click on an HTML element which is a picture and the selection
in the context menu of the Save Picture As option.
Syntax
ret=SavePictureAs(<html_descriptor>, <path> [,<filename>])
Parameters
<html_descriptor>, identifier for the HTML element to save. See HTML descriptor
for each HTML objects identification. Use Recording mode for generating
automatically the descriptor (just record a click on the picture).
<path>, string, directory where to save the file.
<filename>, string, optional parameter to force the name of the file under which
the image is saved. NOTE that the extension cannot be changed, the extension
stays the one as provided by the web site. <filename> MUST NOT include a path
or an extension.
When <filename> is not specified, the picture name is created from the url of the
picture. If for any reason, a valid name cannot be generated, SavePictureAs
generates an automatic filename, bitmapxxxx.
Return value
Ret, numeric return code. The function returns 0 if successfull. If the file cannot
be created (or overwritten), the function returns 26. If an Internet error occurs, a
negative error code is returned. You can use this return code for Error Handling.
List of negative error codes
-1
No browser in use (no previous UsePage or StartBrowser)
-3
Bad descriptor, invalid syntax
-4
The browser has been lost (for instance because of a Closewindow)
-5
Page not found
-8
Specified element not found
-12
Download timeout (the file could not be saved within the
#ActionTimeout time)
-11
Any other error
-404,405
Usual http error codes (requires IE 6 or above)
Remarks
If only the path is specified, the file is saved using the name provided by the web
page. If the specified directory does not exist, it is created.
At replay, the function waits for the HTML element to be displayed before saving
the picture. The timeout is the value of #ActionTimeout (the default is 30
seconds).
Example
On WinTask Web site, we save the image displaying WinTask books:
StartBrowser("IE","www.wintask.com")
UsePage("Macro and Data Extraction with WinTask - the automation software
for Windows and internet")
338
SavePictureAs("IMG[SRC= 'http://www.wintask.com/images/p']",
"c:\test","imageproduct")
CloseBrowser()
The image is saved under name imageproduct.jpg in the c:\test directory.
339
SaveTargetAs
Web function.
The SaveTargetAs function simulates a right click on an HTML element and
selection of Save Target as option in the context menu.
Usage
The function right clicks on an HTML element and selects in the context menu the
Save Target As option.
Syntax
ret=SaveTargetAs(<html_descriptor>, <path>,<extension>)
Parameters
<html_descriptor>, identifier for the HTML element to save. See HTML descriptor
for each HTML objects identification. Use Recording mode for generating
automatically the descriptor (just record a right click on the link).
<path>, string, directory where to save the file.
<extension>, string, extension for the saved file ("htm", "php" for examples). It
must be the correct extension as the one specified when you do the Save Target
As manually.
Return value
Ret, numeric return code. The function returns 0 if successfull. If the file cannot
be created (or overwritten), the function returns 26. If an Internet error occurs, a
negative error code is returned. The dialog boxes opened by the function (Save
as dialog box, File Download dialog box) are automatically closed if an error
occurs.
List of negative error codes
-1
No browser in use (no previous UsePage or StartBrowser)
-3
Bad descriptor, invalid syntax
-4
The browser has been lost (for instance because of a Closewindow)
-5
Page not found
-8
Specified element not found
-12
Download timeout (the file could not be saved within the
#ActionTimeout time)
-11
Any other error
-404,405
Usual http error codes
The return code can be used for Error Handling.
Remarks
Only the path and the extension are specified, the file is saved using the name
provided by the web page. If the specified directory does not exist, it is created.
If the file already exists, it is automatically replaced. If for any reason, the
existing file cannot be deleted before saving the new file with the same name, an
error is reported.
At replay, the function waits for the HTML element to be displayed before saving
the target. The timeout is the value of #ActionTimeout (the default is 30
seconds).
Example
On WinTask Web site, we save the target which is under the link Hottest New
340
Version:
StartBrowser("IE","www.wintask.com")
UsePage("Macro and Data Extraction with WinTask - the automation software
for Windows and internet")
SaveTargetAs("A[INNERTEXT= 'DOWNLOAD your 30-day']", "c:\test", "htm")
CloseBrowser()
The file is saved under c:\test with the name download-wintask.htm which is the
original filename of the HTML element.
341
#ScriptAfterTimeout$
System variable - Program flow management.
The #ScriptAfterTimeout$ system variable specifies the script that will be run
when #ExecTimeout has elapsed. Not available in WinTask Lite.
Usage
If you need to run a script at regular interval whatever error is reported,
#ScriptAfterTimeout$ used in cunjunction with #ExecTimeout allow to rerun
within a clean desktop whatever happened during previous execution.
Syntax
#ScriptAfterTimeout$ = "<script_to_launch.rob>"
Remarks
If within the script, #ExecTimeout has been set up and if this timeout elapses
during execution, the .rob compiled script specified in #ScriptAfterTimeout$ is
launched.
The use of this system variable along with #ExecTimeout allows to recreate a
"clean" environment if the script fails for any reason and so you can rerun the
same script exactly in the same state than if it was the first time ; see below the
example code.
If the script name to call contains spaces, you need to surround the script name
by CHR$(34):
#ScriptAfterTimeout=chr$(34)+"After Timeout.rob+chr$(34)
See also
#ExecTimeout
Examples
#ScriptAfterTimeout$ = "my_script"
'Note that as usual, if a blank is within the full path, you need to
surround the string with Chr$(34) as below :
#ScriptAfterTimeout$=Chr$(34)+"E:\MICHAEL\script timeout\display
message.rob"+Chr$(34)
'With parameters, the line would be :
#ScriptAfterTimeout$=Chr$(34)+"E:\MICHAEL\script timeout\display
message.rob"+Chr$(34)+" param1 param2"
Example code
This script launches Notepad and the Web page www.wintask.com. After
#ExecTimeout seconds (here at 10), the script is killed and the script
killprocesses specified in #ScriptAfterTimeout$ variable is launched. This last
script kills the two processes Notepad and Iexplore, so the environment before
launching the first script is restored.
#ExecTimeout=10
#ScriptAfterTimeout$="killprocesses"
Shell("notepad")
342
StartBrowser("IE", "www.wintask.com")
UsePage("Macro and Data Extraction with WinTask - the automation software
for Windows and internet")
ClickHTMLElement("A[INNERTEXT= 'DOWNLOAD your 30-day']")
pause 20
' Script killprocesses------------------------------------------------'In this example, we kill the two applications Internet Explorer and
notepad.
KillApp("iexplore.exe",1)
KillApp("notepad.exe",1)
343
Sec$
Date/Time function
The Sec$ function returns the seconds of the current time as a two-character
string.
Syntax
a$=Sec$()
Return value
a$, seconds number returned as a string; if the value is less than 10, a leading 0
is added. a$ is always two characters long.
Example
a$=Sec$() 'if its 9:08:05 am, a$ contains "05"
344
Select Case... EndSelect
Program flow control function.
The Select Case...EndSelect structure defines a selection.
Usage
Select Case is similar to an If block but for more complex decisions where there
are several possible answers. For example if you need to process different actions
depending on which weekday it is, you will use a Select Case covering the 7
possible values for the current day.
Syntax
Select Case <tested_expression>
[Case <expressions_1>
<statements_1>]
[Case <expressions_2>
<statements_2>]
[...]
[Case Else
<statements_3>]
EndSelect
Parameters
If <tested_expression> evaluates to one of the <expressions_>, the statements
after the CASE are executed.
examples of <expressions_> are :
CASE "a"
CASE 1
CASE a+b
CASE "red" , "white" , "blue"
<expressions_> can any numeric or string expression.
After CASE ELSE, the <statements_3> are executed when the
<tested_expression> does not evaluate to any of the <expressions_>.
Example
day=weekday()
Select Case day
Case 1
aday$="Sunday"
Case 2
aday$="Monday"
Case 3
aday$="Tuesday"
Case 4
aday$="Wednesday "
Case 5
aday$="Thursday "
Case 6
345
aday$="Friday"
Case 7
aday$="Saturday"
Case Else
aday$="Impossible"
EndSelect
msgbox("Hello, today is "+aday$)
346
SelectDir$
User dialog function.
The SelectDir$ function returns the name of the directory selected by the user in
the standard Browse for Folder dialog. Not available in WinTask Lite.
Syntax
mydir$=SelectDir$(<text$>,<initial_directory$>,<flag>)
Parameters
<text$>: string, explanation for the Browse for Folder dialog.
<initial_directory$>: initial directory from which the search will start.
<flag>: integer value, its the addition of all the flags passed to the Windows API.
1 is the recommended value, only disk directories are listed (not Control panel,
...). Other values are:
8192
for selecting a printer
2
Network neighborhood browsing is not allowed
1
only disk directories are allowed
Remarks
If <initial_directory$> is invalid, the list starts at My computer. Directory names
which must be independent of environment (for instance system folder where
Windows is installed), follow the rules of CSIDL values in C++:
DESKTOP = "0"
PROGRAMS= "2"
CONTROLS= "3"
PRINTERS= "4"
PERSONAL= "5"
FAVORITES= "6"
STARTUP= "7"
RECENT= "8"
SENDTO= "9"
BITBUCKET="a
STARTMENU= "b"
DESKTOPDIRECTORY= "10"
DRIVES= "11"
NETWORK= "12"
NETHOOD= "13"
FONTS= "14"
TEMPLATES= "15"
COMMONSTARTMENU= "16"
COMMONPROGRAMS= "17"
COMMONSTARTUP= "18"
COMMONDESKTOPDIR= "19"
APPDATA= "1a"
PRINTHOOD= "1b"
LOCALAPPDATA= "1c"
ALTSTARTUP= "1d"
COMMONALTSTARTUP= "1e"
COMMONFAVORITES= "1f"
INTERNETCACHE= "20"
COOKIES= "21"
HISTORY= "22"
COMMONAPPDATA= "23"
347
WINDOWS= "24"
SYSTEM= "25"
PROGRAMFILES= "26"
MYPICTURES= "27"
PROFILE= "28"
Return value
mydir$: directory name selected by the user.
See also
SelectFile
Example
Directory selection starting at My computer.
mydir$=selectdir$("Select a folder","0",1)
msgbox(mydir$)
348
SelectedHTMLItem$
Web function.
The SelectedHTMLItem$ function returns the item selected in the specified
combobox/listbox HTML element. Not available in WinTask Lite.
Usage
Used to retrieve what the user has selected in a combo or listbox in a web form
for example.
Syntax
var$=SelectedHTMLItem$(<html_descriptor>)
Parameters
<html_descriptor>, unique identifier for the HTML combobox/listbox to retrieve
the information from. Use Recording mode for generating automatically the html
descriptor.
Return value
var$ returns what has been selected by the user in the specified html
combobox/listbox. If the combo/listbox is not found within the web page specified
by a previous UsePage, var$ is empty.
Remarks
See the second example below to ensure that the HTML combo/list is fully loaded
before invoking SelectedHTMLItem$ function.
Examples
On the demonstration WinTask Web site, we test what the user has selected in
the Contact Us form:
StartBrowser("IE", "www.wintask.com/demos")
UsePage("WinTask Demonstration Pages")
ClickHTMLElement("A[INNERTEXT= 'Form']")
UsePage("Form")
'The SelectHTMLItem waits for #ActionTimeout that the listbox is fully
loaded.
SelectHTMLItem("SELECT[NAME= 'subject']", "Web site")
ClickHTMLElement("INPUT CHECKBOX[NAME= 'contactsoon']")
selection$=SelectedHTMLItem$("SELECT[NAME= 'subject']")
msgbox(selection$) 'Displays Web site
CloseBrowser()
On WinTask Web site, synchronization tips : we suppose that all the pages have
the same title WinTask,
and we want to retrieve what is per default in Subject field
StartBrowser("IE", "www.wintask.com/demos")
UsePage("WinTask Demonstration Pages")
ClickHTMLElement("A[INNERTEXT= 'Same Title Pages']")
'If the new page has the same title as the previous one, the Recording mode
does not generate a UsePage,
349
'so add it manually as below, execution of the UsePage line will finish
only when all the HTML elements
'on the new web page are loaded.
UsePage("Page Title")
WriteHTML("INPUT TEXT[NAME= 'company']", "Typing in first page")
ClickHTMLElement("A[INNERTEXT= 'here']")
'Write an additional UsePage line to force the synchro on the new page with
the same title
UsePage("Page Title")
ClickHTMLElement("A[INNERTEXT= 'previous page']")
CloseBrowser()
350
SelectedItem$
Windows management function.
The SelectedItem$ function returns the item selected in the specified listbox or
combobox. Not available in WinTask Lite.
Usage
Allows to test what the user has selected in a listbox or combobox. Only standard
Windows list/combo will work with SelectedItem$. With a non-standard
list/combo, you can use Clipboard :
SendKeys("<Ctrl c">) to copy the text to Clipboard, and GetClipboard$ function
to retrieve the content of Clipboard.
Syntax
var$=SelectedItem$(<window_name>)
Parameters
<window_name>, string, window name of the listbox or combobox from which
the function retrieves the user selection.
Return value
var$, string, return value which contains the value selected by the user. If the
list/combo does not exist, an empty string is returned.
Example
var$=SelectedItem$("EXPLORER.EXE|ComboBox|Run|1")
351
SelectFile
User dialog function.
The SelectFile function returns the LONG name of the files selected by the user
in the standard File Open dialog. Not available in WinTask Lite.
Syntax
ret=SelectFile(<title>,<directory>,<filter>,<selected_file>,<offset_name>,<offs
et_extension>)
Parameters
<title>: string, title of the File Open dialog.
<directory>: initial directory in the File Open dialog.
<filter>: file extensions listed in the File Open dialog; first the extension, followed
by the label of this extension; all the arguments are separated by the character ;.
<selected_file>: the file specified in the edit box of the File Open dialog; a return
variable, it contains the name of the file selected by the user.
<offset_name>: the position of the first letter of the filename selected. For
example, if the file returned is c:\dir1\dir2\file.ext, this argument contains 14.
<offset_extension>: the position of the first letter of the extension. For instance,
if the file returned is c:\dir1\dir2\file.ext, this argument contains 19 (position of
the letter e).
Return value
ret, numeric return code. When the user has selected the OK button, the function
returns 0, otherwise use this return code for Error Handling.
Example
file_name$ is the LONG name of the selected file.
ret=SelectFile("Select the file", "c:\worddocs","*.txt;text files
(*.txt);*.doc;documents (*.doc)",file_name$,offset_name,offset_ext)
352
SelectHTMLItem
Web function.
The SelectHTMLItem function selects an item in a Combobox/Listbox within a
Web page.
Usage
Used to select an item from a listbox or a combobox displayed on a Web page. If
the list/combo is a non-HTML plugin, SelectHTMLItem function will not recognize
the list, and you can use Clipboard:
SendKeys("<Ctrl C">) to copy the text to Clipboard (use Down key if you need
to select a different item than the one selected), and GetClipboard$ function to
retrieve the content of Clipboard.
Syntax
ret=SelectHTMLItem(<html_descriptor>,item$[,shift|ctrl])
Parameters
<html_descriptor>, unique identifier for the HTML combobox/listbox where to
select the item item$ within the current Web page specified by the last UsePage.
See HTML descriptor for <html_descriptor> syntax. Use Recording mode for
generating automatically the SelectHTMLElement syntax.
<item$>, string, text of the item to select.
shift or ctrl: if a multiple selection is done, the shift keyword is used for the last
item selected, or the ctrl keyword is used for each individual item selected.
Return value
Ret, numeric return code. If the item has been successfully selected within 30
seconds (this default value can be changed using #ActionTimeout), the function
returns 0 otherwise a return code is set but the execution does not stop whatever
#IgnoreErrors value.
List of negative error codes
-1
No browser in use (no previous UsePage or StartBrowser)
-3
Bad descriptor, invalid syntax
-4
The browser has been lost (for instance because of a Closewindow)
-5
Page not found
-11
Specified item not found
-404,405
Usual http error codes (requires IE 6 or above)
Example
On the demonstration WinTask Web site, we click the Form link and then we fill
the form:
StartBrowser("IE","www.wintask.com/demos")
UsePage("WinTask Demonstration Pages")
ClickHTMLElement("A[INNERTEXT= 'Form']")
UsePage("Form")
SelectHTMLItem("SELECT[NAME= 'subject']", "Web site")
WriteHTML("INPUT TEXT[NAME= 'company']", "My Company")
WriteHTML("INPUT TEXT[NAME= 'name']", "My Name")
WriteHTML("INPUT TEXT[NAME= 'email']", "[email protected]")
353
ClickHTMLElement("INPUT CHECKBOX[NAME= 'contactsoon']")
WriteHTML("TEXTAREA[NAME= 'message']", "Message")
ClickHTMLElement("INPUT RESET[VALUE= 'Clear']")
CloseBrowser()
354
SelectMultipleFile
User dialog function.
The SelectMultipleFile function returns an array containing the LONG names of
the files selected by the user in the standard File Open dialog. Not available in
WinTask Lite.
Syntax
SelectMultipleFile(<title>,<directory>,<filter>,<selected_directory>,<array>)
or
a=SelectMultipleFile(<title>,<directory>,<filter>,<selected_directory>,<array>)
Parameters
<title>: string, title of the File Open dialog.
<directory>: initial directory in the File Open dialog; if empty, the current
directory is used.
<filter>: file extensions listed in the File Open dialog; first the extension, followed
by the label of this extension; all the arguments are separated by the character ;.
<selected_directory>: directory selected by the user.
<array>: array containing the list of files selected by the user. The array must
have been previously declared using the DIM statement.
Return value
a, return variable, number of files selected.
Examples
DIM file_tab$(10)
a=SelectMultipleFile("Select the files" , "c:\worddocs","*.txt;text files
(*.txt);*.doc ;documents (*.doc)", dir$, file_tab$())
The array File_tab will contain all the selections made by the user in the File Open
dialog box where all the files in C:\docs are listed:
Dim file_tab$(100)
SelectMultipleFile("Select the files","c:\docs","*.*;All files(*.*)", dir$,
file_tab$())
msgbox(file_tab$(0))
355
SendEmail
System function, Web function.
The SendEmail function sends an email using the SMTP outgoing mail server
defined in WinTask Scheduler email notification Tab. Not available in WinTask
Lite.
Syntax
SendEmail(<From>,<To>,<Subject>,<Message_text>[,<Attachments>[,<Cc>]]
)
or
ret=SendEmail(<From>,<To>,<Subject>,<Message_text>[,<Attachments>[,<C
c>]])
Parameters
<From>: string, email address of the email sender.
<To>: string, email name of the recipient.
<Subject>: string, message title.
<Message_text>: string, body part of the message. The maximum length for the
body part as a simple string is 80 characters, for a longer body text, use a file : if
the first character of the string is the ! character, the message is the content of
the file specified by the filename after this ! character.
<Attachments>: string, one or several filenames to attach (the ; character is the
separator if several files are specified). If the first character is the ! character, the
unique filename specified behind this character is used to send all the files which
are listed line by line in this metafile.
<Cc>: string, email name of other recipient.
Return value
Ret, numeric return code. The function returns 0 if successfull, 1 if any error
occurred trying to send mail. You can use this return code for Error Handling.
Examples
Send a simple email.
SendEmail("[email protected]","[email protected]","Meeting today","The
meeting today is at 8 am")
Send a longer email witht the body text in a file.
SendEmail("[email protected]","[email protected]","Read
this","!C:\bodymail.txt")
Send an email with attachments listed in a metafile text file.
c:\metafileemail.txt for example lists
c:\test1.txt
c:\test2.txt
c:\test3.txt
c:\program files\wintask\scripts\my_scrip.src
The SendEmail line below sends as attached files the 4 files above.
SendEmail("[email protected]","[email protected]","Test metafile","Please
save the attached files","!C:\metafileemail.txt")
356
SendKeys
Windows management function.
The SendKeys function sends keyboard characters to the window specified by
the most recent UseWindow.
Usage
SendKeys function is used primarily to simulate keystrokes being typed into an
application. For instance, the first line in a script could be to open the application
using Shell function, the next step would be a SendKeys to send keystrokes.
Before the SendKeys line, a UseWindow statement would specify the window
where the keystrokes have to be sent.
Syntax
SendKeys(<key_list> [,NoActivate])
or
ret=SendKeys(<key_list> [,NoActivate])
Parameters
<key_list>, string of characters ; each special key has a keyword for the
Sendkeys function. See Keyboard mnemonics. To send a space, use " " (with a
space between the double quotes). If no active Window is found or if an error is
found in <key_list>, an error message is displayed and all the scripts are stopped
(depending on #IgnoreErrors value, see Error handling).
Noactivate : optional keyword. It is used for sending keys to the window which
has the focus without checking that it's the one defined in the most recent
UseWindow. This keyword is useful to send keystrokes to different fields in a form
: instead of a UseWindow line for each individual field in the form, you can use
only one, and then you fill the different fields using SendKeys with Noactivate
parameter, and you use a SendKeys("<Tab>",Noactivate) to go from one field to
another.
Return value
Ret, numeric return code. When SendKeys is successful, the function returns 0,
otherwise use this return code for Error Handling.
Remarks
The variable #SendKeysDelay (set to 0 by default) slows down the typing of
characters. A small delay is added between each typed scan code (for "a<Ctrl a>,
there will be a delay between a, Ctrl and a).
Sendkeys function is not able to send some non-English characters (for instance,
the ñ character in Spanish), see Sendkeys with non-English characters if you
need to type some non-English or not-French characters which are not recognized
by SendKeys.
SendKeys function cannot send as is keyboard mnemonics such as <Alt
<Enter>>, you need to use the keyboard mnemonics for the string to send,
"normal text"+"<Alt <Enter>>"+"normal text".
Examples
In recording mode:
UseWindow("NOTEPAD.EXE|Edit|Untitled - Notepad|1",1)
SendKeys("Hello")
357
SendKeys("<Enter>")
SendKeys("Hello<Enter><Alt <F5>>")
Variables can be used:
UseWindow("NOTEPAD.EXE|Edit|Untitled - Notepad|1",1)
a$="Hello"
SendKeys(a$)
358
#SendKeysDelay
System variable - Windows management
The #SendKeysDelay system variable slows down keyboard simulation and
selections in menus.
Syntax
#SendKeysDelay = <integer>
Parameters
<integer>, integer in tenths of a second (default value is 0) : a time delay of
<integer> x 0.2 second is inserted after each keystroke sent by the SendKeys
function. It's possible to put a negative value (until -10) in order to speed up the
typing. The maximum value is 100.
This system variable also affects selections in menus made by the ChooseMenu
function.
Example
' Delay 1 second
#SendKeysDelay=10
359
SendKeysEncrypted
Windows management function.
The SendKeysEncrypted function sends encrypted keyboard characters to the
window specified by the most recent UseWindow (Not available in WinTask Lite).
Usage
SendKeysEncrypted function is used to simulate encrypted keystrokes being
typed into an application. A set of characters can be encrypted using menu option
Insert/Encrypted string. It will generate the encrypted string from the string
you type and this encrypted string is then use in SendKeysEncrypted function.
Before the SendKeysEncrypted line, a UseWindow statement would specify the
window where the keystrokes have to be sent.
Syntax
SendKeysEncrypted(<encrypted_keys> [,NoActivate])
or
ret=SendKeysEncrypted(<encrypted_keys> [,NoActivate])
Parameters
<encrypted_keys>, string of encrypted characters. If no active Window is found
or if an error is found in <encrypted_keys>, an error message is displayed and all
the scripts are stopped (depending on #IgnoreErrors value, see Error handling).
Noactivate : optional keyword. It is used for sending encrypted keys to the
window which has the focus without checking that it's the one defined in the most
recent UseWindow.
Return value
Ret, numeric return code. When SendKeysEncrytped is successful, the function
returns 0, otherwise use this return code for Error Handling.
Remarks
The variable #SendKeysDelay (set to 0 by default) slows down the typing of
characters. A small delay is added between each typed scan code (for "a<Ctrl A>,
there will be a delay between a, Ctrl and A).
See also
Encrypt
Examples
Generate first the encrypted string using Insert/Encrypted string menu option
(or use Encrypt statement), then you can use the generated string in
SendKeysEncrytped:
UseWindow(focus$())
SendKeysEncrypted("H9hfSsHbGkkF1qj")
SendKeys("<Enter>")
Variables can be used:
UseWindow(focus$())
a$="H9hfSsHbGkkF1qj"
SendKeysEncrypted(a$)
360
361
SetAttr
File management function.
The SetAttr function modifies file attributes.
Syntax
SetAttr(<filename>,<attribute_flags>)
or
ret=SetAttr(<filename>,<attribute_flags>)
Parameters
<filename>, string, name of the file (optional specified with UNC) to modify. The
name can include the wildcards * or ? in order to modify the attributes of multiple
files in the same directory. The specified file must exist.
<attribute_flags>, integer which can be any of these values (or their sum):
0
No attribute
1
Read only
2
Hidden
4
System
32
Archive
Return value
Ret, numeric return code. When the attribute modification is successful, the
function returns 0, otherwise use this return code for Error Handling.
Examples
SetAttr("c:\text\example.*", 0) ' Deletes all the attributes of the files
"c:\text\example.* "
Res = Setattr(File$, a)
362
SetClipboard
Clipboard management function.
The SetClipboard function places the specified string on the Clipboard.
Usage
Mainly used to transfer data from one application to another, with the usual
Windows Copy/Paste method.
Syntax
SetClipboard(<string$>)
Parameters
<string$>, string to place on the Clipboard. The string can then be used by
GetClipboard$ or by the Edit/Paste menu of other applications.
See also
GetClipboard$
Example
SetClipboard("abcdef") ' Puts "abcdef" on the clipboard
SetClipboard (a$) ' Puts the string a$ on the clipboard
363
SetReadPos
File management function.
The SetReadPos function moves the read pointer to a specified position.
Syntax
SetReadPos(<filename>,<value>)
or
ret=SetReadPos(<filename>,<value>)
Parameters
<filename>, string, name of the file where the read pointer is set.
<value>, integer, new position for the read pointer.
Return value
Ret, numeric return code. When the read pointer is successfully repositioned, the
function returns 0, otherwise use this return code for Error Handling.
Remarks
See the Read function for a detailed explanation.
Examples
var = SetReadPos("C:\my directory\my file.txt",3)
See a complete example at the Read function
364
SetXMLAttribute
File management function.
The SetXMLAttribute function modifies or adds an attribute in the specified XML
file. Not available in WinTask Lite
Syntax
SetXMLAttribute(<filename>,<XML_path>,<attribute_name>,<value>)
or
ret=SetXMLAttribute(<filename>,<XML_path>,<attribute_name>,<value>)
Parameters
<filename>, string, name of the XML file where to add/modify the attribute.
<XML_path>, string, list of node descriptors separated by the \ character to go
where the attribute is. The string is not case-sensitive.The structure of such a
path is:
tagname[attributename1='value']
The tagnames are strings without double quotes, they cannot contain spaces or
reserved characters.
The attribute names are strings without double quotes, OR it can be the reserved
keyword <text> or the reserved keyword <index>. <text> is used to specify the
node inner text, <index> is used to specify the node index (first one starts at 1)
when more nodes with the same tag and attributes exist within the same parent.
Several attributes can be listed with the syntax
tagname[attributename1='value1', attributename2='value2']
Examples:
If the XML file contains:
<bookstore>
<book genre="autobiography" publicationdate="1981" ISBN="1-861003-110">
the <XML_path> can be "bookstore\book[genre='autobiography']" or
"bookstore\book[publicationdate='1981']" or
"bookstore\book[publicationdate='1981',genre='autobiography']"
<attribute_name>, string, name of the attribute - not surrounded by double
quotes, OR keyword <text> surrounded by double quotes to add the text as
specified in <value>.
<value>, string, value for the specified attribute
Return value
Ret, numeric return code. When the attribute value is successfully inserted in the
XML file, the function returns 0, otherwise use this return code for Error Handling.
The error codes are :
20
The XML file could not be saved
27
The XML file could not be opened
90
Internal error (COM error when invoking XML COM)
99
Invalid parameters
110
Invalid XML path
See also
AppendXMLNode
GetXMLAttribute
EnumXMLAttributes
365
EnumXMLChildren
Examples
XML file:
<bookstore>
<book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
<title>The Autobiography of Benjamin Franklin</title>
<author>
<first-name>Benjamin</first-name>
<last-name>Franklin</last-name>
</author>
<price>8.99</price>
</book>
</bookstore>
This code will replace in ISBN the value "1-861003-11-0" by "3-8610"
file$ = "c:\program files\wintask\scripts\sample.xml"
setxmlattribute(file$, "bookstore\book[publicationdate='1981']", "ISBN",
"3-8610")
Those 2 other syntaxes give the same result:
setxmlattribute(file$, "bookstore\book[genre='autobiography']", "ISBN", "38610")
setxmlattribute(file$,
"bookstore\book[publicationdate='1981',genre='autobiography']", "ISBN", "38610")
XML file:
<bookstore>
<book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
<title>The Autobiography of Benjamin Franklin</title>
<author>
<first-name>Benjamin</first-name>
<last-name>Franklin</last-name>
</author>
<price></price>
</book>
</bookstore>
We need to add a text in the <price></price> node. To add 8.99 price, the
syntax is:
file$ = "c:\program files\wintask\scripts\sample.xml"
setxmlattribute(file$,
"bookstore\book[publicationdate='1981']\price","<text>","8.99")
XML file:
<bookstore>
<book genre="autobiography" publicationdate="1981">
<title>The Autobiography of Franklin</title>
<author>
<name></name>
<name></name>
</author>
<price>8.99</price>
</book>
<book genre="autobiography" publicationdate="1981">
<title>The Autobiography of Benjamin Franklin</title>
<author>
<first-name></first-name>
<last-name></last-name>
366
</author>
<price>9.01</price>
</book>
</bookstore>
We need to add in the first <name> node Benjamin and in the second <name>
Todd - as there is no way to identify <name> first or second block, <index> has
to be used:
file$ = "c:\program files\wintask\scripts\sample.xml"
setxmlattribute(file$,
"bookstore\book\author\name[<index>=1]","<text>","Benjamin")
setxmlattribute(file$,
"bookstore\book\author\name[<index>=2]","<text>","Todd")
367
Shell
System function.
The Shell function executes a program (.exe, .com, .bat, .doc, .txt, ...).
Usage
The main usage of the Shell function is to start an application or open a
document in preparation to send actions to it (using SendKeys function to send
keystrokes for instance). The Shell function includes an automatic
synchronization and so waits for the application to have finished to load before
moving to the next step. The Shell line is automatically generated in the script if
you use Recording mode; you can use too its wizard by double-clicking Shell
function in Insert statement window (press F4 to open Insert statement window).
Syntax
Shell (<program_name> [,<param>])
or
ret=Shell (<program_name> [,<param>])
Parameters
<program_name>: string, name of the executable module to be run with any
parameters.
<param>: 1 for normal execution, 2 for minimized execution, 3 for maximized
execution.
Return value
Ret, numeric return code. When the program has been launched successfully, the
function returns 0, otherwise use this return code for Error Handling.
Remarks
IMPORTANT : if <program_name> contains a space, you must surround it with
the double-quote character CHR$(34). For example :
Shell(chr$(34)+"C:\program files\accessories\mspaint"+chr$(34))
If the path contains spaces, you must surround it with CHR$(34). For example:
Shell(chr$(34)+"C:\program files\accessories\mspaint"+chr$(34)+" "+
chr$(34)+"C:\program files\accessories\test.bmp"+chr$(34))
Shell wizard creates the necessary CHR$(34) so it is highly recommended to use
the wizard.
The Shell function can be used to launch a new script inside the currently running
script: a new instance of the runtime module TASKEXEC is then opened (see the
Run function to launch a script from another). Here is an example:
Shell(chr$(34)+"c:\program files\wintask\bin\taskexec.exe"+chr$(34)+"
"+chr$(34)+ "c:\program files\wintask\scripts\myscript.rob" +"
"+chr$(34)+"param1"+chr$(34)+" "+chr$(34)+param2$+chr$(34) )
Note the use of CHR$(34) for the ASCII character code ".
See also
Command$, ShellWait, Run
Examples
368
Shell("c:\winword\winword.exe c:\worddocs\my_doc.doc", 1)
Result=Shell("c:\worddocs\my_doc.doc", 1)
Shell( my_exe$, 2)
369
ShellWait
System function.
The ShellWait function executes a program (.exe, .com, .bat, .doc, .txt, ...) and
waits for its termination before running next statement.
Usage
The main usage of the ShellWait function is to start a Dos application, a batch file
or a console application and to wait until the application has finished before
moving to next step. Using ShellWait, you can launch a Dos command such as
xcopy and next step will be executed only when the filecopy has finished.
Syntax
ShellWait (<command$>,<mode>,<timeout>[,<processExitCode>[,output$]])
or
ret=ShellWait
(<command$>,<mode>,<timeout>[,<processExitcode>[,output$]])
Parameters
<command$>: string, name of the program to be run with any parameters
(parameters must be strings).
<mode> speficies window size during exeuction: 1 for normal execution, 2 for
minimized execution, 3 for maximized execution, 4 for hidden (character-mode
applications), 5 for hidden and when <timeout> is elapsed, process is killed ( in
mode 4, process is not killed).
If after <timeout> seconds, the program launched by <command$> is not
terminated, return code ret is set to -1. If <timeout> is set to 0, there is no
limitation for execution duration.
<ProcessExitCode>: optional integer variable; it gives the return code of the
program launched by <command$> at its termination. If <timeout> has been
reached before program termination, <ProcessExitCode> is set to -1.
output$ is a string containing the two outputs stdout and stderr (only if <mode>
is set to 4 or 5). It's the text displayed during character-based or Dos programs
execution. If the program does not output anything to the console, this last
parameter must not be present.
Return value
Ret, numeric return code. When the program has been launched successfully, the
function returns 0, otherwise use this return code for Error Handling.
See also
Shell
Examples
shellwait("xcopy c:\*.* d:\save /S",1,1000)
msgbox("Dos command end")
Dos box is opened, WinTask script execution suspends and the following message
box is displayed either when job in Dos box is finished, either when the specified
timeout of 1000 seconds has been reached.
370
SizeWindow
Windows management function.
The SizeWindow function resizes the specified window.
Syntax
SizeWindow(<window_name>,<instance>,<width>,<height>)
or
ret=SizeWindow(<window_name>,<instance>,<width>,<height>)
Parameters
<window_name>, window name of the window to be resized.
<instance>, instance number of the window to be resized.
<width>,<height>, numeric ; width and height of the window in pixels.
Return value
Ret, numeric return code. When the resizing is successful, the function returns 0,
otherwise use this return code for Error Handling.
Examples
SizeWindow("NOTEPAD.EXE|Notepad|Untitled",1, 200,300)
Result = SizeWindow(win$, 0, var_x, var_y)
371
Sleep
Synchronization function.
The Sleep function makes the current script "sleep" while leaving event handlers
active. Not available in WinTask Lite.
Syntax
Sleep()
Parameters
None.
Remarks
The script is inactive but the events are still managed.
If a script launches another script using the RUN function, the parent script is
"sleeping" until the child script returns control.
A "sleeping" script is ended inside a sub-routine associated with an event handler,
through a STOP or END statement, or in another script by the STOP statement.
Example code
This example shows how the Sleep command is used in order to make the event
handler defined by OnAction remain active.
Sub close()
Disable(wait_close_menu)
res=msgbox("Would you like to close the message box? ",4,"EXAMPLE")
if res=6 then
' if res=6 WinTask closes Explorer and stops the script
CloseWindow("EXPLORER.EXE|ExploreWClass|My Documents",1)
stop
endif
enable(wait_close_menu)
EndSub
shell("explorer")
' Definition of the event handler
' each time the user selects the Close option from the Explorer menu File,
' the script executes the close() function.
OnAction wait_close_menu
Menu("&File|&Close")
InWindow("EXPLORER.EXE|ExploreWClass|My Documents",1)
DoSub close
372
EndAction
sleep()
'leaves the event handler active.
373
SplitIntoArray
String management function.
The SplitIntoArray function converts the specified string into an array of strings.
Syntax
SplitIntoArray(<string$>,<array$> [,<delimiter$>])
or
val=SplitIntoArray(<string$>,<array$> [,<delimiter$>])
Parameters
<string$>, string to be converted into an array.
<array$>, array of strings which will contain the different splitted strings. The
array must be declared at the beginning of the script using the Dim function.
<delimiter$>, string. The space character (" ") is the delimiter by default. You
can specify another delimiter character using this optional parameter (for
example ";").
Return value
val, integer, optional return value which gives the number of splitted strings.
Remarks
If you use successive SplitIntoArray calls using the same array, you need to
reinitialize the array to avoid some old values from the previous call if the second
call returns less values. For example: array$()=""
Examples
Dim splitstring$(10)
num=SplitIntoArray ("Hello WinTask, the powerful automation
software",splitstring$())
' Returns in splitstring$(0) "Hello", in splitstring$(1) "WinTask,", in splitstring$(2)
"the", in splitstring$(3) "powerful", in splitstring$(4) "automation", in
splitstring$(5) "software". And num contains 6.
Dim data$(10)
a$="Hello;WinTask;powerful"
SplitIntoArray(a$,data$(),";")
' Returns in data$(0) "Hello", in data$(1) "WinTask", in data$(2) "powerful"
374
StartBrowser
Web function.
The StartBrowser function launches the specified browser (Internet Explorer
version 6 or above is needed). StartBrowser is not supported under NT and you
must use instead the Shell statement in order to launch Internet Explorer.
Usage
It loads the Web page and waits until the page is finished loading. If a Security
window prevents the page to finish loading, use Shell function instead of
StartBrowser. If you prefer to use another browser than IE, use Shell function to
run it, but you will have to insert a manual synchronization to wait until the page
is finished loading.
Syntax
StartBrowser(<browser_type>[,<start_page>[,<param>]])
or
Ret=StartBrowser(<browser_type>[,<start_page>[,<param>]])
Parameters
<browser_type>, string, only the string "IE" for Internet Explorer version 6 or
above is accepted.
<start_page>, string, optional parameter specifying the start page. If this
parameter is not specified, the default start page for the browser is used.
<param> : 1 for normal execution of Internet Explorer, 2 for minimized
execution of Internet Explorer, 3 for maximized execution of Internet Explorer.
Note that a Startbrowser("IE") function is generated each time you start
Recording after launching a program if you click Internet Explorer as the
application to launch (see Recording mode). If, during execution, a second
StartBrowser is found in the script, a second instance of the browser will be
opened.
Return value
Ret, numeric return code. When the browser has been started correctly and the
page could be loaded within 30 seconds (this default value can be changed using
#ActionTimeout), the function returns 0. Otherwise use this return code for Error
Handling. The return code is -3 if <browser_type> is incorrect. The return code is
-2146697211 if an HTTP error prevents the specified page to load.
Remarks
If at replay, StartBrowser returns a Page timeout error message, see Page
timeout error message topic.
If you want to retry to load the url for a couple of times if StartBrowser fails, such
a script is listed in Advanced_Script_Examples sub-directory of WinTask (script
name is Start browser and retry the url if unsuccessfull).
Example
StartBrowser("IE","www.wintask.com",3)
375
StartService
System function.
The StartService function starts the specified Windows 2000/XP/2003/Vista
Service. Not available in WinTask Lite.
Syntax
StartService(<service_name$>)
or
ret=StartService(<service_name$>)
Parameters
<service_name$>: system name of the Windows 2000/XP/2003/Vista Service to
be started
Return value
Ret, numeric return code. When the specified service has been started correctly,
the function returns 0, otherwise use this return code for Error Handling. The
return code is 109 if WinTaskAdmin Service is not started. The return code is 5 if
the access is denied.
See also
StopService
Example
StartService("WTScheduler") ' Returns 0 if WTScheduler (The WinTask Scheduler
Service) has been started correctly
376
StartTimer
Response time function.
The StartTimer function starts the specified clock. Not available in WinTask Lite.
Syntax
StartTimer(<clock_number>)
Parameters
<clock_number>: number of the clock to be started for measuring response
time; valid values go from 1 to 10.
If the specified clock is already started, the function does nothing.
If <clock_number> is an invalid number, Error Handling rules are used.
See also
StopTimer, ResetTimer, Timer
Examples
This script measures a connection time: connection is supposed achieved when
the text "connected" is displayed in the emulator window (window name :
my_emulator$).
ResetTimer(1)
'After having reset clock number 1, start clock number 1
StartTimer(1)
Pause until
Text("connected")
InWindow(my_emulator$)
EndPause
'Stop the timer
StopTimer(1)
'Timer function returns the result as a number in 1/100 sec.
Comment("connection made in : "+str$(Timer(1)/10))
This script measures how long it takes for a page on www.wintask.com to load
ResetTimer(1)
StartBrowser("IE", "www.wintask.com/demos")
UsePage("WinTask Demonstration Pages")
StartTimer(1)
ClickHTMLElement("A[INNERTEXT= 'Form']")
UsePage("Form")
'Stop the timer
StopTimer(1)
'Timer function returns the result as a number in 1/100 sec.
msgbox("Page How it works loaded in : "+str$(Timer(1))+" hundreds of a sec")
377
Stop
Program flow management function.
The Stop function stops all scripts.
Syntax
Stop
Remarks
You can also stop scripts with the <Ctrl>+<Shift>+<Pause> hotkey.
378
StopLog
Logfile management function.
The StopLog function stops logging statements to the log file. Not available in
WinTask Lite.
Syntax
StopLog
Parameters
None
Example
LogFile("c:\Program Files\Wintask\Logs\current.log",1,1)
Shell("notepad")
LogFile("c:\Program Files\WinTask\Log\history.log",1,1)
UseWindow("NOTEPAD.EXE|Edit|Untitled-Notepad|1",1)
StopLog
SendKeys("Hello<Enter>")
379
StopService
System function.
The StopService function stops the specified Windows 2000/XP/2003/Vista
Service. Not available in WinTask Lite.
Syntax
StopService(<service_name$>)
or
ret=StopService(<service_name$>)
Parameters
<service_name$>: system name of the Windows 2000/XP/2003/Vista Service to
be stopped
Return value
Ret, numeric return code. When the specified service has been stopped correctly,
the function returns 0, otherwise use this return code for Error Handling. The
return code is 109 if WinTaskAdmin Service is not started. The return code is 5 if
the access is denied.
See also
StartService
Example
StopService("WTScheduler") ' Returns 0 if WTScheduler (Service Scheduler) has
been correctly stopped.
380
StopTimer
Response time function.
The StopTimer function stops the specified clock. Not available in WinTask Lite.
Syntax
StopTimer(<clock_number>)
Parameters
<clock_number>: number of the clock to be stopped; valid values go from 1 to
10.
If the specified clock is already stopped, the function does nothing.
If <clock_number> is an invalid number, Error Handling rules are used.
See also
StartTimer, ResetTimer, Timer
Examples
This script measures a connection time : connection is supposed achieved when
the text "connected" is displayed in the emulator window (window name :
my_emulator$).
ResetTimer(1)
'After having reset clock number 1, start clock number 1
StartTimer(1)
Pause until
Text("connected")
InWindow(my_emulator$)
EndPause
'Stop the timer
StopTimer(1)
'Timer function returns the result as a number in 1/100 sec.
Comment("connection made in : "+str$(Timer(1)/10))
This script measures how long it takes for a page on www.wintask.com to load
ResetTimer(1)
StartBrowser("IE", "www.wintask.com/demos")
UsePage("WinTask Demonstration Pages")
StartTimer(1)
ClickHTMLElement("A[INNERTEXT= 'Form']")
UsePage("Form")
'Stop the timer
StopTimer(1)
'Timer function returns the result as a number in 1/100 sec.
msgbox("Page How it works loaded in : "+str$(Timer(1))+" hundreds of a sec")
381
Str$
String management function.
The Str$ function converts the specified numeric value to a string.
Syntax
var$=Str$(<number>)
Parameters
<number>, numeric, integer value to be converted to a string.
Return value
var$, string, return value containing the converted value. If <number> is
negative, the string var$ contains a leading minus sign.
See also
Val
Examples
Var$ = Str$(123 ) ' Returns the string "123"
Var$ = Str$(-123) ' Returns the string "-123"
msgbox(str$(25))
Var$ = Str$(var)
i=0
repeat
msgbox("index is now: "+str$(i))
i=i+1
until i=5
382
Sub...Exitsub...EndSub
Program flow management function.
The Sub...EndSub structure defines a subroutine.
Syntax
Sub <sub_name>([<param1>[,<param2>]....])
[local <variable_name>]
<statements>
[ExitSub]
<statements>
EndSub
Parameters
<sub_name>, name of the subroutine. The maximum length of the name is 32
characters.
<param>, optional parameters. Parameters are passed by reference, not by
value.
The keyword LOCAL permits the declaration of local variables.
ExitSub is used to quit the subroutine inside the procedure.
Remarks
The execution of a subroutine is stopped either by an EndSub statement, or by an
ExitSub statement. ExitSub can be used anywhere within the subroutine.
See also
Function
Program Structure
Global and local variables
Example code
Sub my_routine()
ret=msgbox("Would you like to leave the subroutine?",4,"EXAMPLE")
if ret=6 then
' If ret=yes then leave the subroutine
ExitSub
endif
msgbox("I'm in my subroutine")
EndSub
my_routine()
' execute the subroutine
msgbox("Program end !")
383
Subtract$
Floating point calculation function.
The Subtract$ function subtracts two strings representing floating point
numbers.
Usage
As only integers are supported numbers in WinTask, calculation on floating point
numbers is done using their string representation.
Syntax
res$=Subtract$(a$,b$[,rc])
Parameters
a$, b$ are the strings representing the two floating numbers to subtract.
rc, optional numeric return code.
Values are :
0 if the operation was successful
1 invalid operation because parameters are incorrect (for instance, the string
can't be considered as a number)
2 if the operation causes an overflow
Return value
res$, string representing a$ - b$.
See also
#Precision
Examples
Subtract$("13.56","145.789") 'gives "-132.23"
Subtract$("-45.678","34.8976") 'gives "-80.58"
#Precision=3
Subtract$("567.34257","45.343") 'gives "522.000"
384
Error codes for Synchronization functions
There are no error codes for Synchronization functions. At execution, if an error
prevents even the PauseFalse block to be executed, an error message is
displayed and execution stops. You have to correct the code and then replay.
385
Syntax, general
The WinTask language is much like Visual BasicTM.
A statement can have parameters ; they follow the statement keyword, inside
parentheses. The parameters are separated by commas.
If an argument is a string constant, the argument is enclosed within double
quotes (for example : "qwerty").
Some statements return a result. If this result is a string, the statement keyword
ends with the character $ ; if the result variable is an integer, the last character
of the statement keyword is not a $.
See also:
Program structure
386
Error codes for System functions
The table below lists the possible error codes for the WinTask System functions,
for the errors stopping script execution (unless #IgnoreErrors=1).
-4
-4
-3
-3
-2
-1
-1
1
2
5
34
35
36
37
38
39
66
67
68
69
70
71
72
90
99
103
104
107
109
WinTaskAdmin service not started
(GetCPULoad/GetMemUsage/GetProcessCPULoad functions under
Vista)
Access denied (KillApp, KillAppChildren, KillProcess functions)
Statistical function failed
Action cancelled by user (KillApp, KillAppChildren, KillProcess
functions)
The PID of the application is incorrect (KillProcess function)
Timeout elapsed for the macro (ExecExcelMacro function)
Index too big
Cannot send mail (SendEmail function)
The Excel workbook does not exist
Access denied (StartService, StopService, IsServiceStarted
functions)
DDE failure (Shell/ShellWait functions)
No association (Shell/ShellWait functions)
Access denied (Shell/ShellWait functions)
DLL not found (Shell/ShellWait functions)
Sharing violation (Shell/ShellWait functions)
Empty Shell name (Shell/ShellWait functions)
Empty key name (Registry functions)
Error opening key (Registry functions)
Error setting up key (Registry functions)
Error reading key (Registry functions)
Error deleting key (Registry functions)
Error deleting the value of the key (Registry functions)
Invalid type for the key (Registry functions)
Internal error
Invalid parameter
Cannot reboot
No enough rights to reboot
The macro cannot be found (ExecExcelMacro function)
WinTaskAdmin service not started (StartService/StopService
functions under Vista)
387
#TextLookFrequency
System variable - Synchronization
The #TextLookFrequency system variable is not used anymore.
The frequency used by Pause statement is 1 second if the timeout is given in
seconds.
For Pause on image with the timeout given in ticks, the frequency is as high as
the processor allows TaskExec.
388
Time$
Date/Time function
The Time$ function returns the system time as a string.
Syntax
hur$=Time$()
Return value
hur$, string, system time; the format depends on the Windows Regional Settings.
Example
hur$=Time$() 'for example might return "10:25:59"
389
Timer
Response time function.
The Timer function returns the value of the specified clock. Not available in
WinTask Lite.
Syntax
response_time=Timer(<clock_number>)
Parameters
<clock_number> : number of the clock from which response_time is retrieved ;
valid values go from 1 to 10.
If <clock_number> is an invalid number, Error Handling rules are used.
Return value
response_time : value contained in <clock_number>, in 1/100 seconds. As
system time is not accurate enough to measure 1/1000 sec, WinTask timers have
a maximum precision of 1/100 sec.
See also
StartTimer, StopTimer, ResetTimer
Examples
This script measures a connection time : connection is supposed achieved when
the text "connected" is displayed in the emulator window (window name :
my_emulator$).
ResetTimer(1)
'After having reset clock number 1, start clock number 1
StartTimer(1)
Pause until
Text("connected")
InWindow(my_emulator$)
EndPause
'Stop the timer
StopTimer(1)
'Timer function returns the result as a number in 1/100 sec.
Comment("connection made in : "+str$(Timer(1)/10))
This script measures how long it takes for a page on www.wintask.com to load
ResetTimer(1)
StartBrowser("IE", "www.wintask.com/demos")
UsePage("WinTask Demonstration Pages")
StartTimer(1)
ClickHTMLElement("A[INNERTEXT= 'Form']")
UsePage("Form")
'Stop the timer
StopTimer(1)
'Timer function returns the result as a number in 1/100 sec.
msgbox("Page How it works loaded in : "+str$(Timer(1))+" hundreds of a sec")
390
391
Top$
Windows management function.
The Top$ function returns the name of the main window which has the focus.
Syntax
window_name$=Top$()
Return value
window_name$, string. If the main window contains several child windows, Top$
returns the window name of the main window containing the active child window
(wheras the Focus$() function gives the window name of the child window which
has the focus).
Example code
This script shows the difference between Top$ and Focus$.
Rem Run Sysedit
shell("sysedit")
pause 3 secs
Window_Name$=Focus$()
Text$="Function Focus$ returns : " + Window_Name$
Msgbox(Text$)
Pause 3 secs
Window_Name$=Top$()
Text$="Function Top$ returns : " + Window_Name$ + " (main window)"
Msgbox(Text$)
392
TopInstance
Windows management function.
The TopInstance function returns the instance number of the main window
which has the focus.
Syntax
instance_num=TopInstance()
Return value
instance_num, numeric. Gives the instance number of the main window which
has the focus (the name of that window can be found using Top$ function).
Example
UseWindow("NOTEPAD.EXE|Edit|Untitled - Notepad|1",1)
SendKeys("Hello<Enter>")
a=TopInstance()
msgbox(str$(a))
393
Trim$
String management function.
The Trim$ function removes the leading and trailing spaces/tabulations from a
string.
Usage
Used to take spaces, tabulations and CRLF off the beginning and the end of a
text. To avoid spaces added by mistake during data-entry, use this function.
Syntax
var$=Trim$(<string$>)
Parameters
<string$>, string to be trimmed.
Return value
var$, string, return value containing the trimmed string.
See also
Ltrim$
Rtrim$
Examples
a$ = Trim$(" bcde ") ' Returns "bcde" in a$
a$ = Trim$(a$) ' Deletes the spaces at the beginning and at the end of a$
394
Ucase$
String management function.
The Ucase$ function converts all characters in the specified string to uppercase.
Syntax
var$=Ucase$(<string$>)
Parameters
<string$>, string to be converted.
Return value
var$, string with all characters converted to uppercase (accented letters are not
converted).
Examples
a$ = Ucase$("bCdeF/G") ' Returns BCDEF/G in a$
a$ = Ucase$("bédâF/G") ' Returns BéDâF/G in a$
395
UnlockKbd
System function.
The UnlockKbd function unlocks the keyboard.
Syntax
UnlockKbd
Remarks
Unlocks the keyboard previously locked by the LockKbd function; when the script
ends, the keyboard is always unlocked.
Example
UnlockKbd
396
UnlockMouse
System function.
The UnlockMouse function unlocks the mouse.
Syntax
UnlockMouse
Remarks
Unlocks the mouse previously locked by the LockMouse function; when the script
ends, the mouse is always unlocked.
Example
UnlockMouse
397
#UseExact
System variable - Windows management
The #UseExact system variable controls how window names are handled when
the script is running. The default value is 0, which means that the script finds a
window even if it has a slightly different name than the one it had when the script
was recorded (fuzzy matching).
Syntax
#UseExact = 0
or
#UseExact = 1
Remarks
Some window names change between when the script was recorded and when
the script is run; in that case, if #UseExact=1, the window is not found and an
error message is displayed at execution.
If #UseExact=0 (default value), at execution WinTask looks for a window with
nearly the same name before generating an error.
For instance, assume the window name as recorded in the script is:
"WORDPAD.EXE|RICHEDIT50W|Document - WordPad|1"
At execution, WinTask first looks for a window with exactly that name. If it cannot
find one, it looks for a similar name, removing one character at a time from the
end of the window title and window class. Only the first character of the class
name is required.
In this example, even if the underlined portion is different from the one recorded
in the script, the window will still be found:
""WORDPAD.EXE|RICHEDIT50W|Document - WordPad|1"
If a matching window is still not found after the fuzzy match, the UseWindow fails
and the error message "Window not found" is displayed.
398
UseOCREngine
Capture function.
The UseOCREngine function specifies which OCR engine will be used by
subsequent OCR function calls (not available in WinTask Lite)
Syntax
ret=UseOCREngine(1)
or
ret=UseOCREngine(2)
Parameter
UseOCREngine(1) : the subsequent OCR function calls will use MODI OCR engine.
UseOCREngine(2) : the subsequent OCR function calls will use WinTask OCR
engine.
Return value
Ret, numeric return code. If the specified OCR engine is ready for use, the return
code is 0. If the specified OCR engine is not ready (typically, MODI from Microsoft
Office, is not installed), the return code is 1. If #IgnoreErrors=0 (default value),
an error message is returned and script execution stops. If #IgnoreErrors=1, the
function returns the error code 1 and script execution goes on.
Remarks
When the OCR engine is not specified within a script, the OCR function calls use
WinTask OCR engine.
If UseOCREngine is invoked in the middle of a script, the subsequent OCR
function calls use the new value for the OCR engine.
See also
CaptureAreaOCR$
CaptureOCR$
ClickOnTextOCR
Pause on OCR Text
Examples
var$=CaptureOCR$("NOTEPAD.EXE|Edit|Untitled - Notepad|1",1) 'var$ returns
the OCRized text which is seen in the Notepad window.
'The OCRengine used is the WinTask one as UseOCREngine is not invoked
before.
UseOCREngine(1)
var$=CaptureOCR$("NOTEPAD.EXE|Edit|Untitled - Notepad|1",1) 'var$ returns
the OCRized text which is seen in the Notepad window.
'The OCRengine used is the MODI one.
UseOCREngine(1)
var$=CaptureOCR$("NOTEPAD.EXE|Edit|Untitled - Notepad|1",1,"Japanese")
'var$ returns the OCRized text which is seen in an English Notepad window
using Japanese language for the text within the notepad window.
'The OCRengine used is the MODI one.
399
UsePage
Web function.
The UsePage function specifies the HTML page used by Web functions.
Usage
UsePage is used to bring to foreground/front the specified Web page so that it
may receive the next interactive actions. It includes an automatic synchronization
: the next step in the script is processed only when the specified page has been
found and ready for receiving actions. Wildcards are supported in page titles by
just truncating the unwanted last characters in the page title.
Syntax
UsePage(<page_title>)
or
ret=UsePage(<page_title>)
Parameters
<page_title>, string, Web page title of the Web page to which script actions will
be directed. You can use the SPY tool to generate automatically this statement
when you want to capture an HTML object on this specified Web page.
WinTask will try to find the Web page defined by UsePage for a period of time
defined by the system variable #ActionTimeout (default value is 30 seconds).
Once the page is found, WinTask makes it active and sends all Web actions to it.
If #UsePageExact is not set to 1, if a page with an approaching title is found,
WinTask makes it active and sends all actions to it. An approaching title is any
title starting with the same first character as specified in the UsePage function
(case sensitive).
Return value
Ret, numeric return code. When the <page_title> has been found and can be
activated, the function returns 0, otherwise use this return code for Error
Handling.
List of negative error codes
-1
No browser in use (no previous UsePage or StartBrowser)
-2
No browser having the expected page title has been found
-3
Bad descriptor, invalid syntax
-4
The browser has been lost (for instance because of a Closewindow)
-5
Page with the expected title has not been loaded within the timeout
-8
Specified element not found
-11
Any other error
-404,405
Usual http error codes
An HTTP error prevents the specified page to load (usually due to a
214669721 security reason)
1
Remarks
At execution, a UsePage replay forces the script to wait until the specified page is
fully loaded, even if a same UsePage line has been executed before. Recording
mode does not generate a UsePage line if a new page loads with the same title :
to force the synchronization, you can then add manually the same UsePage line
400
which has not been generated automatically.
See also
#UsePageExact
Example
The script below opens the Web site www.wintask.com, uses the main page of
the Web site, captures a paragraph and displays its content
StartBrowser("IE","www.wintask.com")
UsePage("Macro and Data Extraction with WinTask - the automation software
for Windows and internet")
ret = CaptureHTML("LI[CONTENT='Eliminate']", var$)
Msgbox(var$)
CloseBrowser()
401
#UsePageExact
System variable - Web function
The #UsePageExact system variable controls how HTML Web page titles are
handled when the script is running. The default value is 0, which means that the
script finds a Web page even if it has a slightly different title than the one it had
when the script was recorded (fuzzy matching).
Usage
UsePage function includes an automatic synchronization and waits until the page
is loaded. But if two Web pages have a title beginning with the same characters
and if no ClickHTMLElement line is between the two UsePage lines, you have to
force #UseExact=1 if you want WinTask to see it's 2 different pages. Wildcards in
page title are supported by truncating the page title.
Syntax
#UsePageExact = 0
or
#UsePageExact = 1
Remarks
If #UsePageExact=0 (default value), at execution of a UsePage function, WinTask
looks for a page title which starts with the same characters than those specified
in the UsePage function.
If a matching page title is still not found after the fuzzy match, the UsePage fails
and the error message "Page not found" is displayed (unless #IgnoreErrors=1)
Examples
'The UsePage replays correctly even if the specified title of the page is not the
correct one as the default value for #UsePageExact is 0
StartBrowser("IE", "www.wintask.com/demos")
UsePage("WinTask Demonstration Pages")
ClickHTMLElement("A[INNERTEXT= 'Same Title Pages']")
UsePage("Page With another title")
WriteHTML("INPUT TEXT[NAME= 'company']", "My Company")
'The UsePage does not replay correctly when #UsePageExact is set to 1
StartBrowser("IE", "www.wintask.com/demos")
#UsePageExact=1
UsePage("WinTask Demonstration Pages")
ClickHTMLElement("A[INNERTEXT= 'Same Title Pages']")
UsePage("Page With another title")
WriteHTML("INPUT TEXT[NAME= 'company']", "My Company")
'But this UsePage replays correctly even with #UsePageExact set to 1 as we have
truncated the title
StartBrowser("IE", "www.wintask.com/demos")
#UsePageExact=1
UsePage("WinTask Demonstration Pages")
ClickHTMLElement("A[INNERTEXT= 'Same Title Pages']")
402
UsePage("Page")
WriteHTML("INPUT TEXT[NAME= 'company']", "My Company")
403
Error codes for User dialog functions
There are no error codes for User dialog functions. At execution, the function
returns an empty string in case of an error.
Note that if the timeout is elapsed when executing MsgBox with a timeout, the
return code is 128 (or 1 if the dialog box has only a OK button).
404
UseWindow
Windows management function.
The UseWindow function specifies the window to which subsequent keyboard,
mouse and menu actions are directed.
Usage
UseWindow is used to bring to foreground/front the specified window so that it
may receive keystrokes, mouse clicks and other interactive actions. It includes an
automatic synchronization : the next step in the script is processed only when the
specified window has been found and ready for receiving user actions.
Syntax
UseWindow(<window_name> [,<instance>[,NoActivate]])
or
ret=UseWindow(<window_name> [,<instance>[,NoActivate]])
Parameters
<window_name>, string. window name (see this topic) of the window to which
script actions will be directed. You can use the SPY tool to manually determine
the caption of a window. During Recording mode they will be inserted
automatically. The window name can be truncated, for example
"NOTEPAD.EXE|Edit|Untitled - Notepad" can be truncated in
"NOTEPAD.EXE|Edit|" ; UseWindow function will search for any Edit window in
Notepad whatever document name is.
<instance>, optional parameter, instance number of the window.
WinTask will try to find the window defined by UseWindow for a period of time
defined by the system variable #ActionTimeout. Once the window is found,
WinTask makes it active and sends all actions to it. If #UseExact is not set to 1, if
a window with an approaching name is found, WinTask makes it active and sends
all actions to it.
The keyword NoActivate prevents the window from being activated ; this keyword
is generated automatically when Low level Recording mode is used. In this case,
the statements following UseWindow will activate the window - thus it is not
necessary to activate it beforehand.
Return value
Ret, numeric return code. When the <window_name> has been found and can be
activated, the function returns 0, otherwise use this return code for Error
Handling. At replay, the default behavior when the window is not found is to
display an error message and script execution stops. If #IgnoreErrors=1, the
execution is not stopped and you have to test the return code if you want to
avoid strange issues (for example sending keys to a window which is not the one
you expect as the previous UseWindow has failed and you are not aware of that
as #IgnoreErrors=1).
Remarks
Note that in Recording mode, a UseWindow is generated each time the target
window changes.
During execution, if the target window is minimized, it is automatically restored
and activated.
If #ActionTimeout has been set to a value lower or equal than 10, the exact
405
window name search is used.
See also
#UseExact, UseWindowHandle, Window name
Examples
UseWindow("NOTEPAD.EXE|Edit|Untitled - Notepad", 1)
Result = UseWindow(win$)
UseWindow("NOTEPAD.EXE|Edit|Untitled - Notepad", 1)
'Child window NOTEPAD , file "Untitled" opened, instance 1
UseWindow("NOTEPAD.EXE|Edit|Untitled - Notepad")
'Child window NOTEPAD , file "Untitled" opened, first instance found
UseWindow("NOTEPAD.EXE|Edit",1)
'Child window NOTEPAD , any file opened, instance 1
406
UseWindowHandle
Windows management function.
The UseWindowHandle function specifies the window (through the window
handle) to which subsequent keyboard, mouse and menu actions are directed.
Syntax
UseWindowHandle(<handle>)
or
ret=UseWindowHandle(<handle>)
Parameters
<handle>, numeric. Handle of the window to which subsequent keyboard, mouse
and menu actions are directed.
WinTask will try to find the window defined by UseWindowHandle for a period of
time defined by the system variable #ActionTimeout. Once the window is found,
WinTask makes it active and sends all actions to it. This function works as
UseWindow but allows to send actions to a window where the EXE part of the
window name changes from one execution to an other (for instance, when
installing Acrobat Reader several times).
Return value
Ret, numeric return code. When the window with its <handle> has been found
and can be activated, the function returns 0, otherwise use this return code for
Error Handling.
See also
GetWindowHandle
Examples
#Ignoreerrors=1
#ActionTimeout=12
a=GetWindowhandle("WORDPAD.EXE|RichEdit20A|doc - WordPad|1")
ret=UseWindowhandle(a)
msgbox(ret)
An error code is displayed as WordPad window is not there.
shell("wordpad.exe")
a=GetWindowhandle("WORDPAD.EXE|RichEdit20A|document - WordPad|1")
UseWindowhandle(a)
WordPad window takes focus and is ready to receive actions.
Example code
The script below installs Acrobat ; two functions are defined for testing if the
button we want to click is ready for being clicked ; GetWindowHandle and
UseWindowHandle are used (instead of UseWindow) as window names varies
from one installation to another.
'Function waits for object objet$ to have focus for Tmax seconds
function wait_focus(objet$,Tmax)
407
local i, exitr, a$
i=0
exitr=0
repeat
a$=focus$()
if instr(a$,objet$)=0 then
pause 1
i=i+1
if i > Tmax then
msgbox("wait too long for "+objet$)
stop
endif
else
exitr=1
endif
until exitr=1
endfunction
'-------------------------------------------'Function waits for object objet$ to be on top for Tmax seconds
function wait_top(objet$,Tmax)
local i, exitr, a$
i=0
exitr=0
repeat
a$=top$()
if instr(a$,objet$)=0 then
pause 1
i=i+1
if i > Tmax then
msgbox("wait too long for "+objet$)
stop
endif
else
exitr=1
endif
until exitr=1
endfunction
'----------------------------------------------#ActionTimeout=10
'Start Acrobat setup from CDROM
Shell("f:\Acrobat4\Setup.exe",1)
'License window
wait_focus("License",10)
408
a=getwindowhandle(top$())
usewindowhandle(a)
Click(Button,"&Accept")
'Installation choice
wait_focus("Button|Typical",10)
a=getwindowhandle(top$())
usewindowhandle(a)
Click(Button,"&Next >")
'User information window
wait_top("User information",10)
a=getwindowhandle(top$())
usewindowhandle(a)
Click(Button,"&Next >")
'Confirmation window
wait_focus("Button|&Yes",10)
a=getwindowhandle(top$())
usewindowhandle(a)
Click(Button,"&Yes")
'Last validation
wait_focus("Button|&Next",10)
a=getwindowhandle(top$())
usewindowhandle(a)
Click(Button,"&Next >")
409
UseWindowRegEx
Windows management function.
The UseWindowRegEx function specifies the window to which subsequent
keyboard, mouse and menu actions are directed, using Regular Expressions to
specify the window title part of the window name. Not available in WinTask Lite.
Usage
UseWindow is used to bring to foreground/front the specified window so that it
may receive keystrokes, mouse clicks and other interactive actions. If the exact
window name is not found at replay, a fuzzy match is tried, truncating the
rightmost characters until the specified window name is found. UseWindowRegEx
extends the fuzzy match and can trigger on a sub-string within the window title.
Regular expressions are text patterns that are used for window title matching.
Syntax
UseWindowRegEx(<window_name> [,<instance>[,NoActivate]])
or
ret=UseWindowRegEx(<window_name> [,<instance>[,NoActivate]])
Parameters
<window_name>, string. window name (see this topic) of the window to which
script actions will be directed. You can use the SPY tool to manually determine
the caption of a window. During Recording mode they will be inserted
automatically. The Regular expressions can be used to specify the title part of the
window name, for example if in "NOTEPAD.EXE|Edit|20.txt - Notepad" 20 is a day
number which changes every day, UseWindowRegEx("NOTEPAD.EXE|Edit|[09][0-9].* - Notepad") triggers on a window title whatever day number in it.
<instance>, optional parameter, instance number of the window.
WinTask will try to find the window defined by UseWindowRegEx for a period of
time defined by the system variable #ActionTimeout. Once the window is found,
WinTask makes it active and sends all actions to it. We recommend to set
#UseExact at 1 when using a Regular Expression.
The keyword NoActivate prevents the window from being activated ; this keyword
is generated automatically when Low level Recording mode is used. In this case,
the statements following UseWindowRegEx will activate the window - thus it is
not necessary to activate it beforehand.
Return value
Ret, numeric return code. When the <window_name> has been found and can be
activated, the function returns 0, otherwise use this return code for Error
Handling.
Remarks
We describe below the most common cases for Regular Expressions:
Charac Description
Examples
ter
.
Matches a single character
a.r matches a0r, air, a£r,...
*
Repeats the previous character abc* matches ab, abc, abcc, abccc, ...
zero or several times
+
Repeats the previous character abc+ matches abc, abcc, abccc, ...
one or several times
410
?
Makes the preceding character
optional
|
Alternation, regular expression
equivalent of OR
[]
Matches one out of several
characters
{n}
Repeats n times the previous
character
{n,m} Repeats the previous character
between n and m times
[-]
Matches one out of a range of
several characters
[ ^ - ] Excludes the range of several
characters
^
Outside a [, matches at the start
of the string
$
Matches at the end of the string
\chara A backslash escapes special
ct.
characters above their meaning
During execution, if the target window is
and activated.
abc? matches ab or abc
200[6|7] matches 2006 or 2007
gr[ae]y matches gray, grey but not
graey
a{3} matches aaa
a{2,4} matches aa, aaa, aaaa
gr[0-9]y matches gr0y, gr1y, ... gr9y
but not gr19y
gr[^0-9]y matches gray, grby, grcy, ...
grzy but not gr0y, gr1y,... gr9y
^begin matches begin, beginning, begin
with
end$ matches end, will end, at the end
\+ matches + (and so the + sign does
not have its special meaning)
minimized, it is automatically restored
See also
#UseExact, UseWindowHandle, Window name
Examples
We list below the most common cases
Single character
Keys have to be sent to the notepad window whatever character is after Doc
#UseExact=1
UseWindowRegEx("NOTEPAD.EXE|Edit|Doc. - Notepad|1")
SendKeys("Hello")
Triggers for any window Doca, Docb, ..., Doc0, Doc1, ....
Single character in a list
Keys have to be sent to the notepad window if, after Doc, the year is 2005, 2006
or 2007
#UseExact=1
UseWindowRegEx("NOTEPAD.EXE|Edit|Doc200[567] - Notepad|1")
SendKeys("Hello")
Triggers for any window Doc2005, Doc2006, or Doc2007
Single character NOT in a list
Keys have to be sent to the notepad window if, after Doc, the year is NOT 2005,
2006 or 2007
#UseExact=1
UseWindowRegEx("NOTEPAD.EXE|Edit|Doc200[^567] - Notepad|1")
SendKeys("Hello")
Triggers for any window Doc2000, Doc2001, Doc2002, Doc2003, Doc2004,
Doc2008, Doc2009 and Doc200a, Doc200b, ...
Single character within a range
Keys have to be sent to the notepad window if, after Doc, it can be any year in
the 1990s
#UseExact=1
UseWindowRegEx("NOTEPAD.EXE|Edit|Doc199[0-9] - Notepad|1")
SendKeys("Hello")
Triggers for any window Doc1990, Doc1991,..., Doc1999
411
412
Val
String management function.
The Val function converts a string to a number.
Syntax
Number=Val(<string$>)
Parameters
<string$>, string to be converted to a number.
Remarks
The Val function stops reading the string at the first character which cannot be
considered as a numeric. The Val function removes leading and trailing spaces.
See also
Str$
Examples
number = Val("123") ' Returns the integer 123
number = Val("-123") ' Returns the integer -123
number = Val("12X3") ' Returns the integer 12
number = Val(var$)
Dim array$(10)
ReadExcel("c:\quotation.xls","A10:A10",array$())
number=Val(array$(0)) 'ReadExcel returns a string in array$(0) which is the
content of A10 cell, Val function converts to a number
413
Error codes for Web functions
The table below lists the possible error codes for the WinTask Web functions, for
the errors stopping script execution (unless #IgnoreErrors=1).
214669721
1
-404,-405
-12
-11
-10
-8
-7
-5
-4
-3
-3
-2
-1
-1
-1
414
An HTTP error prevents the specified page to load
Usual HTTP error codes
Download timeout
Internal error
The IE browser object cannot "navigate" the specified address
HTML Element not found
Index too big
Page has not finished to load within the timeout
Browser lost
Bad HTML descriptor
Browser not recognized (Only for StartBrowser function when its first
parameter is different from "IE")
Page not found
Impossible to capture or invalid range (Capture Web functions)
No browser in use (no UsePage or StartBrowser before)
The extraction cannot be done (ExtractLink function)
WeekDay
Date/Time function
The Weekday function returns the current day of the week as a number.
Syntax
day=WeekDay()
Return value
day, integer as below :
1
Sunday
2
Monday
3
Tuesday
4
Wednesday
5
Thursday
6
Friday
7
Saturday
Example
day=WeekDay() ' returns 2 if today is Monday
415
While...Wend
Program flow management function.
The While...wend structure defines a loop with a completion check at the
beginning.
Usage
Used to repeat the same steps a certain number of times or until a condition is
true.
Syntax
While <boolean_expression>
<statements>
Wend
Parameters
<statements>: statements to be executed while <boolean_expression> is true.
See also
Logical operators
Repeat...until
Example
a = 0
While a < 5
beep (100)
a = a + 1
Wend
416
WinDir$
System function
The WinDir$ function returns the name of the directory where Windows is
installed.
Syntax
var$=WinDir$()
Return value
var$, string containing the name of the directory where Windows is installed
Examples
var$=WinDir$()
msgbox(var$) 'Returns C:\Windows if Windows system is installed on C:
a$=windir$()+"\system"
msgbox(a$) 'Returns C:\Windows\system
417
Error codes for Windows management functions
The table below lists the possible error codes for the WinTask Windows
management functions, for the errors stopping script execution (unless
#IgnoreErrors=1).
41
42
43
44
45
46
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
64
65
75
76
77
78
90
95
98
99
105
106
108
418
Window not found (or window handle not found)
Window name empty
No window specified
Impossible to move the window
Impossible to resize the window
Focus change error
Impossible to find Edit box
Impossible to find Combobox
Impossible to attach to Combobox
Impossible to find Listbox control
Impossible to find Combobox control
Impossible to find Listview control
Impossible to find Treeview control
Impossible to find button
Impossible to find checkbox
Impossible to find radiobutton
Impossible to find Tab
Invalid scrollbar
Impossible to create the msgframe
New coordinates for window are out of the screen
Impossible to read window size
Out of screen
Item not found
Empty menu name
Menu not found
Menu attach error
Menu item not found
Internal error
Invalid instance number
Error in key list inside instruction SendKeys
Invalid parameter
Invalid UI command (the User Interface is not available when
running a non-interactive task via Scheduler)
Invalid toolbar
Invalid Regular Expression
Write
File management function.
The Write function writes data to the specified file.
Usage
It writes data to an external text file which can be used in other applications.
Syntax
Write(<filename>,<buffer>)
Write(<filename>,<buffer>,<n>)
Write(<filename>,<buffer>,<sep$>)
Write(<filename>,<buffer>,CRLF)
or
ret=Write(<filename>,<buffer>)
ret=Write(<filename>,<buffer>,<n>)
ret=Write(<filename>,<buffer>,<sep$>)
ret=Write(<filename>,<buffer>,CRLF)
Parameters
<filename>, string, name of the file to which <buffer> is written. It's not
necessary to create the file first ; if the file does not exist, it is created when the
first write is performed. If the file already exists, the write is done after the
existing data. If you use Unicode encoding, the file must have been created first
using CreateUnicodeFile function before Write can write Unicode strings.
<filename> is a string, either a variable either a constant. Long names are
accepted as well as UNC names (such as \\server\c\my directory\my file.txt).
<buffer>: string, it must be a variable. Up to 32K of data can be written with a
single Write. <buffer> is added at the end of file <filename>.
The Write is always performed sequentially; it's not possible to change the write
pointer (as you can with the Read function).
<n>, integer; only the first n bytes of <buffer> are written in the file. If <buffer>
contains less than n characters, it is padded with spaces.
<sep$>, string (variable or constant). First <buffer> is written to the file, then
<sep$> is written.
CRLF: keyword (chr$(13)+chr$(10)), which can be used as a separator in order
to write to a file one line at a time.
Return value
Ret, numeric return code. When the Write is successful, the function returns 0,
otherwise use this return code for Error Handling.
Examples
Write(file$,var$)
Write("c:\sample.txt", var$)
Write(file$,var$,80)
Write(file$,var$,n)
Write(file$,var$,CRLF)
Write(file$,var$,"sample")
419
Example code
For a complete example, see the Read function
420
WriteCom
Com port management function. Function not available anymore since Windows
XP.
The WriteCom function writes the specified string to the specified Com port. Not
available in WinTask Lite.
Syntax
ret=WriteCom(<port_num>,<char$>)
Parameters
<port_num>: Com port number to write to (from 1 to 8, Com1 to Com8).
<char$>: character string to be written.
Return value
Ret, numeric return code. If the string is successfully written, the function returns
0, otherwise use this return code for Error Handling.
See also
OpenCom, CloseCom, ReadCom
Example code
For this example, you must connect two PCs with a NULL MODEM cable (using
COM1).
The sending program installed on one of the PCs sends a 20 character string. The
receiving program installed on the other PC waits until the sender sends a 20character string to it.
Settings for the Com port are:
No flow control, COM1, Speed 9600, no parity, 8 data bits, 1 stop bit.
'******************************************************
'**************** Sending program *********************
'******************************************************
res=OpenCom(1,9600,"n",8,1,"n" )
SendVar$="SERIAL PORT TEST"
' the string SendVar$ will be sent to the serial port.
res=WriteCom(portnum,SendVar$)
res=CloseCom(1)
'******************************************************
'************* Receiving program **********************
'******************************************************
sub main(ByteNb)
421
var$=""
res = ReadCom(1,ByteNb,var$)
Select Case res
Case 0
' we emptied the buffer, we received the 20 characters
message$=message$+var$
out=1
Case 13
'it there are not 20 characters in the buffer, it is necessary to make
another
' read but with the number of characters equal to the number of characters
still
' in the buffer
message$=message$+var$
i=i-len(var$)
Case Else
msgbox("unexpected characters"+str$(res))
stop
EndSelect
Endsub
res=OpenCom(1,9600,"n",8,1,"n" )
i=20
out=0
message$=""
repeat
main(i)
until out=1
res=CloseCom(1)
msgbox(message$,32,"Received")
422
WriteCombo
Windows management function.
The WriteCombo function writes to the edit field of a combobox.
Syntax
WriteCombo(<combo_name>,<text>)
or
ret=WriteCombo(<combo_name>,<text>)
Parameters
<combo_name>, string, name of the combobox used.
<text>, string, text to write to the edit field of the combobox.
Return value
Ret, numeric return code. When the write is successful, the function returns 0,
otherwise use this return code for Error Handling.
Examples
WriteCombo("|1","")
Result = WriteCombo(var_id$, text$)
423
WriteEdit
Windows management function.
The WriteEdit function writes into the specified edit field.
Syntax
WriteEdit(<edit_field>,<text>)
or
ret=WriteEdit(<edit_field>,<text>)
Parameters
<edit_field>, string, name of the edit field.
<text>, string, text to write into the edit field.
Return value
Ret, numeric return code. When the write is successful, the function returns 0,
otherwise use this return code for Error Handling.
Remarks
WriteEdit writes in standard edit fields. If WriteEdit does not work on your specific
edit field, use SendKeys instead such as :
towrite$="my text"
UseWindow(<window_name_of_the_edit_field>)
SendKeys(towrite$,NoActivate)
Sometimes, you will want to delete the content of the edit field before writing
your text, here is an example :
towrite$="my text"
UseWindow(<window_name_of_the_edit_field>)
SendKeys("<Home>",NoActivate)
pause 5 ticks
SendKeys("<Shift <End>>",NoActivate)
pause 5 ticks
SendKeys("<Del>",NoActivate)
pause 5 ticks
SendKeys(towrite$,NoActivate)
Examples
WriteEdit("1", "Hello")
Result = WriteEdit(var_id$, text$)
424
WriteEditEncrypted
Windows management function.
The WriteEditEncrypted function writes an encrypted string into the specified
edit field (Not available in WinTask Lite).
Syntax
WriteEditEncrypted(<edit_field>,<encrypted_text>)
or
ret=WriteEditEncrypted(<edit_field>,<encrypted_text>)
Parameters
<edit_field>, string, name of the edit field.
<encrypted_text>, string, encrypted text to write into the edit field.
Return value
Ret, numeric return code. When the write is successful, the function returns 0,
otherwise use this return code for Error Handling.
Remarks
To encrypt the string you want to send in the edit field, use Insert/Encrypted
string menu option or Encrypt statement.
Examples
WriteEditEncrypted("1", "H9hfSsHbGkkF1qj")
text$="H9hfSsHbGkkF1qj"
var_id$="1"
Result = WriteEditEncrypted(var_id$, text$)
425
WriteExcel
File management function.
The WriteExcel function writes a cell, a row or a column in the specified Excel
workbook. Microsoft Excel must be installed on the PC, but does not need to be
opened. The workbook must exist but must not be opened.
Usage
Mainly used to populate columns or lines of data in an Excel file, those data can
be captured on a Web site, or copied from a Windows application. As the Excel
file must exist, you can use CreateExcelFile function to create it.
Syntax
WriteExcel(<workbook>,<range_descriptor>,<array$>[,<readPasswd$>][,<edit
Passwd$>])
or
ret=WriteExcel(<workbook>,<range_descriptor>,<array$>[,<readPasswd$>][,<
editPasswd$])
Parameters
<workbook>, string, name of the Excel workbook to write. <workbook> is a
string which can be a constant or a variable. Long file names and UNC names are
accepted, such as \\Server\c\my_directory\my_file.xls. If the path is not
specified, the file is searched in the current directory.
<range_descriptor>, string. If only one sheet exists in the workbook, only the
range of cells must be specified, such as A4:F4 for a row or A2:A12 for a column.
If multiple sheets exist in the workbook, the required syntax is
"sheet_name!range_of_cells"; for example, TOOLS!A9:F9
Other range examples: mycell1 (a named cell), A1, A3:B3, tools!$b$2:$b$4
<array$>, array of strings. The array must be declared at the beginning of the
script using Dim. The contents of the non-empty cells in <array> are written to
<range_descriptor>, beginning with cell 0. If the array is larger than the range,
only the number of cells which fit in the range are written.
<readPasswd$>, optional string parameter; password for reading the
<workbook> if needed.
<editPasswd$>, optional string parameter; password for editing the <workbook>
if needed.
Return value
Ret, numeric return code. When the write is successful, the function returns the
number of cells written, otherwise use this return code for Error Handling. The
return code is -1 if an error is reported by Excel or the range is invalid. The
return code is -3 if the Excel file is opened (WriteExcel cannot write in an opened
Excel file).
See also
ReadExcel
CreateExcelFile
CloseExcelCom
How to read all the lines of an Excel worksheet until the cell in the first column is
426
empty
Excel, useful functions
Capture stock data from a website and write them in Excel
Example
dim array$(20)
'fill array$ and then
ret=WriteExcel("C:\My documents\myexcel_file.xls","TOOLS!A9:F9",array$())
Example code
The script below reads all the lines from an Excel file from A column to C column
and writes them in another Excel file.
dim arrayline$(10)
fileexcel$="c:\example1.xls"
filetowritein$="c:\test.xls"
j=1
repeat
' The complex string "sheet1!"+"a"+str$(j)+":c"+str$(j) means if j=1
' "Sheet1!a1:c1"
readexcel(fileexcel$,"sheet1!"+"a"+str$(j)+":c"+str$(j),arrayline$())
WriteExcel(filetowritein$,"sheet1!"+"a"+str$(j)+":c"+str$(j),arrayline$())
j=j+1
until arrayline$(0)=""
427
WriteHTML
Web function.
The WriteHTML function writes text in a Web form.
Usage
Used mainly to fill automatically a form ; the data to write can be retrieved from
an Excel file, an Ascii file, an ODBC database, or just from Clipboard.
Syntax
ret=WriteHTML(<html_descriptor>,<text>)
Parameters
<html_descriptor>, unique identifier for the HTML object where to write within
the current Web page specified by the last UsePage. See HTML descriptor for
HTML tags identification. Use Recording mode for generating automatically the
WriteHTML syntax.
<text>, string, text to be typed in the form control. If the string includes special
characters (for instance a <), keyboard mnemonics must be used ; Recording
mode generates them for you.
Return value
Ret, numeric return code. The function tries to find the HTML object for 30
seconds (this default value can be changed using #ActionTimeout), and then
types the text. If the object has been found, the function returns 0. Otherwise
use this return code for Error Handling.
List of negative error codes
-1
No browser in use (no previous UsePage or StartBrowser)
-3
Bad descriptor, invalid syntax
-4
The browser has been lost (for instance because of a Closewindow)
-5
Page not found
-8
Specified element not found
-11
Any other error
-404,405
Usual http error codes (requires IE 6 or above)
Remarks
If the field in the Web form is already filled, WriteHTML for INPUT TEXT tag
deletes the content and writes the string specified by the function. If you need to
force the the content deletion, use "" as for instance :
WriteHTML("INPUT TEXT[NAME='first_name']","")
BUT WriteHTML for TEXTAREA tag (multiple lines for the text) writes the
specified string where the current cursor is (or a the end of the existing
characters if the text cursor is not within the field). If you need to force the
content deletion, use then <BackSpace> keyboard mnemonic as for instance:
WriteHTML("TEXTAREA[NAME= 'steps']",
"<BackSpace><BackSpace><BackSpace><BackSpace><BackSpace><BackSpac
e>")
WriteHTML function cannot send as is keyboard mnemonics such as <Alt
<Enter>>, you need to use the keyboard mnemonics for the string to send,
"normal text"+"<Alt <Enter>>"+"normal text".
See also
428
#HTMLPosRetry
Examples
On the demonstration WinTask Web site, we click the Form link and then we fill
the form:
StartBrowser("IE", "www.wintask.com/demos")
UsePage("WinTask Demonstration Pages")
ClickHTMLElement("A[INNERTEXT= 'Form']")
UsePage("Form")
WriteHTML("INPUT TEXT[NAME= 'company']", "My Company")
ClickHTMLElement("INPUT RESET[VALUE= 'Clear']")
CloseBrowser()
Fill a form using values read in an Excel file:
' We need to populate an array reading the values in the Excel file. First
line in the script must be the declaration of the array
Dim data$(100)
'Read the excel file
fileexcel$="myexcelfile.xls" ' If you use Excel 2007, the extension is xlsx
'In data$ array, we store the content of the cells from A1 to A100
ReadExcel(fileexcel$,"A1:A100", data$())
'data$(0) contains A1 cell, data$(1) contains A2 cell and so on.
'Now we can fill the form in a loop
i=0
repeat
UsePage("My Web Form")
WriteHTML("INPUT TEXT[NAME= 'q']", data$(i))
i=i+1
until data$(i)=""
429
WriteHTMLEncrypted
Web function.
The WriteHTMLEncrypted function writes an encrypted text in a Web form (Not
available in WinTask Lite).
Usage
Used to fill automatically a password field on a Web page. Use Recording mode to
generate automatically the encrypted password (in Configure/Recording menu,
you must have Encrypt web passwords checked), or use Insert/Encrypted
string menu option if you prefer to generate it yourself.
Syntax
ret=WriteHTMLEncrypted(<html_descriptor>,<encrypted_text>)
Parameters
<html_descriptor>, unique identifier for the HTML object where to write within
the current Web page specified by the last UsePage. See HTML descriptor for
HTML tags identification. Use Recording mode for generating automatically the
WriteHTMLEncrypted syntax.
<encrypted_text>, string, encrypted text to be typed in the password field.
Return value
Ret, numeric return code. The function tries to find the HTML object for 30
seconds (this default value can be changed using #ActionTimeout), and then
types the encrypted text. If the object has been found, the function returns 0.
Otherwise use this return code for Error Handling.
List of negative error codes
-1
No browser in use (no previous UsePage or StartBrowser)
-3
Bad descriptor, invalid syntax
-4
The browser has been lost (for instance because of a Closewindow)
-5
Page not found
-8
Specified element not found
-11
Any other error
-404,405
Usual http error codes (requires IE 6 or above)
See also
Encrypt
Example
UsePage("Barclays")
WriteHTML("INPUT TEXT[NAME= 'nocompte']", "46XT38000T")
WriteHTMLEncrypted("INPUT PASSWORD[NAME= 'passe']", "Hbh0SSJXXjA2vbB1wD2")
ClickHTMLElement("INPUT IMAGE[NAME= 'img3']")
430
WriteIni
System function.
The WriteIni function writes to the specified INI file. Not available in WinTask
Lite.
Usage
An INI file is easy to manage when external data have to be shared with one or
several scripts. Data are organized properly and WriteIni function writes directly
the specified data at the proper place without dealing with read pointers, End Of
File character, record separator character, ...
Syntax
WriteIni(<filename>,<Section>,<Item>,<Value$>)
or
ret=WriteIni(<filename>,<Section>,<Item>,<Value$>)
Parameters
<filename>: string; INI file to write to. It can be a long file name or a UNC name.
If the path is not specified, the file is searched in Windows directory. If
<filename> does not exist, it is created.
<Section>: string; section of the INI file to write to (or to create).
<Item>: string; item of the INI file to write to (or to create).
<Value$>: string; value to be written to the INI file.
Return value
Ret, numeric return code. When the write is successful, the function returns 0,
otherwise use this return code for Error Handling.
See also
ReadIni$
Example
WriteIni("sample.ini", "Section1","Item1","123")
When done, SAMPLE.INI looks like this :
[Section1]
...
Item1 = 123
...
431
WriteReg
System function.
The WriteReg function creates or modifies a string or a numeric value in
Windows Registry. Not available in WinTask Lite.
Syntax
WriteReg(<path>,<type>,<value>)
or
ret=WriteReg(<path>,<type>,<value>)
Parameters
<path>: entire tree before the value ; it does not contain the value.
For instance:
"HKEY_LOCAL_MACHINE\SOFTWARE\TaskWare\WinTask\1.0\Name"
If the path or value do not exist, they are created. If the value already exists, it is
replaced by the new <value>.
<type> can be:
1
string
2
string expand
3
binary
4
integer
7
string multiple
<value> must be a variable.
Return value
Ret, numeric return code. When the registry change is successful, the function
returns 0, otherwise use this return code for Error Handling.
Remarks
If there is an inconsistency between the specified <type> and <value>, a
compilation error is generated.
Under Windows Vista, if you don't have enough rights, writing in Registry is
allowed only under HKEY_CURRENT_USER. If you execute a WriteReg with not
admin rights, writing under HKEY_LOCAL_MACHINE, Windows Vista writes a
virtualized key which is in fact under
HKEY_CURRENT_USER\Software\Classes\VirtualStore
Example
WriteReg("HKEY_LOCAL_MACHINE\SOFTWARE\TaskWare\WinTask\1.0\Name",1,name$)
Example code
#IgnoreErrors=1
path$="HKEY_LOCAL_MACHINE\Personal\Id\"
firstname$="Robert"
lastname$="DUPONT"
age=40
idnumber=300000000
432
binary_key$="01000ff00c0"
res=WriteReg(path$+"FirstName",1,firstname$)
res=WriteReg(path$+"Lastname",1,lastname$)
res=WriteReg(path$+"Age",4,age)
res=WriteReg(path$+"Id",4,idnumber)
res= WriteReg(path$+"Key",3,binary_key$)
msgbox("Return code : "+str$(res),64,"Write to Registry")
433
Year$
Date/Time function
The Year$ function returns the current year as a string.
Syntax
ye$=Year$()
Return value
ye$, string, current 4-character year.
Example
yr$=Year$() ' for instance, yr$ contains "2007"
434
Index
#ActionTimeout .............................................................................................................................38, 446
#CurrentLine .......................................................................................................................................114
#DbDateFormat...................................................................................................................................128
#DecimalSeparator ..............................................................................................................................144
#ErrorCode ..........................................................................................................................................171
#ErrorFunction$ .................................................................................................................................172
#ErrorLine$ .........................................................................................................................................173
#ErrorMsg$..........................................................................................................................................174
#ErrorScript$.......................................................................................................................................175
#ExecTimeout ......................................................................................................................................177
#ExecuteDelay .....................................................................................................................................179
#FTPTimeout.......................................................................................................................................222
#HideIcon ............................................................................................................................................252
#HideTrayIcon.....................................................................................................................................253
#HTMLPosRetry..................................................................................................................................255
#IgnoreErrors ......................................................................................................................................259
#IgnoreHTMLCase .............................................................................................................................260
#LastErrorLine ....................................................................................................................................280
#LastErrorLine$ ..................................................................................................................................280
#PauseTimeout ............................................................................................................................334, 340
#Precision ............................................................................................................................................349
#ScriptAfterTimeout$ ..........................................................................................................................382
#SendKeysDelay ..........................................................................................................................397, 399
#TextLookFrequency...........................................................................................................................429
#UseExact ............................................................................................................................................439
#UsePageExact ....................................................................................................................................443
ABS ........................................................................................................................................................97
Absolute ...............................................................................................................................................305
Active............................................................................................................................................320, 334
Add$ .......................................................................................................................................................40
addition ................................................................................................................................................329
Allocate ..................................................................................................................................................41
Alphabetical WinTask functions list and parameters...........................................................................42
AND .....................................................................................................................................................329
AppendXMLNode ..................................................................................................................................48
Arithmetical operators.........................................................................................................................329
Array ....................................................................................................................................................118
Array operators....................................................................................................................................329
Asc..........................................................................................................................................................50
ASCII character.....................................................................................................................................86
Attribute .................................................................................................................................................51
attributes ..............................................................................................................................149, 197, 402
Beep........................................................................................................................................................52
BeginDialog...EndDialog ......................................................................................................................53
Binary operators for integers ..............................................................................................................329
block-level text tags................................................................................................................................70
BMP .......................................................................................................................................................92
Boolean expressions ............................................................................................................................329
Bottom..........................................................................................................................................311, 313
Button.....................................................................................................................................................87
CallDialog ..............................................................................................................................................57
CapsLock ...............................................................................................................................................58
CAPTION ..............................................................................................................................................53
Capture Bitmap dialog box..................................................................................................................63
Capture$.................................................................................................................................................59
435
CaptureArea$.........................................................................................................................................65
CaptureAreaOCR$ ................................................................................................................................67
CaptureBitmap.......................................................................................................................................69
CaptureHTML .......................................................................................................................................70
CaptureIE$ ............................................................................................................................................71
CaptureOCR$ ........................................................................................................................................72
CaptureTableHTML..............................................................................................................................74
case.......................................................................................................................................................260
character case ......................................................................................................................................260
ChDir .....................................................................................................................................................76
Check ...............................................................................................................................................53, 87
CheckedHTML ......................................................................................................................................77
CheckedW ..............................................................................................................................................78
child window ........................................................................................................................................433
ChooseItem ............................................................................................................................................80
ChooseMenu ..........................................................................................................................................83
Chr$ .......................................................................................................................................................86
CHR$(34).............................................................................................................................................376
Click .......................................................................................................................................................87
ClickHTMLElement ..............................................................................................................................89
ClickMouse ............................................................................................................................................91
ClickOnBitmap ......................................................................................................................................92
ClickOnText...........................................................................................................................................94
ClickOnTextOCR...................................................................................................................................95
ClickScrollBar .......................................................................................................................................97
ClickSpin................................................................................................................................................98
Clipboard .....................................................................................................................................226, 403
clock .............................................................................................................................369, 417, 421, 431
CloseBrowser .........................................................................................................................................99
CloseCom .............................................................................................................................................100
CloseExcelCom....................................................................................................................................101
CloseWindow .......................................................................................................................................103
CloseWindowRegEx ............................................................................................................................104
Com ......................................................................................................................................328, 356, 462
Com port ..............................................................................................................................................100
combobox .................................................................................................................................53, 80, 464
command line.......................................................................................................................................106
Command$...........................................................................................................................................106
Comment..............................................................................................................................................108
Concatenation operator.......................................................................................................................329
context....................................................................................................................................................83
context menu..........................................................................................................................................83
context menu selection ..........................................................................................................................83
coordinates of the mouse.....................................................................................................................304
CopyLink..............................................................................................................................................109
Create ...................................................................................................................................................110
CreateExcelFile ...................................................................................................................................111
CreateUnicodeFile...............................................................................................................................112
CRLF ...........................................................................................................................................352, 460
Curdir$.................................................................................................................................................113
current line number.............................................................................................................................114
current working directory....................................................................................................................113
CurrentPage$.......................................................................................................................................115
CursorX................................................................................................................................................117
CursorY................................................................................................................................................117
data types..............................................................................................................................................118
Date$ ....................................................................................................................................................120
DateBetween ........................................................................................................................................121
DateToDate$ ........................................................................................................................................123
Day$ .....................................................................................................................................................124
436
DbBof ...................................................................................................................................................125
DbClose................................................................................................................................................126
DbConnect ...........................................................................................................................................127
DbDisconnect.......................................................................................................................................129
DbEof ...................................................................................................................................................130
DbExecute............................................................................................................................................131
DbGetFieldNumeric ............................................................................................................................132
DbGetFieldString ................................................................................................................................134
DbMove................................................................................................................................................136
DbMoveFirst ........................................................................................................................................137
DbMoveLast.........................................................................................................................................138
DbMoveNext ........................................................................................................................................139
DbMovePrev ........................................................................................................................................140
DbRecordCount ...................................................................................................................................141
DbSelect ...............................................................................................................................................142
debug....................................................................................................................................................259
decimal Separator................................................................................................................................144
decision making ...................................................................................................................................258
declarations..........................................................................................................................................350
DEFPUSHBUTTON .............................................................................................................................53
Delete ...................................................................................................................................................270
Delete files............................................................................................................................................270
delete the content .................................................................................................................................465
delete the content of the edit field........................................................................................................465
DeleteRegKey.......................................................................................................................................145
DeleteRegValue ...................................................................................................................................146
DelTree.................................................................................................................................................147
dialog box...............................................................................................................................53, 264, 309
Dim.......................................................................................................................................................148
Dir ........................................................................................................................................................149
Directory existence ..............................................................................................................................181
DirTree.................................................................................................................................................151
Disable .................................................................................................................................................153
DiskFree...............................................................................................................................................155
Divide$ .................................................................................................................................................156
division (integer mode) ........................................................................................................................329
Double....................................................................................................................................................91
Down ......................................................................................................................................................91
edit field................................................................................................................................................465
EDITTEXT ............................................................................................................................................53
Else.......................................................................................................................................................258
Enable ..................................................................................................................................................157
EnabledW.............................................................................................................................................158
Encrypt.................................................................................................................................................161
encrypted keystrokes ............................................................................................................................400
encrypted password..............................................................................................................................471
End .......................................................................................................................................................162
end of the file .......................................................................................................................................170
EndFunction........................................................................................................................................224
Endif.....................................................................................................................................................258
EndSelect .............................................................................................................................................385
EndSub.................................................................................................................................................423
EnumXMLAttributes ...........................................................................................................................163
EnumXMLChildren.............................................................................................................................165
Envir$...................................................................................................................................................168
environment variable...........................................................................................................................168
Eof........................................................................................................................................................170
Equal to................................................................................................................................................329
Error codes for Capture functions ........................................................................................................64
Error codes for File management functions ......................................................................................196
437
Error codes for Flow control functions ..............................................................................................204
Error codes for FTP functions............................................................................................................206
Error codes for ODBC functions ........................................................................................................319
Error codes for Synchronization functions ........................................................................................426
Error codes for User dialog functions ................................................................................................445
Error codes for Web functions ............................................................................................................455
Error codes for Windows management functions ..............................................................................459
error sub-routine returning the non-expected page ...........................................................................115
event handler .......................................................................................................................................320
Event management ..............................................................................................................................320
Exact ............................................................................................................................................320, 334
excluded ...............................................................................................................................................192
ExecExcelMacro..................................................................................................................................176
Exist .....................................................................................................................................................180
ExistDir................................................................................................................................................181
ExistHTMLElement ............................................................................................................................182
Exists............................................................................................................................................320, 334
ExistW..................................................................................................................................................184
ExitFunction................................................................................................................................186, 224
ExitSub.........................................................................................................................................187, 423
expand....................................................................................................................................................80
External ...............................................................................................................................................189
external data ................................................................................................................................361, 472
External$ .............................................................................................................................................188
ExtractBetween$..................................................................................................................................192
ExtractLink ..........................................................................................................................................194
FALSE .................................................................................................................................................258
file attributes ........................................................................................................................................402
File existence .......................................................................................................................................180
FileAttr$...............................................................................................................................................197
FileCopy...............................................................................................................................................198
FileDate$ .............................................................................................................................................199
FileSize.................................................................................................................................................201
FileTime$.............................................................................................................................................202
FileVersion$ ........................................................................................................................................203
Fill a form using values read in an Excel file ....................................................................................469
floating numerics.................................................................................................................................118
focus .............................................................................................................................158, 205, 433, 434
Focus$..................................................................................................................................................205
FTPChDir ............................................................................................................................................207
FTPConnect.........................................................................................................................................208
FTPCurrentDir....................................................................................................................................210
FTPDisconnect ....................................................................................................................................211
FTPExistDir ........................................................................................................................................212
FTPExistFile .......................................................................................................................................213
FTPGetFile ..........................................................................................................................................214
FTPKill ................................................................................................................................................216
FTPMkDir ...........................................................................................................................................217
FTPName.............................................................................................................................................218
FTPPutFile ..........................................................................................................................................219
FTPRmDir ...........................................................................................................................................221
Function...............................................................................................................................................224
Functions .............................................................................................................................................350
functions list and parameters ................................................................................................................42
GetClipboard$......................................................................................................................................226
GetCpuLoad.........................................................................................................................................227
GetFocusWindowHandle ....................................................................................................................228
GetFrameSource$................................................................................................................................229
GetHTMLEditText...............................................................................................................................230
GetMemUsage......................................................................................................................................232
438
GetPageSource$ ..................................................................................................................................233
GetProcessCpuLoad ............................................................................................................................234
GetProcessList .....................................................................................................................................235
GetReadPos..................................................................................................................................237, 352
GetTopWindowHandle ........................................................................................................................238
GetWindowHandle ..............................................................................................................................239
GetWindowName$ ...............................................................................................................................242
GetWindowsList...................................................................................................................................243
GetXMLAttribute .................................................................................................................................245
Global variables ..................................................................................................................................248
Go to.....................................................................................................................................................249
Goto......................................................................................................................................................249
Greater than.........................................................................................................................................329
Greater than or equal to ......................................................................................................................329
GROUPBOX ..........................................................................................................................................53
H 97
Handle..................................................................................................................................................239
HardCopy.....................................................................................................................................177, 250
Hour$ ...................................................................................................................................................254
HTML block-level text tags ...................................................................................................................70
HTML tags.............................................................................................................................................70
Hundreds .............................................................................................................................................257
ICON......................................................................................................................................................53
If 258
Immediate ............................................................................................................................................103
ImpersonateUser..................................................................................................................................261
Include .........................................................................................................................................263, 350
included........................................................................................................................................192, 280
INI................................................................................................................................................361, 472
INI file..........................................................................................................................................361, 472
inner text ................................................................................................................................................70
InputBox$ ............................................................................................................................................264
InputBoxSecret$ ..................................................................................................................................265
Instr......................................................................................................................................................266
InstrRev................................................................................................................................................267
integer ..................................................................................................................................................118
Invalid Pause ... Until..........................................................................................................................366
InWindow.............................................................................................................................................334
InWindowAnyInstance................................................................................................................320, 334
IsRunning ............................................................................................................................................268
IsServiceStarted ...................................................................................................................................269
keyboard event .....................................................................................................................................320
keyboard input .....................................................................................................................................397
keyboard shortcut ..................................................................................................................................83
Kill........................................................................................................................................................270
KillApp .................................................................................................................................................271
KillAppChildren...................................................................................................................................273
KillProcess ...........................................................................................................................................275
label......................................................................................................................................................249
Lcase$ ..................................................................................................................................................281
leading and trailing spaces..................................................................................................................435
Left .........................................................................................................................................................91
Left$ .....................................................................................................................................................282
Len .......................................................................................................................................................283
Less than ..............................................................................................................................................329
Less than or equal to ...........................................................................................................................329
LINE ......................................................................................................................................................97
list of files.............................................................................................................................................149
listbox ...............................................................................................................................................53, 80
ListHTMLItem$...................................................................................................................................284
439
ListItem$ ..............................................................................................................................................286
listview....................................................................................................................................................80
LOCAL.................................................................................................................................................423
Local variables....................................................................................................................................248
LockKbd ...............................................................................................................................................288
LockMouse...........................................................................................................................................290
LogFile.................................................................................................................................................291
Logical operators........................................................................................................................293, 329
loop...............................................................................................................................................366, 457
Ltrim$...................................................................................................................................................294
main program ......................................................................................................................................350
MaximizeWindow ................................................................................................................................295
menu event ...........................................................................................................................................320
menu selection by keyboard shortcut ....................................................................................................83
Mid$ .....................................................................................................................................................296
Middle ....................................................................................................................................................95
Min$ .....................................................................................................................................................297
MinimizeWindow.................................................................................................................................298
MkDir...................................................................................................................................................299
module..................................................................................................................................................408
modulus................................................................................................................................................329
Month$.................................................................................................................................................301
mouse event..........................................................................................................................................320
MouseShape.........................................................................................................................................302
MouseX ................................................................................................................................................304
MouseY ................................................................................................................................................304
MoveMouse..........................................................................................................................................305
MoveWindow .......................................................................................................................................308
MsgBox ................................................................................................................................................309
MsgFrame............................................................................................................................................311
MsgFrameTitle ....................................................................................................................................313
multiple decision making.....................................................................................................................385
multiplication.......................................................................................................................................329
Multiply$ ..............................................................................................................................................315
Name ....................................................................................................................................................316
Navigate ...............................................................................................................................................317
Near..............................................................................................................................................320, 334
NOT......................................................................................................................................................329
Not equal to..........................................................................................................................................329
NotActive......................................................................................................................................320, 334
NotExists ......................................................................................................................................320, 334
notification area.....................................................................................................................................80
NumLock .............................................................................................................................................318
OCR engine............................................................................................................................................95
OCR Text .............................................................................................................................................334
off ...........................................................................................................................................................83
on............................................................................................................................................................83
OnAction Error............................................................................................................................250, 325
OnAction...EndAction .........................................................................................................................320
OpenCom .............................................................................................................................................328
Operators .............................................................................................................................................329
OR ........................................................................................................................................................329
OsVersion$...........................................................................................................................................331
OverHTMLElement.............................................................................................................................333
parameters for a script.........................................................................................................................106
parent window......................................................................................................................................433
parenthesis ...........................................................................................................................................329
password...............................................................................................................................................471
Pause....................................................................................................................................................334
PeekInteger ..........................................................................................................................................341
440
PeekString$..........................................................................................................................................342
PG...........................................................................................................................................................97
PokeInteger..........................................................................................................................................344
PokeString ...........................................................................................................................................346
PostData...............................................................................................................................................348
Precedence of operators ......................................................................................................................329
precision...............................................................................................................................................349
program structure ................................................................................................................................350
PUSHBUTTON .....................................................................................................................................53
Radio ................................................................................................................................................53, 87
Random................................................................................................................................................351
Read .....................................................................................................................................................352
ReadCom..............................................................................................................................................356
ReadExcel ............................................................................................................................................359
reading pointer.............................................................................................................................237, 404
ReadIni$...............................................................................................................................................361
ReadReg ...............................................................................................................................................362
reals......................................................................................................................................................118
Reboot ..................................................................................................................................................363
recording mode ....................................................................................................................................446
Relational operators ............................................................................................................................329
Rem ......................................................................................................................................................364
RemoveFrame......................................................................................................................................365
Repeat...................................................................................................................................................366
Replace$...............................................................................................................................................367
ResetTimer ...........................................................................................................................................369
Response time ..............................................................................................................369, 417, 421, 431
Restarts Windows.................................................................................................................................363
RestoreWindow ....................................................................................................................................371
return code...........................................................................................................................................259
return code from a script .....................................................................................................................376
RevertToSelf ........................................................................................................................................372
Right.......................................................................................................................................................91
Right$...................................................................................................................................................373
RmDir...................................................................................................................................................374
Rtrim$ ..................................................................................................................................................375
Run.......................................................................................................................................................376
Run a script from an other script ................................................................................................376, 408
SavePictureAs ......................................................................................................................................378
SaveTargetAs .......................................................................................................................................380
Sec$ ......................................................................................................................................................384
Select Case ...........................................................................................................................................385
SelectDir$.............................................................................................................................................387
SelectedHTMLItem$ ...........................................................................................................................389
SelectedItem$.......................................................................................................................................391
SelectFile .............................................................................................................................................392
SelectHTMLItem .................................................................................................................................393
selections in menus..............................................................................................................................399
SelectMultipleFile................................................................................................................................395
SendEmail............................................................................................................................................396
SendKeys..............................................................................................................................................397
SendKeysEncrypted .............................................................................................................................400
SetAttr ..................................................................................................................................................402
SetClipboard ........................................................................................................................................403
SetReadPos ..................................................................................................................................352, 404
SetXMLAttribute..................................................................................................................................405
Shell .....................................................................................................................................................408
ShellWait..............................................................................................................................................410
Shift key ...............................................................................................................................................333
SizeWindow..........................................................................................................................................411
441
Sleep .....................................................................................................................................................412
source code of the current Web page ..................................................................................................233
SplitIntoArray ......................................................................................................................................414
Spy........................................................................................................................................................446
StartBrowser ........................................................................................................................................415
StartService ..........................................................................................................................................416
StartTimer ............................................................................................................................................417
Stop.......................................................................................................................................................418
StopLog ................................................................................................................................................419
StopService...........................................................................................................................................420
StopTimer.............................................................................................................................................421
Str$ .......................................................................................................................................................422
string ....................................................................................................................................................118
Sub .......................................................................................................................................................423
sub-program.........................................................................................................................................376
Subs......................................................................................................................................................350
Subtract$..............................................................................................................................................425
subtraction ...........................................................................................................................................329
Synchronization on a Date/Hour ........................................................................................................334
Synchronization on a Text ..................................................................................................................334
Synchronization on an Image .............................................................................................................334
Syntax...................................................................................................................................................427
system .....................................................................................................................................................83
System Variables..................................................................................................................................118
systray.....................................................................................................................................................80
Tab .........................................................................................................................................................87
TEXT......................................................................................................................................................53
text check frequency ............................................................................................................................429
TextOCR ..............................................................................................................................................334
Then .....................................................................................................................................................258
tick........................................................................................................................................................179
Time$ ...................................................................................................................................................430
timeout .................................................................................................................................................173
Timer....................................................................................................................................................431
Top$ .....................................................................................................................................................433
TopInstance .........................................................................................................................................434
treeview ..................................................................................................................................................80
trigger...................................................................................................................................................320
Trim$....................................................................................................................................................435
TRUE ...................................................................................................................................................258
Ucase$..................................................................................................................................................436
Unable to activate window...................................................................................................................158
unary ....................................................................................................................................................329
Unicode ................................................................................................................................................112
UnlockKbd ...........................................................................................................................................437
UnlockMouse.......................................................................................................................................438
unsigned integer ..................................................................................................................................118
until ......................................................................................................................................................366
Up ...........................................................................................................................................................91
UseOCREngine....................................................................................................................................440
UsePage ...............................................................................................................................................441
UseWindow ..........................................................................................................................................446
UseWindowHandle ..............................................................................................................................448
UseWindowRegEx ...............................................................................................................................451
V 97
Val ........................................................................................................................................................454
Variables ..............................................................................................................................................118
wait .......................................................................................................................................................179
waits for one window to appear OR a second window to appear .....................................................184
waits for one window to appear OR a second window to appear .......................................................184
442
Weekday ...............................................................................................................................................456
While...wend.........................................................................................................................................457
WinDir$ ...............................................................................................................................................458
Window class .......................................................................................................................................439
window name ...............................................................................................................................439, 446
Window title .........................................................................................................................................439
Windows caret......................................................................................................................................117
Windows regional settings...................................................................................................................120
WinScrollBar .........................................................................................................................................97
WinStatus.....................................................................................................................................320, 334
WinTaskAdmin Service ....................................................................................... 227, 234, 269, 416, 420
Write.....................................................................................................................................................460
Write in Excel a captured OCRized value.............................................................................................67
WriteCom .............................................................................................................................................462
WriteCombo .........................................................................................................................................464
WriteEdit ..............................................................................................................................................465
WriteEditEncrypted .............................................................................................................................466
WriteExcel............................................................................................................................................467
WriteHTML .........................................................................................................................................469
WriteHTMLEncrypted.........................................................................................................................471
WriteIni................................................................................................................................................472
WriteReg ..............................................................................................................................................473
Year$ ....................................................................................................................................................475
Your last browsing session closed .......................................................................................................271
443