autoIt3Help For Vim version 7.3 Last change: 2017 Jun 02 vim:noundofile:foldcolumn=1:filetype=help:autochdir:textwidth=70:wrap:nomodifiable:readonly: ---------------------------------------------------------------------- *IsAdmin* +---------+~ | IsAdmin |~ +---------+~ Checks if the current user has full administrator privileges. > IsAdmin( ) < Parameters~ None. Return Value~ Success ------- Returns 1 if the current user has administrator privileges. Failure ------- Returns 0 if user lacks admin privileges. Remarks~ It returns 1 under Windows Vista only if running with a full administrator token (i.e. #RequireAdmin has been used, or has already been elevated by UAC). Related~ |#RequireAdmin| Example~ > If IsAdmin() Then MsgBox(0, "", "Admin rights detected") < ---------------------------------------------------------------------- *GUICreate* +-----------+~ | GUICreate |~ +-----------+~ Create a GUI window. > GUICreate ( "title" [, width [, height [, left [, top [, style [, exStyle [, parent]]]]]]] ) < Parameters~ title~ ----- The title of the dialog box. width~ ----- [optional] The width of the window. height~ ------ [optional] The height of the window. left~ ----- [optional] The left side of the dialog box. By default ( -1 )~ ------ the window is centered. If defined, top must also be defined. top~ ----- [optional] The top of the dialog box. Default ( -1 ) is centered style~ ----- [optional] defines the style of the window. See GUI Control Styles Appendix. Use -1 for the default style which includes a combination of $WS_MINIMIZEBOX , $WS_CAPTION , $WS_POPUP, $WS_SYSMENU styles. Some styles are always included: $WS_CLIPSIBLINGS , and $WS_SYSMENU if $WS_MAXIMIZEBOX or $WS_SIZEBOX is specified. exStyle [optional]~ ------------------ defines the extended style of the window. See the Extended Style Table below. -1 is the default. parent [optional]~ ------------------ The handle of another previously created window - this new window then becomes a child of that window. Return Value~ Success~ ------- Returns a windows handle. Failure~ ------- Returns 0 if the window cannot be created and sets @error to 1. Remarks~ By default the dialog box is non sizable and non maximizable. So WS_SIZEBOX or WS_MAXIMIZEBOX can be used in the style parameter. As defining only one style just set this style don't forget to combine it with default ones, i.e. just defining WS_SIZEBOX will not set WS_MINIMIZEBOX , WS_CAPTION , WS_POPUP , WS_SYSMENU . So the best method to define a resizeable window is to use WS_OVERLAPPEDWINDOW . When using $WS_EX_MDICHILD the position is relative to client area of the parent window. With $WS_EX_LAYERED it is possible to have a transparent pic on a background pic defined in the parent window. Adding $WS_CLIPCHILDREN style can avoid some flickering when resizing GUI containing Edit control for example. You can enable window draging for GUI without $WS_CAPTION by using $WS_EX_CONTROLPARENT in the exStyle parameter. To combine styles with the default style use BitOr( $GUI_SS_DEFAULT_GUI , newstyle ,...). The size specified is the size of the client area of the window. The border and title bar will make the window slightly larger than specified. Using menu controls will also change the windows height. Extended Style table Extended Style result $WS_EX_ACCEPTFILES Allow an edit or input control within the created GUI window to receive filenames via drag and drop. The control must have also the $GUI_DROPACCEPTED state set by GUICtrlSetState. for other controls the drag&drop info can be retrieved with @GUI_DRAGID , @GUI_DRAGFILE , @GUIDROPID . $WS_EX_APPWINDOW Forces a top-level window onto the taskbar when the window is visible. $WS_EX_CLIENTEDGE Specifies that a window has a border with a sunken edge. $WS_EX_CONTEXTHELP Includes a question mark in the title bar of the window. Cannot be used with the WS_MAXIMIZEBOX or WS_MINIMIZEBOX. $WS_EX_DLGMODALFRAME Creates a window that has a double border; the window can, optionally, be created with a title bar by specifying the WS_CAPTION style in the style parameter. $WS_EX_MDICHILD Create a child window included in its parent window (simulation not real MDI). $WS_EX_OVERLAPPEDWINDOW Combines the WS_EX_CLIENTEDGE and WS_EX_WINDOWEDGE styles. $WS_EX_STATICEDGE Creates a window with a three-dimensional border style intended to be used for items that do not accept user input. $WS_EX_TOPMOST Specifies that a window created with this style should be placed above all non-topmost windows and should stay above them, even when the window is deactivated. $WS_EX_TRANSPARENT The window appears transparent because the bits of underlying sibling windows have already been painted. $WS_EX_TOOLWINDOW Creates a tool window; that is, a window intended to be used as a floating toolbar. A tool window has a title bar that is shorter than a normal title bar, and the window title is drawn using a smaller font. A tool window does not appear in the taskbar or in the dialog box that appears when the user presses ALT+TAB. If a tool window has a system menu, its icon is not displayed on the title bar. However, you can display the system menu by typing ALT+SPACE. $WS_EX_WINDOWEDGE Specifies that a window has a border with a raised edge. $WS_EX_LAYERED Creates a layered window. Note that this cannot be used for child windows. To use the values specified above you must #include in your script. Note: The handle returned from this function is a real windows handle, which means it can be used in the same way as the result of |WinGetHandle|. Related~ GUISetParametersXXX, |GUICtrlCreateXXX, |GUIGetMsg|, |GUISwitch|, |GUIGetStyle|, |GUIDelete|, |WinGetHandle|, |GUICtrlSetDefBkColor|, |GUICtrlSetDefColor|, |GUIGetCursorInfo| Example~ > #include #include Opt('MustDeclareVars', 1) Example1() Example2() ; example 1 Func Example1() Local $msg GUICreate("My GUI") ; will create a dialog box that when displayed is centered GUISetState(@SW_SHOW) ; will display an empty dialog box ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd GUIDelete() EndFunc ;==>Example1 ; example 2 Func Example2() Local $gui, $background, $pic, $basti_stay, $msg Local $sFile = "..\GUI\logo4.gif" $gui = GUICreate("Background", 400, 100) ; background picture $background = GUICtrlCreatePic("..\GUI\msoobe.jpg", 0, 0, 400, 100) GUISetState(@SW_SHOW) ; transparent MDI child window $pic = GUICreate("", 169, 68, 20, 20, $WS_POPUP, BitOR($WS_EX_LAYERED, $WS_EX_MDICHILD), $gui) ; transparent pic $basti_stay = GUICtrlCreatePic($sFile, 0, 0, 169, 68) GUISetState(@SW_SHOW) Do $msg = GUIGetMsg() Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example2 < -------------------------------------------------------------------------------- *GUISwitch* +-----------+~ | GUISwitch |~ +-----------+~ Switches the current window used for GUI functions. > GUISwitch ( winhandle [, tabitemID] ) < Parameters~ winhandle --------- The handle of the window to switch to. tabitemID --------- [optional] controlID of the tabitem control to be selected. Return Value~ Success ------- handle of the previous GUI. Failure ------- a null handle. Remarks~ Many of the GUI specific functions work on the "current" window - this is usually the last window created with GUICreate(). This function allows you to make another window "current". That's does not mean that the referenced window will become active. You have to use WinActivate(). Using the tabitemID allow to create new control in the specified tabitem control. Don't forget to close tabitem definition GUICtrlCreateTabItem("") Related~ |GUICreate|, |GUICtrlCreateTabItem|, |GUIDelete| Example~ > #include Example() Func Example() Local $hGUIParent1 = GUICreate("Parent1") GUICtrlCreateTab(10, 10) Local $idTabItem = GUICtrlCreateTabItem("tab1") GUICtrlCreateTabItem("tab2") GUICtrlCreateTabItem("") Local $hGUIParent2 = GUICreate("Parent2", -1, -1, 100, 100) GUISwitch($hGUIParent2) GUISetState(@SW_SHOW) ; Loop until the user exits. While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE ExitLoop EndSwitch WEnd GUISwitch($hGUIParent1, $idTabItem) GUICtrlCreateButton("OK", 50, 50, 50) GUICtrlCreateTabItem("") GUISetState(@SW_SHOW, $hGUIParent1) While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE ExitLoop EndSwitch WEnd GUIDelete($hGUIParent1) GUIDelete($hGUIParent2) EndFunc ;==>Example < ---------------------------------------------------------------------- *GUISetState* +-------------+~ | GUISetState | ~ +-------------+~ Changes the state of a GUI window. > GUISetState ( [ flag [, winhandle ]] ) < Parameters~ flag [optional]~ --------------- @SW_SHOW = Shows a previously hidden window (default) @SW_HIDE = Hide window @SW_MINIMIZE = Minimize window @SW_MAXIMIZE = Maximize window @SW_RESTORE = Undoes a window minimization @SW_DISABLE = Disables the window @SW_ENABLE = Enables the window @SW_LOCK = Lock the window to avoid repainting. @SW_UNLOCK = Unlock windows to allow painting. winhandle [optional] Windows handle as returned by |GUICreate| (default is the previously used window). Return Value~ Success~ ------- Returns 1 Failure~ ------- Returns 0 Remarks~ When windows are created they are initially hidden so you must use this function to display them ( @SW_SHOW ). Only one window can be locked with @SW_LOCK . Any other @SW_LOCK will lock the requested window. @SW_UNLOCK just ignored the " winhandle " to unlock any locked window. Related~ |GUICreate| Example~ > #include Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("My GUI") ; start the definition GUISetState() ; will display an empty dialog box ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example < ---------------------------------------------------------------------- *GUISetStyle* +-------------+~ | GUISetStyle |~ +-------------+~ Changes the styles of a GUI window. > GUISetStyle ( Style [, ExStyle [, winhandle ]] ) < Parameters~ Style~ ----- defines the style of the window. See GUI Control Styles Appendix. Use -1 to leave it unchanged. exStyle~ ------- [optional] defines the extended style of the window. See the Extended Style Table below. -1 is the default. Use -1 to leave it unchanged. winhandle~ --------- [optional] Windows handle as returned by |GUICreate| (default is the previously used window). Return Value~ Success~ ------- Returns 1 Failure~ ------- Returns 0 Remarks~ No checking is done on style value, neither non interaction with already defined control. It is the designer responsability to take care of this compatibility. Related~ |GUIGetStyle| Example~ > #include #include Opt('MustDeclareVars', 1) Example() Func Example() Local $NewStyle = False, $hWnd, $Style, $Msg $hWnd = GUICreate("Gui Style", 260, 100) $Style = GUICtrlCreateButton("Set Style", 45, 50, 150, 20) GUISetState() While 1 $Msg = GUIGetMsg() Switch $Msg Case $GUI_EVENT_CLOSE Exit Case $Style If Not $NewStyle Then GUISetStyle(BitOR($WS_POPUPWINDOW, $WS_THICKFRAME), BitOR($WS_EX_CLIENTEDGE, $WS_EX_TOOLWINDOW)) GUICtrlSetData($Style, 'Undo Style') $NewStyle = True Else GUISetStyle(BitOR($WS_MINIMIZEBOX, $WS_CAPTION, $WS_POPUP, $WS_SYSMENU), 0) GUICtrlSetData($Style, 'Set Style') $NewStyle = False EndIf Case Else EndSwitch WEnd EndFunc ;==>Example < ---------------------------------------------------------------------- *GUISetBkColor* +---------------+~ | GUISetBkColor |~ +---------------+~ Sets the background color of the GUI window. > GUISetBkColor ( background [, winhandle ] ) < Parameters~ background~ ---------- Background color of the dialog box. winhandle [optional]~ -------------------- Windows handle as returned by |GUICreate| (default is the previously used window). Return Value~ Success~ ------- Returns 1 Failure~ ------- Returns 0 Remarks~ None Related~ |GUICreate| Example~ > #include Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("My GUI") ; will create a dialog box that when displayed is centered GUISetBkColor(0xE0FFFF) ; will change background color GUISetState() ; will display an empty dialog box ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUIDelete* +-----------+~ | GUIDelete |~ +-----------+~ Deletes a GUI window and all controls that it contains. > GUIDelete ( [winhandle] ) < Parameters~ winhandle --------- [optional] Windows handle as returned by GUICreate (default is the previous used). Return Value~ Success ------- Returns 1. Failure ------- Returns 0. Remarks~ None. Related~ |GUICreate|, |GUISwitch| Example~ > #include Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("My GUI") ; will create a dialog box that when displayed is centered GUISetState() ; will display an empty dialog box ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd GUIDelete(); ; will return 1 EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUIGetCursorInfo* +------------------+~ | GUIGetCursorInfo |~ +------------------+~ Gets the mouse cursor position relative to GUI window. > GUIGetCursorInfo ( [winhandle] ) < Parameters~ winhandle --------- [optional] The handle of the window to use. If omitted the "current" window will be used. Return Value~ Success ------- returns a five-element array that containing the mouse cursor information: $array[0] = X coord (horizontal) $array[1] = Y coord (vertical) $array[2] = Primary down (1 if pressed, 0 if not pressed) $array[3] = Secondary down (1 if pressed, 0 if not pressed) $array[4] = ID of the control that the mouse cursor is hovering over (or 0 if none) Failure ------- 0 and set @error to 1 Remarks~ The coordinates given are relative to the GUI window (known as client coords). If the "winhandle" parameter is used then the specified window becomes the new "current" window. The mouse cursor position is successful only on an window created by a GUICreate. When no winhandle it will be successful if the GUI Windows is active. ListViewItem or TreeViewItem controlID will never be returned, only the parent Listview or TreeView control ID is. Related~ |GUICreate|, |GUIGetMsg| Example~ > #include Opt('MustDeclareVars', 1) Global $x, $y Example() Func Example() Local $msg HotKeySet("{Esc}", "GetPos") GUICreate("Press Esc to Get Pos", 400, 400) $x = GUICtrlCreateLabel("0", 10, 10, 50) $y = GUICtrlCreateLabel("0", 10, 30, 50) GUISetState() ; Run the GUI until the dialog is closed Do $msg = GUIGetMsg() Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example Func GetPos() Local $a $a = GUIGetCursorInfo() GUICtrlSetData($x, $a[0]) GUICtrlSetData($y, $a[1]) EndFunc ;==>GetPos < -------------------------------------------------------------------------------- *GUIGetStyle* +-------------+~ | GUIGetStyle |~ +-------------+~ Retrieves the styles of a GUI window. > GUIGetStyle ( [ winhandle] ) < Parameters~ winhandle --------- [optional] Windows handle as returned by GUICreate (default is the previously used window). Return Value~ Success ------- returns a two-element array that containing the styles information: $array[0] = Style $array[1] = ExStyle Failure: Returns 0. Remarks~ Be carefull Style changes after GUISetState(). Related~ |GUICreate|, |GUISetStyle| Example~ > #include #include Opt('MustDeclareVars', 1) Example() Func Example() Local $NewStyle = False, $hWnd, $Style, $GuiStyles, $Msg $hWnd = GUICreate("Gui Style", 260, 100) $Style = GUICtrlCreateButton("Set Style", 45, 50, 150, 20) $GuiStyles = GUIGetStyle($hWnd) ; be careful the style change after opening GUISetState() While 1 $Msg = GUIGetMsg() Switch $Msg Case $GUI_EVENT_CLOSE Exit Case $Style If Not $NewStyle Then GUISetStyle(BitOR($WS_POPUPWINDOW, $WS_THICKFRAME), BitOR($WS_EX_CLIENTEDGE, $WS_EX_TOOLWINDOW)) GUICtrlSetData($Style, 'Undo Style') $NewStyle = True Else GUISetStyle($GuiStyles[0], $GuiStyles[1]) GUICtrlSetData($Style, 'Set Style') $NewStyle = False EndIf Case Else EndSwitch WEnd EndFunc ;==>Example < ---------------------------------------------------------------------- *AutoItSetOption* +-----------------+~ | AutoItSetOption |~ +-----------------+~ Changes the operation of various AutoIt functions/parameters. > AutoItSetOption ( " option " [, param ] ) < Parameters~ option~ ------ The option to change. See Remarks. param~ ----- [optional] The value to assign to the option . The type and meaning vary by option. See remarks below. If the param is not provided, then the function just returns the value already assigned to the option . The keyword Default can be used for the parameter to reset the option to its default value. Return Value~ Success~ ------- Returns the value of the previous setting for the option. Failure~ ------- Sets @error to non-zero. Failure will occur if the parameters are invalid (such as an option that doesn't exist). Remarks~ You may use |Opt|() as an alternative to |AutoItSetOption|(). Options are as follows: Option / Param ~ CaretCoordMode~ -------------- Sets the way coords are used in the caret functions, either absolute coords or coords relative to the current active window: 0 = relative coords to the active window 1 = absolute screen coordinates ( default ) 2 = relative coords to the client area of the active window ExpandEnvStrings~ ---------------- Changes how literal strings and % symbols are interpreted. By default strings are treated literally, this option allows you to use %environment% variables inside strings, e.g., "The temp directory is: %temp% " . 1 = expand environment variables (similar to AutoIt v2) 0 = do not expand environment variables ( default ) Without this option the usual way would be: "The temp directory is: " & EnvGet( " temp " ) ExpandVarStrings Changes how literal strings and variable/macro ($ and @ ) symbols are interpreted. By default strings are treated literally, this option allows you to use variables and macros inside strings, e.g., "The value of var1 is $var1$". 1 = expand variables (when in this mode and you want to use a literal $ or @ then double it up: "This is a single dollar $$ sign". 0 = do not expand variables ( default ) GUICloseOnESC~ ------------- When ESC is pressed on a GUI the $GUI_EVENT_CLOSE message is sent. This option toggles this behavior on and off. 1 = Send the $GUI_EVENT_CLOSE message when ESC is pressed ( default ). 0 = Don't send the $GUI_EVENT_CLOSE message when ESC is pressed. GUICoordMode~ ------------ Alters the position of a control defined by |GUICtrlSetPos|. 1 = absolute coordinates ( default ) still relative to the dialog box. 0 = relative position to the start of the last control (upper left corner). 2 = cell positionining relative to current cell. A -1 for left or top parameter don't increment the start. So next line is -1 , offset ; next cell is offset ,-1 ; current cell is -1 ,-1 . Obviously " offset " cannot be -1 which reserved to indicate the no increment. But if you can use a multiple of the width you choose to skip or go back. GUIDataSeparatorChar Define the character which delimits subitems in |GUICtrlSetData|. The default character is ' | '. GUIOnEventMode~ -------------- Enable/disable OnEvent functions notifications. 0 = (default) disable. 1 = enable. GUIResizeMode~ ------------- Change default resizing for a control. 0 = ( default ) keep default control resizing. <1024 = anytype of resizing see |GUICtrlSetResizing|. GUIEventOptions~ --------------- Change special event behavior or GUI function return values. 0 = ( default ) Windows behavior on click on Minimize,Restore, Maximize, Resize. 1 = suppress windows behavior on minimize, restore or maximize click button or window resize. Just sends the notification. MouseClickDelay~ --------------- Alters the length of the brief pause in between mouse clicks. Time in milliseconds to pause (default= 10 ). MouseClickDownDelay~ ------------------- Alters the length a click is held down before release. Time in milliseconds to pause (default= 10). MouseClickDragDelay~ ------------------- Alters the length of the brief pause at the start and end of a mouse drag operation. Time in milliseconds to pause (default= 250 ). MouseCoordMode~ -------------- Sets the way coords are used in the mouse functions, either absolute coords or coords relative to the current active window: 0 = relative coords to the active window 1 = absolute screen coordinates ( default ) 2 = relative coords to the client area of the active window MustDeclareVars~ --------------- If this option is used then all variables must be pre-declared with |Dim|, |Local| or |Global| before they can be used - removes the chance for misspelled variables causing bugs. 1 = Variables must be pre-declared 0 = Variables don't need to be pre-declared ( default ) PixelCoordMode~ -------------- Sets the way coords are used in the pixel functions, either absolute coords or coords relative to the window defined by hwnd (default active window): 0 = relative coords to the defined window 1 = absolute screen coordinates ( default ) 2 = relative coords to the client area of the defined window SendAttachMode~ -------------- Specifies if AutoIt attaches input threads when using |Send|() function. When not attaching ( default mode= 0 ) detecting the state of capslock/scrolllock and numlock can be unreliable under NT4. However, when you specify attach mode= *1* the |Send|("{... down/up}") syntax will not work and there may be problems with sending keys to "hung" windows. |ControlSend|() ALWAYS attaches and is not affected by this mode. 0 = don't attach ( default ) 1 = attach SendCapslockMode~ ---------------- Specifies if AutoIt should store the state of capslock before a Send function and restore it afterwards. 0 = don't store/restore 1 = store and restore ( default ) SendKeyDelay~ ------------ Alters the the length of the brief pause in between sent keystrokes. A value of 0 removes the delay completely. Time in milliseconds to pause (default= 5 ). SendKeyDownDelay~ ---------------- Alters the length of time a key is held down before being released during a keystroke. For applications that take a while to register keypresses (and many games) you may need to raise this value from the default. A value of 0 removes the delay completely. Time in milliseconds to pause (default= 5 ). TCPTimeout~ ---------- Defines the time before TCP functions stop if no communication. Time in milliseconds before timeout (default= 100 ). TrayAutoPause~ ------------- Script pauses when click on tray icon. 0 = no pause 1 = pause ( default ). If there is no DefaultMenu no pause will occurs. TrayIconDebug~ ------------- If enabled shows the current script line in the tray icon tip to help debugging. 0 = no debug information ( default ) 1 = show debug TrayIconHide~ ------------ Hides the AutoIt tray icon. Note: The icon will still initially appear ~750 milliseconds. 0 = show icon ( default ) 1 = hide icon TrayMenuMode~ ------------ Extend the behaviour of the script tray icon/menu. This can be done with a combination (adding) of the following values. 0 = default menu items (Script Paused/Exit) are appended to the usercreated menu; usercreated checked items will automatically unchecked; if you double click the tray icon then the controlid is returned which has the "Default"-style (default). 1 = no default menu 2 = user created checked items will not automatically unchecked if you click it 4 = don't return the menuitemID which has the "default"-style in the main contextmenu if you double click the tray icon 8 = turn off auto check of radio item groups TrayOnEventMode~ --------------- Enable/disable OnEvent functions notifications for the tray. 0 = ( default ) disable 1 = enable WinDetectHiddenText~ ------------------- Specifies if hidden window text can be "seen" by the window matching functions. 0 = Do not detect hidden text ( default ) 1 = Detect hidden text WinSearchChildren~ ----------------- Allows the window search routines to search child windows as well as top-level windows. 0 = Only search top-level windows ( default ) 1 = Search top-level and child windows WinTextMatchMode~ ---------------- Alters the method that is used to match window text during search operations. 1 = Complete / Slow mode ( default ) 2 = Quick mode In quick mode AutoIt can usually only "see" dialog text, button text and the captions of some controls. In the default mode much more text can be seen (for instance the contents of the Notepad window). If you are having performance problems when performing many window searches then changing to the "quick" mode may help. WinTitleMatchMode~ ----------------- Alters the method that is used to match window titles during search operations. 1 = Match the title from the start ( default ) 2 = Match any substring in the title 3 = Exact title match 4 = Advanced mode, see Window Titles & Text (Advanced) -1 to -4 = force lower case match according to other type of match. WinWaitDelay~ ------------ Alters how long a script should briefly pause after a successful window-related operation. Time in milliseconds to pause (default= 250). Related~ Many! Example~ > ; copy any you want to change ;default value is listed first Opt("CaretCoordMode", 1) ;1=absolute, 0=relative, 2=client Opt("ExpandEnvStrings", 0) ;0=don't expand, 1=do expand Opt("ExpandVarStrings", 0) ;0=don't expand, 1=do expand Opt("GUICloseOnESC", 1) ;1=ESC closes, 0=ESC won't close Opt("GUICoordMode", 1) ;1=absolute, 0=relative, 2=cell Opt("GUIDataSeparatorChar","|") ;"|" is the default Opt("GUIOnEventMode", 0) ;0=disabled, 1=OnEvent mode enabled Opt("GUIResizeMode", 0) ;0=no resizing, <1024 special resizing Opt("GUIEventOptions",0) ;0=default, 1=just notification, 2=GuiCtrlRead tab index Opt("MouseClickDelay", 10) ;10 milliseconds Opt("MouseClickDownDelay", 10) ;10 milliseconds Opt("MouseClickDragDelay", 250) ;250 milliseconds Opt("MouseCoordMode", 1) ;1=absolute, 0=relative, 2=client Opt("MustDeclareVars", 0) ;0=no, 1=require pre-declare Opt("PixelCoordMode", 1) ;1=absolute, 0=relative, 2=client Opt("SendAttachMode", 0) ;0=don't attach, 1=do attach Opt("SendCapslockMode", 1) ;1=store and restore, 0=don't Opt("SendKeyDelay", 5) ;5 milliseconds Opt("SendKeyDownDelay", 1) ;1 millisecond Opt("TCPTimeout",100) ;100 milliseconds Opt("TrayAutoPause",1) ;0=no pause, 1=Pause Opt("TrayIconDebug", 0) ;0=no info, 1=debug line info Opt("TrayIconHide", 0) ;0=show, 1=hide tray icon Opt("TrayMenuMode",0) ;0=append, 1=no default menu, 2=no automatic check, 4=menuitemID not return Opt("TrayOnEventMode",0) ;0=disable, 1=enable Opt("WinDetectHiddenText", 0) ;0=don't detect, 1=do detect Opt("WinSearchChildren", 1) ;0=no, 1=search children also Opt("WinTextMatchMode", 1) ;1=complete, 2=quick Opt("WinTitleMatchMode", 1) ;1=start, 2=subStr, 3=exact, 4=advanced, -1 to -4=Nocase Opt("WinWaitDelay", 250) ;250 milliseconds < ---------------------------------------------------------------------- *_GUICtrlAVI_Show* +------------------+~ | _GUICtrlAVI_Show |~ +------------------+~ Show/Hide the AVI control > #include < GuiAVI.au3 > _GUICtrlAVI_Show ( $hWnd , $iState ) < Parameters~ $hWnd~ ----- Control ID/Handle to the control $iState~ ------- State of the AVI, can be the following values: Return Value~ True~ ----- The control was previously visible False~ ----- The control was previously hidden Remarks~ None. Example~ > #include #include $Debug_AVI = False ; Check ClassName being passed to AVI functions, set to True and use a handle to another control to see it work Global $hAVI _Example_Internal() _Example_External() Func _Example_Internal() Local $btn_start, $btn_stop, $btn_show ; Create GUI GUICreate("(Internal) AVI Play", 350, 200) $hAVI = GUICtrlCreateAvi(@SystemDir & "\shell32.dll", 160, 10, 10) $btn_start = GUICtrlCreateButton("start", 25, 150, 70, 22) $btn_stop = GUICtrlCreateButton("stop", 125, 150, 70, 22) $btn_show = GUICtrlCreateButton("hide", 225, 150, 70, 22) GUISetState() ; Loop until user exits While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE ExitLoop Case $btn_start ; Play part of the AVI clip _GUICtrlAVI_Play($hAVI) Case $btn_stop ; Stop AVI clip _GUICtrlAVI_Stop($hAVI) Case $btn_show If GUICtrlRead($btn_show) = "hide" Then _GUICtrlAVI_Show($hAVI, @SW_HIDE) GUICtrlSetData($btn_show, "show") Else _GUICtrlAVI_Show($hAVI, @SW_SHOW) GUICtrlSetData($btn_show, "hide") EndIf EndSwitch WEnd ; Close AVI clip _GUICtrlAVI_Close($hAVI) GUIDelete() EndFunc ;==>_Example_Internal Func _Example_External() Local $hGUI, $btn_start, $btn_stop, $btn_show ; Create GUI $hGUI = GUICreate("(External) AVI Play", 350, 200) $hAVI = _GUICtrlAVI_Create($hGUI, @SystemDir & "\Shell32.dll", 160, 10, 10) $btn_start = GUICtrlCreateButton("start", 25, 150, 70, 22) $btn_stop = GUICtrlCreateButton("stop", 125, 150, 70, 22) $btn_show = GUICtrlCreateButton("hide", 225, 150, 70, 22) GUISetState() ; Loop until user exits While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE ExitLoop Case $btn_start ; Play part of the AVI clip _GUICtrlAVI_Play($hAVI) Case $btn_stop ; Stop AVI clip _GUICtrlAVI_Stop($hAVI) Case $btn_show If GUICtrlRead($btn_show) = "hide" Then _GUICtrlAVI_Show($hAVI, @SW_HIDE) GUICtrlSetData($btn_show, "show") Else _GUICtrlAVI_Show($hAVI, @SW_SHOW) GUICtrlSetData($btn_show, "hide") EndIf EndSwitch WEnd ; Close AVI clip _GUICtrlAVI_Close($hAVI) GUIDelete() EndFunc ;==>_Example_External < ---------------------------------------------------------------------- *GUICtrlSetState* +-----------------+~ | GUICtrlSetState |~ +-----------------+~ Changes the state of a control. > GUICtrlSetState ( controlID , state ) < Parameters~ controlID The control identifier ( controlID ) as returned by a |GUICtrlCreate|... function. state See the State table below. Return Value~ Success~ ------- Returns 1 Failure~ ------- Returns 0 Remarks~ State table State Comments No Change 0 $GUI_UNCHECKED Radio, Checkbox or ListViewItem will be unchecked. $GUI_CHECKED Radio, Checkbox or ListViewItem will be checked. $GUI_INDETERMINATE Checkbox having the tristate attribute will be greyed. $GUI_AVISTART Avi control will start playing. $GUI_AVISTOP Avi control will stop playing. $GUI_AVICLOSE Avi control will stop playing and release resource. $GUI_DROPACCEPTED Control will accept drop action : from file or from a drag of another control. See remarks. $GUI_NODROPACCEPTED Control will not accept drop action. $GUI_SHOW Control will be visible. On Tabitem control will select the first tab to be displayed. $GUI_HIDE Control will not be visible. $GUI_ENABLE Control will be enabled. $GUI_DISABLE Control will be greyed out. $GUI_FOCUS Control will be given input/selected focus. $GUI_NOFOCUS Listview control will loose focus. $GUI_DEFBUTTON Control will be set as the default button on the window. See remark about TreeviewItems . $GUI_EXPAND TreeViewItem will expand its child items. $GUI_ONTOP Control will be have the ontop attribute for the window (zOrdering). State values can be summed up as for example $GUI_DISABLE + $GUI_HIDE sets the control in an disabled and hidden state. If an AVI control has to be hidden with $GUI_HIDE it should be closed with $GUI_AVICLOSE . State of a "contextmenu" control cannot be changed. State of a "listviewitem" control can be changed if the associated "listview" control has been created with an extended style $LVS_EX_CHECKBOXES . $GUI_FOCUS and $GUI_NOFOCUS can be used on specific listviewitem provided listview control style allows to display it : $LVS_SHOWSELALWAYS . State of a "menu or a ""menuitem" control cannot be hidden. ! Important information for $GUI_EXPAND : this state is only used for TreeViewItems . If you want to use this 'action' then at least 1 Sub-TreeViewItem has to exist/created under this item ! If you want to select another item in a TreeView then you can use $GUI_FOCUS - the parent TreeView gets the window focus and the specified item is marked as selected. If you want to set a treeview item as a default item which means painting it bold you can use $GUI_DEFBUTTON - to turn it off just use another value but $GUI_DEFBUTTON , for instance 0 . This state will not be returned by GUICtrlGetState . If $GUI_DROPACCEPTED is set to a visible control a drag&drop can be taken in account. The edit/input control will be set with the filename. For other controls on reception of $GUI_EVENT_DROPPED , @GUI_DRAGID will return the controlID from where the drag start ( -1 if from a file, @GUI_DRAGFILE contain the filename being dropped) and @GUI_DROPID returns the controlID of the dropped control. Only dragging a ListviewItem will start the drag & drop process. The @GUI_DRAGID will be the ListView controlID . Related~ GUICtrlCreateXXX, |GUICtrlGetState| Example~ > #include Example() Func Example() Local $msg GUICreate("My GUI state") ; will create a dialog box that when displayed is centered GUICtrlCreateLabel("my disable label", 10, 20) GUICtrlSetState(-1, $GUI_DISABLE) ; the label is in disable state GUICtrlCreateButton("my button", 50, 50) GUICtrlSetState(-1, $GUI_FOCUS) ; the focus is on this button GUISetState() ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example < ---------------------------------------------------------------------- *RegRead* +---------+~ | RegRead |~ +---------+~ Reads a value from the registry. > RegRead ( " keyname ", " valuename " ) < Parameters~ keyname~ ------- The registry key to read. valuename~ --------- The value to read. Return Value~ Success~ ------- Returns the requested registry value. @EXTENDED is set to the type of the value $REG_... . These types are defined in the " Constants.au3 " include file. Failure~ ------- Returns "" and sets the @error flag: 1 if unable to open requested key 2 if unable to open requested main key 3 if unable to remote connect to the registry -1 if unable to open requested value -2 if value type not supported Remarks~ A registry key must start with " HKEY_LOCAL_MACHINE " (" HKLM ") or " HKEY_USERS " (" HKU ") or " HKEY_CURRENT_USER " (" HKCU ") or " HKEY_CLASSES_ROOT " (" HKCR ") or " HKEY_CURRENT_CONFIG " (" HKCC "). When running on 64-bit Windows if you want to read a value specific to the 64-bit environment you have to suffix the HK... with 64 i.e. HKLM64. AutoIt supports registry keys of type REG_BINARY , REG_SZ , REG_MULTI_SZ , REG_EXPAND_SZ , and REG_DWORD . To access the (Default) value use "" (a blank string) for the valuename. When reading a REG_BINARY key the result is a binary datatype (in previous versions it was a string of hex characters). When reading a REG_MULTI_SZ key the multiple entries are separated by @LF - use with |StringSplit| ( ... , @LF ) to get each entry. It is possible to access remote registries by using a keyname in the form " \\computername\keyname ". To use this feature you must have the correct access rights. Related~ |RegDelete|, |RegWrite|, |StringSplit| Example~ > $var = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion", "ProgramFilesDir") MsgBox(4096, "Program files are in:", $var) < ---------------------------------------------------------------------- *macro_reference__autoit_related* **************************************~ ** **~ ** Macro Reference - AutoIT Related **~ ** **~ **************************************~ Below is a list of AutoIt-related macros. The full list of macros can be found here. Macro Description ~ @compiled Returns 1 if script is a compiled executable; otherwise, returns 0 . @error Status of the error flag. See the SetError function. @exitCode Exit code as set by |Exit| statement. @exitMethod See the Func |OnAutoItExitRegister|(). @extended Extended function return - used in certain functions such as |StringReplace| . @NumParams Number of parameters used in calling the user function. @ScriptName Filename of the running script. @ScriptDir Directory containing the running script. (Result does not contain a trailing backslash) @ScriptFullPath Equivalent to @ScriptDir & "\" & @ScriptName @ScriptLineNumber Line number currently being executed. Useful for debug statements specially when a function is call you can pass the caller line number. (Not significant in compiled script) @WorkingDir Current/active working directory. (Result does not contain a trailing backslash) @AutoItExe The full path and filename of the AutoIt executable currently running. For compiled scripts it is the path of the compiled script. @AutoItPID PID of the process in which the script is running. @AutoItVersion Version number of AutoIt such as 3.0.102.0 @AutoItX64 Returns 1 if the script is running under the native x64 version of AutoIt. @COM_EventObj Object the COM event is being fired on. Only valid in a COM event Function. @GUI_CtrlId Last click GUI Control identifier . Only valid in an event Function. See the |GUICtrlSetOnEvent| function. @GUI_CtrlHandle Last click GUI Control handle. Only valid in an event Function. See the |GUICtrlSetOnEvent| function. @GUI_DragID Drag GUI Control identifier . Only valid on Drop Event. See the |GUISetOnEvent| function. @GUI_DragFile Filename of the file being dropped. Only valid on Drop Event. See the |GUISetOnEvent| function. @GUI_DropID Drop GUI Control identifier. Only valid on Drop Event. See the GUISetOnEvent function. @GUI_WinHandle Last click GUI Window handle. Only valid in an event Function. See the |GUICtrlSetOnEvent| function. @HotKeyPressed Last HotKey pressed. See the |HotkeySet| function For use with the |WinSetState|, |Run|, |RunWait|, |FileCreateShortcut| and |FileGetShortcut| functions: @SW_DISABLE Disables the window. @SW_ENABLE Enables the window. @SW_HIDE Hides the window and activates another window. @SW_LOCK Lock window to avoid painting. @SW_MAXIMIZE Maximizes the specified window. @SW_MINIMIZE Minimizes the specified window and activates the next top-level window in the Z order. @SW_RESTORE Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when restoring a minimized window. @SW_SHOW Activates the window and displays it in its current size and position. @SW_SHOWDEFAULT Sets the show state based on the SW_ value specified by the program that started the application. @SW_SHOWMAXIMIZED Activates the window and displays it as a maximized window. @SW_SHOWMINIMIZED Activates the window and displays it as a minimized window. @SW_SHOWMINNOACTIVE Displays the window as a minimized window. This value is similar to @SW_SHOWMINIMIZED, except the window is not activated. @SW_SHOWNA Displays the window in its current size and position. This value is similar to @SW_SHOW , except the window is not activated. @SW_SHOWNOACTIVATE Displays a window in its most recent size and position. This value is similar to @SW_SHOWNORMAL , except the window is not activated. @SW_SHOWNORMAL Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time. @SW_UNLOCK Unlock windows to allow painting. @TRAY_ID Last clicked item identifier during a TraySet( Item ) |OnEvent| action. @TrayIconFlashing Returns 1 if tray icon is flashing; otherwise, returns 0 . @TrayIconVisible Returns 1 if tray icon is visible; otherwise, returns 0 . @CR Carriage return, Chr( 13 ); sometimes used for line breaks. @LF Line feed, Chr( 10 ); typically used for line breaks. @CRLF = @CR & @LF ;occasionally used for line breaks. @TAB Tab character, Chr( 9 ) ---------------------------------------------------------------------- *macro_reference__full_list* *********************************~ ** **~ ** Macro Reference - Full List **~ ** **~ *********************************~ Below is an alphabetized list of all the macros available in AutoIt. Macro Description ~ ------------------------------------------------------------------------------ @AppDataCommonDir path to Application Data @AppDataDir path to current user's Application Data @AutoItExe The full path and filename of the AutoIt executable currently running. For compiled scripts it is the path of the compiled script. @AutoItPID PID of the process running the script. @AutoItVersion Version number of AutoIt such as 3.0.81.0 @AutoItX64 Returns 1 if the script is running under the native x64 version of AutoIt. @COM_EventObj Object the COM event is being fired on. Only valid in a COM event Function. @CommonFilesDir path to Common Files folder @Compiled Returns 1 if script is a compiled executable; otherwise, returns 0. @ComputerName Computer's network name. @ComSpec value of %comspec% , the SPECified secondary COMmand interpreter; primarily for command line uses, e.g. Run( @ComSpec & " /k help | more ") @CPUArch Returns " X86 " when the CPU is a 32-bit CPU and " X64 " when the CPU is 64-bit. @CR Carriage return, Chr( 13 ); sometimes used for line breaks. @CRLF = @CR & @LF ;occasionally used for line breaks. @DesktopCommonDir path to Desktop @DesktopDir path to current user's Desktop @DesktopHeight Height of the desktop screen in pixels. (vertical resolution) @DesktopWidth Width of the desktop screen in pixels. (horizontal resolution) @DesktopDepth Depth of the desktop screen in bits per pixel. @DesktopRefresh Refresh rate of the desktop screen in hertz. @DocumentsCommonDir path to Documents *@err*orAAA Status of the error flag. See the SetError function. @exitCode Exit code as set by Exit statement. @exitMethod Exit method. See the Func OnAutoItExitRegister(). @extended Extended function return - used in certain functions such as StringReplace. @FavoritesCommonDir path to Favorites @FavoritesDir path to current user's Favorites @GUI_CtrlId Last click control identifier. Only valid in an event Function. See the GUICtrlSetOnEvent function. @GUI_CtrlHandle Last click control handle. Only valid in an event Function. See the GUICtrlSetOnEvent function. @GUI_DragId Drag control identifier. Only valid on Drop Event. See the GUISetOnEvent function. @GUI_DragFile Filename of the file being dropped. Only valid on Drop Event. See the GUISetOnEvent function. @GUI_DropId Drop control identifier. Only valid on Drop Event. See the GUISetOnEvent function. @GUI_WinHandle Last click GUI window handle. Only valid in an event Function. See the |GUICtrlSetOnEvent| function. @HomeDrive Drive letter of drive containing current user's home directory. @HomePath Directory part of current user's home directory. To get the full path, use in conjunction with @HomeDrive. @HomeShare Server and share name containing current user's home directory. @HOUR Hours value of clock in 24-hour format. Range is 00 to 23 @HotKeyPressed Last hotkey pressed. See the HotKeySet function. @IPAddress1 IP address of first network adapter. Tends to return 127.0.0.1 on some computers. @IPAddress2 IP address of second network adapter. Returns 0.0.0.0 if not applicable. @IPAddress3 IP address of third network adapter. Returns 0.0.0.0 if not applicable. @IPAddress4 IP address of fourth network adapter. Returns 0.0.0.0 if not applicable. @KBLayout Returns code denoting Keyboard Layout. See Appendix for possible values. @LF Line feed, Chr( 10 ); typically used for line breaks. @LogonDNSDomain Logon DNS Domain. @LogonDomain Logon Domain. @LogonServer Logon server. @MDAY Current day of month. Range is 01 to 31 @MIN Minutes value of clock. Range is 00 to 59 @MON Current month. Range is 01 to 12 @MSEC Milliseconds value of clock. Range is 00 to 999 @MUILang Returns code denoting Multi Language if available (Vista is OK by default). See Appendix for possible values. @MyDocumentsDir path to My Documents target @NumParams Number of parameters used to call the user functions @OSArch Returns one of the following: " X86 ", " IA64 ", " X64 " - this is the architecture type of the currently running operating system. @OSBuild Returns the OS build number. For example, Windows 2003 Server returns 3790 @OSLang Returns code denoting OS Language. See Appendix for possible values. @OSServicePack Service pack info in the form of "Service Pack 3". @OSType Returns "WIN32_NT" for NT/2000/XP/2003/Vista/2008/Win7/2008R2. @OSVersion Returns one of the following: " WIN_2008R2 ", " WIN_7 ", " WIN_2008 ", " WIN_VISTA ", " WIN_2003 ", " WIN_XP ", " WIN_XPe ", " WIN_2000 ". @ProgramFilesDir path to Program Files folder @ProgramsCommonDir path to Start Menu's Programs folder @ProgramsDir path to current user's Programs (folder on Start Menu ) @ScriptDir Directory containing the running script. (Result does not contain a trailing backslash) @ScriptFullPath Equivalent to @ScriptDir & "\" & @ScriptName @ScriptLineNumber Line number of the currently executed script line. Useful for debug statements specially when a function is call you can pass the caller line number. (Not significant in complied script) @ScriptName Long filename of the running script. @SEC Seconds value of clock. Range is 00 to 59 @StartMenuCommonDir path to Start Menu folder @StartMenuDir path to current user's Start Menu @StartupCommonDir path to Startup folder @StartupDir current user's Startup folder @SW_DISABLE Disables the window. @SW_ENABLE Enables the window. @SW_HIDE Hides the window and activates another window. @SW_LOCK Lock the window to avoid repainting. @SW_MAXIMIZE Maximizes the specified window. @SW_MINIMIZE Minimizes the specified window and activates the next top-level window in the Z order. @SW_RESTORE Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when restoring a minimized window. @SW_SHOW Activates the window and displays it in its current size and position. @SW_SHOWDEFAULT Sets the show state based on the SW_ value specified by the program that started the application. @SW_SHOWMAXIMIZED Activates the window and displays it as a maximized window. @SW_SHOWMINIMIZED Activates the window and displays it as a minimized window. @SW_SHOWMINNOACTIVE Displays the window as a minimized window. This value is similar to @SW_SHOWMINIMIZED , except the window is not activated. @SW_SHOWNA Displays the window in its current size and position. This value is similar to @SW_SHOW , except the window is not activated. @SW_SHOWNOACTIVATE Displays a window in its most recent size and position. This value is similar to @SW_SHOWNORMAL , except the window is not activated. @SW_SHOWNORMAL Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time. @SW_UNLOCK Unlock windows to allow painting. @SystemDir path to Windows' System (or System32) folder @TAB Tab character, Chr( 9 ) @TempDir Path to the temporary files folder. @TRAY_ID Last clicked item identifier during a TraySet ( Item ) OnEvent action. @TrayIconFlashing Returns 1 if tray icon is flashing; otherwise, returns 0 . @TrayIconVisible Returns 1 if tray icon is visible; otherwise, returns 0 . @UserProfileDir Path to current user's Profile folder. @UserName ID of the currently logged on user. @WDAY Numeric day of week. Range is 1 to 7 which corresponds to Sunday through Saturday. @WindowsDir path to Windows folder @WorkingDir Current/active working directory. (Result does not contain a trailing backslash) @YDAY Current day of year. Range is 001 to 366 (or 001 to 365 if not a leap year) @YEAR Current four-digit year ---------------------------------------------------------------------- *MsgBox* +--------+~ | MsgBox |~ +--------+~ Displays a simple message box with optional timeout. > MsgBox ( flag , " title ", " text " [, timeout [, hwnd ]] ) < Parameters~ flag~ ----- The flag indicates the type of message box and the possible button combinations. See remarks. title~ ----- The title of the message box. text~ ----- The text of the message box. timeout~ ------- [optional] Timeout in seconds. After the timeout has elapsed the message box will be automatically closed. The default is 0, which is no timeout. hwnd~ ----- [optional] The window handle to use as the parent for this dialog. Return Value~ Success~ ------- Returns the ID of the button pressed. Failure~ ------- Returns -1 if the message box timed out. Button Pressed Return Value ~ OK 1 CANCEL 2 ABORT 3 RETRY 4 IGNORE 5 YES 6 NO 7 TRY AGAIN ** 10 CONTINUE ** 11 Note: best to use constants defined in {programs}\AutoIt3\Include\MsgBoxConstants.au3 Remarks~ The flag parameter can be a combination of the following values: decimal flag Button-related Result hexadecimal flag~ 0 OK button 0x0 1 OK and Cancel 0x1 2 Abort, Retry, and Ignore 0x2 3 Yes, No, and Cancel 0x3 4 Yes and No 0x4 5 Retry and Cancel 0x5 6 ** Cancel, Try Again, Continue 0x6 decimal flag Icon-related Result hexadecimal flag~ 0 (No icon) 0x0 16 Stop-sign icon 0x10 32 Question-mark icon 0x20 48 Exclamation-point icon 0x30 64 Information-sign icon consisting of 0x40 an 'i' in a circle decimal flag Default-related Result hexadecimal flag~ 0 First button is default button 0x0 256 Second button is default button 0x100 512 Third button is default button 0x200 decimal flag Modality-related Result hexadecimal flag~ 0 Application 0x0 4096 System modal (dialog has an icon) 0x1000 8192 Task modal 0x2000 decimal flag Miscellaneous-related Result hexadecimal flag~ 0 (nothing else special) 0x0 262144 MsgBox has top-most attribute set 0x40000 524288 title and text are right-justified 0x80000 ** Only valid on Windows 2000/XP and above. For example, to specify a SYSTEMMODAL box with the YES/NO buttons the flag value would be 4096 + 4 (or 4100 ) If using hexadecimal flags, that would be 0x1000 + 0x4 (or 0x1004 ). A message box appears centered on screen and resizes according to the text it contains. However, the title could get truncated if the SYSTEMMODAL flag ( 4096 ) is used. If " title " is equal to Default keyword @Scriptname is used Related~ |InputBox|, |ToolTip|, |TrayTip|, |SplashTextOn| Example~ > MsgBox(4096, "Test", "This box will time out in 10 seconds", 10) < ---------------------------------------------------------------------- *_SoundOpen* +------------+~ | _SoundOpen |~ +------------+~ Opens a sound file for use with other _Sound functions. > #include _SoundOpen ( $sFile ) < Parameters~ $sFile~ ------ Path to sound file Return Value~ Success~ ------- Returns a 4-element array containing the following information: $array[0] = Sound file ID string $array[1] = VBR length correction factor $array[2] = VBR timing correction factor $array[3] = Sound ID marker Failure~ ------- 0 and set @error @error : 1 = MCI open error 2 = File does not exist @Extended : 0 = No Error Integer other than 0 = MCI Error Remarks~ Although many of the |_Sound| functions will accept the filename as a parameter, if there is a possibility of the file being VBR (variable bit rate) encoded it is highly recommended to use |_SoundOpen| initially and then use the returned array as the identity parameter in other |_Sound|...() functions. This is because because the MCI DLL assumes all files are CBR (constant bit rate) encoded and produces incorrect results from those |_Sound|...() functions dealing with length and position when the sound file has been VBR (variable bit rate) encoded. If using the array as the ID parameter with the |_Sound|...() functions which alter the VBR correction factors (|_SoundStop|) the ID array will be updated when needed. The individual elements of the returned array have no utility outside the |_Sound| functions and their internal use is transparent to the user. Related~ |_SoundClose|, |_SoundLength|, |_SoundPause|, |_SoundPlay|, |_SoundPos|, |_SoundResume|, |_SoundStatus|, |_SoundStop| Example~ > #include ;open sound file : must be modified if run under Vista $sound = _SoundOpen(@WindowsDir & "\media\Windows XP Startup.wav") If @error = 2 Then MsgBox(0, "Error", "The file does not exist") Exit ElseIf @extended <> 0 Then $extended = @extended ;assign because @extended will be set after DllCall $stText = DllStructCreate("char[128]") $errorstring = DllCall("winmm.dll", "short", "mciGetErrorStringA", "str", $extended, "ptr", DllStructGetPtr($stText), "int", 128) MsgBox(0, "Error", "The open failed." & @CRLF & "Error Number: " & $extended & @CRLF & "Error Description: " & DllStructGetData($stText, 1) & @CRLF & "Please Note: The sound may still play correctly.") Else MsgBox(0, "Success", "The file opened successfully") EndIf _SoundClose($sound) < ---------------------------------------------------------------------- *MouseMove* +-----------+~ | MouseMove |~ +-----------+~ Moves the mouse pointer > MouseMove ( x , y [, speed ] ) < Parameters~ x~ ----- The screen x coordinate to move the mouse to y~ ----- The screen y coordinate to move the mouse to speed [optional]~ ---------------- the speed to move the mouse in the range 1 (fastest) to 100 (slowest). A speed of 0 will move the mouse instantly. Default speed is 10. Return Value~ None. Remarks~ User mouse movement is hindered during a non-instantaneous MouseMove operation. If MouseCoordMode is relative positioning, numbers may be negative. Related~ |MouseClick|, |MouseClickDrag|, |MouseGetPos|, MouseCoordMode (Option), |MouseDown|, |MouseUp|, |MouseWheel| Example~ > MouseMove(10, 100) MouseMove(700, 700, 0) < ---------------------------------------------------------------------- *language_reference__variables* ************************************~ ** **~ ** **~ ** Language Reference - Variables **~ ** **~ ** **~ ************************************~ A variable is just a place to store data in memory so that it can be accessed quickly. Think of it as a mailbox in memory that you can put information in or take information out of. For example you might create a variable to store the number a user's response to a question, or the result to a math equation. Each variable has a name (again, similar to a mailbox) and must start with the $ character and may only contain letters, numbers and the underscore _ character. Here are some example names: > $var1 $my_variable < Each variable is stored as a |variant| Declaring Variables~ Variables are declared and created with the Dim, Local and Global keywords: > Dim $var1 < Or you can declare multiple variables at once: > Dim $var1, $myvariable < You can also assign a variable without declaring it first, but many prefer explicit declarations. > $var1 = "create and assign" < Declaring Constants~ Constants are declared and created using Const keyword like: > Const $const1 = 1, $const2=12 < Constants can be declared and initialized using Enum keyword like: > Enum $const1 = 1, $const2, $const3 ; 1, 2, 3 Enum STEP 2 $incr0, $incr2, $incr4 ; 0, 2, 4 Enum STEP *2 $mult1, $mult2, $mult4 ; 1, 2, 4 < Constants cannot redeclare an existing variable. Scope~ A variable's scope is controlled by when and how you declare the variable. If you declare a variable at the start of your script and outside any functions it exists in the Global scope and can be read or changed from anywhere in the script. If you declare a variable inside a function it is in Local scope and can only be used within that same function. Variables created inside functions are automatically destroyed when the function ends. By default when variables are declared using Dim or assigned in a function they have Local scope unless there is a global variable of the same name (in which case the global variable is reused). This can be altered by using the Local and Global keywords to declare variables and force the scope you want. Arrays~ An Array is a variable containing series of data elements of the same type and size. Each element in this variable can be accessed by an index number. An example: Let's say you want to store these series of characters: "A", "U", "T", "O", "I", "T" and "3". You could use seven separate variables to do so, but using an Array is more efficient: > $Array[0]="A" $Array[1]="U" ..etc.. $Array[6]="3" < To access a specific value in an Array, you only have to know the index number: > $MyChar=$Array[2] < This results in $MyChar containing the letter "T" (See also: 'operators'). The index number can also be substituted by another variable or an expression, so you can build complex ways to assign or access elements in an array. Arrays can also be multi dimensional, when you use multiple series of index numbers, like: > $Array[0][0]="Upper-Left" $Array[1][0]="Lower-Left" $Array[0][1]="Upper-Right" $Array[1][1]="Lower-Right" < (These values are just examples) You can use up to 64 dimensions in an Array. The total number of entries cannot be greater than 2^24 (16 777 216). Before you can start using Arrays in your script, you must define their bounds using the 'Dim' keyword. Data types in Arrays~ It was said that an Array contains only one datatype of the same type. But technically speaking, a Variant in AutoIt can contain anything from a number to a boolean value. So an AutoIt-Array could also contain different types, even other Arrays: > $Array[0]=1 $Array[1]=true $Array[2]="Text" $Array[3]=$AnotherArray < This has not been strictly forbidden in AutoIt. However, it is NOT ADVISABLE to mix different datatypes in an Array. Especially the use of an Array inside another Array will severely affect the execution speed of your script. ---------------------------------------------------------------------- *language_reference__datatypes* ************************************~ ** **~ ** **~ ** Language Reference - Datatypes **~ ** **~ ** **~ ************************************~ In AutoIt there is only one datatype called a Variant. A variant can contain numeric or string data and decides how to use the data depending on the situation it is being used in. For example, if you try and multiply two variants they will be treated as numbers, if you try and concatenate (join) two variants they will be treated as strings. Some examples: 10 * 20 equals the number 200 (* is used to multiply two numbers) 10 * "20" equals the number 200 "10" * "20" equals the number 200 10 & 20 equals the string "1020" (& is used to join strings) If a string is used as a number, an implicit call to Number() function is done. So if it doesn't contain a valid number, it will be assumed to equal 0. For example, 10 * "fgh" equals the number 0. If a string is used as a boolean and it is an empty string "" , it will be assumed to equal False (see below). For example, NOT "" equals the Boolean true. Numbers~ Numbers can be standard decimal numbers like 2, 4.566, and -7. Scientific notation is also supported; therefore, you could write 1.5e3 instead of 1500. Integers (whole numbers) can also be represented in hexadecimal notation by preceding the integer with 0x as in 0x409 or 0x4fff (when using hex notation only 32-bit numbers are valid). Strings~ Strings are enclosed in double-quotes like "this". If you want a string to actually contain a double-quote use it twice like: "here is a ""double-quote"" - ok?" You can also use single-quotes like 'this' and 'here is a ' 'single-quote' ' - ok?' You can mix quote types to make for easier working and to avoid having to double-up your quotes to get what you want. For example if you want to use a lot of double-quotes in your strings then you should use single-quotes for declaring them: 'This "sentence" contains "lots" of "double-quotes" does it not?' is much simpler than: "This ""sentence"" contains ""lots"" of ""double-quotes"" does it not?" When evaluated, strings can have Env variables or Var variables substitution according to Opt() function definition. Booleans~ Booleans are logical values. Only two Boolean values exist: true and false. They can be used in variable assignments, together with the Boolean operators and, or and not. Examples: > $Boolean1 = true $Boolean2 = false $Boolean3 = $Boolean1 AND $Boolean2 < This will result in $Boolean3 being false > $Boolean1 = false $Boolean2 = not $boolean1 < This will result in $Boolean2 being true If Boolean values are used together with numbers, the following rules apply: A value 0 will be equal to Boolean false Any other number value will be equal to Boolean true Example: > $Number1 = 0 $Boolean1 = true $Boolean2 = $Number1 and $Boolean1 < This will result in $Boolean2 being false If you use arithmetics together with Boolean values (which is not advisable!), the following rules apply: A Boolean true will be converted into the numeric value 1 A Boolean false will be converted into the numeric value 0 Example: > $Boolean1 = true $Number1 = 100 $Number2 = $Boolean1 + $Number1 < This will result in $Number2 to be the numeric value 101 If you use strings together with Boolean values, they will be converted as follows: A Boolean true will be the string value "True" A Boolean false will be the string value "False" Example: > $Boolean1=true $String1="Test is: " $String2=$String1 & $Boolean1 < This will result in $String2 being the string value "Test is: True" The other way around however is different. When you use string comparisons with Boolean values, the following rules apply: Only an empty string ("") will be a Boolean false Any other string values (including a string equal "0") will be a Boolean true Binary~ Binary type can store any byte value. they are converted in hexadecimal representation when stored in a string variable. Example: > $bin = Binary("abc") $str = String($bin) ; "0x616263" < Pointer~ Pointer types store a memory address which is 32bits or 64bits depending on if the 32bit or 64 bit of AutoIt is used. They are converted to hexadecimal representation when stored in a string variable. Window handles (HWnd) as returned from WinGetHandle are a pointer type. Datatypes and Ranges~ The following table shows the internal variant datatypes and their ranges. Data Sub-type Range and Notes~ ------------------------------------------------------------------------- Int32 A 32bit signed integer number. Int64 A 64bit signed integer number Double A double-precision floating point number. String Can contain strings of up to 2147483647 characters. Binary Binary data, can contain up to 2147483647 bytes. Pointer A memory address pointer. 32bit or 64bit depending on the version of AutoIt used. Some functions in AutoIt only work with 32 bit numbers (e.g. BitAND) and are converted automatically - these functions are documented where required. ---------------------------------------------------------------------- *WinGetHandle* +--------------+~ | WinGetHandle |~ +--------------+~ Retrieves the internal handle of a window > WinGetHandle ( "title" [, "text"] ) < Parameters~ title~ ----- The title of the window to read. See Title special definition. text [optional]~ --------------- The text of the window to read. Return Value~ Success~ ------- Returns handle to the window. Failure~ ------- Returns "" (blank string) and sets @error to 1 if no window matches the criteria. Remarks~ This function allows you to use handles to specify windows rather than "title" and "text". Once you have obtained the handle you can access the required window even if its title changes. Related~ |WinSetTitle|, |GUICreate|, |WinList| Example~ > ; Identify the Notepad window that contains the text "this one" and get a handle to it ; Get the handle of a notepad window that contains "this one" Local $handle = WinGetHandle("[CLASS:Notepad]", "this one") If @error Then MsgBox(4096, "Error", "Could not find the correct window") Else ; Send some text directly to this window's edit control ControlSend($handle, "", "Edit1", "AbCdE") EndIf < ---------------------------------------------------------------------- *WinActivate* +-------------+~ | WinActivate |~ +-------------+~ Activates (gives focus to) a window. > WinActivate ( "title" [, "text"] ) < Parameters~ title ~ ----- The title of the window to activate. See Title special definition. text~ ----- [optional] The text of the window to activate. Return Value~ Success~ ------- Returns the handle of the window. Failure~ ------- Returns 0 if window is not found or cannot be activated. Remarks~ You can use the WinActive function to check if WinActivate succeeded. If multiple windows match the criteria, the window that was most recently active is the one activated. WinActivate works on minimized windows. However, a window that is "Always On Top" could still cover up a window you Activated. @extended contains additional info about how the activated process was done. Related~ |WinClose|, |WinSetState|, |WinTitleMatchMode| (Option), |WinKill|, |WinMove| Example~ > WinActivate("[CLASS:Notepad]", "") < ---------------------------------------------------------------------- *WinActive* +-----------+~ | WinActive |~ +-----------+~ Checks to see if a specified window exists and is currently active. > WinActive ( "title" [, "text"] ) < Parameters~ title~ ----- The title of the window to check. See Title special definition. text [optional]~ --------------- The text of the window to check. Return Value~ Success~ ------- Returns the handle to the window if it is active. Failure~ ------- Returns 0 otherwise. Remarks~ None. Related~ |WinExists|, |WinWait|, |WinWaitActive|, |WinWaitClose|, |WinWaitNotActive|, WinTitleMatchMode (Option) Example~ > If WinActive("[CLASS:Notepad]") Then MsgBox(0, "", "Window was active") EndIf < ---------------------------------------------------------------------- *InputBox* +----------+~ | InputBox |~ +----------+~ Displays an input box to ask the user to enter a string > InputBox ( " title ", " prompt " [, " default " [, "password char " [, width [, height [, left [, top [, timeout [, hwnd ]]]]]]]] ) < Parameters~ title~ ----- The title of the input box. prompt~ ------ A message to the user indicating what kind of input is expected default [optional]~ ------------------ The value that the input box starts with password [optional]~ ------------------- The character to replace all typed char~ ----- characters with in the display. If you want the actual typed character to appear, define with an empty string ("") (default) or a space for the first character. If you provide a multi-character string, only the first character is used for character masking. There are special meanings for the second and subsequent characters. See Remarks width [optional]~ ---------------- The width of the window height [optional]~ ----------------- The height of the window left [optional]~ --------------- The left side of the input box. By default, the box is centered. top [optional]~ -------------- The top of the input box. By default, the box is centered. timeout [optional]~ ------------------ How many seconds to wait before automatically cancelling the InputBox. hwnd [optional]~ --------------- The window handle to use as the parent for this dialog. Return Value~ Success~ ------- Returns the string that was entered. Failure~ ------- Returns "" (blank string) and sets @error as follows: @Error 0 = The string returned is valid. 1 = The Cancel button was pushed. 2 = The Timeout time was reached. 3 = The InputBox failed to open. This is usually caused by bad arguments. 4 = The InputBox cannot be displayed on any monitor. 5 = Invalid parameters width without height or left without top. Remarks~ The InputBox is user-resizable, but has a minimum size of approximately 190 x 115 pixels. Default size is approximately 250 x 190 pixels. The string returned will not exceed 254 characters and if input contains carriage returns or linefeeds, the result will be truncated at the first occurrence of those characters. The second and subsequent characters of the password field can be used to restrict input. Use a space to fill the first character to still see the characters typed. Putting an M after the first character indicates that input is Mandatory; i.e. you must enter something. Nothing will happen if you press the Ok button when there is nothing in the InputBox. It will not close and return the string. You can also specify the maximum length at the end of the password field. Just enter a number as the last character(s) to specify the length of the string. Related~ |MsgBox| Example~ > > ;Places the input box in the top left corner displaying the characters as they ;are typed. Local $answer = InputBox("Question", "Where were you born?", "Planet Earth", "", _ - 1, -1, 0, 0) ;Asks the user to enter a password. Don't forget to validate it! Local $passwd = InputBox("Security Check", "Enter your password.", "", "*") ;Asks the user to enter a 1 or 2 character response. The M in the password ;field indicates that blank string are not accepted and the 2 indicates that the ;responce will be at most 2 characters long. Local $value = InputBox("Testing", "Enter the 1 or 2 character code.", "", " M2") < ---------------------------------------------------------------------- *MouseGetPos* +-------------+~ | MouseGetPos |~ +-------------+~ Retrieves the current position of the mouse cursor > MouseGetPos ( [dimension] ) < Parameters~ dimension [optional~ ------------------- argument that determines what the return value will be. See Return Value. Return Value~ Dimension Values None Returns a two-element array containing the mouse coordinates: $array[0] = X coord (horizontal), $array[1] = Y coord (vertical) 0 Returns the X co-ordinate as an integer. 1 Returns the Y co-ordinate as an integer. If dimension is not a number @error will be set to 1. Remarks~ See |MouseCoordMode| for relative/absolute position settings. If relative positioning, numbers may be negative. Related~ |MouseClick|, |MouseClickDrag|, |MouseMove|, MouseCoordMode ( Option ), |MouseDown|, |MouseGetCursor|, |MouseUp|, |MouseWheel|, |PixelGetColor| ---------------------------------------------------------------------- *MouseClick* +------------+~ | MouseClick |~ +------------+~ Perform a mouse click operation > MouseClick ( " button " [, x , y [, clicks [, speed ]]] ) < Parameters~ button~ ------ The button to click: "left", "right", "middle", "main", "menu", "primary", "secondary". x , y [optional]~ ---------------- The x/y coordinates to move the mouse to. If no x and y coords are given, the current position is used (default). clicks [optional]~ ----------------- The number of times to click the mouse. Default is 1. speed [optional]~ ---------------- the speed to move the mouse in the range 1 (fastest) to 100 (slowest). A speed of 0 will move the mouse instantly. Default speed is 10. Return Value~ Success~ ------- Returns 1. Failure~ ------- Returns 0, the button is not in the list or invalid parameter as x without y. Remarks~ If the button is an empty string, the left button will be clicked. If x or y equal to the Default keyword no move occurs in the corresponding coordinate. If the user has swapped the left and right mouse buttons in the control panel, then the behaviour of the buttons is different. "Left" and "right" always click those buttons, whether the buttons are swapped or not. The "primary" or "main" button will be the main click, whether or not the buttons are swapped. The "secondary" or "menu" buttons will usually bring up the context menu, whether the buttons are swapped or not. Button Normal Swapped~ "" Left Left "left" Left Left "middle" Middle Middle "right" Right Right "primary" Left Right "main" Left Right "secondary" Right Left "menu" Right Left Related~ |MouseClickDrag|, |MouseGetPos|, |MouseMove|, MouseCoordMode (Option), MouseClickDelay ( Option ), |ControlClick|, |MouseDown|, |MouseUp|, |MouseWheel| Example~ > ; Double click at the current mouse pos MouseClick("left") MouseClick("left") ; Double click at 0,500 MouseClick("left", 0, 500, 2) ; SAFER VERSION of Double click at 0,500 - takes into account user's control panel settings MouseClick("primary", 0, 500, 2) < ---------------------------------------------------------------------- *WinGetPos* +-----------+~ | WinGetPos |~ +-----------+~ Retrieves the position and size of a given window. > WinGetPos ( " title " [, " text "] ) < Parameters~ title~ ----- The title of the window to read. See Title special definition. text [optional]~ --------------- The text of the window to read. Return Value~ Success~ ------- Returns a 4-element array containing the following information: $array [ 0 ] = X position $array [ 1 ] = Y position $array [ 2 ] = Width $array [ 3 ] = Height Failure : Returns 0 and sets @error to 1 if windows is not found. Remarks~ |WinGetPos| returns negative numbers such as -32000 for minimized windows, but works fine with (non-minimized) hidden windows. If the window title "Program Manager" is used, the function will return the size of the desktop. If multiple windows match the criteria, the most recently active window is used. Related~ |WinGetClientSize|, |WinMove|, |WinGetState| Example~ > Local $size = WinGetPos("[active]") MsgBox(0, "Active window stats (x,y,width,height):", $size[0] & " " & $size[1] & " " & $size[2] & " " & $size[3]) < ---------------------------------------------------------------------- *WinExists* +-----------+~ | WinExists |~ +-----------+~ Checks to see if a specified window exists. > WinExists ( "title" [, "text"] ) < Parameters~ title~ ----- The title of the window to check. See Title special definition. text [optional] The text of the window to check. Return Value~ Success~ ------- Returns 1 if the window exists. Failure~ ------- Returns 0 otherwise. Remarks~ WinExists will return 1 even if the window is hidden. Related~ |WinActive|, |WinWait|, |WinWaitActive|, |WinWaitClose|, |WinWaitNotActive|, WinTitleMatchMode (Option), |ProcessExists|, |WinClose| Example~ > If WinExists("[CLASS:Notepad]") Then MsgBox(0, "", "Window exists") EndIf < ---------------------------------------------------------------------- *command_line_parameters* *****************************~ ** **~ ** **~ ** Command Line Parameters **~ ** **~ ** **~ *****************************~ The special array $CmdLine is initialized with the command line parameters passed in to your AutoIt script. Note the scriptname is not classed as a parameter; get this information with @ScriptName instead. A parameter that contains spaces must be surrounded by "double quotes". Compiled scripts accept command line parameters in the same way. $CmdLine[0] is number of parameters $CmdLine[1] is param 1 (after the script name) $CmdLine[2] is param 2 etc ... $CmdLine[$CmdLine[0]] is one way to get the last parameter... So if your script is run like this: AutoIt3.exe myscript.au3 param1 "this is another param" $CmdLine[0] equals... 2 $CmdLine[1] equals... param1 $CmdLine[2] equals... this is another param @ScriptName equals... myscript.au3 In addition to $CmdLine there is a variable called $CmdLineRaw that contains the entire command line unsplit, so for the above example: $CmdLineRaw equals... myscript.au3 param1 "this is another param" If the script was compiled it would have been run like this: myscript.exe param1 "this is another param" $CmdLineRaw equals... param1 "this is another param" Note that $CmdLineRaw just return the parameters. Note : only 63 parameters can be return by $CmdLine[...], but $CmdLineRaw will always returns the entire command line. ---------------------------------------------------------------------- *autoIt_on_windows_vista* *****************************~ ** **~ ** **~ ** AutoIt on Windows Vista **~ ** **~ ** **~ *****************************~ Windows Vista brings new security features to restrict the running of files that require administrative rights. Even administrator users will be prompted every time an executable runs which will perform some administrative operation (such as writing to the registry key HKEY_LOCAL_MACHINE or writing to the C:\Windows directory). This is called User Account Control (UAC). By default AutoIt scripts run with standard user permissions but AutoIt has been coded to allow the script writer the option to "tag" a script in order to tell AutoIt if it needs to run with full admin rights or not. To force a script to attempt to run itself with administrative rights add the #requireadmin directive at the top of your script as follows: > ; This script requires full Administrative rights #requireadmin MsgBox(0, "Info", "This script has admin rights! ") < When the script runs AutoIt will check if it already has full admin rights and if not it will cause the operating system to prompt the user for permission as shown in "UAC Prompts". If permission is not given by the user the script will terminate. UAC Prompts~ The prompts that Vista will show when launching a program with administrative rights are shown below. The type of prompt displayed will depend on if the user is a "standard user" or an "adminstrator user" (remember even administrators need to get elevated permissions to perform admin operations). Note: The prompts shown are for the digitally signed version of AutoIt - all release versions are signed but beta versions may not be and will give a warning as shown in "Compiled Scripts" below. Standard User Prompt~ +-User Account Control-----------------------------------[ X ]+ | ----------------------------------------------------------- | | +---+ | | \!/ A program needs your permission to continue | | --V-------------------------------------------------------- | | | | If you started this program, continue | | /---\ | | | A | AutoIt v3 Script | | \---/ Jonathan Bennett | | To continue, type an administrator password, then click ok | | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | | +-----+ | | | \ / | Administrator | | | o | | | | / \ | | | +-----+ | | | | +-----+ | | |/-oo | Jon | | | |o | [ Password ] | | |// \ | | | +-----+ | | | | V details [ OK ] [ Cancel ] | | | | User Account Control helps stop unauthorized changes... | +=============================================================+ A standard user must select a user name and enter a password in order to continue and run the script with elevated rights. Administrator User Prompt~ +-User Account Control-----------------------------------[ X ]+ | ------------------------------------------------------------| | +---+ | | \!/ A program needs your permission to continue | | --V---------------------------------------------------------| | | | If you started this program, continue | | /---\ | | | A | AutoIt v3 Script | | \---/ Jonathan Bennett | | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | | | | V details [ Continue ] [ Cancel ] | | | | User Account Control helps stop unauthorized changes... | +=============================================================+ Compiled Scripts~ Compiled scripts (and possibly beta versions of AutoIt) are not digitally signed and will give a more serious looking warning as shown: +-User Account Control-----------------------------------[ X ]+ | ----------------------------------------------------------- | | +---+ | | \!/ An unidentified program wants to access you computer | | --V-------------------------------------------------------- | | | | Don't run the program unless you know where it's from or | | you've used it before. | | +---+ | | || /| compiledscript.exe | | +---+ Unidentified publisher | | | | + - - - - - - - - - - - - - - - - - - - - - - - - - - - -+ | | |-> Cancel | | | | I don't know what this program is or what it's for | | | + - - - - - - - - - - - - - - - - - - - - - - - - - - - -+ | | -> Allow | | I trust this program. I know where it's from or I'v_ | | | | | | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | | | | V details | | | | User Account Control helps stop unauthorized changes... | +=============================================================+ The user must click on Allow to continue (or enter a password if they are a standard user). If you have your own Authenticode signature you may sign your compiled scripts yourself Important: Whether AutoIt or a compiled script is signed or not, you should only run scripts from sources you trust! Even signed code can be malicious! ---------------------------------------------------------------------- *language_reference__conditional_statements* *************************************************~ ** **~ ** **~ ** Language Reference - Conditional Statements **~ ** **~ ** **~ *************************************************~ You will often want to change the flow of your script based on a condition or series of conditions. Is one number bigger than another? Or, does a string contain a certain value? Conditions are evaluated as true (non-zero) or false (zero). Conditions generally use comparison operators like ==, <>, >=. The following conditional statements are available in AutoIt: > If...Then...Else Select...Case Switch...Case < All three statements are similar and decide which code to execute depending on the condition(s) given. Here is an example of an If statement that pops up a message box depending on the value of a variable. If .. Then .. Else~ > $var = -20 If $var > 0 Then MsgBox(0, "Example", "$var was positive!") ElseIf $var < 0 Then MsgBox(0, "Example", "$var was negative!") Else MsgBox(0, "Example", "$var was zero.") EndIf In the example above, the expression $var > 0 evaluated to false because the variable was less than zero. When the first condition failed, the second condition was tested. The expression $var < 0 evaluated to true. This caused the If statement to execute the second MsgBox line and display "$var was negative!". Select~ A Select statement is very similar, but is generally used for situations where you want to test a large number of conditions as it is generally easier to read than a large If/ElseIf type block. e.g. > $var = 30 Select Case $var > 1 AND $var <= 10 MsgBox(0, "Example", "$var was greater than 1") Case $var > 10 AND $var <= 20 MsgBox(0, "Example", "$var was greater than 10") Case $var > 20 AND $var <= 30 MsgBox(0, "Example", "$var was greater than 20") Case $var > 30 AND $var <= 40 MsgBox(0, "Example", "$var was greater than 30") Case $var > 40 MsgBox(0, "Example", "$var was greater than 40") EndSelect < Switch~ A Switch statement is very similar to Select statement, but is generally used for situations where the same expression is tested against some different possible values. > $var = 30 Switch Int($var) Case 1 To 10 MsgBox(0, "Example", "$var was greater than 1") Case 11 To 20 MsgBox(0, "Example", "$var was greater than 10") Case 21 To 30 MsgBox(0, "Example", "$var was greater than 20") Case 31 To 40 MsgBox(0, "Example", "$var was greater than 30") Case Else MsgBox(0, "Example", "$var was greater than 40 or less or equal to 0") EndSwitch < To Sum Up~ With each of these structures, the first condition that is true controls which group of statements get executed. All subsequent conditions and their associated statements get ignored. ---------------------------------------------------------------------- *language_reference__loop_statements* ******************************************~ ** **~ ** **~ ** Language Reference - Loop Statements **~ ** **~ ** **~ ******************************************~ A loop is how you refer to a section of script that you repeat a number of times. You might want to loop a given number of times or you might wish to repeat a section of script as long as a certain condition is true or false. The following loop statements are available in AutoIt: |For__To__Step__Next| |While__WEnd| |Do__Until| |For__In__Next| While (no pun intended) all the statements perform similar functions, they are slightly different and one will usually be more appropriate than another for a given situation. ---------------------------------------------------------------------- *language_reference__user_functions* *****************************************~ ** **~ ** **~ ** Language Reference - User Functions **~ ** **~ ** **~ *****************************************~ A function is a section of code that can be called from the script to perform a certain "function". There are two sorts of functions in AutoIt, built-in functions and user functions. User Functions~ User functions are declared using the Func...EndFunc statements. Functions can accept parameters and return values as required. Function names must start with either a letter or an underscore, and the remainder of the name can contain any combination of letters and numbers and underscores. Some valid function names are: MyFunc Func1 _My_Func1 Here is an example of using a function to double a number 10 times: > $val = 10 For $i = 1 To 10 $doubled = MyDouble($val) MsgBox(0, "", $val & " doubled is " & $doubled) $val = $doubled Next Exit Func MyDouble($value) $value = $value * 2 Return $value EndFunc < ---------------------------------------------------------------------- *language_reference__gui_reference* ****************************************~ ** **~ ** **~ ** Language Reference - GUI Reference **~ ** **~ ** **~ ****************************************~ AutoIt has the ability to create simple Graphical User Interfaces (GUIs) that consist of windows and controls. GUI Concepts~ A GUI consists of one or more windows and each window contains one or more controls. GUIs are "event driven" which means you react to events - like a button that is clicked. You spend most of your time idling and waiting for an event to happen - this is a little different to a normal script where you are in control of what happens and when! Think of it as waiting by the door for the postman - you sit there until a letter pops through the postbox and then you look at the letters and decide what to do with them - this is exactly how GUIs work - you wait for the postman to come to you. Of course, you may choose to do other tasks while the GUI is active - for example you might use the GUI functions to create an elaborate progress box that you update while your script performs complex actions. GUI Controls~ All users will be familiar with controls - anything you click on or interact with in a window is a type of control. The types of controls that can be created with AutoIt are listed below - you will have used most of them in other Windows programs. Label A plain piece of text. Button A simple button. Input A single line control that you can enter text into. Edit A multi-line control that you can enter text into. Checkbox A box that can be "checked" or "unchecked". Radio A set of circular buttons - only one can be active at once. Combo A list with a dropdown box. List A list. Date A date picker. Pic A picture. Icon An icon. Progress A progress bar. Tab A group of controls that are contained in tabs. UpDown A control that can be added to input controls. Avi Display an AVI format clip. Menu A menu across the top of the window. ContextMenu A menu that appears when you right click inside the window. TreeView A control similar to the windows file-explorer. Slider A control similar to the windows sound volume control. ListView A control displaying columns information. ListViewItem A control displaying item in a listview control. Graphic A control displaying graphics drawn with GUICtrlSetGraphic. Dummy A dummy user control. Here is an example of a single window GUI that contains many of the controls available. As you can see it is possible to create very detailed GUIs! https://www.autoitscript.com/autoit3/files/beta/autoit/docs/images/SampleGuiScreenshot.png Controls are created with the GUICtrlCreate... set of functions. When a control is created a Control ID is returned. The most important things to note about a control ID is that: The control ID is a positive number (that is, a number greater than 0) Each control ID is unique - even when there are multiple windows The control ID is actually the same value as the Control ID that the AutoIt Window Info Tool shows. GUI Basic Functions~ These are the main functions that you will need to create a GUI. They are just the basics though, there are many more when you are ready to create some really advanced GUIs. Function Explanation~ |GUICreate| Create a window. |GUICtrlCreate|... Create various controls in a window. |GUISetState| Display or hide the window. |GUIGetMsg| Poll the GUI to see if an event has happened (MessageLoop mode only) |GUICtrlRead| Read the data in a control. |GUICtrlSetData| Set/change the data in a control. |GUICtrlUpdate|... Change various options for a control (color, style, etc.) You will need to #include for basic GUI related constants. There are other files containing constants related to the various controls you can create on the GUI. First let's create a window, call it "Hello World" and make it 200 by 100 pixels in size. When a new window is created it is hidden - so we must "show" it. @@SyntaxHighlighting@@ #include GUICreate("Hello World", 200, 100) GUISetState(@SW_SHOW) Sleep(2000) @@End@@ If your run the above script you will see a window open and close after 2 seconds. Not very interesting...let's add some text and an OK button. The text will be added at position 30, 10 and the button at 70, 50 and the button will be 60 pixels wide. @@SyntaxHighlighting@@ #include GUICreate("Hello World", 200, 100) GUICtrlCreateLabel("Hello world! How are you?", 30, 10) GUICtrlCreateButton("OK", 70, 50, 60) GUISetState(@SW_SHOW) Sleep(2000) @@End@@ That's pretty good, but how do we make the GUI react to us clicking the button? Well, this is where we must make a decision as to how we will process events - via a MessageLoop or via OnEvent functions. GUI Event Modes~ As mentioned above there are two basic GUI modes: MessageLoop mode and OnEvent mode. The modes are simply two different ways of reacting to GUI events. The mode you choose will depend on personal preference, and to some extent the type of GUI you wish to create. Both modes are equally capable of creating any GUI you wish but sometimes one mode is more suited to a task than the other. The default mode is the MessageLoop mode. To switch to OnEvent mode use Opt("GUIOnEventMode", 1). Message-loop Mode (default)~ In the Message-loop mode your script will spend the majority of its time in a tight loop. This loop will simply poll the GUI using the GUIGetMsg function. When an event has occurred the return value of the GUIGetMsg function will show the details (a button is clicked, the GUI has been closed, etc.). In this mode you will only receive events while you are actively polling the GUIGetMsg function so you must ensure that you call it many times a second otherwise your GUI will be unresponsive. This mode is best for GUIs where the GUI is "king" and all you care about is waiting for user events. See this page for a more detailed explanation of the MessageLoop mode. OnEvent Mode~ In the OnEvent mode instead of constantly polling the GUI to find out if anything has happened you make the GUI temporarily pause your script and call a pre-defined function to handle the event. For example, if the user clicks Button1 the GUI halts your main script and calls a previously defined user function that deals with Button1. When the function call is completed the main script is resumed. This mode is similar to the Visual Basic forms method. This mode is best for GUIs where the GUI is of secondary importance and your script has other tasks to perform in addition to looking after the GUI. See this page for a more detailed explanation of the OnEvent mode. ---------------------------------------------------------------------- *GUIGetMsg* +-----------+~ | GUIGetMsg |~ +-----------+~ Polls the GUI to see if any events have occurred. > GUIGetMsg ( [advanced] ) < Parameters~ advanced [optional] return extended information in an array. 0 = (default) Returns a single event. 1 = returns an array containing the event and extended information. Return Value~ Returns an event, or an array depending on the "advanced" parameter. The "event" returned is the control ID of the control sending the message, or it is a special event (like the window is closing, minimizing). Or if there is no message, the event is 0. Event ID the ID of the control sending the message 0 No event $GUI_EVENT_CLOSE dialog box being closed (either by defined button or system menu). $GUI_EVENT_MINIMIZE dialog box minimized with Windows title bar button. $GUI_EVENT_RESTORE dialog box restored by click on task bar icon. $GUI_EVENT_MAXIMIZE dialog box maximized with Windows title bar button. $GUI_EVENT_MOUSEMOVE the mouse cursor has moved. $GUI_EVENT_PRIMARYDOWN the primary mouse button was pressed. $GUI_EVENT_PRIMARYUP the primary mouse button was released. $GUI_EVENT_SECONDARYDOWN the secondary mouse button was pressed. $GUI_EVENT_SECONDARYUP the secondary mouse button was released. $GUI_EVENT_RESIZED dialog box has been resized. $GUI_EVENT_DROPPED End of a Drag&Drop action @GUI_DRAGID, @GUI_DRAGFILE and @GUI_DROPID will be used to retrieve the ID's/file corresponding to the involve control. ---------------------------------------------------------------------- *gui_control_creation_functions_reference* **********************************************~ ** **~ ** **~ ** GUI Control creation functions Reference **~ ** **~ ** **~ **********************************************~ Below is a complete list of the functions available in AutoIt. Click on a function name for a detailed description. See Gui Constants include files if you need to use the related controls Constants. Function Description~ |GUICtrlCreateAvi| Creates an AVI video control for the GUI. |GUICtrlCreateButton| Creates a Button control for the GUI. |GUICtrlCreateCheckbox| Creates a Checkbox control for the GUI. |GUICtrlCreateCombo| Creates a ComboBox control for the GUI. |GUICtrlCreateContextMenu| Creates a context menu for a control or entire GUI window. |GUICtrlCreateDate| Creates a date control for the GUI. |GUICtrlCreateDummy| Creates a Dummy control for the GUI. |GUICtrlCreateEdit| Creates an Edit control for the GUI. |GUICtrlCreateGraphic| Creates a Graphic control for the GUI. |GUICtrlCreateGroup| Creates a Group control for the GUI. |GUICtrlCreateIcon| Creates an Icon control for the GUI. |GUICtrlCreateInput| Creates an Input control for the GUI. |GUICtrlCreateLabel| Creates a static Label control for the GUI. |GUICtrlCreateList| Creates a List control for the GUI. |GUICtrlCreateListView| Creates a ListView control for the GUI. |GUICtrlCreateListViewItem| Creates a ListView item. |GUICtrlCreateMenu| Creates a Menu control for the GUI. |GUICtrlCreateMenuItem| Creates a MenuItem control for the GUI. |GUICtrlCreateMonthCal| Creates a month calendar control for the GUI. |GUICtrlCreateObj| Creates an ActiveX control in the GUI. |GUICtrlCreatePic| Creates a Picture control for the GUI. |GUICtrlCreateProgress| Creates a Progress control for the GUI. |GUICtrlCreateRadio| Creates a Radio button control for the GUI. |GUICtrlCreateSlider| Creates a Slider control for the GUI. |GUICtrlCreateTab| Creates a Tab control for the GUI. |GUICtrlCreateTabItem| Creates a TabItem control within an existing tab control in the GUI. |GUICtrlCreateTreeView| Creates a TreeView control for the GUI. |GUICtrlCreateTreeViewItem| Creates a TreeViewItem control for the GUI. |GUICtrlCreateUpdown| Creates an UpDown control for the GUI. |GUICtrlDelete| Deletes a control. When using the "advanced" parameter the information is returned in an array with extended information: $array[0] = 0 or Event ID or Control ID $array[1] = The window handle the event is from $array[2] = The control handle the event is from (if applicable) $array[3] = The current X position of the mouse cursor (relative to the GUI window) $array[4] = The current Y position of the mouse cursor (relative to the GUI window) If the GUIOnEventMode option is set to 1 then the return from GUIGetMsg is always 0 and the @error is set to 1. If the option GUIEventOptions is set to 1 the minimize, restore and maximize button will not do any action on the window just a simple notification. Remarks~ This function automatically idles the CPU when required so that it can be safely used in tight loops without hogging all the CPU. Information about the mouse position and the hovering control can be retrieved with GUIGetCursorInfo. No event is fired when the mouse is over a control so GUIGetCursorInfo must be called to retrieve the ControlID. Related~ |GUICreate|, GUICtrlCreateXXX, |GUICtrlRead|, |GUIOnEventMode| (Option), |GUIEventOptions| (Option), |GUIGetCursorInfo|, |GUICtrlSendMsg|, |GUICtrlSetOnEvent| Example~ > #include Example() ;------------------------------------------------------------------------------------- ; Example - Press the button to see the value of the radio boxes ; The script also detects state changes (closed/minimized/timeouts, etc). Func Example() Local $button_1, $radio_1, $radio_3 Local $radioval1, $msg Opt("GUICoordMode", 1) GUICreate("Radio Box Demo", 400, 280) ; Create the controls $button_1 = GUICtrlCreateButton("B&utton 1", 30, 20, 120, 40) GUICtrlCreateGroup("Group 1", 30, 90, 165, 160) GUIStartGroup() $radio_1 = GUICtrlCreateRadio("Radio &0", 50, 120, 70, 20) GUICtrlCreateRadio("Radio &1", 50, 150, 60, 20) $radio_3 = GUICtrlCreateRadio("Radio &2", 50, 180, 60, 20) ; Init our vars that we will use to keep track of GUI events $radioval1 = 0 ; We will assume 0 = first radio button selected, 2 = last button ; Show the GUI GUISetState() ; In this message loop we use variables to keep track of changes to the radios, another ; way would be to use GUICtrlRead() at the end to read in the state of each control While 1 $msg = GUIGetMsg() Select Case $msg = $GUI_EVENT_CLOSE MsgBox(0, "", "Dialog was closed") Exit Case $msg = $GUI_EVENT_MINIMIZE MsgBox(0, "", "Dialog minimized", 2) Case $msg = $GUI_EVENT_MAXIMIZE MsgBox(0, "", "Dialog restored", 2) Case $msg = $button_1 MsgBox(0, "Default button clicked", "Radio " & $radioval1) Case $msg >= $radio_1 And $msg <= $radio_3 $radioval1 = $msg - $radio_1 EndSelect WEnd EndFunc ;==>Example < ---------------------------------------------------------------------- *GUICtrlRead* +-------------+~ | GUICtrlRead |~ +-------------+~ Read state or data of a control. > GUICtrlRead ( controlID [, advanced ] ) < Parameters~ controlID~ --------- The control identifier (controlID) as returned by a |GUICtrlCreate|... function. advanced~ -------- [optional] returns extended information of a control. 0 = (Default) Returns a value with state or data of a control. 1 = Returns extended information of a control (see Remarks). Return Value~ Success~ ------- Returns depending the control (see below). Failure~ ------- Returns 0. Type Value ~ ----------------------------------------------------------------------- Checkbox, Radio state of the button. See State table Combo, List The value selected Input, Edit The text entered Button The display text Date The selected date in the format defined by the regional settings Progress Current percentage Slider Current value Tab The number or the controlID of the tabitem selected depending of the advanced parameter value. Menu, MenuItem State of the menu/item. See State table TreeView Control identifier (controlID) of the selected TreeViewItem TreeViewItem State of the TreeViewItem ListView Control identifier (controlID) of the selected ListViewItem. 0 means no item is selected Dummy The value set by GUICtrlSendToDummy or GUICtrlSetData Remarks~ In 'advanced' mode the return value contains additional data of the control (see below). Note: not for all known controls there is additional data available! Type Additional Value~ ----------------------------------------------------------------------- Checkbox, Radio The text of the control. Menu, MenuItem The text of the control. TreeView The text of the current selected TreeViewItem. TreeViewItem The text of the TreeViewItem. ListViewItem The state of the ListViewItem if $LVS_EX_CHECKBOXES exStyle used in advanced mode. See State table Tab The controlID of the tabitem selected For Checkbox, Radio control several states can be returned as $GUI_FOCUS and $GUI_CHECKED,. So use i.e. BitAnd(GUICtrlRead($Item),$GUI_CHECKED) to test if the control is checked. For Listview items several states can be returned as $GUI_CHECKED and $GUI_UNCHECKED (only for listview controls with LVS_EX_CHECKBOXES-exstyle and on 'advanced' return) . So use i.e. BitAnd(GUICtrlRead($Item),$GUI_CHECKED) to test if the item is checked. For Treeview items several states can be returned as $GUI_FOCUS, $GUI_EXPAND and $GUI_CHECKED, $GUI_UNCHECKED (only for treeview controls with TVS_CHECKBOXES-style . So use i.e. BitAnd(GUICtrlRead($Item),$GUI_CHECKED) to test if the item is checked. Related~ GUICtrlUpdateXXX, |GUIGetMsg|, |GUICtrlSetData|, GUIEventOptions (Option), GUICtrlCreateXXX, |GUICtrlGetState|, |GUICtrlSendToDummy|, |GUICtrlSendMsg| Example~ > #include Example() Func Example() Local $menu1, $n1, $n2, $msg, $menustate, $menutext GUICreate("My GUICtrlRead") ; will create a dialog box that when displayed is centered $menu1 = GUICtrlCreateMenu("File") $n1 = GUICtrlCreateList("", 10, 10, -1, 100) GUICtrlSetData(-1, "item1|item2|item3", "item2") $n2 = GUICtrlCreateButton("Read", 10, 110, 50) GUICtrlSetState(-1, $GUI_FOCUS) ; the focus is on this button GUISetState() ; will display an empty dialog box ; Run the GUI until the dialog is closed Do $msg = GUIGetMsg() If $msg = $n2 Then MsgBox(0, "Selected listbox entry", GUICtrlRead($n1)) ; display the selected listbox entry $menustate = GUICtrlRead($menu1) ; return the state of the menu item $menutext = GUICtrlRead($menu1, 1) ; return the text of the menu item MsgBox(0, "State and text of the menuitem", "state:" & $menustate & @LF & "text:" & $menutext) EndIf Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example < ---------------------------------------------------------------------- *GUICtrlSendMsg* +----------------+~ | GUICtrlSendMsg |~ +----------------+~ Send a message to a control. > GUICtrlSendMsg ( controlID , msg , wParam , lParam ) < Parameters~ controlID~ --------- The control identifier (controlID) as returned by a GUICtrlCreate... function. msg~ ----- type of message to be send to the control as defined in the Windows control documentation. wParam~ ------ The first param to send to the control. lParam~ ------ The second param to send to the control. Return Value~ Success~ ------- Returns the value returned by the SendMessage Windows API. Failure~ ------- Returns 0. Remarks~ This function allows the sending of special Windows messages directly to the control using the SendMessage API. It is used to enable special control features not available with the simple GUICtrlRead() and GUICtrlUpdate...() range of functions. The parameters (wParam and lParam) can be an integer or a string. GUICtrlSendMsg should be used for messages that have no special return types. For more advanced messages where you must be able to receive extra data you must use GUICtrlRecvMsg(). Related~ |GUICtrlRecvMsg|, GUICtrlCreateXXX, GUICtrlUpdateXXX, |GUIGetMsg|, |GUICtrlRead| Example~ > #include #include GUICreate("My GUI") ; will create a dialog box that when displayed is centered Local $nEdit = GUICtrlCreateEdit("line 0", 10, 10) GUICtrlCreateButton("Ok", 20, 200, 50) GUISetState() Local $n For $n = 1 To 5 GUICtrlSetData($nEdit, @CRLF & "line " & $n) Next ; Run the GUI until the dialog is closed Do Local $msg = GUIGetMsg() If $msg > 0 Then $n = GUICtrlSendMsg($nEdit, $EM_LINEINDEX, -1, 0) Local $nline = GUICtrlSendMsg($nEdit, $EM_LINEFROMCHAR, $n, 0) GUICtrlSetState($nEdit, $GUI_FOCUS) ; set focus MsgBox(0, "Currentline", $nline) EndIf Until $msg = $GUI_EVENT_CLOSE < ---------------------------------------------------------------------- *Sleep* +-------+~ | Sleep |~ +-------+~ Pause script execution. > Sleep ( delay ) < Parameters~ delay~ ----- Amount of time to pause (in milliseconds). Return Value~ None. Remarks~ Maximum sleep time is 2147483647 milliseconds (24 days). Related~ None. Example~ > Sleep(5000) ;five seconds < ---------------------------------------------------------------------- *Send* +------+~ | Send |~ +------+~ Sends simulated keystrokes to the active window. > Send ( "keys" [, flag] ) < Parameters~ keys The sequence of keys to send. flag [optional]~ --------------- Changes how "keys" is processed: flag = 0 (default)~ ------------------ Text contains special characters like + and ! to indicate SHIFT and ALT key-presses. flag = 1~ -------- keys are sent raw. Return Value~ None. Remarks~ See the Appendix for some tips on using Send. AutoIt can send all ASCII and Extended ASCII characters (0-255), to send UNICODE characters you must use the "ASC" option and the code of the character you wish to send (see {ASC} at the bottom of the table below). The "Send" command syntax is similar to that of ScriptIt and the Visual Basic "SendKeys" command. Characters are sent as written with the exception of the following characters: '!'~ ----- This tells AutoIt to send an ALT keystroke, therefore Send("This is text!a") would send the keys "This is text" and then press "ALT+a". N.B. Some programs are very choosy about capital letters and ALT keys, i.e. "!A" is different to "!a". The first says ALT+SHIFT+A, the second is ALT+a. If in doubt, use lowercase! '+'~ ----- This tells AutoIt to send a SHIFT keystroke, therefore Send("Hell+o") would send the text "HellO". Send("!+a") would send "ALT+SHIFT+a". '^'~ ----- This tells AutoIt to send a CONTROL keystroke, therefore Send("^!a") would send "CTRL+ALT+a". N.B. Some programs are very choosy about capital letters and CTRL keys, i.e. "^A" is different from "^a". The first says CTRL+SHIFT+A, the second is CTRL+a. If in doubt, use lowercase! '#'~ ----- The hash now sends a Windows keystroke; therefore, Send("#r") would send Win+r which launches the Run dialog box. You can set SendCapslockMode to make CAPS LOCK disabled at the start of a Send operation and restored upon completion. However, if a user is holding down the Shift key when a Send function begins, text may be sent in uppercase. One workaround is to Send("{SHIFTDOWN}{SHIFTUP}") before the other Send operations. Certain keyboard as the Czech one send different characters when using the Shift Key or being in CAPS LOCK enabled and sending a char. Due to the send AutoIt implementation the CAPS LOCKed char will be sent as Shifted one so it will not work. Certain special keys can be sent and should be enclosed in braces: N.B. Windows does not allow the simulation of the "CTRL-ALT-DEL" combination! Send Command (if zero flag) Resulting Keypress {!} ! {#} # {+} + {^} ^ {{} { {}} } {SPACE} SPACE {ENTER} ENTER key on the main keyboard {ALT} ALT {BACKSPACE} or {BS} BACKSPACE {DELETE} or {DEL} DELETE {UP} Up arrow {DOWN} Down arrow {LEFT} Left arrow {RIGHT} Right arrow {HOME} HOME {END} END {ESCAPE} or {ESC} ESCAPE {INSERT} or {INS} INS {PGUP} PageUp {PGDN} PageDown {F1} - {F12} Function keys {TAB} TAB {PRINTSCREEN} Print Screen key {LWIN} Left Windows key {RWIN} Right Windows key {NUMLOCK on} NUMLOCK (on/off/toggle) {CAPSLOCK off} CAPSLOCK (on/off/toggle) {SCROLLLOCK toggle} SCROLLLOCK (on/off/toggle) {BREAK} for Ctrl+Break processing {PAUSE} PAUSE {NUMPAD0} - {NUMPAD9} Numpad digits {NUMPADMULT} Numpad Multiply {NUMPADADD} Numpad Add {NUMPADSUB} Numpad Subtract {NUMPADDIV} Numpad Divide {NUMPADDOT} Numpad period {NUMPADENTER} Enter key on the numpad {APPSKEY} Windows App key {LALT} Left ALT key {RALT} Right ALT key {LCTRL} Left CTRL key {RCTRL} Right CTRL key {LSHIFT} Left Shift key {RSHIFT} Right Shift key {SLEEP} Computer SLEEP key {ALTDOWN} Holds the ALT key down until {ALTUP} is sent {SHIFTDOWN} Holds the SHIFT key down until {SHIFTUP} is sent {CTRLDOWN} Holds the CTRL key down until {CTRLUP} is sent {LWINDOWN} Holds the left Windows key down until {LWINUP} is sent {RWINDOWN} Holds the right Windows key down until {RWINUP} is sent {ASC nnnn} Send the ALT+nnnn key combination {BROWSER_BACK} 2000/XP Only: Select the browser "back" button {BROWSER_FORWARD} 2000/XP Only: Select the browser "forward" button {BROWSER_REFRESH} 2000/XP Only: Select the browser "refresh" button {BROWSER_STOP} 2000/XP Only: Select the browser "stop" button {BROWSER_SEARCH} 2000/XP Only: Select the browser "search" button {BROWSER_FAVORITES} 2000/XP Only: Select the browser "favorites" button {BROWSER_HOME} 2000/XP Only: Launch the browser and go to the home page {VOLUME_MUTE} 2000/XP Only: Mute the volume {VOLUME_DOWN} 2000/XP Only: Reduce the volume {VOLUME_UP} 2000/XP Only: Increase the volume {MEDIA_NEXT} 2000/XP Only: Select next track in media player {MEDIA_PREV} 2000/XP Only: Select previous track in media player {MEDIA_STOP} 2000/XP Only: Stop media player {MEDIA_PLAY_PAUSE} 2000/XP Only: Play/pause media player {LAUNCH_MAIL} 2000/XP Only: Launch the email application {LAUNCH_MEDIA} 2000/XP Only: Launch media player {LAUNCH_APP1} 2000/XP Only: Launch user app1 {LAUNCH_APP2} 2000/XP Only: Launch user app2 To send the ASCII value A (same as pressing ALT+065 on the numeric keypad) Send("{ASC 065}") (When using 2 digit ASCII codes you must use a leading 0, otherwise an obsolete 437 code page is used). To send UNICODE characters enter the character code (decimal or hex), for example this sends a Chinese character Send("{ASC 2709}") or Send("{ASC 0xA95}") Single keys can also be repeated, e.g. > Send("{DEL 4}") ;Presses the DEL key 4 times Send("{S 30}") ;Sends 30 'S' characters Send("+{TAB 4}") ;Presses SHIFT+TAB 4 times < The key will be send at least once even if the count is zero. To hold a key down > Send("{a down}") ;Holds the A key down Send("{a up}") ;Releases the A key < To set the state of the capslock, numlock and scrolllock keys > Send("{NumLock on}") ;Turns the NumLock key on Send("{CapsLock off}") ;Turns the CapsLock key off Send("{ScrollLock toggle}") ;Toggles the state of ScrollLock < If you wish to use a variable for the count, try > $n = 4 Send("+{TAB " & $n & "}") < If you wish to send the ASCII value A four times, then try > $x = Chr(65) Send("{" & $x & " 4}") < Most laptop computer keyboards have a special Fn key. This key cannot be simulated. Note, by setting the flag parameter to 1 the above "special" processing will be disabled. This is useful when you want to send some text copied from a variable and you want the text sent exactly as written. For example, open Folder Options (in the control panel) and try the following: > Send("{TAB}") Navigate to next control (button, checkbox, etc) Send("+{TAB}") Navigate to previous control. Send("^{TAB}") Navigate to next WindowTab (on a Tabbed dialog window) Send("^+{TAB}") Navigate to previous WindowTab. Send("{SPACE}") Can be used to toggle a checkbox or click a button. Send("{+}") Usually checks a checkbox (if it's a "real" checkbox.) Send("{-}") Usually unchecks a checkbox. Send("{NumPadMult}") Recursively expands folders in a SysTreeView32. < Use Alt-key combos to access menu items. Also, open Notepad and try the following: Send("!f") Send Alt+f, the access key for Notepad's file menu. Try other letters! > Send("{DOWN}") Move down a menu. Send("{UP}") Move up a menu. Send("{LEFT}") Move leftward to new menu or expand a submenu. Send("{RIGHT}") Move rightward to new menu or collapse a submenu. < See Windows' Help--press Win+F1--for a complete list of keyboard shortcuts if you don't know the importance of Alt+F4, PrintScreen, Ctrl+C, and so on. When running a script on a remote computer through a program as psexec (www.sysinternals.com) or beyondexec (www.beyondlogic.org) it is necessary, specially when sending strokes to a program launch by the script with a Run function, to use ControlSend or other ControlXXX functions to directly communicate with the control. Send even with Opt("SendAttachMode",1) is not working. Using the -s mode when submitting can help to have better right on the remote computer. Opt("SendKeyDelay",...)~ ----------------------- alters the the length of the brief pause in between sent keystrokes. Opt("SendKeyDownDelay",...)~ --------------------------- alters the length of time a key is held down before being released during a keystroke. Set both "SendKeyDelay" and "SendKeyDownDelay" to 0 to remove all delays when sending keystrokes. This may be required under certain circumstances, for example, when locking the system ("#l") it may be necessary to remove the delays in order to prevent the WIN key from being stuck down. Related~ SendAttachMode (Option), |SendKeepActive|, SendKeyDelay (Option), SendKeyDownDelay (Option), |ControlSend|, |BlockInput|, |HotKeySet|, |WinMenuSelectItem| Example~ > Send("#r") WinWaitActive("Run") Send("notepad.exe{Enter}") WinWaitActive("[CLASS:Notepad]") Send("Today's time/date is {F5}") < ---------------------------------------------------------------------- *While__Wend* +--------------+~ | While...WEnd |~ +--------------+~ Loop based on an expression. > While statements ... WEnd < Parameters~ expression~ ---------- If the expression is true the following statements up to the WEnd statement are executed. This loop continues until the expression is false. Remarks~ While...WEnd statements may be nested. The expression is tested before the loop is executed so the loop will be executed zero or more times. To create an infinite loop, you can use a non-zero number as the expression. Related~ |ContinueLoop|, |ExitLoop| Example~ > Local $i = 0 While $i <= 10 MsgBox(0, "Value of $i is:", $i) $i = $i + 1 WEnd < ---------------------------------------------------------------------- *For__To__Step__Next* +------------------+~ | For To Step Next |~ +------------------+~ For...To...Step...Next Loop based on an expression. > For = To [Step ] statements ... Next Parameters~ variable~ -------- The variable used for the count. start~ ----- The initial numeric value of the variable. stop~ ----- The final numeric value of the variable. stepval [optional]~ ------------------ The numeric value (possibly fractional) that the count is increased by each loop. Default is 1. Remarks~ The Variable will be created automatically with a LOCAL scope, even when MustDeclareVars is on. For...Next statements may be nested. The For loop terminates when the value of variable exceeds the stop threshold. If stepVal or stop is a variable, its value is only read the first time the loop executes. A For loop will execute zero times if: start > stop and step > 0, or start < stop and step is negative Related~ |ContinueLoop|, |ExitLoop| Example~ > > For $i = 5 To 1 Step -1 MsgBox(0, "Count down!", $i) Next MsgBox(0, "", "Blast Off!") < ---------------------------------------------------------------------- *For__In__Next* +-----------------+~ | For...In...Next |~ +-----------------+~ Enumerates elements in an Object collection or an Array > For <$Variable> In statements ... Next < Parameters~ Variable~ -------- A variable to which an element is being assigned expression~ ---------- Must be an expression resulting in an Object, or an Array with at least one element Remarks~ ------- The Variable will be created automatically with a Local scope, even when MustDeclareVars is on. If the expression is an Object collection with no elements, or an multi-dimensional array, the loop will be skipped and the Variable will contain an empty string. If the expression is not an Object nor an Array, the script stops with an error, unless a COM Error handler had been configured. AutoIt Arrays are read-only when using For...In. While you can assign the variable inside the For...In loop a value, this change is not reflected in the array itself. To modify the contents of an array during enumeration, use a For...To loop. For...In...Next statements may be nested. Related~ |With__EndWith| Example~ > > ;Using an Array Local $aArray[4] $aArray[0] = "a" $aArray[1] = 0 $aArray[2] = 1.3434 $aArray[3] = "test" Local $string = "" For $element In $aArray $string = $string & $element & @CRLF Next MsgBox(0, "For..IN Arraytest", "Result is: " & @CRLF & $string) ;Using an Object Collection Local $oShell = ObjCreate("shell.application") Local $oShellWindows = $oShell.windows If IsObj($oShellWindows) Then $string = "" For $Window In $oShellWindows $string = $string & $Window.LocationName & @CRLF Next MsgBox(0, "", "You have the following windows open:" & @CRLF & $string) Else MsgBox(0, "", "you have no open shell windows.") EndIf ---------------------------------------------------------------------- *Do__Until* +------------+~ | Do...Until |~ +------------+~ Loop based on an expression. > Do statements ... Until < Parameters~ expression~ ---------- The statements in between Do and Until are executed until the expression is true. Remarks~ ------- Do...Until statements may be nested. The expression is tested after the loop is executed, so the loop will be executed one or more times. Related~ |ContinueLoop|, |ExitLoop| Example~ > Local $i = 0 Do MsgBox(0, "Value of $i is:", $i) $i = $i + 1 Until $i = 10 < ---------------------------------------------------------------------- *ContinueLoop* +-------------------------------+~ | Continue a While/Do/For loop. |~ +-------------------------------+~ > ContinueLoop [level] < Parameters~ level [optional]~ ---------------- The level of the loop to restart. The default is 1 (meaning the current loop). Remarks~ ContinueLoop will continue execution of the loop at the expression testing statement (that is the While, Until or Next statement). A negative level or zero value has no effect. Even though any program that uses ContinueLoop can be rewritten using If-ElseIf-EndIf statements, ContinueLoop can make long scripts easier to understand. Be careful with While/Do loops; you can create infinite loops by using ContinueLoop incorrectly. Related~ |ExitLoop|, |For__To__Step__Next|, |While__WEnd|, |Do__Until| Example~ > ;Print all numbers from 1 to 10 except number 7 For $i = 1 To 10 If $i = 7 Then ContinueLoop MsgBox(0, "The value of $i is:", $i) Next ;Example of using level is needed. < ---------------------------------------------------------------------- *ExitLoop* +----------+~ | ExitLoop |~ +----------+~ Terminate a While/Do/For loop. > ExitLoop [level] < Parameters~ level [optional]~ ---------------- The number of loop levels to exit from. The default is 1 (meaning the current loop). Remarks~ A negative level or zero value has no effect. ExitLoop will break out of a While, Do or For loop. ExitLoop is useful when you would otherwise need to perform error checking in both the loop-test and the loop-body. Related~ |ContinueLoop|, |Exit|, |For__To__Step__Next|, |Do__Until|, |While__WEnd| Example~ > Local $sum = 0 While 1 ;use infinite loop since ExitLoop will get called Local $ans = InputBox("Running total=" & $sum, _ " Enter a positive number. (A negative number exits)") If $ans < 0 Then ExitLoop $sum = $sum + $ans WEnd MsgBox(0, "The sum was", $sum) < ---------------------------------------------------------------------- *Exit* +------+~ | Exit |~ +------+~ Terminates the script. > Exit [return code] < Parameters~ return code [optional]~ ---------------------- Integer that sets the script's return code. This code can be used by Windows or the DOS variable %ERRORLEVEL%. The default is 0. Scripts normally set an errorlevel of 0 if the script executed properly; error levels 1 and above typically indicate that the script did not execute properly. Remarks~ The parameter, if included, can be enclosed in parentheses. Thus, the following are equivalent: Exit, Exit 0, and Exit(0). However, Exit() is invalid. The code can be retrieved in an OnAutoItExitRegister function by @EXITCODE. Related~ |ExitLoop|, |OnAutoItExitRegister| Example~ > ;First Example Exit ;Second Example ; Terminate script if no command-line arguments If $CmdLine[0] = 0 Then Exit (1) ;Third Example ; Open file specified as first command-line argument Local $file = FileOpen($CmdLine[1], 0) ; Check if file opened for reading OK If $file = -1 Then Exit (2) ; If file is empty then exit (script is successful) Local $line = FileReadLine($file) If @error = -1 Then Exit ;code to process file goes here FileClose($file) Exit ;is optional if last line of script < ---------------------------------------------------------------------- *HotKeySet* +-----------+~ | HotKeySet |~ +-----------+~ Sets a hotkey that calls a user function. > HotKeySet ( "key" [, "function"] ) < Parameters~ key The key combination to use as the hotkey. Same format as |Send|(). function [optional] The name of the function to call when the key is pressed. Not specifying this parameter will unset a previous hotkey. Return Value~ Success~ ------- Returns 1. Failure~ ------- Returns 0. Remarks~ It is better to use the lower keyboard key as for keyboard as Russian one, the unshifted key is not the lower value. I.E. "D" is not the upper case of "B". The Hotkey will not be set and a failure will occur. If two AutoIt scripts set the same HotKeys, you should avoid running those scripts simultaneously. (The second script cannot capture the hotkey unless the first script terminates or unregisters the key prior to the second script setting the hotkey.) A hotkey-press *typically* interrupts the active AutoIt function/statement and runs its user function until it completes or is interrupted. Exceptions are as follows: 1) If the current function is a "blocking" function, then the key-presses are buffered and execute as soon as the blocking function completes. MsgBox and FileSelectFolder are examples of blocking functions. Try the behavior of Shift-Alt-d in the Example. 2) If you have paused the script by clicking on the AutoIt Tray icon, any hotkeys pressed during this paused state are ignored. The following hotkeys cannot be set: Ctrl+Alt+Delete It is reserved by Windows F12 It is also reserved by Windows, according to its API. NumPad's Enter Key Instead, use {Enter} which captures both Enter keys on the keyboard. Win+B,D,E,F,L,M,R,U; and Win+Shift+M These are built-in Windows shortcuts. Note: Win+B and Win+L might only be reserved on Windows XP and above. Alt, Ctrl, Shift, Win These are the modifier keys themselves! Other Any global hotkeys a user has defined using third-party software, any combos of two or more "base keys" such as '{F1}{F2}', and any keys of the form '{LALT}' or '{ALTDOWN}'. When you set a hotkey, AutoIt captures the key-press and does not pass it on to the active application, with one exception: the Lock keys (NumLock, CapsLock, and ScrollLock) still toggle their respective state! To Send() a key combination which will trigger a HotKeySet() event, either use ControlSend() or unregister the HotKeySet() event, otherwise, the Send() event may trigger an infinite loop. > ; capture and pass along a keypress HotKeySet("{Esc}", "captureEsc") Func captureEsc() ; ... can do stuff here HotKeySet("{Esc}") Send("{Esc}") HotKeySet("{Esc}", "captureEsc") EndFunc < The called function can not be given parameters. They will be ignored. @HotKeyPressed macro can be used inside the function to handle several keys in the same function. Related~ |Send|, |GUISetAccelerators| Example~ > ; Press Esc to terminate script, Pause/Break to "pause" Global $Paused HotKeySet("{PAUSE}", "TogglePause") HotKeySet("{ESC}", "Terminate") HotKeySet("+!d", "ShowMessage") ;Shift-Alt-d ;;;; Body of program would go here ;;;; While 1 Sleep(100) WEnd ;;;;;;;; Func TogglePause() $Paused = Not $Paused While $Paused Sleep(100) ToolTip('Script is "Paused"', 0, 0) WEnd ToolTip("") EndFunc ;==>TogglePause Func Terminate() Exit 0 EndFunc ;==>Terminate Func ShowMessage() MsgBox(4096, "", "This is a message.") EndFunc ;==>ShowMessage < ---------------------------------------------------------------------- *If__Then* +----------+~ | If..Then |~ +----------+~ Conditionally run a single statement. > If Then statement < Parameters~ expression~ ---------- If the expression is true, the statement is executed. Remarks~ This version of the If statement is used to execute a single statement without the overhead of an EndIf. The expression can contain the boolean operators of AND, OR, and NOT as well as the logical operators <, <=, >, >=, =, ==, and <> grouped with parentheses as needed. Related~ |If__Else__EndIf|, |Select__Case__EndSelect|, |Switch__EndSwitch| Example~ > ;Terminates script if no command-line arguments If $CmdLine[0] = 0 Then Exit ;Alternative: If $CmdLine[0] = 0 Then Exit EndIf < ---------------------------------------------------------------------- *If__Else__EndIf* *If__ElseIf__Else__EndIf* +----------------------------+~ | If...Else...EndIf |~ | If...ElseIf...Else...EndIf |~ +----------------------------+~ Conditionally run statements. > If Then statements ... [ElseIf expression-n Then [elseif statements ... ]] ... [Else [else statements] ... EndIf < Parameters~ expression If the expression is true, the first statement block is executed. If not, the first true ElseIf block is executed. Otherwise, the "Else" block is executed. Remarks~ If statements may be nested. The expression can contain the boolean operators of AND, OR, and NOT as well as the logical operators <, <=, >, >=, =, ==, and <> grouped with parentheses as needed. Related~ |If__Then|, |Select__Case__EndSelect|, |Switch__EndSwitch| Example~ > Local $var = "" If $var > 0 Then MsgBox(4096, "", "Value is positive.") ElseIf $var < 0 Then MsgBox(4096, "", "Value is negative.") Else If StringIsXDigit($var) Then MsgBox(4096, "", "Value might be hexadecimal!") Else MsgBox(4096, "", "Value is a string.") EndIf EndIf < ---------------------------------------------------------------------- *Select__Case__EndSelect* +---------------------------+~ | Select...Case...EndSelect |~ +---------------------------+~ Conditionally run statements. > Select Case statement1 ... [Case statement2 ...] [Case Else statementN ...] EndSelect < Parameters~ ------------ If the expression is true the following statements up to the next Case or EndSelect statement are executed. If more than one of the Case statements are true, only the first one is executed. Remarks~ Select statements may be nested. The expression can contain the boolean operators of AND, OR, and NOT as well as the logical operators <, <=, >, >=, =, ==, and <> grouped with parentheses as needed. Related~ |If__Then|, |If__Else__EndIf|, |Switch__EndSwitch|, |ContinueCase| Example~ > Local $var = 0 Local $var2 = "" Select Case $var = 1 MsgBox(0, "", "First Case expression was true") Case $var2 = "test" MsgBox(0, "", "Second Case expression was true") Case Else MsgBox(0, "", "No preceding case was true!") EndSelect < ---------------------------------------------------------------------- *Switch__Case__EndSwitch* +---------------------------+~ | Switch...Case...EndSwitch |~ +---------------------------+~ Conditionally run statements. > Switch Case [To ] [, [To ] ...] statement1 ... [Case [To ] [, [To ] ...] statement2 ...] [Case Else statementN ...] EndSwitch < Parameters~ ------------ An expression that returns a value. The value from the expression is then compared against the values of each case until a match is found. This expression is always evaluted exactly once each time through the structure. To ~ ------------------ The case is executed if the expression is between the two values. ~ ------- The case is executed if the expression matches the value. Remarks~ If no cases match the Switch value, then the Case Else section, if present, is executed. If no cases match and Case Else is not defined, then none of the code inside the Switch structure, other than the condition, will be executed. Switch statements may be nested. Switch statements are case-insensitive. Related~ |If__Then|, |If__Else__EndIf|, |Select__EndSelect|, |ContinueCase| Example~ > Local $msg Switch @HOUR Case 6 To 11 $msg = "Good Morning" Case 12 To 17 $msg = "Good Afternoon" Case 18 To 21 $msg = "Good Evening" Case Else $msg = "What are you still doing up?" EndSwitch MsgBox(0, Default, $msg) < ---------------------------------------------------------------------- *WinSetState* +-------------+~ | WinSetState |~ +-------------+~ Shows, hides, minimizes, maximizes, or restores a window. > WinSetState ( "title", "text", flag ) < Parameters~ title~ ----- The title of the window to show. See Title special definition. text~ ----- The text of the window to show. flag~ ----- The "show" flag of the executed program: @SW_HIDE = Hide window @SW_SHOW = Shows a previously hidden window @SW_MINIMIZE = Minimize window @SW_MAXIMIZE = Maximize window @SW_RESTORE = Undoes a window minimization or maximization @SW_DISABLE = Disables the window @SW_ENABLE = Enables the window Return Value~ Success:~ -------- Returns 1. Failure:~ -------- Returns 0 if window is not found. Remarks~ If multiple windows match the criteria, the most recently active window is used. @SW_MINIMIZE and @SW_MAXIMIZE even work on modal dialog windows. Related~ |WinActivate|, |WinClose|, |ControlHide|, |WinFlash|, |WinKill|, |WinMinimizeAll|, |WinMinimizeAllUndo|, |WinMove|, |WinSetOnTop| Example~ > WinSetState("[CLASS:Notepad]", "", @SW_HIDE) Sleep(3000) WinSetState("[CLASS:Notepad]", "", @SW_SHOW) < ---------------------------------------------------------------------- *file_directory_and_disk_functions_reference* +----------------------------------------------+~ | File, Directory and Disk functions Reference |~ +----------------------------------------------+~ Below is a complete list of the functions available in AutoIt. Click on a function name for a detailed description. Function Description ~ |ConsoleRead| Read from the STDIN stream of the AutoIt script process. |ConsoleWrite| Writes data to the STDOUT stream. Some text editors can read this stream as can other programs which may be expecting data on this stream. |ConsoleWriteError| Writes data to the STDERR stream. Some text editors can read this stream as can other programs which may be expecting data on this stream. |DirCopy| Copies a directory and all sub-directories and files (Similar to xcopy). |DirCreate| Creates a directory/folder. |DirGetSize| Returns the size in bytes of a given directory. |DirMove| Moves a directory and all sub-directories and files. |DirRemove| Deletes a directory/folder. |DriveGetDrive| Returns an array containing the enumerated drives. |DriveGetFileSystem| Returns File System Type of a drive. |DriveGetLabel| Returns Volume Label of a drive, if it has one. |DriveGetSerial| Returns Serial Number of a drive. |DriveGetType| Returns drive type. |DriveMapAdd| Maps a network drive. |DriveMapDel| Disconnects a network drive. |DriveMapGet| Retrieves the details of a mapped drive. |DriveSetLabel| Sets the Volume Label of a drive. |DriveSpaceFree| Returns the free disk space of a path in Megabytes. |DriveSpaceTotal| Returns the total disk space of a path in Megabytes. |DriveStatus| Returns the status of the drive as a string. |FileChangeDir| Changes the current working directory. |FileClose| Closes a previously opened text file. |FileCopy| Copies one or more files. |FileCreateNTFSLink| Creates an NTFS hardlink to a file or a directory |FileCreateShortcut| Creates a shortcut (.lnk) to a file. |FileDelete| Delete one or more files. |FileExists| Checks if a file or directory exists. |FileFindFirstFile| Returns a search "handle" according to file search string. |FileFindNextFile| Returns a filename according to a previous call to FileFindFirstFile. |FileFlush| Flushes the file's buffer to disk. |FileGetAttrib| Returns a code string representing a file's attributes. |FileGetEncoding| Determines the text encoding used in a file. |FileGetLongName| Returns the long path+name of the path+name passed. |FileGetPos| Retrieves the current file position. |FileGetShortcut| Retrieves details about a shortcut. |FileGetShortName| Returns the 8.3 short path+name of the path+name passed. |FileGetSize| Returns the size of a file in bytes. |FileGetTime| Returns the time and date information for a file. |FileGetVersion| Returns the "File" version information. |FileInstall| Include and install a file with the compiled script. |FileMove| Moves one or more files |FileOpen| Opens a text file for reading or writing. |FileOpenDialog| Initiates a Open File Dialog. |FileRead| Read in a number of characters from a previously opened text file. |FileReadLine| Read in a line of text from a previously opened text file. |FileRecycle| Sends a file or directory to the recycle bin. |FileRecycleEmpty| Empties the recycle bin. |FileSaveDialog| Initiates a Save File Dialog. |FileSelectFolder| Initiates a Browse For Folder dialog. |FileSetAttrib| Sets the attributes of one or more files. |FileSetPos| Sets the current file position. |FileSetTime| Sets the timestamp of one of more files. |FileWrite| Append a text/data to the end of a previously opened file. |FileWriteLine| Append a line of text to the end of a previously opened text file. |IniDelete| Deletes a value from a standard format .ini file. |IniRead| Reads a value from a standard format .ini file. |IniReadSection| Reads all key/value pairs from a section in a standard format .ini file. |IniReadSectionNames| Reads all sections in a standard format .ini file. |IniRenameSection| Renames a section in a standard format .ini file. |IniWrite| Writes a value to a standard format .ini file. |IniWriteSection| Writes a section to a standard format .ini file. -------------------------------------------------------------------------------- *ConsoleRead* +-------------+~ | ConsoleRead |~ +-------------+~ Read from the STDIN stream of the AutoIt script process. > ConsoleRead ( [peek = false[, binary = false ]]) < Parameters~ peek ----- [optional] If true the function does not remove the read characters from the stream. binary ------ [optional] If true the function reads the data as binary instead of text (default is text). Return Value~ Success ------- Returns the data read. @extended contains the number of bytes read. Failure ------- Sets @error to non-zero if EOF is reached, STDIN is not connected for the process or other error. Remarks~ ConsoleRead reads from the console standard input stream of the AutoIt script process, which is normally used by console applications to read input from a parent process. ConsoleRead does not block, it will return immediately. In order to get all data, it must be called in a loop. Peeking on the stream does not remove the data from the buffer, however, it does return the available data as normal. By default, data is returned in text format. By using the binary option, the data will be returned in binary format. Related~ |ConsoleWrite|, |ConsoleWriteError|, |Run| Example~ > ; Compile this script to "ConsoleRead.exe". ; Open a command prompt to the directory where ConsoleRead.exe resides. ; Type the following on the command line: ; echo Hello! | ConsoleRead.exe ; ; When invoked in a console window, the above command echos the text "Hello!" ; but instead of dispalying it, the | tells the console to pipe it to the STDIN stream ; of the ConsoleRead.exe process. If Not @Compiled Then MsgBox(0, "", "This script must be compiled in order to properly demonstrate it's functionality.") Exit -1 EndIf Local $data While True $data &= ConsoleRead() If @error Then ExitLoop Sleep(25) WEnd MsgBox(0, "", "Received: " & @CRLF & @CRLF & $data) < -------------------------------------------------------------------------------- *ConsoleWrite* +--------------+~ | ConsoleWrite |~ +--------------+~ Writes data to the STDOUT stream. Some text editors can read this stream as can other programs which may be expecting data on this stream. > ConsoleWrite ( "data" ) < Parameters~ data ----- The data you wish to output. This may either be text or binary. Return Value~ The amount of data written. If writing binary, the number of bytes written, if writing text, the number of characters written. Remarks~ The purpose for this function is to write to the STDOUT stream. Many popular text editors can read this stream. Scripts compiled as Console applications also have a STDOUT stream. This does not write to a DOS console unless the script is compiled as a console application.. Characters are converted to ANSI before being written. Binary data is written as-is. It will not be converted to a string. To print the hex representation of binary data, use the String() function to explicitly cast the data to a string. Related~ |ConsoleWriteError|, |ConsoleRead| Example~ > Local $var = "Test" ConsoleWrite("var=" & $var & @CRLF) ; Running this in a text editor which can trap console output should produce "var=Test" < -------------------------------------------------------------------------------- *ConsoleWriteError* +-------------------+~ | ConsoleWriteError |~ +-------------------+~ Writes data to the STDERR stream. Some text editors can read this stream as can other programs which may be expecting data on this stream. > ConsoleWriteError ( "data" ) < Parameters~ data The data you wish to output. This may either be text or binary. Return Value~ The amount of data written. If writing binary, the number of bytes written, if writing text, the number of characters written. Remarks~ The purpose for this function is to write to the STDERR stream. Many popular text editors can read this stream. Scripts compiled as Console applications also have a STDERR stream. This does not write to a DOS console unless the script is compiled as a console application.. Characters are converted to ANSI before being written. Binary data is written as-is. It will not be converted to a string. To print the hex representation of binary data, use the String() function to explicitly cast the data to a string. Related~ |ConsoleWrite|, |ConsoleRead| Example~ > Local $var = "Test" ConsoleWriteError("var=" & $var & @CRLF) ; Running this in a text editor which can trap console output should produce "var=Test" < -------------------------------------------------------------------------------- *DirCopy* +---------+~ | DirCopy |~ +---------+~ Copies a directory and all sub-directories and files (Similar to xcopy). > DirCopy ( "source dir", "dest dir" [, flag] ) < Parameters~ source ------ dir Path of the source directory (with no trailing backslash). e.g. "C:\Path1" dest ----- dir Path of the destination dir (with no trailing backslash). e.g. "C:\Path_Copy" flag ---- [optional] this flag determines whether to overwrite file if they already exist: 0 = (default) do not overwrite existing files 1 = overwrite existing files Return Value~ Success ------- Returns 1. Failure ------- Returns 0 if there is an error copying the directory. Remarks~ If the destination directory structure doesn't exist, it will be created (if possible). Related~ |DirRemove|, |FileCopy| Example~ > DirCopy(@MyDocumentsDir, "C:\Backups\MyDocs", 1) < -------------------------------------------------------------------------------- *DirCreate* +-----------+~ | DirCreate |~ +-----------+~ Creates a directory/folder. > DirCreate ( "path" ) < Parameters~ path ----- Path of the directory to create. Return Value~ Success ------- Returns 1. Failure ------- Returns 0 if there is an error creating the directory. Remarks~ This function will also create all parent directories given in "path" if they do not already exist. Related~ |DirRemove|, |FileCopy| Example~ > DirCreate("C:\Test1\Folder1\Folder2") < -------------------------------------------------------------------------------- *DirGetSize* +------------+~ | DirGetSize |~ +------------+~ Returns the size in bytes of a given directory. > DirGetSize ( "path" [, flag] ) < Parameters~ path ----- The directory path to get the size from, e.g. "C:\Windows". flag ----- [optional] this flag determines the behaviour and result of the function, and can be a combination of the following: 0 = (default) 1 = Extended mode is On -> returns an array that contains extended information (see Remarks). 2 = Don't get the size of files in subdirectories (recursive mode is Off) Return Value~ Success ------- Returns >= 0 the sizes Failure ------- Returns -1 and sets @error to 1 if the path doesn't exist. Remarks~ If the script is paused then this function is paused too and will only continue when the script continues! If you use the extended mode then the array returned from this function is a single dimension array containing the following elements: $array[0] = Size $array[1] = Files count $array[2] = Dirs Count Related~ None. Example~ > $size = DirGetSize(@HomeDrive) Msgbox(0,"","Size(MegaBytes):" & Round($size / 1024 / 1024)) $size = DirGetSize(@WindowsDir, 2) Msgbox(0,"","Size(MegaBytes):" & Round($size / 1024 / 1024)) $timer = TimerInit() $size = DirGetSize("\\10.0.0.1\h$",1) $diff = Round(TimerDiff($timer) / 1000) ; time in seconds If IsArray($size) Then Msgbox(0,"DirGetSize-Info","Size(Bytes):" & $size[0] & @LF _ & "Files:" & $size[1] & @LF & "Dirs:" & $size[2] & @LF _ & "TimeDiff(Sec):" & $diff) EndIf < -------------------------------------------------------------------------------- *DirMove* +---------+~ | DirMove |~ +---------+~ Moves a directory and all sub-directories and files. > DirMove ( "source dir", "dest dir" [, flag] ) < Parameters~ source dir Path of the source directory (with no trailing backslash). e.g. "C:\Path1" dest dir Path of the destination dir (with no trailing backslash). e.g. "C:\Path_Copy" flag ----- [optional] this flag determines whether to overwrite files if they already exist: 0 = (default) do not overwrite existing files 1 = overwrite existing files Return Value~ Success ------- Returns 1. Failure ------- Returns 0 if there is an error moving the directory. Remarks~ If the source and destination are on different volumes or UNC paths are used then a copy/delete operation will be performed rather than a move. If the destination already exists and the overwrite flag is specified then the source directory will be moved inside the destination. Because AutoIt lacks a "DirRename" function, use DirMove to rename a folder! Related~ |DirRemove|, |FileMove| Example~ > DirMove(@MyDocumentsDir, "C:\Backups\MyDocs") < -------------------------------------------------------------------------------- *DirRemove* +-----------+~ | DirRemove |~ +-----------+~ Deletes a directory/folder. > DirRemove ( "path" [, recurse] ) < Parameters~ path ----- Path of the directory to remove. recurse ------- [optional] Use this flag to specify if you want to delete sub-directories too. 0 = (default) do not remove files and sub-directories 1 = remove files and subdirectories (like the DOS DelTree command) Return Value~ Success ------- Returns 1. Failure ------- Returns 0 if there is an error removing the directory (or if directory does not exist). Remarks~ Some dir attributes can make the removal impossible. Related~ |DirCreate|, |FileRecycle|, |DirCopy|, |DirMove|, |FileDelete| Example~ > ; Delete C:\Test1 and all subdirs and files DirRemove("C:\Test1", 1) < -------------------------------------------------------------------------------- *DriveGetDrive* +---------------+~ | DriveGetDrive |~ +---------------+~ Returns an array containing the enumerated drives. > DriveGetDrive ( "type" ) < Parameters~ type ----- Type of drive to find: "ALL", "CDROM", "REMOVABLE", "FIXED", "NETWORK", "RAMDISK", or "UNKNOWN" Return Value~ Success ------- Returns an array of strings (drive letter followed by colon) of drives found. The zeroth array element contains the number of drives. Failure ------- Returns "" and sets @error to 1. Remarks~ None. Related~ |DriveGetFileSystem|, |DriveGetLabel|, |DriveGetSerial|, |DriveGetType|, |DriveSetLabel|, |DriveSpaceFree|, |DriveSpaceTotal|, |DriveStatus| Example~ > $var = DriveGetDrive( "all" ) If NOT @error Then MsgBox(4096,"", "Found " & $var[0] & " drives") For $i = 1 to $var[0] MsgBox(4096,"Drive " & $i, $var[$i]) Next EndIf < -------------------------------------------------------------------------------- *DriveGetFileSystem* +--------------------+~ | DriveGetFileSystem |~ +--------------------+~ Returns File System Type of a drive. > DriveGetFileSystem ( "path" ) < Parameters~ path ----- Path of drive to receive information from. Return Value~ Success ------- Returns the File System Type of the drive as a string; see table below. Failure ------- Sets @error to 1. Return Value Interpretation ~ 1 (numeric) Drive does NOT contain media (CD, Floppy, Zip) or media is unformatted (RAW). "FAT" Typical file system for drives under ~500 MB such as Floppy, RAM disks, USB "pen" drives, etc. "FAT32" Typical file system for Windows 9x/Me hard drives. "NTFS" Typical file system for Windows NT/2000/XP hard drives. "NWFS" Typical file system for Novell Netware file servers. "CDFS" Typically indicates a CD (or an ISO image mounted as a virtual CD drive). "UDF" Typically indicates a DVD. Remarks~ The list of possible return values might be incomplete. Related~ |DriveGetDrive|, |DriveGetLabel|, |DriveGetSerial|, |DriveGetType|, |DriveSetLabel|, |DriveSpaceFree|, |DriveSpaceTotal|, |DriveStatus| Example~ > $var = DriveGetFileSystem( "c:\" ) MsgBox(4096,"File System Type:", $var) < -------------------------------------------------------------------------------- *DriveGetLabel* +---------------+~ | DriveGetLabel |~ +---------------+~ Returns Volume Label of a drive, if it has one. > DriveGetLabel ( "path" ) < Parameters~ path ----- Path of drive to receive information from. Return Value~ Success ------- Returns the Volume Label of the drive as a string. Failure ------- Sets @error to 1. Remarks~ None. Related~ |DriveGetDrive|, |DriveGetFileSystem|, |DriveGetSerial|, |DriveGetType|, |DriveSetLabel|, |DriveSpaceFree|, |DriveSpaceTotal|, |DriveStatus| Example~ > $var = DriveGetLabel( "c:\" ) MsgBox(4096,"Volume Label: ",$var) < -------------------------------------------------------------------------------- *DriveGetSerial* +----------------+~ | DriveGetSerial |~ +----------------+~ Returns Serial Number of a drive. > DriveGetSerial ( "path" ) < Parameters~ path ----- Path of drive to receive information from. Return Value~ Success ------- Returns the Serial Number of the drive as a string. Failure ------- Sets @error to 1. Remarks~ The value returned is not the hardware serial number as found on the label of the drive, it is the Windows Volume ID for the drive. Related~ |DriveGetDrive|, |DriveGetFileSystem|, |DriveGetLabel|, |DriveGetType|, |DriveSetLabel|, |DriveSpaceFree|, |DriveSpaceTotal|, |DriveStatus| Example~ > $var = DriveGetSerial( "c:\" ) MsgBox(4096, "Serial Number: ", $var) < -------------------------------------------------------------------------------- *DriveGetType* +--------------+~ | DriveGetType |~ +--------------+~ Returns drive type. > DriveGetType ( "path" ) < Parameters~ path ----- Path of drive to receive information from. Return Value~ Success ------- Returns the type of drive: "Unknown", "Removable", "Fixed", "Network", "CDROM", "RAMDisk" Failure ------- Returns "" and sets @error to 1. Remarks~ The list of possible return values might be incomplete. Related~ |DriveGetDrive|, |DriveGetFileSystem|, |DriveGetLabel|, |DriveGetSerial|, |DriveSetLabel|, |DriveSpaceFree|, |DriveSpaceTotal|, |DriveStatus|, |CDTray| Example~ > $var = DriveGetType( "c:\" ) MsgBox(4096, "Drive Type:", $var) < -------------------------------------------------------------------------------- *DriveMapAdd* +-------------+~ | DriveMapAdd |~ +-------------+~ Maps a network drive. > DriveMapAdd ( "device", "remote share" [, flags [, "user" [, "password"]]] ) < Parameters~ device ------ The device to map, for example "O:" or "LPT1:". If you pass a blank string for this parameter a connection is made but not mapped to a specific drive. If you specify "*" an unused drive letter will be automatically selected. remote share ------------ The remote share to connect to in the form "\\server\share". flags ------ [optional] A combination of the following: 0 = default 1 = Persistent mapping 8 = Show authentication dialog if required user ----- [optional] The username to use to connect. In the form "username" or "domain\username". password -------- [optional] The password to use to connect. Return Value~ Success ------- Returns 1. (See Remarks) Failure ------- Returns 0 if a new mapping could not be created and sets @error (see below). (See Remarks) Remarks~ When the function fails (returns 0) @error contains extended information: 1 = Undefined / Other error. @extended set with Windows API return 2 = Access to the remote share was denied 3 = The device is already assigned 4 = Invalid device name 5 = Invalid remote share 6 = Invalid password Note: When using "*" for the device parameter the drive letter selected will be returned instead of 1 or 0, e.g. "U:". If there was an error using "*" then a blank string "" will be returned. If defined the user/password will be presented to the remote computer that will validate the credential. Related~ |DriveMapDel|, |DriveMapGet| Example~ > ; Map X drive to \\myserver\stuff using current user DriveMapAdd("X:", "\\myserver\stuff") ; Map X drive to \\myserver2\stuff2 using the user "jon" from "domainx" with password "tickle" DriveMapAdd("X:", "\\myserver2\stuff2", 0, "domainx\jon", "tickle") < -------------------------------------------------------------------------------- *DriveMapDel* +-------------+~ | DriveMapDel |~ +-------------+~ Disconnects a network drive. > DriveMapDel ( "drive" ) < Parameters~ drive ----- The device to disconnect, e.g. "O:" or "LPT1:". Return Value~ Success ------- Returns 1. Failure ------- Returns 0 if the disconnection was unsuccessful. Remarks~ If a connection has no drive letter mapped you may use the connection name to disconnect, e.g. \\server\share Related~ |DriveMapAdd|, |DriveMapGet| Example~ > ; Map X drive to \\myserver\stuff using current user DriveMapAdd("X:", "\\myserver\stuff") ; Disconnect DriveMapDel("X:") < -------------------------------------------------------------------------------- *DriveMapGet* +-------------+~ | DriveMapGet |~ +-------------+~ Retrieves the details of a mapped drive. > DriveMapGet ( "device" ) < Parameters~ device ------ The device (drive or printer) letter to query, e.g. "O:" or "LPT1:" Return Value~ Success ------- Returns details of the mapping, e.g. \\server\share Failure ------- Returns a blank string "" and sets @error to 1. Remarks~ None. Related~ |DriveMapAdd|, |DriveMapDel| Example~ > ; Map X drive to \\myserver\stuff using current user DriveMapAdd("X:", "\\myserver\stuff") ; Get details of the mapping MsgBox(0, "Drive X: is mapped to", DriveMapGet("X:")) < -------------------------------------------------------------------------------- *DriveSetLabel* +---------------+~ | DriveSetLabel |~ +---------------+~ Sets the Volume Label of a drive. > DriveSetLabel ( "path", "label" ) < Parameters~ path ----- Path of drive to change. label ----- New volume label for the drive. (11 characters is usually max length) Return Value~ Success ------- Returns 1. Failure ------- Returns 0. Remarks~ Most hard drives have a maximum label length of 11 characters, and DriveSetLabel will fail if max length is exceeded. Also, FAT32 partition labels tend to revert to all capital letters. Related~ |DriveGetDrive|, |DriveGetFileSystem|, |DriveGetLabel|, |DriveGetSerial|, |DriveGetType|, |DriveSpaceFree|, |DriveSpaceTotal|, |DriveStatus| Example~ > DriveSetLabel("C:\", "New_Label") < -------------------------------------------------------------------------------- *DriveSpaceFree* +----------------+~ | DriveSpaceFree |~ +----------------+~ Returns the free disk space of a path in Megabytes. > DriveSpaceFree ( "path" ) < Parameters~ path ----- Path of drive to receive information from. Return Value~ Success ------- Returns free disk space in Megabytes as a float number. Failure ------- Returns 0 and sets @error to 1. Remarks~ DriveSpaceFree may even work when a complete directory path (that exists) is given. However, a file path won't work. Use the Round function if the return value is too precise. Related~ |DriveGetDrive|, |DriveGetFileSystem|, |DriveGetLabel|, |DriveGetSerial|, |DriveGetType|, |DriveSetLabel|, |DriveSpaceTotal|, |DriveStatus| Example~ > $var = DriveSpaceFree( "c:\" ) MsgBox(4096, "Free space on C:", $var & " MB") < -------------------------------------------------------------------------------- *DriveSpaceTotal* +-----------------+~ | DriveSpaceTotal |~ +-----------------+~ Returns the total disk space of a path in Megabytes. > DriveSpaceTotal ( "path" ) < Parameters~ path ----- Path of drive to receive information from. Return Value~ Success ------- Returns diskspace in Megabytes as a float number. Failure ------- Sets @error to 1. Remarks~ DriveSpaceTotal may even work when a complete directory path (that exists) is given. However, a file path won't work. Related~ |DriveGetDrive|, |DriveGetFileSystem|, |DriveGetLabel|, |DriveGetSerial|, |DriveGetType|, |DriveSetLabel|, |DriveSpaceFree|, |DriveStatus|, |FileGetSize| Example~ > $var = DriveSpaceTotal( "c:\" ) MsgBox(4096, "Total Space on C:", $var & " MB") < -------------------------------------------------------------------------------- *DriveStatus* +-------------+~ | DriveStatus |~ +-------------+~ Returns the status of the drive as a string. > DriveStatus ( "path" ) < Parameters~ path ----- Path of drive to receive information from. Return Value~ Value Interpretation UNKNOWN Drive may be unformatted (RAW). READY Typical of hard drives and drives that contain removable media. NOTREADY Typical of floppy and CD drives that do not contain media. INVALID May indicate the drive letter does not exist or that a mapped network drive is inaccessible. Remarks~ The list of possible return values may be incomplete. DriveStatus may even work when a complete directory path (which exists) is given. However, a file path won't work. Related~ |DriveGetDrive|, |DriveGetFileSystem|, |DriveGetLabel|, |DriveGetSerial|, |DriveGetType|, |DriveSetLabel|, |DriveSpaceFree|, |DriveSpaceTotal|, |CDTray|, |FileExists| Example~ > $var = DriveStatus( "c:\" ) MsgBox(4096,"Status",$var) < -------------------------------------------------------------------------------- *FileChangeDir* +---------------+~ | FileChangeDir |~ +---------------+~ Changes the current working directory. > FileChangeDir ( "path" ) < Parameters~ path ----- The path to make the current working directory. Return Value~ Success ------- Returns 1. Failure ------- Returns 0 if working directory not changed. Remarks~ None. Related~ |@WorkingDir| Example~ > FileChangeDir(@WindowsDir) < -------------------------------------------------------------------------------- *FileClose* +-----------+~ | FileClose |~ +-----------+~ Closes a previously opened text file. > FileClose ( filehandle ) < Parameters~ filehandle ---------- The handle of a file, as returned by a previous call to FileOpen. Return Value~ Success ------- Returns 1. Failure ------- Returns 0 if the filehandle is invalid. Remarks~ Upon termination, AutoIt automatically closes any files it opened, but calling FileClose is still a good idea. This function is also used to close search handles as returned by FileFindFirstFile(). Related~ |FileFindFirstFile|, |FileOpen|, |FileFindNextFile|, |FileFlush| Example~ > $handle = FileOpen("test.txt", 0) FileClose($handle) < -------------------------------------------------------------------------------- *FileCopy* +----------+~ | FileCopy |~ +----------+~ Copies one or more files. > FileCopy ( "source", "dest" [, flag] ) < Parameters~ source ------ The source path of the file(s) to copy. Wildcards are supported. dest ----- The destination path of the copied file(s). flag ----- [optional] this flag determines whether to overwrite files if they already exist. Can be a combination of the following: 0 = (default) do not overwrite existing files 1 = overwrite existing files 8 = Create destination directory structure if it doesn't exist (See Remarks). Return Value~ Success ------- Returns 1. Failure ------- Returns 0. Remarks~ The destination directory must already exist, except using with flag value '8'. For instance the combined flag '9' (1 + 8) overwrites the target file and pre-checks for the destination directory structure and if it doesn't exist creates it automatically. See |FileFindFirstFile| for a discussion of wildcards. Some file attributes can make the overwriting impossible. Related~ |FileMove|, |FileDelete|, |DirCopy|, |DirCreate| Example~ > FileCopy("C:\*.au3", "D:\mydir\*.*") ; Method to copy a folder (with its contents) DirCreate("C:\new") FileCopy("C:\old\*.*", "C:\new\") FileCopy("C:\Temp\*.txt", "C:\Temp\TxtFiles\", 8) ; RIGHT - 'TxtFiles' is now the target directory and the file names are given by the source names FileCopy("C:\Temp\*.txt", "C:\Temp\TxtFiles\", 9) ; Flag = 1 + 8 (overwrite + create target directory structure) ; Copy the txt-files from source to target and overwrite target files with same name < -------------------------------------------------------------------------------- *FileCreateNTFSLink* +--------------------+~ | FileCreateNTFSLink |~ +--------------------+~ Creates an NTFS hardlink to a file or a directory > FileCreateNTFSLink ( "source", "hardlink" [, flag] ) < Parameters~ source ------ Path of the source to which the hardlink will be created. hardlink -------- Path of the hardlink. flag ----- [optional] this flag determines whether to overwrite link if they already exist. Can be a combination of the following: 0 = (default) do not overwrite existing link 1 = overwrite existing link Return Value~ Success ------- Returns 1. Failure ------- Returns 0. Remarks~ The destination directory must already exist. This function works only on volume with NTFS File system. If the source is a file, the hardlink must be on the same volume. If the source is a directory cross volume is allowed. |FileDelete| or |FileMove| can be used on hardlink. To manage the link with the explorer you can use the shell extension NTFSLink Related~ |FileCreateShortcut| Example~ > FileChangeDir(@ScriptDir) DirCreate('dir') FileWriteLine("test.txt","test") MsgBox(0,"Hardlink", FileCreateNTFSLink("test.txt", "dir\test.log", 1)) < -------------------------------------------------------------------------------- *FileCreateShortcut* +--------------------+~ | FileCreateShortcut |~ +--------------------+~ Creates a shortcut (.lnk) to a file. > FileCreateShortcut ( "file", "lnk" [, "workdir" [, "args" [, "desc" [, "icon" [, "hotkey" [, icon number [, state]]]]]]] ) < Parameters~ file ----- Full path and file name of file to create shortcut to. lnk ----- Full path and file name of the shortcut. workdir ------- [optional] Working directory. args ----- [optional] Additional file arguments. desc ----- [optional] File Description. icon ----- [optional] Full Path/File name of icon to use. hotkey ------ [optional] Hotkey - same as the Send() key format. icon number ----------- [optional] The icon instance to use (usually 0) state ------ [optional] The state the shortcut is launched in. Use either |@SW_SHOWNORMAL|, |@SW_SHOWMINNOACTIVE| or |@SW_SHOWMAXIMIZED| Return Value~ Success ------- Returns 1. Failure ------- Returns 0 if lnk cannot be created. Remarks~ Hotkeys for windows shortcuts are of the following form: Ctrl+Alt+X, Ctrl+Shift+X, Shift+Alt+X, Ctrl+NumPadKey, or Alt+NumPadKey where X represents a letter, number, punctuation, or function key. If you specify an invalid form, Windows typically defaults to Ctrl+Alt Note that Windows distinguishes number pad keys from regular number and punctuation keys. FileCreateShortcut allows you to create Ctrl+X and Alt+X shortcuts (which Windows normally only allows when X is a NumPadKey); however, you should avoid these assignments as they may conflict with standard application hotkeys. Windows prohibits ESC, ENTER, TAB, SPACEBAR, PRINT SCREEN, SHIFT, or BACKSPACE from being used in hotkeys. FileCreateShortcut does not require a valid target, workdir, icon, or hotkey in order to "successfully" create the LNK file; however, the destination of the LNK file must be valid! If the hotkey you choose is already in use, your new shortcut takes precedence. Also, if you create a shortcut with the same path\name as as a pre-existing shortcut, it gets overwritten with your new version. Related~ |FileGetShortcut|, |FileCreateNTFSLink| Example~ > ; Sets a shortcut with ctrl+alt+t hotkey FileCreateShortcut(@WindowsDir & "\Explorer.exe",@DesktopDir & "\Shortcut Test.lnk",@WindowsDir,"/e,c:\", "This is an Explorer link;-)", @SystemDir & "\shell32.dll", "^!t", "15", @SW_MINIMIZE) < -------------------------------------------------------------------------------- *FileDelete* +------------+~ | FileDelete |~ +------------+~ Delete one or more files. > FileDelete ( "path" ) < Parameters~ Path ----- The path of the file(s) to delete. Wildcards are supported. Return Value~ Success ------- Return 1. Failure ------- Returns 0 if files are not deleted or do not exist. Remarks~ Note: If the "path" passed to FileDelete is a folder, the files therein will be deleted just as if you had used the *.* mask. See |FileFindFirstFile| for a discussion of wildcards. Some file attributes can make the deletion impossible. Related~ |FileCopy|, |FileMove|, |FileRecycle|, |DirRemove|, |FileRecycleEmpty| Example~ > FileDelete("D:\*.tmp") < -------------------------------------------------------------------------------- *FileExists* +------------+~ | FileExists |~ +------------+~ Checks if a file or directory exists. > FileExists ( "path" ) < Parameters~ Path ----- The directory or file to check. Return Value~ Success ------- Returns 1. Failure ------- Returns 0 if path/file does not exist. Remarks~ FileExists returns 0 if you specify a floppy drive which does not contain a disk. Related~ |FileGetAttrib|, |DriveStatus| Example~ > If FileExists("C:\autoexec.bat") Then MsgBox(4096, "C:\autoexec.bat File", "Exists") Else MsgBox(4096,"C:\autoexec.bat File", "Does NOT exists") EndIf If FileExists("C:\") Then MsgBox(4096, "C:\ Dir ", "Exists") Else MsgBox(4096,"C:\ Dir" , "Does NOT exists") EndIf If FileExists("D:") Then MsgBox(4096, "D: Drive", "Exists") Else MsgBox(4096,"D: Drive", "Does NOT exists") EndIf < -------------------------------------------------------------------------------- *FileFindFirstFile* +-------------------+~ | FileFindFirstFile |~ +-------------------+~ Returns a search "handle" according to file search string. > FileFindFirstFile ( "filename" ) < Parameters~ filename -------- File search string. (* and ? wildcards accepted) Return Value~ Success ------- Returns a search "handle" for use with subsequent FileFindNextFile functions. Failure ------- Returns -1 if error occurs. If the Folder is empty the @error is set to 1. Remarks~ The search string is not case sensitive. Wildcards: In general, * denotes zero or more characters, and ? denotes zero or one character. If your file search string contains only wildcards (or is "*.*"), then see the example below for the return value! You can use only one wildcard in the filename part or in the extension part i.e. a*.b?. ?? seems equivalent to * (not described in Microsoft documentation). When using a 3-char extension any extension starting with those 3 chars will match, .e.g. "*.log" will match "test.log_1". (not described either in Microsoft documentation). When you have finished searching with the FileFind... functions you must call FileClose() to release the search handle. Directory name are return according to the wildcards if any. Related~ |FileClose|, |FileFindNextFile| Example~ > ; Shows the filenames of all files in the current directory. $search = FileFindFirstFile("*.*") ; Check if the search was successful If $search = -1 Then MsgBox(0, "Error", "No files/directories matched the search pattern") Exit EndIf While 1 $file = FileFindNextFile($search) If @error Then ExitLoop MsgBox(4096, "File:", $file) WEnd ; Close the search handle FileClose($search) < -------------------------------------------------------------------------------- *FileFindNextFile* +------------------+~ | FileFindNextFile |~ +------------------+~ Returns a filename according to a previous call to FileFindFirstFile. > FileFindNextFile ( search ) < Parameters~ search ------ The search handle, as returned by FileFindFirstFile. Return Value~ Success ------- Returns a filename according to a previous call to FileFindFirstFile, @extended set to 1 if filename is a directory. Failure ------- Sets @error to 1 if no more files/directories match the search. Remarks~ A previous call to FileFindFirstFile is necessary to setup the search and get a search handle. Every subsequent call to FileFindNextFile will return the next file found according to the search string supplied to FileFindFirstFile. When @error = 1, no more files found matching the original search string. When you have finished searching with the FileFind... functions you must call FileClose() to release the search handle. Related~ |FileClose|, |FileFindFirstFile| Example~ > ; Shows the filenames of all files in the current directory $search = FileFindFirstFile("*.*") ; Check if the search was successful If $search = -1 Then MsgBox(0, "Error", "No files/directories matched the search pattern") Exit EndIf While 1 $file = FileFindNextFile($search) If @error Then ExitLoop MsgBox(4096, "File:", $file) WEnd ; Close the search handle FileClose($search) < -------------------------------------------------------------------------------- *FileFlush* +-----------+~ | FileFlush |~ +-----------+~ Flushes the file's buffer to disk. > FileFlush ( handle ) < Parameters~ handle ------ A handle to a file previously opened with FileOpen(). Return Value~ Success ------- Returns true if the buffer was flushed (or did not need to be flushed). Failure ------- Returns false. Remarks~ A file is flushed when it's handle is closed or when Windows internal buffer is full. This function forces an immediate flushing of the buffer. This function can only be used with file handles returned from FileOpen(). Related~ |FileClose|, |FileOpen|, |FileWrite|, |FileWriteLine|, |FileSetPos| Example~ > Local Const $sFile = "test.txt" Local $hFile = FileOpen($sFile, 1) ; Check if file opened for writing OK If $hFile = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf ; Write something to the file. FileWriteLine($hFile, "Line1") ; Run notepad to show that the file is empty because it hasn't been flushed yet. RunWait("notepad.exe " & $sFile) ; Flush the file to disk. FileFlush($hFile) ; Run notepad again to show that the contents of the file are now flushed to disk. RunWait("notepad.exe " & $sFile) ; Close the handle. FileClose($hFile) ; Clean up the temporary file. FileDelete($sFile) < -------------------------------------------------------------------------------- *FileGetAttrib* +------------+~ | FileAttrib |~ +------------+~ Returns a code string representing a file's attributes. > FileGetAttrib ( "filename" ) < Parameters~ filename -------- Filename (or directory) to check. Return Value~ Success ------- Returns a code string representing a files attributes. Failure ------- Returns "" (blank string) and sets @error to 1. Remarks~ String returned could contain a combination of these letters "RASHNDOCT": "R" = READONLY "A" = ARCHIVE "S" = SYSTEM "H" = HIDDEN "N" = NORMAL "D" = DIRECTORY "O" = OFFLINE "C" = COMPRESSED (NTFS compression, not ZIP compression) "T" = TEMPORARY Related~ |FileGetTime|, |FileSetAttrib|, |FileExists|, |FileGetSize|, |FileSetTime| Example~ > $attrib = FileGetAttrib("c:\boot.ini") If @error Then MsgBox(4096,"Error", "Could not obtain attributes.") Exit Else If StringInStr($attrib, "R") Then MsgBox(4096,"", "File is read-only.") EndIf EndIf ; Display full attribute information in text form ; Arrays rely upon the fact that each capital letter is unique ; Figuring out how this works is a good string exercise... $input = StringSplit("R,A,S,H,N,D,O,C,T",",") $output = StringSplit("Read-only /, Archive /, System /, Hidden /" & _ ", Normal /, Directory /, Offline /, Compressed /, Temporary /", ",") For $i = 1 to 9 $attrib = StringReplace($attrib, $input[$i], $output[$i], 0, 1) ; last parameter in StringReplace means case-sensitivity Next $attrib = StringTrimRight($attrib, 2) ;remove trailing slash MsgBox(0,"Full file attributes:", $attrib) < -------------------------------------------------------------------------------- *FileGetEncoding* +-----------------+~ | FileGetEncoding |~ +-----------------+~ Determines the text encoding used in a file. > FileGetEncoding ( "filehandle/filename" [, mode] ) < Parameters~ filehandle/filename ------------------- The handle of a file, as returned by a previous call to FileOpen. Alternatively you may use a string filename as the first parameter. mode ----- [optional] The UTF8 detection mode to use. 1 = Check entire file for UTF8 sequences (default) 2 = Check first part of file for UTF8 sequences (the same as FileOpen uses by default) Return Value~ Success ------- Returns the file encoding using similar values to the FileOpen function: 0 = ANSI 32 = UTF16 Little Endian. 64 = UTF16 Big Endian. 128 = UTF8 (with BOM). 256 = (without BOM). Failure ------- Returns -1. Remarks~ If a filename is given rather than a file handle - the file will be opened and closed during the function call. Note: Do not mix filehandles and filenames, i.e., don't FileOpen a file and then use a filename in this function. Use either filehandles or filenames in your routines, not both! If a file handle is used then the "mode" parameter has no effect - the mode used for FileOpen takes precedence. Related~ |FileOpen|, |FileRead|, |FileReadLine|, |FileWrite|, |FileWriteLine| -------------------------------------------------------------------------------- *FileGetLongName* +-----------------+~ | FileGetLongName |~ +-----------------+~ Returns the long path+name of the path+name passed. > FileGetLongName ( "file" [, flag] ) < Parameters~ file ----- full path and file name to convert flag ----- [optional] if 1 file can have relative dir, e.g. "..\file.txt" Return Value~ Success ------- Returns the long path+name of the path+name passed. Failure ------- Returns the parameter and sets @error to 1. Remarks~ None. Related~ |FileGetShortName| Example~ > $a = FileGetLongName(@HomeDrive & "\PROGRA~1\") msgbox(0,"long file name", $a) ;$a is probably "x:\Program Files" < -------------------------------------------------------------------------------- *FileGetPos* +------------+~ | FileGetPos |~ +------------+~ Retrieves the current file position. > FileGetPos ( handle ) < Parameters~ handle ------ A handle to a file previously opened with FileOpen(). Return Value~ Success ------- Returns the position offset from the beginning of the file (First index is 0). Failure ------- Returns 0 and sets @error. Remarks~ Failure returns 0 but 0 is also a valid file position so check @error to determine error conditions. Related~ |FileSetPos|, |FileRead|, |FileReadLine|, |FileWrite|, |FileWriteLine|, |FileOpen| Example~ > #include Local Const $sFile = "test.txt" Local $hFile = FileOpen($sFile, 2) ; Check if file opened for writing OK If $hFile = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf ; Write something to the file. FileWriteLine($hFile, "Line1") FileWriteLine($hFile, "Line2") FileWriteLine($hFile, "Line3") ; Flush the file to disk. FileFlush($hFile) ; Check file position and try to read contents for current position. MsgBox(0, "", "Position: " & FileGetPos($hFile) & @CRLF & "Data: " & @CRLF & FileRead($hFile)) ; Now, adjust the position to the beginning. Local $n = FileSetPos($hFile, 0, $FILE_BEGIN) ; Check file position and try to read contents for current position. MsgBox(0, "", "Position: " & FileGetPos($hFile) & @CRLF & "Data: " & @CRLF & FileRead($hFile)) ; Close the handle. FileClose($hFile) ; Clean up the temporary file. FileDelete($sFile) < -------------------------------------------------------------------------------- *FileGetShortcut* +-----------------+~ | FileGetShortcut |~ +-----------------+~ Retrieves details about a shortcut. > FileGetShortcut ( "lnk" ) < Parameters~ lnk ----- Full path and file name of the shortcut. Return Value~ Success ------- Returns an array that contains the shortcut information. See Remarks. Failure ------- Sets @error to 1 if the shortcut could not be accessed. Remarks~ The array returned from this function is a single dimension array containing the following elements: $array[0] = Shortcut target path $array[1] = Working directory $array[2] = Arguments $array[3] = Description $array[4] = Icon filename $array[5] = Icon index $array[6] = The shortcut state (@SW_SHOWNORMAL, @SW_SHOWMINNOACTIVE, @SW_SHOWMAXIMIZED) Related~ |FileCreateShortcut| Example~ > ; Sets a shortcut with ctrl+alt+t hotkey FileCreateShortcut(@WindowsDir & "\Explorer.exe",@DesktopDir & "\Shortcut Test.lnk",@WindowsDir,"/e,c:\", "This is an Explorer link;-)", @SystemDir & "\shell32.dll", "^!t", "15", @SW_MINIMIZE) ; Read in the path of a shortcut $details = FileGetShortcut(@DesktopDir & "\Shortcut Test.lnk") MsgBox(0, "Path:", $details[0]) < -------------------------------------------------------------------------------- *FileGetShortName* +------------------+~ | FileGetShortName |~ +------------------+~ Returns the 8.3 short path+name of the path+name passed. > FileGetShortName ( "file" [, flag] ) < Parameters~ file ----- full path and file name to convert flag ----- [optional] if 1 file can have relative dir, e.g. "..\file.txt" Return Value~ Success ------- Returns the 8.3 short path+name of the path+name passed. Failure ------- Returns the parameter and sets @error to 1. Remarks~ The file need to exist as there is no way to known the exact ~i if several file have the same 8 first characters. Related~ |FileGetLongName| Example~ > $a = FileGetShortName(@HomeDrive & "\Program Files") msgbox(0,"long file name", $a) ;$a is probably "x:\PROGRA~1" < -------------------------------------------------------------------------------- *FileGetSize* +-------------+~ | FileGetSize |~ +-------------+~ Returns the size of a file in bytes. > FileGetSize ( "filename" ) < Parameters~ filename -------- Filename to check. Return Value~ Success ------- Returns the size of the file in bytes. Failure ------- Returns 0 and set the @error to 1. Remarks~ Does not work on directories. Divide result by 1024 to get kilobyte equivalent, or divide by 1048576 to get megabyte equivalent. Related~ |FileGetAttrib|, |FileGetTime|, |DriveSpaceTotal|, |FileGetVersion| Example~ > $size = FileGetSize("AutoIt.exe") < -------------------------------------------------------------------------------- *FileGetTime* +-------------+~ | FileGetTime |~ +-------------+~ Returns the time and date information for a file. > FileGetTime ( "filename" [, option [, format]] ) < Parameters~ filename -------- Filename to check. option ------ [optional] Flag to indicate which timestamp 0 = Modified (default) 1 = Created 2 = Accessed format ------ [optional] to specify type of return 0 = return an array (default) 1 = return a string YYYYMMDDHHMMSS Return Value~ Success ------- Returns an array or string that contains the file time information. See Remarks. Failure ------- Returns 0 and sets @error to 1. Remarks~ The array is a single dimension array containing six elements: $array[0] = year (four digits) $array[1] = month (range 01 - 12) $array[2] = day (range 01 - 31) $array[3] = hour (range 00 - 23) $array[4] = min (range 00 - 59) $array[5] = sec (range 00 - 59) Notice that return values are zero-padded. Related~ |FileGetSize|, |FileGetAttrib|, |FileGetVersion|, |FileSetTime|, |FileSetAttrib| Example~ > $t = FileGetTime(@Windowsdir & "\Notepad.exe", 1) If Not @error Then $yyyymd = $t[0] & "/" & $t[1] & "/" & $t[2] MsgBox(0, "Creation date of notepad.exe", $yyyymd) EndIf < -------------------------------------------------------------------------------- *FileGetVersion* +----------------+~ | FileGetVersion |~ +----------------+~ Returns the "File" version information. > FileGetVersion ( "filename" [,"stringname"] ) < Parameters~ filename -------- Filename to check. stringname ---------- [optional] name of the field to be retrieved from the header version file info. Return Value~ Success ------- Returns a string containing the version information, e.g. "3.0.81.0". Failure ------- Returns "0.0.0.0" if no version information (or other error) or "" when retrieving a stringname, and sets @error to 1. Remarks~ stringname can be the basic one as : Comments, InternalName, ProductName, CompanyName, LegalCopyright, ProductVersion, FileDescription, LegalTrademarks, PrivateBuild, FileVersion, OriginalFilename, SpecialBuild Or a special one "CompiledScript" which is set for a compiled script. FileGetVersion(@AutoItExe, "CompiledScript") will return "AutoIt v3 Script : 3, 2, 1, 2". Another special stringname is "DefaultLangCodepage" can be used to retrieve the default language and codepage. The language and codepage can be used if needed to differentiate the "stringname" i.e. "080904b0\Comments" (see MSDN StringFileInfo in VerQueryValue function). Related~ |FileGetSize|, |FileGetTime| Example~ > $ver = FileGetVersion("Explorer.exe") MsgBox(0, "Explorer version", $ver) -------------------------------------------------------------------------------- *FileInstall* +-------------+~ | FileInstall |~ +-------------+~ Include and install a file with the compiled script. > FileInstall ( "source", "dest" [, flag] ) < Parameters~ source ------ The source path of the file to compile. This must be a literal string; it cannot be a variable or the result of a function call. It can be a relative path (using .\ or ..\ in the path) to the source file (.au3). dest ----- The destination path of the file with trailing backslash if only the directory is used. This can be a variable. flag [optional] this flag determines whether to overwrite files if they already exist: 0 = (default) do not overwrite existing files 1 = overwrite existing files Return Value~ Success ------- Returns 1. Failure ------- Returns 0. Remarks~ The FileInstall function is designed to include files into a compiled AutoIt script. These included files can then be "extracted" during execution of the compiled script if the statement is executed. Keep in mind that files such as images can greatly increase the size of a compiled script. The source file must be specified using a string literal and can not be a variable, a calculation nor function call. The file must be able to be found during compiling, however variables, calculations and function calls do not get resolved until the script itself is running, long after compiling, making them unsuitable to define the source file. The source cannot contain wildcards. When this function is used from a non-compiled script, a copy operation is performed instead (to allow for easy testing pre-compilation). Files maintain their original creation/modification timestamps when installed. The destination directory path must already exist before this function is called, or the FileInstall will fail, returning 0 and not creating the file, nor path. See DirCreate() for information about creating the directory path. The file attributes on an existing file may prevent the file from being overwritten. Use FileDelete() or FileSetAttrib() to ensure the file can be installed without issue. Related~ |DirCreate|, |FileDelete|, |FileSetAttrib| Example~ > ; Include a bitmap found in "C:\test.bmp" with the compiled program and put it in "D:\mydir\test.bmp" when it is run $b = True If $b = True Then FileInstall("C:\test.bmp", "D:\mydir\test.bmp") < -------------------------------------------------------------------------------- *FileMove* +----------+~ | FileMove |~ +----------+~ Moves one or more files > FileMove ( "source", "dest" [, flag] ) < Parameters~ source ------ The source path and filename of the file to move. (* wildcards are supported) dest ----- The destination path and filename of the moved file. (* wildcards are supported) flag [optional] this flag determines whether to overwrite files if they already exist: Can be a combination of the following: 0 = (default) do not overwrite existing files 1 = overwrite existing files 8 = Create destination directory structure if it doesn't exist (See Remarks). Return Value~ Success ------- Returns 1. Failure ------- Returns 0 if source cannot be moved or if dest already exists and flag=0. Remarks~ If the source and destination paths are on different volumes a copy and delete operation is performed rather than a move. Because AutoIt lacks a "FileRename" function, use FileMove to rename a file! The destination directory must already exist, except using with flag value '8'. For instance the combined flag '9' (1 + 8) overwrites the target file and prechecks for the destination directory structure and if it doesn't exist creates it automatically. Some file attributes can make the overwriting impossible. Related~ |FileCopy|, |FileDelete|, |FileRecycle|, |DirMove| Example~ > FileMove("C:\foo.au3", "D:\mydir\bak.au3") ; Second example: ; uses flags '1' (owerwriting) and '8' (autocreating target dir structure) together ; moves all txt-files from temp to txtfiles and prechecks if ; target directory structure exists, if not then automatically creates it FileMove(@TempDir & "\*.txt", @TempDir & "\TxtFiles\", 9) < -------------------------------------------------------------------------------- *FileOpen* +----------+~ | FileOpen |~ +----------+~ Opens a file for reading or writing. > FileOpen ( "filename" [, mode = 0] ) < Parameters~ filename -------- Filename of the file to open. mode ----- [optional] Mode to open the file in. Can be a combination of the following: $FO_READ (0) = Read mode (default) $FO_APPEND (1) = Write mode (append to end of file) $FO_OVERWRITE (2) = Write mode (erase previous contents) $FO_CREATEPATH (8) = Create directory structure if it doesn't exist (See Remarks). $FO_BINARY (16) = Force binary mode (See Remarks). $FO_UNICODE or $FO_UTF16_LE (32) = Use Unicode UTF16 Little Endian reading and writing mode. $FO_UTF16_BE (64) = Use Unicode UTF16 Big Endian reading and writing mode. $FO_UTF8 (128) = Use Unicode UTF8 (with BOM) reading and writing mode. $FO_UTF8_NOBOM (256) = Use Unicode UTF8 (without BOM) reading and writing mode. $FO_ANSI (512) = Use ANSI reading and writing mode. $FO_UTF16_LE_NOBOM (1024) = Use Unicode UTF16 Little Endian (without BOM) reading and writing mode. $FO_UTF16_BE_NOBOM (2048) = Use Unicode UTF16 Big Endian (without BOM) reading and writing mode. $FO_FULLFILE_DETECT (16384) = When opening for reading and no BOM is present, use the entire file to determine if it is UTF8 or UTF16. If this is not used then only the initial part of the file (up to 64KB) is checked for performance reasons. The folder path must already exist (except using $FO_CREATEPATH mode - See Remarks). Constants are defined in FileConstants.au3. Note recent versions of AutoIt seem to try and 'second guess' what type of data is coming in when you go ahead and use FileRead. See next note for a workaround. This is really a bit annoying I found IMHO because it seems to force you to have to 'second guess' what it is gonna 'second guess' is the type of data coming in. I personally found it much better when you could call FileRead and know it was just gonna treat incoming data as String. Then if you wanted to you could override it by using $FO_BINARY. (See |FileOpen|.) The New Way seems to be to try to be more intelligent when user makes a call to FileRead. As a result you could end up with Variant Binary (see 'Remarks' in |FileRead|) or String depending on what mood it was in. Sometimes it chooses Binary. Sometimes it doesn't. Note You can force FileRead not to go into Binary by or-ing flag $FO_UTF8 onto FileOpen. This seems to be the way you have to handle the problem. Note the other way as suggested by Melba23 https://www.autoitscript.com/forum/topic/187927-help-im-trying-to-read-sequence-of-chars-with-number/ is to use the 'filter' function BinaryToString. The latter you could call after you call FileRead which thus would guarantee the result it returned is of type string. Return Value~ Success ------- a file "handle" for use with subsequent file functions. Failure ------- -1 if error occurs. Remarks~ The file handle must be closed with the FileClose() function. A file may fail to open due to access rights or attributes. The default mode when writing text is UTF8 (without BOM) - use the unicode mode flags to change this. When reading without an explicit unicode mode flag, the content of the file is examined and a guess is made whether the file is UTF8, UTF16 or ANSI. If opening an existing file and that file has a BOM then the BOM will be honored regardless of the unicode mode flags passed. Opening a file in write mode creates the file if it does not exist. Directories are not created unless the correct flag is used. When reading and writing via the same file handle, the FileSetPos() function must be used to update the current file position. A file can be read as binary (byte) data by using FileOpen() with the binary flag. See "Unicode Support" for a detailed description. Related~ |FileClose|, |FileFlush|, |FileGetPos|, |FileRead|, |FileReadLine|, |FileSetPos|, |FileWrite|, |FileWriteLine| Example~ Example 1 > #include #include #include Example() Func Example() ; Create a constant variable in Local scope of the filepath that will be read/written to. Local Const $sFilePath = _WinAPI_GetTempFileName(@TempDir) ; Create a temporary file to read data from. If Not FileWrite($sFilePath, "This is an example of using FileOpen.") Then MsgBox($MB_SYSTEMMODAL, "", "An error occurred whilst writing the temporary file.") Return False EndIf ; Open the file for reading and store the handle to a variable. Local $hFileOpen = FileOpen($sFilePath, $FO_READ) If $hFileOpen = -1 Then MsgBox($MB_SYSTEMMODAL, "", "An error occurred when reading the file.") Return False EndIf ; Read the contents of the file using the handle returned by FileOpen. Local $sFileRead = FileRead($hFileOpen) ; Close the handle returned by FileOpen. FileClose($hFileOpen) ; Display the contents of the file. MsgBox($MB_SYSTEMMODAL, "", "Contents of the file:" & @CRLF & $sFileRead) ; Delete the temporary file. FileDelete($sFilePath) EndFunc ;==>Example < Example 2 > #include #include #include Example() Func Example() ; Create a constant variable in Local scope of the filepath that will be read/written to. Local Const $sFilePath = _WinAPI_GetTempFileName(@TempDir) ; Open the file for read/write access. Local $hFileOpen = FileOpen($sFilePath, $FO_READ + $FO_OVERWRITE) If $hFileOpen = -1 Then MsgBox($MB_SYSTEMMODAL, "", "An error occurred when reading/writing the file.") Return False EndIf ; Write some data. FileWrite($hFileOpen, "This is some data to show that the handle was open with read/write access." & @CRLF) ; Retrieve the current position in the file. Local $iFilePos = FileGetPos($hFileOpen) ; Now, adjust the position to the beginning. FileSetPos($hFileOpen, 0, $FILE_BEGIN) ; Display the contents of the file. MsgBox($MB_SYSTEMMODAL, "", FileRead($hFileOpen)) ; Now, adjust the position back to the previous position. FileSetPos($hFileOpen, 0, $iFilePos) ; Write some addition data. FileWrite($hFileOpen, "This is some additional data.") ; Adjust the position back to the previous position. FileSetPos($hFileOpen, 0, $FILE_BEGIN) ; Display the contents of the file. MsgBox($MB_SYSTEMMODAL, "", FileRead($hFileOpen)) ; Close the handle returned by FileOpen. FileClose($hFileOpen) ; Delete the temporary file. FileDelete($sFilePath) Return True EndFunc ;==>Example < -------------------------------------------------------------------------------- *FileOpenDialog* +----------------+~ | FileOpenDialog |~ +----------------+~ Initiates a Open File Dialog. > FileOpenDialog ( "title", "init dir", "filter" [, options [, "default name" [, hwnd]]] ) < Parameters~ title ----- Title text of the Dialog GUI. init dir -------- Initial directory selected in the GUI file tree. filter ------ File type single filter such as "All (*.*)" or "Text files (*.txt)" or multiple filter groups such as "All (*.*)|Text files (*.txt)" (See Remarks). Note make sure this is done properly because because otherwise function just exits options ------- [optional] Dialog Options: To use more than one option, add the required values together. 1 = File Must Exist (if user types a filename) 2 = Path Must Exist (if user types a path, ending with a backslash) 4 = Allow MultiSelect 8 = Prompt to Create New File (if does not exist) default name ------------ [optional] Suggested file name for the user to open. Default is blank (""). hwnd ----- [optional] The window handle to use as the parent for this dialog. Return Value~ Success ------- Returns the full path of the file(s) chosen. Results for multiple selections are: > "Directory|file1|file2|..." < Failure ------- Sets @error @error: 1 - File selection failed. 2 - Bad file filter Remarks~ Separate the file filters with a semicolon as shown in the example. Multiple groups of filters are separated by a pipe "|". If default name is given, options must also be given. If none of the options are wanted, use 0 for options. Special Windows folders (such as "My Documents") can sometimes be set as the init dir; see Appendix. @WorkingDir is changed on successful return. Related~ |FileSaveDialog|, |FileSelectFolder|, |StringSplit| Example~ > $message = "Hold down Ctrl or Shift to choose multiple files." $var = FileOpenDialog($message, @WindowsDir & "\", "Images (*.jpg;*.bmp)", 1 + 4 ) If @error Then MsgBox(4096,"","No File(s) chosen") Else $var = StringReplace($var, "|", @CRLF) MsgBox(4096,"","You chose " & $var) EndIf ; Multiple filter group $message = "Hold down Ctrl or Shift to choose multiple files." $var = FileOpenDialog($message, @WindowsDir & "", "Images (*.jpg;*.bmp)|Videos (*.avi;*.mpg)", 1 + 4 ) If @error Then MsgBox(4096,"","No File(s) chosen") Else $var = StringReplace($var, "|", @CRLF) MsgBox(4096,"","You chose " & $var) EndIf < -------------------------------------------------------------------------------- *FileRead* +----------+~ | FileRead |~ +----------+~ Read in a number of characters from a previously opened text file. > FileRead ( "filehandle/filename" [, count] ) < Parameters~ filehandle/filename ------------------- The handle of a file, as returned by a previous call to FileOpen. Alternatively you may use a string filename as the first parameter. count ----- [optional] The number of characters to read. Default read the entire file. Return Value~ Success ------- Returns the binary/string read. @extended is set to the number of bytes/characters returned. Special: Sets @error to -1 if end-of-file is reached. Failure ------- Sets @error to 1 if file not opened in read mode or other error. Remarks~ If a filename is given rather than a file handle - the file will be opened and closed during the function call - for parsing large text files this will be much slower than using filehandles. Note: Do not mix filehandles and filenames, i.e., don't FileOpen a file and then use a filename in this function. Use either filehandles or filenames in your routines, not both! Both ANSI and UTF16/UTF8 text formats can be read - AutoIt will automatically determine the type. A file can be read as binary(byte) data by using FileOpen with the binary flag - in this case count is in bytes rather than characters. Related~ |FileOpen|, |FileReadLine|, |FileWrite|, |FileWriteLine|, |String|, |FileSetPos|, |FileGetPos| Example~ > $file = FileOpen("test.txt", 0) ; Check if file opened for reading OK If $file = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf ; Read in 1 character at a time until the EOF is reached While 1 $chars = FileRead($file, 1) If @error = -1 Then ExitLoop MsgBox(0, "Char read:", $chars) Wend FileClose($file) < -------------------------------------------------------------------------------- *FileReadLine* +--------------+~ | FileReadLine |~ +--------------+~ Read in a line of text from a previously opened text file. > FileReadLine ( "filehandle/filename" [, line] ) < Parameters~ filehandle/filename ------------------- The handle of a file, as returned by a previous call to FileOpen. Alternatively you may use a string filename as the first parameter. line ----- [optional] The line number to read. The first line of a text file is line 1 (not zero), last line is -1. Return Value~ Success ------- Returns a line of text. Special Sets @error to -1 if end-of-file is reached. Failure ------- Sets @error to 1 if file not opened in read mode or other error. Remarks~ Returns the text of the line read, any newline characters ( CHR(10) or @LF ) at the end of a line read in are automatically stripped. If no line number to read is given, the "next" line will be read. ("Next" for a newly opened file is initially the first line.) If a filename is given rather than a file handle - the file will be opened and closed during the function call - for parsing large text files this will be much slower than using filehandles. Note: Do not mix filehandles and filenames, i.e., don't FileOpen a file and then use a filename in this function. Use either filehandles or filenames in your routines, not both! From a performance standpoint it is a bad idea to read line by line specifying "line" parameter whose value is incrementing by one. This forces AutoIt to reread the file from the beginning until it reach the specified line. Both ANSI and UTF16/UTF8 text formats can be read - AutoIt will automatically determine the type. Related~ |IniRead|, |FileOpen|, |FileRead|, |FileWrite|, |FileWriteLine|, |FileSetPos|, |FileGetPos| Example~ > $file = FileOpen("test.txt", 0) ; Check if file opened for reading OK If $file = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf ; Read in lines of text until the EOF is reached While 1 $line = FileReadLine($file) If @error = -1 Then ExitLoop MsgBox(0, "Line read:", $line) Wend FileClose($file) < -------------------------------------------------------------------------------- *FileRecycle* +-------------+~ | FileRecycle |~ +-------------+~ Sends a file or directory to the recycle bin. > FileRecycle ( "source" ) < Parameters~ source ------ The source path of the file(s) or directory to Recycle. Wildcards are supported. Return Value~ Success ------- Returns 1. Failure ------- Returns 0 (typically meaning the file is in use or does not exist). Remarks~ See FileFindFirstFile for a discussion of wildcards. To remove a directory, simply give the path without a trailing backslash. Related~ |FileDelete|, |FileRecycleEmpty|, |DirRemove|, |FileMove| Example~ > FileRecycle("C:\*.tmp") < -------------------------------------------------------------------------------- *FileRecycleEmpty* +------------------+~ | FileRecycleEmpty |~ +------------------+~ Empties the recycle bin. > FileRecycleEmpty ( ["source"] ) < Parameters~ source ------ [optional] The rootpath to empty - if omitted the recycle bin for all drives is emptied. Return Value~ Success ------- Returns 1. Failure ------- Returns 0 (the recycle bin cannot be emptied - see below). Remarks~ For this function to work IE4+ must be available. Related~ |FileDelete|, |FileRecycle| Example~ > FileRecycleEmpty("C:\") < -------------------------------------------------------------------------------- *FileSaveDialog* +----------------+~ | FileSaveDialog |~ +----------------+~ Initiates a Save File Dialog. > FileSaveDialog ( "title", "init dir", "filter" [, options [, "default name" [, hwnd]]] ) < Parameters~ title ----- Title text of the Dialog GUI. init dir -------- Initial directory selected in the GUI file tree. filter ------ File type single filter such as "All (*.*)" or "Text files (*.txt)" or multiple filter groups such as "All (*.*)|Text files (*.txt)" (See Remarks). options ------- [optional] 2 = Path Must Exist (if user types a path, ending with a backslash) 16 = Prompt to OverWrite File default name ------------ [optional] File name to suggest to the user to save the file with. Default is blank (""). hwnd ----- [optional] The window handle to use as the parent for this dialog. Return Value~ Success ------- Returns the full path of the file chosen. Results for multiple selections are "Directory|file1|file2|..." Failure ------- Sets @error @error: 1 - File selection failed. 2 - Bad file filter Remarks~ Separate the file filters with a semicolon as shown in the example. Multiple groups of filters are separated by a pipe "|". If default name is given, options must also be given. If none of the options are wanted, use 0 for options. Special Windows folders (such as "My Documents") can sometimes be set as the init dir; see Appendix. |@WorkingDir| is changed on successful return. Related~ |FileOpenDialog|, |FileSelectFolder| Example~ > $MyDocsFolder = "::{450D8FBA-AD25-11D0-98A8-0800361B1103}" $var = FileSaveDialog( "Choose a name.", $MyDocsFolder, "Scripts (*.aut;*.au3)", 2) ; option 2 = dialog remains until valid path/file selected If @error Then MsgBox(4096,"","Save cancelled.") Else MsgBox(4096,"","You chose " & $var) EndIf ; Multiple filter group $var = FileSaveDialog( "Choose a name.", $MyDocsFolder, "Scripts (*.aut;*.au3)|Text files (*.ini;*.txt)", 2) ; option 2 = dialog remains until valid path/file selected If @error Then MsgBox(4096,"","Save cancelled.") Else MsgBox(4096,"","You chose " & $var) EndIf < -------------------------------------------------------------------------------- *FileSelectFolder* +------------------+~ | FileSelectFolder |~ +------------------+~ Initiates a Browse For Folder dialog. > FileSelectFolder ( "dialog text", "root dir" [, flag [, "initial dir" [, hwnd]]] ) < Parameters~ dialog text ----------- Text greeting in dialog. root dir -------- Root directory of GUI file tree. Use "" for Desktop to be root. flag ----- [optional] 1 = Show Create Folder Button (requires IE6.0 or later) 2 = Use New Dialog Style (requires IE5.0 or later) 4 = Show Edit Control (to type a foldername) initial dir ----------- [optional] Initial/start directory that will be selected if exist. Default is blank (""). hwnd ----- [optional] The window handle to use as the parent for this dialog. Return Value~ Success ------- Returns full path of the folder chosen. Failure ------- Returns "" (blank string) and sets @error to 1 if user cancels/closes the window. Remarks~ The root dir will be chosen if the initial dir (if given) does not exist. A nonexistent root dir will also cause the Desktop folder to be root. The "Create Folder Button" option may require Windows XP with IE6 in order to work. Special Windows folders (such as "My Documents") can be set as root by using the right CLSID detailed in the Appendix. UNC paths are not supported. If you think that user's may choose files on a UNC path then the path needs to be mapped as a drive first. Related~ |FileSaveDialog|, |FileOpenDialog| Example~ > $var = FileSelectFolder("Choose a folder.", "") < -------------------------------------------------------------------------------- *FileSetAttrib* +---------------+~ | FileSetAttrib |~ +---------------+~ Sets the attributes of one or more files. > FileSetAttrib ( "file pattern", "+-RASHNOT" [, recurse] ) < Parameters~ file pattern ------------ File(s) to change, e.g. C:\*.au3, C:\Dir +-RASHNOT --------- Attribute(s) to set/clear. e.g. "+A", "+RA-SH" recurse ------- [optional] If this is set to 1, then directories are recursed into. Default is 0 (no recursion). Return Value~ Success ------- Returns 1. Failure ------- Returns 0 if encountered any errors. Remarks~ The file pattern cannot contain spaces! The attributes that can be modified with the function are + or -: "R" = READONLY "A" = ARCHIVE "S" = SYSTEM "H" = HIDDEN "N" = NORMAL "O" = OFFLINE "T" = TEMPORARY (Note that you cannot set the compressed/directory attributes with this function.) Related~ |FileGetAttrib|, |FileGetTime|, |FileSetTime| Example~ > ;mark all .au3 files in current directory as read-only and system If Not FileSetAttrib("*.au3", "+RS") Then MsgBox(4096,"Error", "Problem setting attributes.") EndIf ;make all .bmp files in C:\ and sub-directories writable and archived If Not FileSetAttrib("C:\*.bmp", "-R+A", 1) Then MsgBox(4096,"Error", "Problem setting attributes.") EndIf < -------------------------------------------------------------------------------- *FileSetPos* +------------+~ | FileSetPos |~ +------------+~ Sets the current file position. > FileSetPos ( handle, offset, origin ) < Parameters~ handle ------ A handle to a file previously opened with FileOpen(). offset ----- The offset to move from the origin. This value may be positive or negative. Negative values move backwards from the origin. origin ------ Must be one of the following: 0 - Beginning of the file ($FILE_BEGIN from Constants.au3). 1 - Current position ($FILE_CURRENT from Constants.au3). 2 - End of the file ($FILE_END from Constants.au3). Return Value~ Success ------- True if the operation succeeded. Failure ------- False. Remarks~ Include Constants.au3 in your script to use the symbolic name in parentheses to specify the origin. Using FileSetPos() it is possible to both read and write to the same file. When attempting to read and write to the same file, always call FileFlush() between each write and read operation. Moving the pointer to the middle of the data can be used to overwrite data. Related~ |FileGetPos|, |FileFlush|, |FileRead|, |FileReadLine|, |FileWrite|, |FileWriteLine|, |FileOpen| Example~ > #include Local Const $sFile = "test.txt" Local $hFile = FileOpen($sFile, 2) ; Check if file opened for writing OK If $hFile = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf ; Write something to the file. FileWriteLine($hFile, "Line1") FileWriteLine($hFile, "Line2") FileWriteLine($hFile, "Line3") ; Flush the file to disk. FileFlush($hFile) ; Check file position and try to read contents for current position. MsgBox(0, "", "Position: " & FileGetPos($hFile) & @CRLF & "Data: " & @CRLF & FileRead($hFile)) ; Now, adjust the position to the beginning. Local $n = FileSetPos($hFile, 0, $FILE_BEGIN) ; Check file position and try to read contents for current position. MsgBox(0, "", "Position: " & FileGetPos($hFile) & @CRLF & "Data: " & @CRLF & FileRead($hFile)) ; Close the handle. FileClose($hFile) ; Clean up the temporary file. FileDelete($sFile) < -------------------------------------------------------------------------------- *FileSetTime* +-------------+~ | FileSetTime |~ +-------------+~ Sets the timestamp of one of more files. > FileSetTime ( "file pattern", "time" [, type [, recurse] ] ) < Parameters~ file pattern ----- File(s) to change, e.g. C:\*.au3, C:\Dir time ----- The new time to set in the format "YYYYMMDDHHMMSS" (Year, month, day, hours (24hr clock), seconds). If the time is blank "" then the current time is used. type ----- [optional] The timestamp to change: 0 = Modified (default), 1 = Created, 2 = Accessed recurse ------- [optional] If this is set to 1, then directories are recursed into. Default is 0 (no recursion). Return Value~ Success ----- Returns 1. Failure ------- Returns 0 if error changing timestamp(s). Remarks~ Using a date earlier than 1980-01-01 will have no effect. Trying to change a timestamp on read-only files will result in a error. Related~ |FileGetTime|, |FileGetAttrib|, |FileSetAttrib| Example~ > ;change file.au3's "modified" timestamp to 1st Nov 2003 and current time $var = FileSetTime("file.au3", "20031101") < -------------------------------------------------------------------------------- *FileWrite* +-----------+~ | FileWrite |~ +-----------+~ Append a text/data to the end of a previously opened file. > FileWrite ( "filehandle/filename", "text/data" ) < Parameters~ filehandle/filename ------------------- The handle of a file, as returned by a previous call to FileOpen. Alternatively, you may use a string filename as the first parameter. text/data --------- The text/data to write to the file. The text is written as is - no @CR or @LF characters are added. See remark for data type. Return Value~ Success ------- Returns 1. Failure ------- Returns 0 if file not opened in writemode, file is read only, or file cannot otherwise be written to. Remarks~ The file must be opened in write mode or the FileWrite command will fail. If a filename is given rather than a file handle, the file will be opened and closed during the function call. For parsing large text files this will be much slower than using filehandles. However, filename will be created if it does not already exist. Note: Do not mix filehandles and filenames, i.e., don't FileOpen a file and then use a filename in this function. Either use filehandles or filenames in your routines, not both. When writing text AutoIt will write using ANSI by default. To write in Unicode mode the file must be opened with FileOpen() and the relevant flags. If the data is a binary type variant (and not text) it will be written to the file byte by byte. Binary operation can also be forced by using Fileopen with the binary flag. Related~ |FileFlush|, |FileOpen|, |FileRead|, |FileReadLine|, |FileWriteLine|, |Binary|, |FileSetPos|, |FileGetPos| Example~ > $file = FileOpen("test.txt", 1) ; Check if file opened for writing OK If $file = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf FileWrite($file, "Line1") FileWrite($file, "Still Line1" & @CRLF) FileWrite($file, "Line2") FileClose($file) < -------------------------------------------------------------------------------- *FileWriteLine* +---------------+~ | FileWriteLine |~ +---------------+~ Append a line of text to the end of a previously opened text file. > FileWriteLine ( "filehandle/filename", "line" ) < Parameters~ filehandle/filename ------------------- The handle of a file, as returned by a previous call to FileOpen. Alternatively, you may use a string filename as the first parameter. line The line of text to write to the text file. If the line does NOT end in @CR or @LF then a DOS linefeed (@CRLF) will be automatically added. Return Value~ Success ------- Returns 1. Failure ------- Returns 0 if file not opened in writemode, file is read only, or file cannot otherwise be written to. Remarks~ The text file must be opened in write mode or the FileWriteLine command will fail. If a filename is given rather than a file handle, the file will be opened and closed during the function call. For parsing large text files this will be much slower than using filehandles. However, filename will be created if it does not already exist. Note: Do not mix filehandles and filenames, i.e., don't FileOpen a file and then use a filename in this function. Either use filehandles or filenames in your routines, not both. When writing text AutoIt will write using ANSI by default. To write in Unicode mode the file must be opened with FileOpen() and the relevant flags. The text to write cannot contain Chr(0) characters as the output is truncated. FileWrite() using a file opened in binary mode must be used to write such characters. Related~ |FileFlush|, |FileOpen|, |FileRead|, |FileReadLine|, |FileWrite|, |FileSetPos|, |FileGetPos| Example~ > $file = FileOpen("test.txt", 1) ; Check if file opened for writing OK If $file = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf FileWriteLine($file, "Line1") FileWriteLine($file, "Line2" & @CRLF) FileWriteLine($file, "Line3") FileClose($file) < -------------------------------------------------------------------------------- *IniDelete* +-----------+~ | IniDelete |~ +-----------+~ Deletes a value from a standard format .ini file. > IniDelete ( "filename", "section" [, "key"] ) < Parameters~ filename -------- The filename of the .ini file. section ------- The section name in the .ini file. key ----- [optional] The key name in the .ini file to delete. If the key name is not given the entire section is deleted. The Default keyword may also be used which will cause the section to be deleted. Return Value~ Success ------- Returns 1. Failure ------- Returns 0 if the INI file does not exist or if the file is read-only. Note this is the only thing that returns a fail. Literally as it says, if file is read-only! https://www.autoitscript.com/forum/topic/188096-inidelete-returning-success-no-key-being-deleted/ Remarks~ A standard ini file looks like: [SectionName] Key=Value Related~ |IniRead|, |IniWrite|, |IniReadSection|, |IniReadSectionNames|, |IniRenameSection|, |IniWriteSection| Example~ > IniDelete("C:\Temp\myfile.ini", "section2", "key") < -------------------------------------------------------------------------------- *IniRead* +---------+~ | IniRead |~ +---------+~ Reads a value from a standard format .ini file. > IniRead ( "filename", "section", "key", "default" ) < Parameters~ filename -------- The filename of the .ini file. section ------- The section name in the .ini file. key ----- The key name in the in the .ini file. default ------- The default value to return if the requested key is not found. Return Value~ Success ------- Returns the requested key value. Failure ------- Returns the default string if requested key not found. Remarks~ A standard ini file looks like: [SectionName] Key=Value Related~ |IniDelete|, |IniWrite|, |FileReadLine|, |IniReadSection|, |IniReadSectionNames|, |IniRenameSection|, |IniWriteSection| Example~ > $var = IniRead("C:\Temp\myfile.ini", "section2", "key", "NotFound") MsgBox(4096, "Result", $var) < -------------------------------------------------------------------------------- *IniReadSection* +----------------+~ | IniReadSection |~ +----------------+~ Reads all key/value pairs from a section in a standard format .ini file. > IniReadSection ( "filename", "section" ) < Parameters~ filename -------- The filename of the .ini file. section ------- The section name in the .ini file. Return Value~ Success ------- Returns a 2 dimensional array where element[n][0] is the key and element[n][1] is the value. Failure ------- Sets @error=1 if unable to read the section (The INI file may not exist or the section may not exist) Remarks~ A standard ini file looks like: [SectionName] Key=Value The number of elements returned will be in $result[0][0]. If an @error occurs, no array is created. Only the first 32767 chars are taken in account in an section due to Win9x compatibility. Related~ |IniDelete|, |IniWrite|, |IniRead|, |IniReadSectionNames|, |IniRenameSection|, |IniWriteSection| Example~ > $var = IniReadSection("C:\Temp\myfile.ini", "section2") If @error Then MsgBox(4096, "", "Error occurred, probably no INI file.") Else For $i = 1 To $var[0][0] MsgBox(4096, "", "Key: " & $var[$i][0] & @CRLF & "Value: " & $var[$i][1]) Next EndIf < -------------------------------------------------------------------------------- *IniReadSectionNames* +---------------------+~ | IniReadSectionNames |~ +---------------------+~ Reads all sections in a standard format .ini file. > IniReadSectionNames ( "filename" ) < Parameters~ filename -------- The filename of the .ini file. Return Value~ Success ------- Returns an array of all section names in the INI file. Failure ------- Sets @error on failure. Remarks~ A standard ini file looks like: [SectionName] Key=Value The number of elements returned will be in $result[0]. If an @error occurs, no array is created. Only the first 32767 chars are taken in account in an section due to Win9x compatibility. Related~ |IniDelete|, |IniWrite|, |IniRead|, |IniReadSection|, |IniRenameSection|, |IniWriteSection| Example~ > $var = IniReadSectionNames(@WindowsDir & "\win.ini") If @error Then MsgBox(4096, "", "Error occurred, probably no INI file.") Else For $i = 1 To $var[0] MsgBox(4096, "", $var[$i]) Next EndIf < -------------------------------------------------------------------------------- *IniRenameSection* +------------------+~ | IniRenameSection |~ +------------------+~ Renames a section in a standard format .ini file. > IniRenameSection ( "filename", "section", "new section" [, flag] ) < Parameters~ filename -------- The filename of the .ini file. section ------- The section name in the .ini file. new section ----------- The new section name. flag ----- [optional] 0 (Default) - Fail if "new section" already exists. 1 - Overwrite "new section". This will erase any existing keys in "new section" Return Value~ Success ----- Non-zero. Failure ------- 0 and may set @error if the section couldn't be overwritten (flag = 0 only). Remarks~ A standard ini file looks like: [SectionName] Key=Value Related~ |IniRead|, |IniDelete|, |IniWrite|, |IniReadSection|, |IniReadSectionNames|, |IniWriteSection| Example~ > $res = IniRenameSection(@ScriptDir & "My.ini", "MySection", "MyNewSection") < -------------------------------------------------------------------------------- *IniWrite* +----------+~ | IniWrite |~ +----------+~ Writes a value to a standard format .ini file. > IniWrite ( "filename", "section", "key", "value" ) < Parameters~ filename -------- The filename of the .ini file. section ------- The section name in the .ini file. key ----- The key name in the in the .ini file. value ----- The value to write/change. Return Value~ Success ------- Returns 1. Failure ------- Returns 0 if file is read-only. Note this is the only thing that returns a fail. Literally as it says, if file is read-only! https://www.autoitscript.com/forum/topic/188096-inidelete-returning-success-no-key-being-deleted/ Remarks~ A standard ini file looks like: [SectionName] Key=Value If file does not exist, it is created. Any directories that do not exist, will not be created. Keys and/or sections are added to the end and are not sorted in any way."? When writing a value that is quoted, the quotes are stripped. In order to write the quote marks to the value, you must double up the quoting. For example: ""This is a test"" will produce "This is a test" in the file. Leading and trailing whitespace is stripped. In order to preserve the whitespace, the string must be quoted. For example, " this is a test" will preserve the whitespace but per above, the quotation marks are stripped. Multi-line values are not possible. Related~ |IniDelete|, |IniRead|, |IniReadSection|, |IniReadSectionNames|, |IniWriteSection|, |IniRenameSection| Example~ > IniWrite("C:\Temp\myfile.ini", "section2", "key", "this is a new value") < -------------------------------------------------------------------------------- *IniWriteSection* +-----------------+~ | IniWriteSection |~ +-----------------+~ Writes a section to a standard format .ini file. > IniWriteSection ( "filename", "section", "data" [, index ] ) < Parameters~ filename -------- The filename of the .ini file. section ------- The section name in the .ini file. data ----- The data to write. The data can either be a string or an array. If the data is a string, then each key=value pair must be delimited by @LF. If the data is an array, the array must be 2-dimensional and the second dimension must be 2 elements. index ----- [optional] If an array is passed as data, this specifies the index to start writing from. By default, this is 1 so that the return value of IniReadSection() can be used immediately. For manually created arrays, this value may need to be different depending on how the array was created. This parameter is ignored if a string is passed as data. Return Value~ Success ------- Returns 1. Failure ------- Returns 0. The function will set @error to 1 if the data format is invalid. Remarks~ A standard ini file looks like: [SectionName] Key=Value If file does not exist, it is created. Any directories that do not exist, will not be created. Keys and/or sections are added to the end and are not sorted in any way."? If the section being written already exists, it's contents will be overwritten. Related~ |IniDelete|, |IniRead|, |IniReadSection|, |IniReadSectionNames|, |IniWrite|, |IniRenameSection| Example~ > ; This is the INI file we will write to. It will be created on the Desktop. $sIni = @DesktopDir & "\AutoIt-Test.ini" ; Demonstrate creating a new section using a string as input. $sData = "Key1=Value1" & @LF & "Key2=Value2" & @LF & "Key3=Value3" IniWriteSection($sIni, "Section1", $sData) ; Demonstrate creating a new section using an array as input. $aData1 = IniReadSection($sIni, "Section1") ; Read in what we just wrote above. For $i = 1 To UBound($aData1) - 1 $aData1[$i][1] &= "-" & $i ; Change the data some Next IniWriteSection($sIni, "Section2", $aData1) ; Write to a new section. ; Demonstrate creating an array manually and using it as input. Dim $aData2[3][2] = [ [ "FirstKey", "FirstValue" ], [ "SecondKey", "SecondValue" ], [ "ThirdKey", "ThirdValue" ] ] ; Since the array we made starts at element 0, we need to tell IniWriteSection() to start writing from element 0. IniWriteSection($sIni, "Section3", $aData2, 0) < -------------------------------------------------------------------------------- *Frequently_asked_questions_(FAQ)* +----------------------------+~ | Frequently Asked Questions |~ +----------------------------+~ This section gives some of the more frequently asked questions from the forum. If you can't find the answer you seek here then the forum should be your first port of call. Questions~ 1. Why doesn't my old AutoIt v2.64 script run in v3? 2. Isn't v3 much more difficult than previous versions? 3. How can I convert my v2.64 scripts to v3? 4. Where is the "goto" command? 5. How can I run a DOS program from within AutoIt? 6. Why can I only use Run() to execute .exe and .com files? What about .msi / .txt and others? 7. Why do I get errors when I try and use double quotes (") ? 8. What do the window "title" and "text" parameters mean? 9. Why can't I print a variable using "My var is $variable"? 10. When I use Send() to send a variable odd things happen? 11. What is the difference between the return value and @error? 12. How can I exit my script with a hot-key? 13. How can I use a custom icon when compiling my scripts? 14. How can I make sure only one copy of my script is run? 15. What are the current technical limits of AutoIt v3? 16. I get a missing picture symbol in the Help file under the Examples. *why_doesn't_my_old_autoit_v2.64_script_run_in_v3?* 1. Why doesn't my old AutoIt v2.64 script run in v3?~ v3 has a different language structure to v2.64. Previous versions of AutoIt were fine for what they were designed for - writing simple scripts to help with software installations. Over time people began using it for general and complicated scripting tasks. The old syntax and structure made this possible but very very difficult and cumbersome. The decision was made to make AutoIt more suitable for general automation tasks and to achieve that a more standard and basic-like language was made. This also means that if you already know a scripting language you will pick AutoIt v3 up easily. *isn't_v3_much_more_difficult_than_previous_versions?* 2. Isn't v3 much more difficult than previous versions?~ No. In fact in many instances it's much easier than previous versions as you don't have to try and force the language to do something it was never designed to do. It also uses a familiar BASIC-like language, and BASIC is known for being...well...basic :) The vast majority of old AutoIt scripts were focused around software installation and clicking "Next" a lot in dialog boxes. Most of these scripts can be converted to v3 simply by adding a couple of brackets here and there. Here is an example of such a script in v2 and v3 (simulating a software installation with a few dialogs that have a Next button and a Finish button) > ; v2.64 Script WinWaitActive, Welcome, Welcome to the XSoft installation Send, !n WinWaitActive, Choose Destination, Please choose the Send, !n WinWaitActive, Ready to install, Click Next to install Send, !n WinWaitActive, Installation Complete, Click Finish to exit Send, !f WinWaitClose, Installation Complete ; v3 Script WinWaitActive("Welcome", "Welcome to the XSoft installation") Send("!n") WinWaitActive("Choose Destination", "Please choose the") Send("!n") WinWaitActive("Ready to install", "Click Next to install") Send("!n") WinWaitActive("Installation Complete", "Click Finish to exit") Send("!f") WinWaitClose("Installation Complete") < Now, that wasn't so bad! :) As all "strings" are enclosed in quotes you no longer have to wrestle with problems caused by leading and trailing spaces in text. There is also fantastic support for many text editors so that when you are writing v3 scripts you can have syntax highlighting which makes everything much easier. *how_can_I_convert_my_v2.64_scripts_to_v3?* 3. How can I convert my v2.64 scripts to v3?~ The first thing you should ask yourself is "Do I need to convert my script?". v2.64 will continue to be downloadable and supported so don't update all your scripts just for the sake of it - well not unless you want to :) There is a section in the Help file that shows how the commands in v2 and v3 are related - click here to see the page. One of the AutoIt v3 authors has written a utility to automatically convert v2 scripts to v3. Conversion is pretty good unless your code is a rats-nest of gotos :) You can find the converter in the "Extras" directory (Start \ AutoIt v3 \ Extras - or look in the directory that you installed AutoIt v3). *where_is_the_goto_command?* 4. Where is the "goto" command?~ Gone. It's evil. No, you can't ask why - it just is. It's like that lump of rock they find in the microwave at the end of the film Time Bandits :) AutoIt v3 features most of the common "loops" in use today and with these Goto is no longer required. Look up While, Do, For, ExitLoop, ContinueLoop and Functions for the modern way of doing things :) And while you are looking at help file sections check out these on loops, conditional statements and functions. I promise you, once you have got the hang of such things you will be able to script in virtually any other language within a couple of minutes. Just to get you started, the most basic use of Goto in version 2.64 was an infinite loop like: > :mylabel ...do something... ...and something else... goto, mylabel < A simple v3 version of that is a While loop that is always "true". > While 1 = 1 ...do something... ...do something else... Wend < *how_can_I_run_a_DOS_program_from_within_autoit?* 5. How can I run a DOS program from within AutoIt?~ If you wanted to run something like a DOS "Dir" command then you must run it though the command interpreter (command.com or cmd.exe depending on your OS). The @Comspec macro contains the correct location of this file. You should use the RunWait() function as it waits for the DOS program to finish before continuing with the next line of the script. Here is an example of running the DOS Dir command on the C: drive: (effectively running the command command.com /c Dir C:\ ) > RunWait(@COMSPEC & " /c Dir C:\") < *why_can_I_only_use_Run()_to_execute_.exe_files?* 6. Why can I only use Run() to execute .exe files? What about .msi /~ .txt and others?~ Only a few file extensions are usually "runable" - these are .exe, .bat, .com, .pif. Other file types like .txt and .msi are actually executed with another program. When you double click on a "myfile.msi" file what actually happens in the background is that "msiexec.exe myfile.msi" is executed. So to run a .msi file from AutoIt you would do: > RunWait("msiexec myfile.msi") < Or, run the command "start" which will automatically work out how to execute the file for you: > RunWait(@COMSPEC & " /c Start myfile.msi") < Or, use the ShellExecuteWait function which will automatically work out how to execute the file for you: > ShellExecuteWait("myfile.msi") < *Why_do_i_get_errors_when_i_try_and_use_double_quotes?* 7. Why do I get errors when I try and use double quotes (") ?~ If you want to use double-quotes inside a string then you must "double them up". So for every one quote you want you should use two. For example if you wanted to set a variable to the string: A word in "this" sentence has quotes around it! You would do: > $var = "A word in ""this"" sentence has quotes around it!" < or use single quotes instead: > $var = 'A word in "this" sentence has quotes around it!' < *what_do_the_window_title_and_text_parameters_mean* 8. What do the window "title" and "text" parameters mean?~ There is a detailed description here |window_titles_and_text_(basic)|. *why_can't_I_print_a_variable_using_My_var_is_$variable* 9. Why can't I print a variable using "My var is $variable"?~ If you have a variable called $msg and you want to print in inside a MsgBox then this will NOT work: > MsgBox(0, "Example", "My variable is $msg") < It will actually print My variable is $msg . What you need to do is tell AutoIt to join the string and the variable together using the & operator: > MsgBox(0, "Example", "My variable is " & $msg) < Advanced: If you have many variables to add into a string then you may find the StringFormat() function useful. For example, if I wanted to insert $var1 to $var5 into a string then it may be easier to do: > $msg = StringFormat("Var1 is %s, Var2 is %s, Var3 is %s, Var4 is %s, Var5 is %s", $var1, $var2, $var3, $var4, $var5) MsgBox(0, "Example", $msg) < *when_I_use_send()_to_send_a_variable_odd_things_happen* 10. When I use Send() to send a variable odd things happen?~ If you are sending the contents of a variable then be mindful that if it contains special send characters like ! ^ + {SPACE} then these will be translated into special keystrokes - rarely what is wanted. To overcome this use the RAW mode of Send() that does not translate special keys: > Send($myvar, 1) < *what_is_the_difference_between_the_return_value_and_@error* 11. What is the difference between the return value and @error?~ Generally a return value is used to indicate the success of a function. But, if a function is already returning something ( like WinGetText() ) then we need to have a way of working out if the function was successful, so we set @error instead. *how_can_I_exit_my_script_with_a_hot-key* 12. How can I exit my script with a hot-key?~ Ah, an easy one. If you want to make your script exit when you press a certain key combination then use the HotKeySet() function to make a user function run when the desired key is pressed. This user function should just contain the Exit keyword. Here some code that will cause the script to exit when CTRL+ALT+x is pressed: > HotKeySet("^!x", "MyExit") ... ... ; Rest of Script ... ... Func MyExit() Exit EndFunc < *how_can_I_use_a_custom_icon_when_compiling_my_scripts* 13. How can I use a custom icon when compiling my scripts?~ You need to run the full compiler program (rather than just right-clicking a script and selecting compile). This page describes the compiler in detail. *how_can_I_make_sure_only_one_copy_of_my_script_is_run?* 14. How can I make sure only one copy of my script is run?~ Use the _Singleton() function. See the User Defined Functions documentation for more information on _Singleton() and how to use it. *what_are_the_current_technical_limits_of_AutoIt_v3* 15. What are the current technical limits of AutoIt v3?~ Here are details of the current technical limits of AutoIt. Please note that some of the limits are theoretical and you may run into performance or memory related problems before you reach the actual limit. Maximum length of a single script line: 4,095 Maximum string length: 2,147,483,647 characters Number range (floating point): 1.7E–308 to 1.7E+308 with 15-digit precision Number range (integers): 64-bit signed integer Hexadecimal numbers: 32-bit signed integer (0x80000000 to 0x7FFFFFFF) Arrays: A maximum of 64 dimensions and/or a total of 16 million elements Maximum depth of recursive function calls: 5100 levels Maximum number of variables in use at one time: No limit Maximum number of user defined functions: No limit Maximum number of GUI windows: No limit Maximum number of GUI controls: 65532 *I_get_a_missing_picture_symbol_in_the_Help_file_under_the_examples* 16. I get a missing picture symbol in the Help file under the~ Examples.~ This should be the Open button that enable you to open the Examples in the Help file. This issue is that the hhctrl.ocx isn't properly registered or corrupted. Try registering it by doing "regsvr32 hhctrl.ocx" from the command prompt or check if the file is still valid. -------------------------------------------------------------------------------- *window_titles_and_text_(basic)* +--------------------------------+~ | Window Titles and Text (Basic) |~ +--------------------------------+~ When automating, most windows can be uniquely identified by their title or a combination of their title & text. And by using AutoIt Window Info Tool (or even by sight) this information is easy to obtain. The titles of most windows are fairly obvious, for example Untitled - Notepad is the title of the notepad.exe editor and in many cases this is enough to automate. Note: If a blank string "" is given for both title and text then the currently Active window will be used (this is not true in some of the more advanced WinTitleMatchModes)! Window titles and text are case sensitive. You must match the case and punctuation exactly. To avoid problems select the title/text in the Window Info Tool and use ctrl-c to copy it and then paste it directly into your script. You can force match in lower case using advanced modes. Most of AutoIt's window functions have space for a title and text entry, here is the WinWaitActive function. This function pauses execution of the script until the specified window appears and is active. > WinWaitActive ( "title", ["text"], [timeout] ) < title is the only required parameter for this function, both the text and timeout are optional. In some functions the text parameter is not optional, if you do not wish to specify any text then just use "" (a blank string). A blank string, or nothing at all, in the text tells AutoIt that any text is valid. To use the above function with any notepad window both these methods will work: > WinWaitActive("Untitled - Notepad") < and > WinWaitActive("Untitled - Notepad", "") < If the same notepad window had "This is a line of text" typed into the window, the Window Info Tool would show: https://www.autoitscript.com/autoit3/docs/images/au3spy.png Note that the Window Info Tool has seen the title and text of the notepad window. Whatever the Window Info Tool can see is what AutoIt can see. Now we have enough information to identify this exact window even if there are lots of other notepad windows open. In this case we use: > WinWaitActive("Untitled - Notepad", "This is some text!") < Window Text~ The window text consists of all the text that AutoIt can "see". This will usually be things like the contents of edit controls (as above with "This is a line of text") but will also include other text like: Button text ----------- like &Yes, &No, &Next (the & indicates an underlined letter) Dialog text ----------- like "Are you sure you wish to continue?" Control text ------------ Misc text ------------ sometimes you don't know what it is :) The important thing is that you can use the text along with the title to uniquely identify a window to work with. When you specify the text parameter in a window function it is treated as a substring. So for the example above if you used the text "is some " you would get a match. What has been described is the default mode that AutoIt operates in, there are a number of more advanced modes to use when things are not as simple as this. Note: Hidden window can be matched by "title" only if "text" is empty (""). -------------------------------------------------------------------------------- *GUICtrlCreateAvi* +------------------+~ | GUICtrlCreateAvi |~ +------------------+~ Creates an AVI video control for the GUI. > GUICtrlCreateAvi ( filename, subfileid, left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ filename -------- The filename of the video. Only .avi files are supported. subfileid --------- id of the subfile to be used. If the file only contains one video then use -1. left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default is the previously used width). height ----- [optional] The height of the control (default is the previously used height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default (-1) : $ACS_TRANSPARENT $ACS_TRANSPARENT is always used unless $ACS_NONTRANSPARENT is specified. exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To obtain the value of the control see GUICtrlRead. To set or change information in the control see GUICtrlUpdate.... To start the video as soon as the control is created use the $ACS_AUTOPLAY style. You can can start and stop the animation by setting the state to 1 or 0 with GUICtrlSetState. See example. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_AVI, newstyle,...). To use the values specified above you must #include in your script. Default resizing is $GUI_DOCKSIZE. Related~ |GUICoordMode| (option), GUICtrlUpdate ..., |GUIGetMsg| Example~ > #include Opt('MustDeclareVars', 1) Example() Func Example() Local $ani1, $buttonstart, $buttonstop, $msg GUICreate("My GUI Animation", 300, 200) $ani1 = GUICtrlCreateAvi(@SystemDir & "\shell32.dll", 165, 50, 10) $buttonstart = GUICtrlCreateButton("start", 50, 150, 70, 22) $buttonstop = GUICtrlCreateButton("stop", 150, 150, 70, 22) GUISetState() ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() Select Case $msg = $GUI_EVENT_CLOSE ExitLoop Case $msg = $buttonstart GUICtrlSetState($ani1, 1) Case $msg = $buttonstop GUICtrlSetState($ani1, 0) EndSelect WEnd EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateButton* +---------------------+~ | GUICtrlCreateButton |~ +---------------------+~ Creates a Button control for the GUI. > GUICtrlCreateButton ( "text", left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ text ----- The text of the button control. left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default text autofit in width). height ------ [optional] The height of the control (default text autofit in height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : none. forced styles : $WS_TABSTOP exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To set or change information in the control see GUICtrlUpdate.... A Button control can display an icon or image by using the $BS_ICON or $BS_BITMAP style. Use GUICtrlSetImage to specify the picture to use. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_BUTTON, newstyle,...). To use the values specified above you must #include in your script. Default resizing is $GUI_DOCKSIZE Related~ GUICoordMode (Option), GUICtrlUpdate..., |GUIGetMsg| Example~ > #include Opt('MustDeclareVars', 1) Example() Func Example() Local $Button_1, $Button_2, $msg GUICreate("My GUI Button") ; will create a dialog box that when displayed is centered Opt("GUICoordMode", 2) $Button_1 = GUICtrlCreateButton("Run Notepad", 10, 30, 100) $Button_2 = GUICtrlCreateButton("Button Test", 0, -1) GUISetState() ; will display an dialog box with 2 button ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() Select Case $msg = $GUI_EVENT_CLOSE ExitLoop Case $msg = $Button_1 Run('Notepad.exe') ; Will Run/Open Notepad Case $msg = $Button_2 MsgBox(0, 'Testing', 'Button 2 was pressed') ; Will demonstrate Button 2 being pressed EndSelect WEnd EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateCheckbox* +-----------------------+~ | GUICtrlCreateCheckbox |~ +-----------------------+~ Creates a Checkbox control for the GUI. > GUICtrlCreateCheckbox ( "text", left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ text ----- The text of the control checkbox. left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default text autofit in width). height ------ [optional] The height of the control (default text autofit in height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : $BS_AUTOCHECKBOX. forced styles : $WS_TABSTOP, and $BS_AUTOCHECKBOX if no checkbox style defined. exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To obtain the value of the control see GUICtrlRead. To set or change information in the control see GUICtrlUpdate.... A Checkbox control can display an icon or image by using the $BS_ICON or $BS_BITMAP style. Use GUICtrlSetImage to specify the picture to use. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_CHECKBOX, newstyle,...). To use the values specified above you must #include in your script. Default resizing is $GUI_DOCKHEIGHT. Related~ GUICoordMode (Option), GUICtrlUpdateXXX, |GUIGetMsg| Example~ > #include Opt('MustDeclareVars', 1) Example() Func Example() Local $checkCN, $msg GUICreate("My GUI Checkbox") ; will create a dialog box that when displayed is centered $checkCN = GUICtrlCreateCheckbox("CHECKBOX 1", 10, 10, 120, 20) GUISetState() ; will display an dialog box with 1 checkbox ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateCombo* +--------------------+~ | GUICtrlCreateCombo |~ +--------------------+~ Creates a ComboBox control for the GUI. > GUICtrlCreateCombo ( "text", left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ text ----- The text which will appear in the combo control. left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default is the previously used width). height ------ [optional] The height of the control (default is the previously used height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default (-1) : $CBS_DROPDOWN, $CBS_AUTOHSCROLL, $WS_VSCROLL forced style : $WS_TABSTOP exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To obtain the value of the control see |GUICtrlRead| . To set or change information in the control see GUICtrlUpdate.... Under Windows XP/2003 Windows will adjust the size of the opened combo. On other Windows versions you can define this size with the "height" parameter if the default value is not BIG enough to contain at least one line. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_COMBO, newstyle,...). To use the values specified above you must #include in your script. Default resizing is $GUI_DOCKHEIGHT. Related~ GUICoordMode (Option), |GUICtrlSetData|, GUICtrlUpdateXXX, |GUIGetMsg| Example~ > #include Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("My GUI combo") ; will create a dialog box that when displayed is centered GUICtrlCreateCombo("item1", 10, 10) ; create first item GUICtrlSetData(-1, "item2|item3", "item3") ; add other item snd set a new default GUISetState() ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateContextMenu* +--------------------------+~ | GUICtrlCreateContextMenu |~ +--------------------------+~ Creates a context menu for a control or entire GUI window. > GUICtrlCreateContextMenu ( [controlID] ) < Parameters~ controlID --------- [optional] Control identifier as returned by GUICtrlCreate... Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ After creating the context menu main control with this function, each menu item can be created by using GUICtrlCreateMenuItem. Sub-menus can be created using GUICtrlCreateMenu. If you use no parameters or -1 in this function then the context menu that is created is associated with the entire GUI window rather than an individual control. Only one context menu per control is possible. If you wish to create a new context menu one you have to delete the existing menu first. Note: You can't create context menus for controls that already have system context menus, i.e. edit or input controls. Related~ |GUICtrlCreateMenuItem|, |GUICtrlCreateMenu|, |GUICtrlGetHandle|, |GUICtrlSetState|, |GUICtrlDelete| Example~ > #include #include Opt('MustDeclareVars', 1) Example1() Example2() ; **************** ; * First sample * ; **************** Func Example1() Local $contextmenu, $button, $buttoncontext, $buttonitem, $msg Local $newsubmenu, $textitem, $fileitem, $saveitem, $infoitem ;right click on gui to bring up context Menu. ;right click on the "ok" button to bring up a controll specific context menu. GUICreate("My GUI Context Menu", 300, 200) $contextmenu = GUICtrlCreateContextMenu() $button = GUICtrlCreateButton("OK", 100, 100, 70, 20) $buttoncontext = GUICtrlCreateContextMenu($button) $buttonitem = GUICtrlCreateMenuItem("About button", $buttoncontext) $newsubmenu = GUICtrlCreateMenu("new", $contextmenu) $textitem = GUICtrlCreateMenuItem("text", $newsubmenu) $fileitem = GUICtrlCreateMenuItem("Open", $contextmenu) $saveitem = GUICtrlCreateMenuItem("Save", $contextmenu) GUICtrlCreateMenuItem("", $contextmenu) ; separator $infoitem = GUICtrlCreateMenuItem("Info", $contextmenu) GUISetState() ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd GUIDelete() EndFunc ;==>Example1 ; ***************** ; * Second sample * ; ***************** Func Example2() Local $hGui, $OptionsBtn, $OptionsDummy, $OptionsContext, $OptionsCommon, $OptionsFile, $msg Local $OptionsExit, $HelpBtn, $HelpDummy, $HelpContext, $HelpWWW, $HelpAbout $hGui = GUICreate("My GUI", 170, 40) $OptionsBtn = GUICtrlCreateButton("&Options", 10, 10, 70, 20, $BS_FLAT) ; At first create a dummy control for the options and a contextmenu for it $OptionsDummy = GUICtrlCreateDummy() $OptionsContext = GUICtrlCreateContextMenu($OptionsDummy) $OptionsCommon = GUICtrlCreateMenuItem("Common", $OptionsContext) $OptionsFile = GUICtrlCreateMenuItem("File", $OptionsContext) GUICtrlCreateMenuItem("", $OptionsContext) $OptionsExit = GUICtrlCreateMenuItem("Exit", $OptionsContext) $HelpBtn = GUICtrlCreateButton("&Help", 90, 10, 70, 20, $BS_FLAT) ; Create a dummy control and a contextmenu for the help too $HelpDummy = GUICtrlCreateDummy() $HelpContext = GUICtrlCreateContextMenu($HelpDummy) $HelpWWW = GUICtrlCreateMenuItem("Website", $HelpContext) GUICtrlCreateMenuItem("", $HelpContext) $HelpAbout = GUICtrlCreateMenuItem("About...", $HelpContext) GUISetState() While 1 $msg = GUIGetMsg() Switch $msg Case $OptionsExit, $GUI_EVENT_CLOSE ExitLoop Case $OptionsBtn ShowMenu($hGui, $msg, $OptionsContext) Case $HelpBtn ShowMenu($hGui, $msg, $HelpContext) Case $HelpAbout MsgBox(64, "About...", "GUICtrlGetHandle-Sample") EndSwitch WEnd GUIDelete() EndFunc ;==>Example2 ; Show a menu in a given GUI window which belongs to a given GUI ctrl Func ShowMenu($hWnd, $CtrlID, $nContextID) Local $arPos, $x, $y Local $hMenu = GUICtrlGetHandle($nContextID) $arPos = ControlGetPos($hWnd, "", $CtrlID) $x = $arPos[0] $y = $arPos[1] + $arPos[3] ClientToScreen($hWnd, $x, $y) TrackPopupMenu($hWnd, $hMenu, $x, $y) EndFunc ;==>ShowMenu ; Convert the client (GUI) coordinates to screen (desktop) coordinates Func ClientToScreen($hWnd, ByRef $x, ByRef $y) Local $stPoint = DllStructCreate("int;int") DllStructSetData($stPoint, 1, $x) DllStructSetData($stPoint, 2, $y) DllCall("user32.dll", "int", "ClientToScreen", "hwnd", $hWnd, "ptr", DllStructGetPtr($stPoint)) $x = DllStructGetData($stPoint, 1) $y = DllStructGetData($stPoint, 2) ; release Struct not really needed as it is a local $stPoint = 0 EndFunc ;==>ClientToScreen ; Show at the given coordinates (x, y) the popup menu (hMenu) which belongs to a given GUI window (hWnd) Func TrackPopupMenu($hWnd, $hMenu, $x, $y) DllCall("user32.dll", "int", "TrackPopupMenuEx", "hwnd", $hMenu, "int", 0, "int", $x, "int", $y, "hwnd", $hWnd, "ptr", 0) EndFunc ;==>TrackPopupMenu < -------------------------------------------------------------------------------- *GUICtrlCreateDate* +-------------------+~ | GUICtrlCreateDate |~ +-------------------+~ Creates a date control for the GUI. > GUICtrlCreateDate ( "text", left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ text ----- The preselected date (always as "yyyy/mm/dd"). left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default is the previously used width). height ------ [optional] The height of the control (default is the previously used height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default (-1) : $DTS_LONGDATEFORMAT forced style : $WS_TABSTOP exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table. default (-1) : WS_EX_CLIENTEDGE Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To obtain the value of the control see GUICtrlRead. To set or change information in the control see GUICtrlUpdate.... To combine styles with the default style use BitOr($GUI_SS_DEFAULT_DATE, newstyle,...). To Format the date/time see example 3 to understand how to use a GuiCtrlSendMsg with a $DTM_SETFORMAT. To use the values specified above you must #include in your script. Default resizing is $GUI_DOCKHEIGHT. Related~ GUICoordMode (Option), |GUICtrlSetState|, |GUIGetMsg|, |GUICtrlRead| Example~ > #include #include Opt('MustDeclareVars', 1) Example1() Example2() Example3() Example4() ; example1 Func Example1() Local $date, $msg GUICreate("My GUI get date", 200, 200, 800, 200) $date = GUICtrlCreateDate("1953/04/25", 10, 10, 185, 20) GUISetState() ; Run the GUI until the dialog is closed Do $msg = GUIGetMsg() Until $msg = $GUI_EVENT_CLOSE MsgBox(0, "Date", GUICtrlRead($date)) GUIDelete() EndFunc ;==>Example1 ; example2 Func Example2() Local $n, $msg GUICreate("My GUI get date", 200, 200, 800, 200) $n = GUICtrlCreateDate("", 10, 10, 100, 20, $DTS_SHORTDATEFORMAT) GUISetState() ; Run the GUI until the dialog is closed Do $msg = GUIGetMsg() Until $msg = $GUI_EVENT_CLOSE MsgBox(0, "Date", GUICtrlRead($n)) GUIDelete() EndFunc ;==>Example2 ; example3 Func Example3() Local $date, $DTM_SETFORMAT_, $style GUICreate("My GUI get date", 200, 200, 800, 200) $date = GUICtrlCreateDate("1953/04/25", 10, 10, 185, 20) ; to select a specific default format $DTM_SETFORMAT_ = 0x1032 ; $DTM_SETFORMATW $style = "yyyy/MM/dd HH:mm:ss" GUICtrlSendMsg($date, $DTM_SETFORMAT_, 0, $style) GUISetState() While GUIGetMsg() <> $GUI_EVENT_CLOSE WEnd MsgBox(0, "Time", GUICtrlRead($date)) EndFunc ;==>Example3 ; example4 Func Example4() Local $n, $msg GUICreate("My GUI get time", 200, 200, 800, 200) $n = GUICtrlCreateDate("", 20, 20, 100, 20, $DTS_TIMEFORMAT) GUISetState() ; Run the GUI until the dialog is closed Do $msg = GUIGetMsg() Until $msg = $GUI_EVENT_CLOSE MsgBox(0, "Time", GUICtrlRead($n)) GUIDelete() EndFunc ;==>Example4 < -------------------------------------------------------------------------------- *GUICtrlCreateDummy* +--------------------+~ | GUICtrlCreateDummy |~ +--------------------+~ Creates a Dummy control for the GUI. > GUICtrlCreateDummy ( ) < Parameters~ None. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ This control can receive messages through a GUICtrlSendToDummy call. The control will "notify" as normal and the value sent with GUISendToDummy can be read with GUICtrlRead. Related~ |GUICtrlSendToDummy|, |GUICtrlSetOnEvent|, |GUICtrlRead|, |GUICtrlSetData| Example~ > #include Opt('MustDeclareVars', 1) Example() Func Example() Local $user, $button, $cancel, $msg GUICreate("GUICtrlCreateDummy", 250, 200, 100, 200) GUISetBkColor(0x00E0FFFF) ; will change background color $user = GUICtrlCreateDummy() $button = GUICtrlCreateButton("event", 75, 170, 70, 20) $cancel = GUICtrlCreateButton("Cancel", 150, 170, 70, 20) GUISetState() Do $msg = GUIGetMsg() Select Case $msg = $button GUICtrlSendToDummy($user) Case $msg = $cancel GUICtrlSendToDummy($user) Case $msg = $user ; special action before closing ; ... Exit EndSelect Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateEdit* +-------------------+~ | GUICtrlCreateEdit |~ +-------------------+~ Creates an Edit control for the GUI. > GUICtrlCreateEdit ( "text", left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ text ----- The text of the control. left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default is the previously used width). height ------ [optional] The height of the control (default is the previously used height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : $ES_WANTRETURN, $WS_VSCROLL, $WS_HSCROLL, $ES_AUTOVSCROLL, $ES_AUTOHSCROLL forced styles : $ES_MULTILINE, $WS_TABSTOP only if not $ES_READONLY exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To obtain the value of the control see GUICtrlRead. To set or change information in the control see GUICtrlUpdate.... To combine styles with the default style use BitOr($GUI_SS_DEFAULT_EDIT, newstyle,...). If you want to drag & drop a filename onto this control just add the WS_EX_ACCEPTFILES extended style on the GUICreate() and set the state to $GUI_DROPACCEPTED. Multiple selected files will be dropped as separate lines. To use the values specified above you must #include in your script. Default resizing is $GUI_DOCKAUTO size and position will occur. Creating a RichEdit control is too complex so it will not be included as a basic control. You have to use the GuiCtrlCreateObj. See the second example if you need to have a RichEdit control. Related~ GUICoordMode (Option), |GUICtrlSetData|, |GUICtrlSetState|, |GUICtrlSetLimit|, |GUIGetMsg|, |GUICtrlRead| Example~ > #include #include #include #include Opt('MustDeclareVars', 1) Global $oMyError Example() RichEditExample() Func Example() Local $myedit, $msg GUICreate("My GUI edit") ; will create a dialog box that when displayed is centered $myedit = GUICtrlCreateEdit("First line" & @CRLF, 176, 32, 121, 97, $ES_AUTOVSCROLL + $WS_VSCROLL) GUISetState() Send("{END}") ; will be append dont' forget 3rd parameter GUICtrlSetData($myedit, "Second line", 1) ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd GUIDelete() EndFunc ;==>Example ; Rich edit control EXAMPLE using GUICtrlCreateObj ; Author: Kåre Johansson ; AutoIt Version: 3.1.1.55 ; Description: Very Simple example: Embedding RICHTEXT object ; Needs: MSCOMCT2.OCX in system32 but it's probably already there ; Date: 3 jul 2005 Func RichEditExample() Local $oRP, $TagsPageC, $AboutC, $PrefsC, $StatC, $GUIActiveX, $msg $oMyError = ObjEvent("AutoIt.Error", "MyErrFunc") $oRP = ObjCreate("RICHTEXT.RichtextCtrl.1") GUICreate("Embedded RICHTEXT control Test", 320, 200, -1, -1, BitOR($WS_OVERLAPPEDWINDOW, $WS_CLIPSIBLINGS, $WS_CLIPCHILDREN)) $TagsPageC = GUICtrlCreateLabel('Visit Tags Page', 5, 180, 100, 15, $SS_CENTER) GUICtrlSetFont($TagsPageC, 9, 400, 4) GUICtrlSetColor($TagsPageC, 0x0000ff) GUICtrlSetCursor($TagsPageC, 0) $AboutC = GUICtrlCreateButton('About', 105, 177, 70, 20) $PrefsC = GUICtrlCreateButton('FontSize', 175, 177, 70, 20) $StatC = GUICtrlCreateButton('Plain Style', 245, 177, 70, 20) $GUIActiveX = GUICtrlCreateObj($oRP, 10, 10, 400, 260) GUICtrlSetPos($GUIActiveX, 10, 10, 300, 160) With $oRP; Object tag pool .OLEDrag() .Font = 'Arial' .text = "Hello - Au3 supports ActiveX components like the RICHTEXT thanks to SvenP" & @CRLF & 'Try write some text and quit to reload' ;.FileName = @ScriptDir & '\RichText.rtf' ;.BackColor = 0xff00 EndWith GUISetState();Show GUI While 1 $msg = GUIGetMsg() Select Case $msg = $GUI_EVENT_CLOSE $oRP.SaveFile(@ScriptDir & "\RichText.rtf", 0) ExitLoop Case $msg = $TagsPageC Run(@ComSpec & ' /c start http://www.myplugins.info/guids/typeinfo/typeinfo.php?clsid={3B7C8860-D78F-101B-B9B5-04021C009402}', '', @SW_HIDE) Case $msg = $AboutC $oRP.AboutBox() Case $msg = $PrefsC $oRP.SelFontSize = 12 Case $msg = $StatC $oRP.SelBold = False $oRP.SelItalic = False $oRP.SelUnderline = False $oRP.SelFontSize = 8 EndSelect WEnd GUIDelete() EndFunc ;==>RichEditExample Func MyErrFunc() MsgBox(0, "AutoItCOM Test", "We intercepted a COM Error !" & @CRLF & @CRLF & _ "err.description is: " & @TAB & $oMyError.description & @CRLF & _ "err.windescription:" & @TAB & $oMyError.windescription & @CRLF & _ "err.number is: " & @TAB & Hex($oMyError.number, 8) & @CRLF & _ "err.lastdllerror is: " & @TAB & $oMyError.lastdllerror & @CRLF & _ "err.scriptline is: " & @TAB & $oMyError.scriptline & @CRLF & _ "err.source is: " & @TAB & $oMyError.source & @CRLF & _ "err.helpfile is: " & @TAB & $oMyError.helpfile & @CRLF & _ "err.helpcontext is: " & @TAB & $oMyError.helpcontext _ , 5) ; Will automatically continue after 5 seconds Local $err = $oMyError.number If $err = 0 Then $err = -1 SetError($err) ; to check for after this function returns EndFunc ;==>MyErrFunc < -------------------------------------------------------------------------------- *GUICtrlCreateGraphic* +----------------------+~ | GUICtrlCreateGraphic |~ +----------------------+~ Creates a Graphic control for the GUI. > GUICtrlCreateGraphic ( left, top [, width [, height [, style]]] ) < Parameters~ left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default is the previously used width). height ------ [optional] The height of the control (default is the previously used height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : $SS_NOTIFY. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To draw in the control see |GUICtrlSetGraphic|. The border and background color can be set with GUICtrlSetBkColor and GUICtrlSetColor. Graphic control can be clicked so they should not overlap with other controls. If overlap is needed it is important to disable the graphic control : GuiCtrlSetState(-1,$GUI_DISABLE). This control cannot be resized due to fix graphic relative addressing creation but can be dock with GUICtrlSetResizing(). Related~ |GUICtrlSetGraphic|, |GUICtrlSetBkColor|, |GUICtrlSetColor|, |GUICtrlDelete|, GUICoordMode (Option), |GUICtrlSetStyle|, |GUICtrlSetResizing|, |GUIGetMsg| Example~ > #include #include Opt('MustDeclareVars', 1) Global $MAXGr = 6, $del Global $a[$MAXGr + 1] ; 0 and $MAXGr entries not used to allow GUICtrlDelete result Example() Func Example() Local $msg, $inc, $i CreateChild() $i = 1 $inc = 1 Do $msg = GUIGetMsg() If $msg = $del Then GUICtrlDelete($a[$i]) $i = $i + $inc If $i < 0 Or $i > $MAXGr Then Exit EndIf If $msg > 0 Then MsgBox(0, "clicked", $msg & @LF & $a[5], 2) Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example Func CreateChild() Local $child $child = GUICreate("My Draw") $del = GUICtrlCreateButton("Delete", 50, 165, 50) $a[1] = GUICtrlCreateGraphic(20, 50, 100, 100) GUICtrlSetBkColor(-1, 0xffffff) GUICtrlSetColor(-1, 0) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0xff0000, 0xff0000) GUICtrlSetGraphic(-1, $GUI_GR_PIE, 50, 50, 40, 30, 270) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0x00ff00, 0xffffff) GUICtrlSetGraphic(-1, $GUI_GR_PIE, 58, 50, 40, -60, 90) GUICtrlSetGraphic(-1, $GUI_GR_ELLIPSE, 100, 100, 50, 80) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0x00ff00, 0xc0c0ff) GUICtrlSetGraphic(-1, $GUI_GR_RECT, 350, 200, 50, 80) GUICtrlCreateLabel("label", 65, 100, 30) GUICtrlSetColor(-1, 0xff) $a[2] = GUICtrlCreateGraphic(220, 50, 100, 100) GUICtrlSetStyle(-1, $SS_NOTIFY) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0, 0xff) GUICtrlSetGraphic(-1, $GUI_GR_PIE, 50, 50, 40, 30, 270) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0x00ff00, 0xffffff) GUICtrlSetGraphic(-1, $GUI_GR_PIE, 58, 50, 40, -60, 90) $a[3] = GUICtrlCreateGraphic(220, 150, 100, 100, 0) GUICtrlSetBkColor(-1, 0xf08080) GUICtrlSetColor(-1, 0xff) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0xff00) GUICtrlSetGraphic(-1, $GUI_GR_RECT, 50, 50, 80, 80) $a[4] = GUICtrlCreateGraphic(20, 200, 80, 80) GUICtrlSetState(-1, $GUI_DISABLE) GUICtrlSetBkColor(-1, 0xffffff) GUICtrlSetGraphic(-1, $GUI_GR_MOVE, 10, 10) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0xff) GUICtrlSetGraphic(-1, $GUI_GR_LINE, 30, 40) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0xff00) GUICtrlSetGraphic(-1, $GUI_GR_LINE, 70, 70) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0xff0000) GUICtrlSetGraphic(-1, $GUI_GR_LINE, 10, 50) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0xffff00) GUICtrlSetGraphic(-1, $GUI_GR_LINE, 10, 10) $a[5] = GUICtrlCreateGraphic(150, 10, 50, 50, 0) GUICtrlSetBkColor(-1, 0xa0ffa0) GUICtrlSetGraphic(-1, $GUI_GR_MOVE, 20, 20) ; start point ; it is better to draw line and after point ; to avoid to switch color at each drawing GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0x0000ff) GUICtrlSetGraphic(-1, $GUI_GR_DOT, 30, 30) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0) GUICtrlSetGraphic(-1, $GUI_GR_LINE, 20, 40) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0xff0000) GUICtrlSetGraphic(-1, $GUI_GR_DOT, 25, 25) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0) GUICtrlSetGraphic(-1, $GUI_GR_LINE, 40, 40) GUICtrlSetGraphic(-1, $GUI_GR_DOT, 40, 40) GUISetState() EndFunc ;==>CreateChild < -------------------------------------------------------------------------------- *GUICtrlCreateGroup* +--------------------+~ | GUICtrlCreateGroup |~ +--------------------+~ Creates a Group control for the GUI. > GUICtrlCreateGroup ( "text", left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ text ----- The text of the control. left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default is the previously used width). height ------ [optional] The height of the control (default is the previously used height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : none. forced styles : $WS_GROUP, $BS_GROUPBOX. exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ----- Returns 0. Remarks~ A group control is the thin line you see around controls (usually only Radio button) that visually groups them together. Only one Radio button within a Group can be selected at once. If you want to have multiple groups without the visible line then you must use GUIStartGroup() to group your Radio buttons. To use the values specified above you must #include in your script. Default resizing is $GUI_DOCKAUTO size and position will occur. Related~ GUICoordMode (Option), |GUIStartGroup| Example~ > #include Opt('MustDeclareVars', 1) Example() Func Example() Local $radio_1, $radio_2, $msg GUICreate("My GUI group") ; will create a dialog box that when displayed is centered GUICtrlCreateGroup("Group 1", 190, 60, 90, 140) $radio_1 = GUICtrlCreateRadio("Radio 1", 210, 90, 50, 20) $radio_2 = GUICtrlCreateRadio("Radio 2", 210, 110, 60, 50) GUICtrlCreateGroup("", -99, -99, 1, 1) ;close group GUISetState() ; will display an empty dialog box ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateIcon* +-------------------+~ | GUICtrlCreateIcon |~ +-------------------+~ Creates an Icon control for the GUI. > GUICtrlCreateIcon ( filename, iconName, left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ filename -------- filename of the icon to be loaded. iconName -------- Icon name if the file contain multiple icon. Can be an ordinal name if negative number. Otherwise -1. left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default is 32). height ------ [optional] The height of the control (default is 32). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : $SS_NOTIFY forced styles : $WS_TABSTOP, $SS_ICON exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To set or change information in the control see GUICtrlUpdate.... To update the icon after the dialog box is displayed use |GUICtrlSetImage| iconID can reference the icon group number. Use a resource hacker to know the value. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_ICON, newstyle,...). To use the values specified above you must #include in your script. Default resizing is $GUI_DOCKSIZE. Passing a positive number will reference the string equivalent icon name. Passing a negative number causes 1-based "index" behaviour. Some Dll can have icon extracted just with negative numbers. Related~ GUICoordMode (Option), |GUICtrlSetImage|, GUICtrlUpdateXXX, |GUIGetMsg| Example~ > #include Opt('MustDeclareVars', 1) Example1() Example2() ;example1 --------------------------- Func Example1() Local $icon, $n1, $n2, $msg GUICreate(" My GUI Icons", 250, 250) $icon = GUICtrlCreateIcon("shell32.dll", 10, 20, 20) $n1 = GUICtrlCreateIcon(@WindowsDir & "\cursors\horse.ani", -1, 20, 40, 32, 32) $n2 = GUICtrlCreateIcon("shell32.dll", 7, 20, 75, 32, 32) GUISetState() ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd GUIDelete() EndFunc ;==>Example1 ; example2 --------------------------- Func Example2() Local $iOldOpt, $n1, $n2, $a, $b $iOldOpt = Opt("GUICoordMode", 1) GUICreate("My GUI icon Race", 350, 74, -1, -1) GUICtrlCreateLabel("", 331, 0, 1, 74, 5) $n1 = GUICtrlCreateIcon(@WindowsDir & "\cursors\dinosaur.ani", -1, 0, 0, 32, 32) $n2 = GUICtrlCreateIcon(@WindowsDir & "\cursors\horse.ani", -1, 0, 40, 32, 32) GUISetState(@SW_SHOW) Dim $a = 0, $b = 0 While ($a < 300) And ($b < 300) $a = $a + Int(Random(0, 1) + 0.5) $b = $b + Int(Random(0, 1) + 0.5) GUICtrlSetPos($n1, $a, 0) GUICtrlSetPos($n2, $b, 40) Sleep(20) WEnd Sleep(1000) Opt("GUICoordMode", $iOldOpt) EndFunc ;==>Example2 < -------------------------------------------------------------------------------- *GUICtrlCreateInput* +--------------------+~ | GUICtrlCreateInput |~ +--------------------+~ Creates an Input control for the GUI. > GUICtrlCreateInput ( "text", left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ text ----- The text of the control. left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default is the previously used width). height ----- [optional] The height of the control (default is the previously used height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : $ES_LEFT, $ES_AUTOHSCROLL forced styles : $WS_TABSTOP only if no $ES_READONLY. $ES_MULTILINE is always reset. exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To obtain the value of the control see |GUICtrlRead|. To set or change information in the control see GUICtrlUpdate.... For defining an input control for entering passwords (input is hidden with an asterisk) use the $ES_PASSWORD style. If you want to drag & drop a filename onto this control just add the WS_EX_ACCEPTFILES extended style on the GUICreate() and set the state to $GUI_DROPACCEPTED. After multiple drag and drop files on this control, you can retrieve the files name which are separated by "|" with GuiCtrlRead. To use the values specified above you must #include in your script. Default resizing is $GUI_DOCKHEIGHT. Related~ GUICoordMode (Option), GUICtrlUpdateXXX, |GUIGetMsg|, |GUICtrlRead|, |GUICtrlCreateUpdown|, |GUICtrlSetLimit| Example~ > #include Opt('MustDeclareVars', 1) Example() Func Example() Local $file, $btn, $msg GUICreate(" My GUI input acceptfile", 320, 120, @DesktopWidth / 2 - 160, @DesktopHeight / 2 - 45, -1, 0x00000018); WS_EX_ACCEPTFILES $file = GUICtrlCreateInput("", 10, 5, 300, 20) GUICtrlSetState(-1, $GUI_DROPACCEPTED) GUICtrlCreateInput("", 10, 35, 300, 20) ; will not accept drag&drop files $btn = GUICtrlCreateButton("Ok", 40, 75, 60, 20) GUISetState() $msg = 0 While $msg <> $GUI_EVENT_CLOSE $msg = GUIGetMsg() Select Case $msg = $btn ExitLoop EndSelect WEnd MsgBox(4096, "drag drop file", GUICtrlRead($file)) EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateLabel* +--------------------+~ | GUICtrlCreateLabel |~ +--------------------+~ Creates a static Label control for the GUI. > GUICtrlCreateLabel ( "text", left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ text ----- The text of the control. left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default text autofit in width). height ----- [optional] The height of the control (default text autofit in height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : none. forced styles : $SS_NOTIFY, $SS_LEFT exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To set or change information in the control see GUICtrlUpdate.... To combine styles with the default style use BitOr($GUI_SS_DEFAULT_LABEL, newstyle,...). To use the values specified above you must #include in your script. Default resizing is $GUI_DOCKAUTO size and position will occur. The extended style $GUI_WS_EX_PARENTDRAG can be used to allow the dragging of the parent window for windows that don't have a titlebar (no $WS_CAPTION style in GUICreate). To set the background to transparent, use GUICtrlSetBkColor(-1, $GUI_BKCOLOR_TRANSPARENT). Related~ GUICoordMode (Option), GUICtrlUpdateXXX, |GUIGetMsg| Example~ > #include Opt('MustDeclareVars', 1) Example() Func Example() Local $widthCell, $msg, $iOldOpt GUICreate("My GUI") ; will create a dialog box that when displayed is centered GUISetHelp("notepad") ; will run notepad if F1 is typed $iOldOpt = Opt("GUICoordMode", 2) $widthCell = 70 GUICtrlCreateLabel("Line 1 Cell 1", 10, 30, $widthCell) ; first cell 70 width GUICtrlCreateLabel("Line 2 Cell 1", -1, 0) ; next line GUICtrlCreateLabel("Line 3 Cell 2", 0, 0) ; next line and next cell GUICtrlCreateLabel("Line 3 Cell 3", 0, -1) ; next cell same line GUICtrlCreateLabel("Line 4 Cell 1", -3 * $widthCell, 0) ; next line Cell1 GUISetState() ; will display an empty dialog box ; Run the GUI until the dialog is closed Do $msg = GUIGetMsg() Until $msg = $GUI_EVENT_CLOSE $iOldOpt = Opt("GUICoordMode", $iOldOpt) EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateList* +-------------------+~ | GUICtrlCreateList |~ +-------------------+~ Creates a List control for the GUI. > GUICtrlCreateList ( "text", left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ text ----- The text of the control. left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default is the previously used width). height ----- [optional] The height of the control (default is the previously used height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : $LBS_SORT, $WS_BORDER, $WS_VSCROLL forced styles : $WS_TABSTOP, $LBS_NOTIFY exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To obtain the value of the control see GUICtrlRead. To set or change information in the control see GUICtrlUpdate.... The different list entries that can be selected can be set with GUICtrlSetData To limit horizontal scrolling use GUICtrlSetLimit To combine styles with the default style use BitOr($GUI_SS_DEFAULT_LIST, newstyle,...). To use the values specified above you must #include in your script. Default resizing is $GUI_DOCKAUTO size and position will occur. Related~ GUICoordMode (Option), |GUICtrlSetData|, |GUICtrlSetLimit|, GUICtrlUpdateXXX, |GUIGetMsg| Example~ > #include Opt('MustDeclareVars', 1) Example() Func Example() Local $MESSAGE = "The following buttons have been clicked" Local $add, $clear, $mylist, $close, $msg GUICreate("My GUI list") ; will create a dialog box that when displayed is centered $add = GUICtrlCreateButton("Add", 64, 32, 75, 25) $clear = GUICtrlCreateButton("Clear", 64, 72, 75, 25) $mylist = GUICtrlCreateList("buttons that have been clicked", 176, 32, 121, 97) GUICtrlSetLimit(-1, 200) ; to limit horizontal scrolling GUICtrlSetData(-1, $MESSAGE) $close = GUICtrlCreateButton("my closing button", 64, 160, 175, 25) GUISetState() $msg = 0 While $msg <> $GUI_EVENT_CLOSE $msg = GUIGetMsg() Select Case $msg = $add GUICtrlSetData($mylist, "You clicked button No1|") Case $msg = $clear GUICtrlSetData($mylist, "") Case $msg = $close MsgBox(0, "", "the closing button has been clicked", 2) Exit EndSelect WEnd EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateListView* +-----------------------+~ | GUICtrlCreateListView |~ +-----------------------+~ Creates a ListView control for the GUI. > GUICtrlCreateListView ( "text", left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ text ----- definition of columns heading. Each of them are separated with Opt("GUIDataSeparatorChar"). left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default is the previously used width). height ----- [optional] The height of the control (default is the previously used height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default (-1) : $LVS_SHOWSELALWAYS, $LVS_SINGLESEL forced style : $LVS_REPORT exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table or ListView Extended Style Table. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To add items to a ListView control use GUICtrlCreateListViewItem The ListView will appear by default as in the Explorer view "Details" (LVS_REPORT style is forced). You can control initial column size by padding blanks to the column heading definition. The column can be extend during the GUICtrlCreateListViewItem according to item size. Size of a column will be up to around 25 characters. No resizing will be done during an update by GUICtrlSetData. To create a ListView with Icon-, SmallIcon- or List-style just use after creation: GUICtrlSetStyle with the styles $LVS_ICON, $LVS_LIST or $LVS_SMALLICON. Sorting the list by clicking the column name (as in Explorer) is not currently implemented. To have the entire line visually selected use the extended style LVS_EX_FULLROWSELECT. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_LISTVIEW, newstyle,...). To use the values specified above you must #include in your script. The special flag $GUI_BKCOLOR_LV_ALTERNATE can be used with Listview control to give alternate background of the ListviewItems lines. The odd lines will get the color set by GUICtrlSetBkColor of the Listview control. The even lines will get the color set by GUICtrlSetBkColor of the ListviewItem control. Related~ |GUICtrlCreateListViewItem|, |GUICtrlRegisterListViewSort|, GUICoordMode (Option), |GUICtrlSetData|, |GUIGetMsg|, GUIDataSeparatorChar (Option) Example~ > #include #include Opt('MustDeclareVars', 1) Example() Func Example() Local $listview, $button, $item1, $item2, $item3, $input1, $msg GUICreate("listview items", 220, 250, 100, 200, -1, $WS_EX_ACCEPTFILES) GUISetBkColor(0x00E0FFFF) ; will change background color $listview = GUICtrlCreateListView("col1 |col2|col3 ", 10, 10, 200, 150);,$LVS_SORTDESCENDING) $button = GUICtrlCreateButton("Value?", 75, 170, 70, 20) $item1 = GUICtrlCreateListViewItem("item2|col22|col23", $listview) $item2 = GUICtrlCreateListViewItem("item1|col12|col13", $listview) $item3 = GUICtrlCreateListViewItem("item3|col32|col33", $listview) $input1 = GUICtrlCreateInput("", 20, 200, 150) GUICtrlSetState(-1, $GUI_DROPACCEPTED) ; to allow drag and dropping GUISetState() GUICtrlSetData($item2, "ITEM1") GUICtrlSetData($item3, "||COL33") GUICtrlDelete($item1) Do $msg = GUIGetMsg() Select Case $msg = $button MsgBox(0, "listview item", GUICtrlRead(GUICtrlRead($listview)), 2) Case $msg = $listview MsgBox(0, "listview", "clicked=" & GUICtrlGetState($listview), 2) EndSelect Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateListViewItem* +---------------------------+~ | GUICtrlCreateListViewItem |~ +---------------------------+~ Creates a ListView item. > GUICtrlCreateListViewItem ( "text", listviewID ) < Parameters~ text ----- subitemtext separated with Opt("GUIDataSeparatorChar"). listviewID ---------- controlID of the ListView control holding the item. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ This function creates the individual ListView items that can be selected. The items function as normal controls and can be set with GUICtrlSetData. Items can be deleted as with any other control by using GUICtrlDelete. ListView items can be dragged and drop into an Edit or Input control with a $GUI_DROPACCEPTED state. See GUICtrlCreateListView about resizing of the column. The special flag $GUI_BKCOLOR_LV_ALTERNATE can be used with Listview control to give alternate background of the ListviewItems lines. The odd lines will get the color set by GUICtrlSetBkColor of the Listview control. The even lines will get the color set by GUICtrlSetBkColor of the ListviewItem control. Related~ |GUICtrlCreateListView|, |GUICtrlSetData|, |GUICtrlSetState|, |GUICtrlDelete|, |GUIGetMsg|, |GUICtrlRead|, GUIDataSeparatorChar (Option) Example~ > #include #include Opt('MustDeclareVars', 1) Example() Func Example() Local $listview, $button, $item1, $item2, $item3, $input1, $msg GUICreate("listview items", 220, 250, 100, 200, -1, $WS_EX_ACCEPTFILES) GUISetBkColor(0x00E0FFFF) ; will change background color $listview = GUICtrlCreateListView("col1 |col2|col3 ", 10, 10, 200, 150);,$LVS_SORTDESCENDING) $button = GUICtrlCreateButton("Value?", 75, 170, 70, 20) $item1 = GUICtrlCreateListViewItem("item2|col22|col23", $listview) $item2 = GUICtrlCreateListViewItem("............item1|col12|col13", $listview) $item3 = GUICtrlCreateListViewItem("item3|col32|col33", $listview) $input1 = GUICtrlCreateInput("", 20, 200, 150) GUICtrlSetState(-1, $GUI_DROPACCEPTED) ; to allow drag and dropping GUISetState() GUICtrlSetData($item2, "|ITEM1") GUICtrlSetData($item3, "||COL33") GUICtrlDelete($item1) Do $msg = GUIGetMsg() Select Case $msg = $button MsgBox(0, "listview item", GUICtrlRead(GUICtrlRead($listview)), 2) Case $msg = $listview MsgBox(0, "listview", "clicked=" & GUICtrlGetState($listview), 2) EndSelect Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateMenu* +-------------------+~ | GUICtrlCreateMenu |~ +-------------------+~ Creates a Menu control for the GUI. > GUICtrlCreateMenu ( "submenutext" [, menuID [, menuentry]] ) < Parameters~ submenutext ----------- The submenu text. menuID ------ [optional] If defined, allows you to create a submenu in the referenced menu. If equal -1 it refers to first level menu. menuentry --------- [optional] Allows you to define the entry number to be created. The entries are numbered starting at 0. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To set or change information in the control see GUICtrlUpdate.... Related~ |GUICtrlSetState|, |GUIGetMsg|, |GUICtrlCreateMenuItem|, |GUICtrlGetHandle|, |GUICtrlCreateContextMenu| Example~ > #include #include Opt('MustDeclareVars', 1) Example() Func Example() Local $defaultstatus = "Ready", $status, $filemenu, $fileitem Local $helpmenu, $saveitem, $infoitem, $exititem, $recentfilesmenu Local $separator1, $viewmenu, $viewstatusitem, $okbutton, $cancelbutton Local $statuslabel, $msg, $file GUICreate("My GUI menu", 300, 200) $filemenu = GUICtrlCreateMenu("&File") $fileitem = GUICtrlCreateMenuItem("Open", $filemenu) GUICtrlSetState(-1, $GUI_DEFBUTTON) $helpmenu = GUICtrlCreateMenu("?") $saveitem = GUICtrlCreateMenuItem("Save", $filemenu) GUICtrlSetState(-1, $GUI_DISABLE) $infoitem = GUICtrlCreateMenuItem("Info", $helpmenu) $exititem = GUICtrlCreateMenuItem("Exit", $filemenu) $recentfilesmenu = GUICtrlCreateMenu("Recent Files", $filemenu, 1) $separator1 = GUICtrlCreateMenuItem("", $filemenu, 2) ; create a separator line $viewmenu = GUICtrlCreateMenu("View", -1, 1) ; is created before "?" menu $viewstatusitem = GUICtrlCreateMenuItem("Statusbar", $viewmenu) GUICtrlSetState(-1, $GUI_CHECKED) $okbutton = GUICtrlCreateButton("OK", 50, 130, 70, 20) GUICtrlSetState(-1, $GUI_FOCUS) $cancelbutton = GUICtrlCreateButton("Cancel", 180, 130, 70, 20) $statuslabel = GUICtrlCreateLabel($defaultstatus, 0, 165, 300, 16, BitOR($SS_SIMPLE, $SS_SUNKEN)) GUISetState() While 1 $msg = GUIGetMsg() If $msg = $fileitem Then $file = FileOpenDialog("Choose file...", @TempDir, "All (*.*)") If @error <> 1 Then GUICtrlCreateMenuItem($file, $recentfilesmenu) EndIf If $msg = $viewstatusitem Then If BitAND(GUICtrlRead($viewstatusitem), $GUI_CHECKED) = $GUI_CHECKED Then GUICtrlSetState($viewstatusitem, $GUI_UNCHECKED) GUICtrlSetState($statuslabel, $GUI_HIDE) Else GUICtrlSetState($viewstatusitem, $GUI_CHECKED) GUICtrlSetState($statuslabel, $GUI_SHOW) EndIf EndIf If $msg = $GUI_EVENT_CLOSE Or $msg = $cancelbutton Or $msg = $exititem Then ExitLoop If $msg = $infoitem Then MsgBox(0, "Info", "Only a test...") WEnd GUIDelete() EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateMenuItem* +-----------------------+~ | GUICtrlCreateMenuItem |~ +-----------------------+~ Creates a MenuItem control for the GUI. > GUICtrlCreateMenuItem ( "text", menuID [, menuentry [, menuradioitem]] ) < Parameters~ text ----- The text of the control. menuID ------ Allows you to create a submenu in the referenced menu. If equal -1 it refers to the first level menu. menuentry --------- [optional] Allows you to define the entry number to be created. The entries are numbered starting at 0. menuradioitem ------------- [optional] 0 (default) = create a normal menuitem, 1 = create a menuradioitem Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To set or change information in the control see GUICtrlUpdate.... If the Text parameter is a "" then a separator line is created. GUICtrlSetState can be used as for other controls. See example. Related~ GUICtrlUpdateXXX, |GUIGetMsg|, |GUICtrlCreateMenu|, |GUICtrlCreateContextMenu| Example~ > #include #include Opt('MustDeclareVars', 1) Example() Func Example() Local $defaultstatus, $status, $filemenu, $fileitem, $helpmenu, $saveitem Local $infoitem, $exititem, $recentfilesmenu, $separator1, $viewmenu Local $viewstatusitem, $okbutton, $cancelbutton, $statuslabel, $msg, $file GUICreate("My GUI menu", 300, 200) Global $defaultstatus = "Ready" Global $status $filemenu = GUICtrlCreateMenu("&File") $fileitem = GUICtrlCreateMenuItem("Open", $filemenu) GUICtrlSetState(-1, $GUI_DEFBUTTON) $helpmenu = GUICtrlCreateMenu("?") $saveitem = GUICtrlCreateMenuItem("Save", $filemenu) GUICtrlSetState(-1, $GUI_DISABLE) $infoitem = GUICtrlCreateMenuItem("Info", $helpmenu) $exititem = GUICtrlCreateMenuItem("Exit", $filemenu) $recentfilesmenu = GUICtrlCreateMenu("Recent Files", $filemenu, 1) $separator1 = GUICtrlCreateMenuItem("", $filemenu, 2) ; create a separator line $viewmenu = GUICtrlCreateMenu("View", -1, 1) ; is created before "?" menu $viewstatusitem = GUICtrlCreateMenuItem("Statusbar", $viewmenu) GUICtrlSetState(-1, $GUI_CHECKED) $okbutton = GUICtrlCreateButton("OK", 50, 130, 70, 20) GUICtrlSetState(-1, $GUI_FOCUS) $cancelbutton = GUICtrlCreateButton("Cancel", 180, 130, 70, 20) $statuslabel = GUICtrlCreateLabel($defaultstatus, 0, 165, 300, 16, BitOR($SS_SIMPLE, $SS_SUNKEN)) GUISetState() While 1 $msg = GUIGetMsg() If $msg = $fileitem Then $file = FileOpenDialog("Choose file...", @TempDir, "All (*.*)") If @error <> 1 Then GUICtrlCreateMenuItem($file, $recentfilesmenu) EndIf If $msg = $viewstatusitem Then If BitAND(GUICtrlRead($viewstatusitem), $GUI_CHECKED) = $GUI_CHECKED Then GUICtrlSetState($viewstatusitem, $GUI_UNCHECKED) GUICtrlSetState($statuslabel, $GUI_HIDE) Else GUICtrlSetState($viewstatusitem, $GUI_CHECKED) GUICtrlSetState($statuslabel, $GUI_SHOW) EndIf EndIf If $msg = $GUI_EVENT_CLOSE Or $msg = $cancelbutton Or $msg = $exititem Then ExitLoop If $msg = $infoitem Then MsgBox(0, "Info", "Only a test...") WEnd GUIDelete() EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateMonthCal* +-----------------------+~ | GUICtrlCreateMonthCal |~ +-----------------------+~ Creates a month calendar control for the GUI. > GUICtrlCreateMonthCal ( "text", left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ text ----- The preselected date (always as "yyyy/mm/dd"). left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default is the previously used width). height ------ [optional] The height of the control (default is the previously used height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default (-1) : none. forced style : $WS_TABSTOP exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table. default (-1) : WS_EX_CLIENTEDGE Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To obtain the value of the control see |GUICtrlRead|. Default resizing is $GUI_DOCKSIZE. Related~ GUICoordMode (Option), |GUIGetMsg|, |GUICtrlRead| Example~ > #include Opt('MustDeclareVars', 1) Example() Func Example() Local $Date, $msg GUICreate("Get date", 210, 190) $Date = GUICtrlCreateMonthCal("1953/03/25", 10, 10) GUISetState() ; Run the GUI until the dialog is closed or timeout Do $msg = GUIGetMsg() If $msg = $Date Then MsgBox(0, "debug", "calendar clicked") Until $msg = $GUI_EVENT_CLOSE MsgBox(0, $msg, GUICtrlRead($Date), 2) EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateObj* +------------------+~ | GUICtrlCreateObj |~ +------------------+~ Creates an ActiveX control in the GUI. > GUICtrlCreateObj ( ObjectVar, left, top [, width [, height ]] ) < Parameters~ ObjectVar --------- A variable pointing to a previously opened object left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default is the previously used width). height ----- [optional] The height of the control (default is the previously used height). Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ This function attempts to embed an 'ActiveX Control' or a 'Document Object' inside the GUI. Not every control can be embedded. They must at least support an 'IDispatch' interface. 'Document Objects' will only be visible if the Windows style $WS_CLIPCHILDREN has been used in GUICreate(). The GUI functions GUICtrlRead and GUICtrlSet have no effect on this control. The object can only be controlled using 'methods' or 'properties' on the $ObjectVar. Related~ |ObjCreate|, |ObjGet|, |ObjEvent|, |IsObj| Example~ > #include #include Opt('MustDeclareVars', 1) Example() ; Simple example: Embedding an Internet Explorer Object inside an AutoIt GUI ; ; See also: http://msdn.microsoft.com/workshop/browser/webbrowser/reference/objects/internetexplorer.asp Func Example() Local $oIE, $GUIActiveX, $GUI_Button_Back, $GUI_Button_Forward Local $GUI_Button_Home, $GUI_Button_Stop, $msg $oIE = ObjCreate("Shell.Explorer.2") ; Create a simple GUI for our output GUICreate("Embedded Web control Test", 640, 580, (@DesktopWidth - 640) / 2, (@DesktopHeight - 580) / 2, BitOR($WS_OVERLAPPEDWINDOW, $WS_CLIPSIBLINGS, $WS_CLIPCHILDREN)) $GUIActiveX = GUICtrlCreateObj ($oIE, 10, 40, 600, 360) $GUI_Button_Back = GUICtrlCreateButton("Back", 10, 420, 100, 30) $GUI_Button_Forward = GUICtrlCreateButton("Forward", 120, 420, 100, 30) $GUI_Button_Home = GUICtrlCreateButton("Home", 230, 420, 100, 30) $GUI_Button_Stop = GUICtrlCreateButton("Stop", 330, 420, 100, 30) GUISetState() ;Show GUI $oIE.navigate("http://www.autoitscript.com") ; Waiting for user to close the window While 1 $msg = GUIGetMsg() Select Case $msg = $GUI_EVENT_CLOSE ExitLoop Case $msg = $GUI_Button_Home $oIE.navigate("http://www.autoitscript.com") Case $msg = $GUI_Button_Back $oIE.GoBack Case $msg = $GUI_Button_Forward $oIE.GoForward Case $msg = $GUI_Button_Stop $oIE.Stop EndSelect WEnd GUIDelete() EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreatePic* +------------------+~ | GUICtrlCreatePic | ~ +------------------+~ Creates a Picture control for the GUI. > GUICtrlCreatePic ( filename, left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ filename -------- filename of the picture to be loaded : supported types BMP, JPG, GIF(but not animated). left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default is the previously used width). height ------ [optional] The height of the control (default is the previously used height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default (-1) : $SS_NOTIFY forced style : $SS_BITMAP exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0 if picture cannot be created. Remarks~ To set or change information in the control see GUICtrlUpdate.... To update the picture after the dialog box is displayed just use GUICtrlSetImage If you want to have a picture having the same size as the file content just use width=height=0. To have a transparent picture it is needed to create the GUI window with WS_EX_LAYERED extended style. The left-top pixel will be used as the transparency color. If several pictures are created the last picture is defining the transparent color. See example 2. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_PIC, newstyle,...). To use the values specified above you must #include in your script. Default resizing is $GUI_DOCKSIZE. If a picture is set as a background picture, as the other controls will overlap, it's important to disable the pic control and create it after the others controls: GuiCtrlSetState(-1,$GUI_DISABLE). This is not enough for Tab or Listview control which behave differently. In this case you need to create the picture with the $WS_CLIPSIBLINGS style, GuiCtrlSetState(-1,$GUI_ONTOP) is necessary for the Tab, TreeView or Listview control. The extended style $GUI_WS_EX_PARENTDRAG can be used to allow the dragging of the parent window for windows that don't have a titlebar (no $WS_CAPTION style in GUICreate). The background is always set to transparent. GUICtrlSetBkColor() has not effect on pic control. PNG can be used with GDI+. See example 3. Related~ GUICoordMode (Option), |GUICtrlSetImage|, GUICtrlUpdateXXX, |GUIGetMsg| Example~ > #include #include Opt('MustDeclareVars', 1) Global $gui, $guiPos, $pic, $picPos Example1() Example2() ;----- example 1 ---- Func Example1() Local $n, $msg GUICreate("My GUI picture", 350, 300, -1, -1, $WS_SIZEBOX + $WS_SYSMENU) ; will create a dialog box that when displayed is centered GUISetBkColor(0xE0FFFF) $n = GUICtrlCreatePic("..\GUI\mslogo.jpg", 50, 50, 200, 50) GUISetState() ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd ; resize the control $n = GUICtrlSetPos($n, 50, 50, 200, 100) ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd GUIDelete() EndFunc ;==>Example1 ;----- example 2 Func Example2() Local $msg $gui = GUICreate("test transparentpic", 200, 100) $pic = GUICreate("", 68, 71, 10, 20, $WS_POPUP, BitOR($WS_EX_LAYERED, $WS_EX_MDICHILD), $gui) GUICtrlCreatePic("..\GUI\merlin.gif", 0, 0, 0, 0) GUISetState(@SW_SHOW, $pic) GUISetState(@SW_SHOW, $gui) HotKeySet("{ESC}", "main") HotKeySet("{LEFT}", "left") HotKeySet("{RIGHT}", "right") HotKeySet("{DOWN}", "down") HotKeySet("{UP}", "up") $picPos = WinGetPos($pic) $guiPos = WinGetPos($gui) Do $msg = GUIGetMsg() Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example2 Func main() $guiPos = WinGetPos($gui) WinMove($gui, "", $guiPos[0] + 10, $guiPos[1] + 10) EndFunc ;==>main Func left() $picPos = WinGetPos($pic) WinMove($pic, "", $picPos[0] - 10, $picPos[1]) EndFunc ;==>left Func right() $picPos = WinGetPos($pic) WinMove($pic, "", $picPos[0] + 10, $picPos[1]) EndFunc ;==>right Func down() $picPos = WinGetPos($pic) WinMove($pic, "", $picPos[0], $picPos[1] + 10) EndFunc ;==>down Func up() $picPos = WinGetPos($pic) WinMove($pic, "", $picPos[0], $picPos[1] - 10) EndFunc ;==>up ;----- example 3 PNG work araund by Zedna #include #include #include #Include Global $hGUI, $hImage, $hGraphic, $hImage1 ; Create GUI $hGUI = GUICreate("Show PNG", 250, 250) ; Load PNG image _GDIPlus_StartUp() $hImage = _GDIPlus_ImageLoadFromFile("..\GUI\Torus.png") $hGraphic = _GDIPlus_GraphicsCreateFromHWND($hGUI) GUIRegisterMsg($WM_PAINT, "MY_WM_PAINT") GUISetState() ; Loop until user exits do until GUIGetMsg() = $GUI_EVENT_CLOSE ; Clean up resources _GDIPlus_GraphicsDispose($hGraphic) _GDIPlus_ImageDispose($hImage) _GDIPlus_ShutDown() ; Draw PNG image Func MY_WM_PAINT($hWnd, $Msg, $wParam, $lParam) _WinAPI_RedrawWindow($hGUI, 0, 0, $RDW_UPDATENOW) _GDIPlus_GraphicsDrawImage($hGraphic, $hImage, 0, 0) _WinAPI_RedrawWindow($hGUI, 0, 0, $RDW_VALIDATE) Return $GUI_RUNDEFMSG EndFunc < -------------------------------------------------------------------------------- *GUICtrlCreateProgress* +-----------------------+~ | GUICtrlCreateProgress |~ +-----------------------+~ Creates a Progress control for the GUI. > GUICtrlCreateProgress ( left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default is the previously used width). height ------ [optional] The height of the control (default is the previously used height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To obtain the value of the control see GUICtrlRead. To set or change information in the control see GUICtrlUpdate.... To update the bar position just use GUICtrlSetData. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_PROGRESS, newstyle,...). To use the values specified above you must #include in your script. Default resizing is $GUI_DOCKAUTO size and position will occur. Related~ GUICoordMode (Option), |GUICtrlSetData|, GUICtrlUpdateXXX, |GUIGetMsg| Example~ > #include #include Opt('MustDeclareVars', 1) Example() Func Example() Local $progressbar1, $progressbar2, $button, $wait, $s, $msg, $m GUICreate("My GUI Progressbar", 220, 100, 100, 200) $progressbar1 = GUICtrlCreateProgress(10, 10, 200, 20) GUICtrlSetColor(-1, 32250); not working with Windows XP Style $progressbar2 = GUICtrlCreateProgress(10, 40, 200, 20, $PBS_SMOOTH) $button = GUICtrlCreateButton("Start", 75, 70, 70, 20) GUISetState() $wait = 20; wait 20ms for next progressstep $s = 0; progressbar-saveposition Do $msg = GUIGetMsg() If $msg = $button Then GUICtrlSetData($button, "Stop") For $i = $s To 100 If GUICtrlRead($progressbar1) = 50 Then MsgBox(0, "Info", "The half is done...", 1) $m = GUIGetMsg() If $m = -3 Then ExitLoop If $m = $button Then GUICtrlSetData($button, "Next") $s = $i;save the current bar-position to $s ExitLoop Else $s = 0 GUICtrlSetData($progressbar1, $i) GUICtrlSetData($progressbar2, (100 - $i)) Sleep($wait) EndIf Next If $i > 100 Then ; $s=0 GUICtrlSetData($button, "Start") EndIf EndIf Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateRadio* +--------------------+~ | GUICtrlCreateRadio |~ +--------------------+~ Creates a Radio button control for the GUI. > GUICtrlCreateRadio ( "text", left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ text ----- The text of the control. left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default text autofit in width). height ------ [optional] The height of the control (default text autofit in height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : none. forced styles : $BS_AUTORADIOBUTTON and $WS_TABSTOP if first radio in the group. exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To obtain the value of the control see GUICtrlRead. To set or change information in the control see GUICtrlUpdate.... To combine styles with the default style use BitOr($GUI_SS_DEFAULT_RADIO, newstyle,...). To use the values specified above you must #include in your script. Default resizing is $GUI_DOCKHEIGHT. Related~ GUICoordMode (Option), GUICtrlUpdateXXX, |GUIGetMsg| Example~ > #include Opt('MustDeclareVars', 1) Example() Func Example() Local $radio1, $radio2, $msg GUICreate("My GUI radio") ; will create a dialog box that when displayed is centered $radio1 = GUICtrlCreateRadio("Radio 1", 10, 10, 120, 20) $radio2 = GUICtrlCreateRadio("Radio 2", 10, 40, 120, 20) GUICtrlSetState($radio2, $GUI_CHECKED) GUISetState() ; will display an dialog box with 1 checkbox ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() Select Case $msg = $GUI_EVENT_CLOSE ExitLoop Case $msg = $radio1 And BitAND(GUICtrlRead($radio1), $GUI_CHECKED) = $GUI_CHECKED MsgBox(64, 'Info:', 'You clicked the Radio 1 and it is Checked.') Case $msg = $radio2 And BitAND(GUICtrlRead($radio2), $GUI_CHECKED) = $GUI_CHECKED MsgBox(64, 'Info:', 'You clicked on Radio 2 and it is Checked.') EndSelect WEnd EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateSlider* +---------------------+~ | GUICtrlCreateSlider |~ +---------------------+~ Creates a Slider control for the GUI. > GUICtrlCreateSlider ( left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default is the previously used width). height ------ [optional] The height of the control (default is the previously used height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default (-1) : $TBS_AUTOTICKS exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To obtain the value of the control see GUICtrlRead. To set or change information in the control see GUICtrlUpdate.... To update the bar position just use GUICtrlSetData. To set the min and max value use GUICtrlSetLimit. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_SLIDER, newstyle,...). To use the values specified above you must #include in your script. Default resizing is $GUI_DOCKAUTO size and position will occur. Related~ GUICoordMode (Option), |GUICtrlSetData|, |GUICtrlSetLimit|, GUICtrlUpdateXXX, |GUIGetMsg| Example~ > #include Opt('MustDeclareVars', 1) Example() Func Example() Local $slider1, $button, $msg GUICreate("slider", 220, 100, 100, 200) GUISetBkColor(0x00E0FFFF) ; will change background color $slider1 = GUICtrlCreateSlider(10, 10, 200, 20) GUICtrlSetLimit(-1, 200, 0) ; change min/max value $button = GUICtrlCreateButton("Value?", 75, 70, 70, 20) GUISetState() GUICtrlSetData($slider1, 45) ; set cursor Do $msg = GUIGetMsg() If $msg = $button Then MsgBox(0, "slider1", GUICtrlRead($slider1), 2) EndIf Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateTab* +------------------+~ | GUICtrlCreateTab |~ +------------------+~ Creates a Tab control for the GUI. > GUICtrlCreateTab ( left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default is the previously used width). height ------ [optional] The height of the control (default is the previously used height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : none. forced styles : $WS_TABSTOP, $WS_CLIPSIBLINGS exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ This control is just a control in which the tabitem controls will be created and after the specific control related to a specific tabitem will be created with GUICtrlCreate... controls. To set or change information in the control see GUICtrlUpdate.... To combine styles with the default style use BitOr($GUI_SS_DEFAULT_TAB, newstyle,...). To use the value specified above you must #include in your script. Default resizing is $GUI_DOCKSIZE. ONLY one Tab control can be created by window. But a script can creates several windows having a tab in. Related~ |GUICtrlCreateTabItem|, GUICoordMode (Option), GUICtrlCreateXXX, GUICtrlUpdateXXX, |GUIGetMsg| Example~ > #include Opt('MustDeclareVars', 1) Example() Func Example() Local $tab, $tab0, $tab0OK, $tab0input Local $tab1, $tab1combo, $tab1OK Local $tab2, $tab2OK, $msg GUICreate("My GUI Tab") ; will create a dialog box that when displayed is centered GUISetBkColor(0x00E0FFFF) GUISetFont(9, 300) $tab = GUICtrlCreateTab(10, 10, 200, 100) $tab0 = GUICtrlCreateTabItem("tab0") GUICtrlCreateLabel("label0", 30, 80, 50, 20) $tab0OK = GUICtrlCreateButton("OK0", 20, 50, 50, 20) $tab0input = GUICtrlCreateInput("default", 80, 50, 70, 20) $tab1 = GUICtrlCreateTabItem("tab----1") GUICtrlCreateLabel("label1", 30, 80, 50, 20) $tab1combo = GUICtrlCreateCombo("", 20, 50, 60, 120) GUICtrlSetData(-1, "Trids|CyberSlug|Larry|Jon|Tylo", "Jon") ; default Jon $tab1OK = GUICtrlCreateButton("OK1", 80, 50, 50, 20) $tab2 = GUICtrlCreateTabItem("tab2") GUICtrlSetState(-1, $GUI_SHOW) ; will be display first GUICtrlCreateLabel("label2", 30, 80, 50, 20) $tab2OK = GUICtrlCreateButton("OK2", 140, 50, 50) GUICtrlCreateTabItem("") ; end tabitem definition GUICtrlCreateLabel("label3", 20, 130, 50, 20) GUISetState() ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateTabItem* +----------------------+~ | GUICtrlCreateTabItem |~ +----------------------+~ Creates a TabItem control for the GUI. > GUICtrlCreateTabItem ( "text" ) < Parameters~ text ----- The text of the control. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ For setting more information see GUICtrlUpdate.... To select a specific tabitem to be shown when the dialog box open just issue a GUICtrlSetState(-1,$GUI_SHOW) see example. To terminate the tab control just create a last "tabitem" control with a null text "". The "tabitem" control cannot be painted (too much code ...). When advanced mode is used, GUICtrlRead($tab,1) will return the controlID instead of index of the clicked tab item. To create a new control on an existing tabitem use GUISwitch($hWin,$tabitem) to select it and just create your new control. Don't forget to close your tabitem creation with GUICtrlCreateTabItem(""). Related~ |GUICtrlSetState|, |GUISwitch|, |GUIGetMsg|, |GUICtrlRead|, GUIEventOptions (Option), |GUICtrlCreateTab| Example~ > #include Opt('MustDeclareVars', 1) Example() Func Example() Local $tab, $tab0, $tab0OK, $tab0input Local $tab1, $tab1combo, $tab1OK Local $tab2, $tab2OK, $msg GUICreate("My GUI Tab", 250, 150); will create a dialog box that when displayed is centered GUISetBkColor(0x00E0FFFF) GUISetFont(9, 300) $tab = GUICtrlCreateTab(10, 10, 200, 100) $tab0 = GUICtrlCreateTabItem("tab0") GUICtrlCreateLabel("label0", 30, 80, 50, 20) $tab0OK = GUICtrlCreateButton("OK0", 20, 50, 50, 20) $tab0input = GUICtrlCreateInput("default", 80, 50, 70, 20) $tab1 = GUICtrlCreateTabItem("tab----1") GUICtrlCreateLabel("label1", 30, 80, 50, 20) $tab1combo = GUICtrlCreateCombo("", 20, 50, 60, 120) GUICtrlSetData(-1, "Trids|CyberSlug|Larry|Jon|Tylo", "Jon"); default Jon $tab1OK = GUICtrlCreateButton("OK1", 80, 50, 50, 20) $tab2 = GUICtrlCreateTabItem("tab2") GUICtrlSetState(-1, $GUI_SHOW); will be display first GUICtrlCreateLabel("label2", 30, 80, 50, 20) $tab2OK = GUICtrlCreateButton("OK2", 140, 50, 50) GUICtrlCreateTabItem(""); end tabitem definition GUICtrlCreateLabel("Click on tab and see the title", 20, 130, 250, 20) GUISetState() ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop If $msg = $tab Then ; display the clicked tab WinSetTitle("My GUI Tab", "", "My GUI Tab" & GUICtrlRead($tab)) EndIf WEnd EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlCreateTreeView* +-----------------------+~ | GUICtrlCreateTreeView |~ +-----------------------+~ Creates a TreeView control for the GUI. > GUICtrlCreateTreeView ( left, top [, width [, height [, style [, exStyle]]]] ) < Parameters~ left ----- The left side of the control. If -1 is used then left will be computed according to GUICoordMode. top ----- The top of the control. If -1 is used then top will be computed according to GUICoordMode. width ----- [optional] The width of the control (default is the previously used width). height ------ [optional] The height of the control (default is the previously used height). style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default (-1) : $TVS_HASBUTTONS, $TVS_HASLINES, $TVS_LINESATROOT, $TVS_DISABLEDRAGDROP, $TVS_SHOWSELALWAYS forced style : $WS_TABSTOP exStyle ------- [optional] Defines the extended style of the control. See Extended Style Table. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To set or change information in the control see GUICtrlUpdate.... To combine styles with the default style use BitOr($GUI_SS_DEFAULT_TREEVIEW, newstyle,...). To use the values specified above you must #include in your script. Related~ |GUICtrlCreateTreeViewItem|, GUICoordMode (Option), GUICtrlUpdateXXX, |GUIGetMsg|, |GUICtrlRead| Example~ > #include #include #include #include Opt('MustDeclareVars', 1) Example() Func Example() Local $treeview, $generalitem, $displayitem, $aboutitem, $compitem Local $useritem, $resitem, $otheritem, $startlabel, $aboutlabel, $compinfo Local $togglebutton, $infobutton, $statebutton, $cancelbutton Local $msg, $item, $hItem, $text GUICreate("My GUI with treeview", 350, 215) $treeview = GUICtrlCreateTreeView(6, 6, 100, 150, BitOR($TVS_HASBUTTONS, $TVS_HASLINES, $TVS_LINESATROOT, $TVS_DISABLEDRAGDROP, $TVS_SHOWSELALWAYS), $WS_EX_CLIENTEDGE) $generalitem = GUICtrlCreateTreeViewItem("General", $treeview) GUICtrlSetColor(-1, 0x0000C0) $displayitem = GUICtrlCreateTreeViewItem("Display", $treeview) GUICtrlSetColor(-1, 0x0000C0) $aboutitem = GUICtrlCreateTreeViewItem("About", $generalitem) $compitem = GUICtrlCreateTreeViewItem("Computer", $generalitem) $useritem = GUICtrlCreateTreeViewItem("User", $generalitem) $resitem = GUICtrlCreateTreeViewItem("Resolution", $displayitem) $otheritem = GUICtrlCreateTreeViewItem("Other", $displayitem) $startlabel = GUICtrlCreateLabel("TreeView Demo", 190, 90, 100, 20) $aboutlabel = GUICtrlCreateLabel("This little scripts demonstates the using of a treeview-control.", 190, 70, 100, 60) GUICtrlSetState(-1, $GUI_HIDE) ; Hides the "aboutlabel"-text during initialization $compinfo = GUICtrlCreateLabel("Name:" & @TAB & @ComputerName & @LF & "OS:" & @TAB & @OSVersion & @LF & "SP:" & @TAB & @OSServicePack, 120, 30, 200, 80) GUICtrlSetState(-1, $GUI_HIDE) ; Hides the "compinfo"-text during initialization GUICtrlCreateLabel("", 0, 170, 350, 2, $SS_SUNKEN) $togglebutton = GUICtrlCreateButton("&Toggle", 35, 185, 70, 20) $infobutton = GUICtrlCreateButton("&Info", 105, 185, 70, 20) $statebutton = GUICtrlCreateButton("Col./Exp.", 175, 185, 70, 20) $cancelbutton = GUICtrlCreateButton("&Cancel", 245, 185, 70, 20) GUICtrlSetState($generalitem, BitOR($GUI_EXPAND, $GUI_DEFBUTTON)) ; Expand the "General"-item and paint in bold GUICtrlSetState($displayitem, BitOR($GUI_EXPAND, $GUI_DEFBUTTON)) ; Expand the "Display"-item and paint in bold GUISetState() While 1 $msg = GUIGetMsg() Select Case $msg = $cancelbutton Or $msg = $GUI_EVENT_CLOSE ExitLoop Case $msg = $togglebutton ; Toggle the bold painting If BitAND(GUICtrlRead($generalitem), $GUI_DEFBUTTON) Then GUICtrlSetState($generalitem, 0) GUICtrlSetState($displayitem, 0) Else GUICtrlSetState($generalitem, $GUI_DEFBUTTON) GUICtrlSetState($displayitem, $GUI_DEFBUTTON) EndIf Case $msg = $infobutton $item = GUICtrlRead($treeview) ; Get the controlID of the current selected treeview item If $item = 0 Then MsgBox(64, "TreeView Demo", "No item currently selected") Else $text = GUICtrlRead($item, 1) ; Get the text of the treeview item If $text == "" Then MsgBox(16, "Error", "Error while retrieving infos about item") Else MsgBox(64, "TreeView Demo", "Current item selected is: " & $text) ; $advmsg[0] contains the text and $advmsg[1] the state value of the treeview item EndIf EndIf Case $msg = $statebutton $item = GUICtrlRead($treeview) If $item > 0 Then $hItem = GUICtrlGetHandle($item) GUICtrlSendMsg($treeview, $TVM_EXPAND, $TVE_TOGGLE, $hItem) EndIf ; The following items will hide the other labels (1st and 2nd parameter) and then show the 'own' labels (3rd and 4th parameter) Case $msg = $generalitem GUIChangeItems($aboutlabel, $compinfo, $startlabel, $startlabel) Case $msg = $aboutitem GUICtrlSetState($compinfo, $GUI_HIDE) GUIChangeItems($startlabel, $startlabel, $aboutlabel, $aboutlabel) Case $msg = $compitem GUIChangeItems($startlabel, $aboutlabel, $compinfo, $compinfo) EndSelect WEnd GUIDelete() EndFunc ;==>Example Func GUIChangeItems($hidestart, $hideend, $showstart, $showend) Local $idx For $idx = $hidestart To $hideend GUICtrlSetState($idx, $GUI_HIDE) Next For $idx = $showstart To $showend GUICtrlSetState($idx, $GUI_SHOW) Next EndFunc ;==>GUIChangeItems < -------------------------------------------------------------------------------- *GUICtrlCreateTreeViewItem* +---------------------------+~ | GUICtrlCreateTreeViewItem |~ +---------------------------+~ Creates a TreeViewItem control for the GUI. > GUICtrlCreateTreeViewItem ( "text", treeviewID ) < Parameters~ text ----- The text of the control. treeviewID ---------- treeview identifier as return by treeview or treeviewitem creation if subtree is created. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ For setting more information see GUICtrlUpdate.... To paint a treeview item in bold (to show as default) use GuiCtrlSetState($treeviewItem, $GUI_DEFBUTTON), to turn off this behaviour use GUICtrlSetState() with another value but $GUI_DEFBUTTON, for instance GuiCtrlSetState($treeviewItem, 0). To expand a treeview item use GuiCtrlSetState($treeviewItem, $GUI_EXPAND). To select a specific treeview item use GuiCtrlSetState($treeviewItem, $GUI_FOCUS). Related~ |GUICtrlCreateTreeView|, GUICtrlUpdateXXX, |GUIGetMsg|, |GUICtrlRead|, |GUICtrlGetHandle| Example~ > #include #include #include #include Opt('MustDeclareVars', 1) Example() Func Example() Local $treeview, $generalitem, $displayitem, $aboutitem, $compitem Local $useritem, $resitem, $otheritem, $startlabel, $aboutlabel Local $compinfo, $togglebutton, $infobutton, $statebutton, $cancelbutton Local $msg, $item, $text, $hItem GUICreate("My GUI with treeview", 350, 215) $treeview = GUICtrlCreateTreeView(6, 6, 100, 150, BitOR($TVS_HASBUTTONS, $TVS_HASLINES, $TVS_LINESATROOT, $TVS_DISABLEDRAGDROP, $TVS_SHOWSELALWAYS), $WS_EX_CLIENTEDGE) $generalitem = GUICtrlCreateTreeViewItem("General", $treeview) GUICtrlSetColor(-1, 0x0000C0) $displayitem = GUICtrlCreateTreeViewItem("Display", $treeview) GUICtrlSetColor(-1, 0x0000C0) $aboutitem = GUICtrlCreateTreeViewItem("About", $generalitem) $compitem = GUICtrlCreateTreeViewItem("Computer", $generalitem) $useritem = GUICtrlCreateTreeViewItem("User", $generalitem) $resitem = GUICtrlCreateTreeViewItem("Resolution", $displayitem) $otheritem = GUICtrlCreateTreeViewItem("Other", $displayitem) $startlabel = GUICtrlCreateLabel("TreeView Demo", 190, 90, 100, 20) $aboutlabel = GUICtrlCreateLabel("This little scripts demonstates the using of a treeview-control.", 190, 70, 100, 60) GUICtrlSetState(-1, $GUI_HIDE) ; Hides the "aboutlabel"-text during initialization $compinfo = GUICtrlCreateLabel("Name:" & @TAB & @ComputerName & @LF & "OS:" & @TAB & @OSVersion & @LF & "SP:" & @TAB & @OSServicePack, 120, 30, 200, 80) GUICtrlSetState(-1, $GUI_HIDE) ; Hides the "compinfo"-text during initialization GUICtrlCreateLabel("", 0, 170, 350, 2, $SS_SUNKEN) $togglebutton = GUICtrlCreateButton("&Toggle", 35, 185, 70, 20) $infobutton = GUICtrlCreateButton("&Info", 105, 185, 70, 20) $statebutton = GUICtrlCreateButton("Col./Exp.", 175, 185, 70, 20) $cancelbutton = GUICtrlCreateButton("&Cancel", 245, 185, 70, 20) GUICtrlSetState($generalitem, BitOR($GUI_EXPAND, $GUI_DEFBUTTON)) ; Expand the "General"-item and paint in bold GUICtrlSetState($displayitem, BitOR($GUI_EXPAND, $GUI_DEFBUTTON)) ; Expand the "Display"-item and paint in bold GUISetState() While 1 $msg = GUIGetMsg() Select Case $msg = $cancelbutton Or $msg = $GUI_EVENT_CLOSE ExitLoop Case $msg = $togglebutton ; Toggle the bold painting If BitAND(GUICtrlRead($generalitem), $GUI_DEFBUTTON) Then GUICtrlSetState($generalitem, 0) GUICtrlSetState($displayitem, 0) Else GUICtrlSetState($generalitem, $GUI_DEFBUTTON) GUICtrlSetState($displayitem, $GUI_DEFBUTTON) EndIf Case $msg = $infobutton $item = GUICtrlRead($treeview) ; Get the controlID of the current selected treeview item If $item = 0 Then MsgBox(64, "TreeView Demo", "No item currently selected") Else $text = GUICtrlRead($item, 1) ; Get the text of the treeview item If $text == "" Then MsgBox(16, "Error", "Error while retrieving infos about item") Else MsgBox(64, "TreeView Demo", "Current item selected is: " & $text) EndIf EndIf Case $msg = $statebutton $item = GUICtrlRead($treeview) If $item > 0 Then $hItem = GUICtrlGetHandle($item) DllCall("user32.dll", "int", "SendMessage", "hwnd", GUICtrlGetHandle($treeview), "int", $TVM_EXPAND, "int", $TVE_TOGGLE, "hwnd", $hItem) EndIf ; The following items will hide the other labels (1st and 2nd parameter) and then show the 'own' labels (3rd and 4th parameter) Case $msg = $generalitem GUIChangeItems($aboutlabel, $compinfo, $startlabel, $startlabel) Case $msg = $aboutitem GUICtrlSetState($compinfo, $GUI_HIDE) GUIChangeItems($startlabel, $startlabel, $aboutlabel, $aboutlabel) Case $msg = $compitem GUIChangeItems($startlabel, $aboutlabel, $compinfo, $compinfo) EndSelect WEnd GUIDelete() EndFunc ;==>Example Func GUIChangeItems($hidestart, $hideend, $showstart, $showend) Local $idx For $idx = $hidestart To $hideend GUICtrlSetState($idx, $GUI_HIDE) Next For $idx = $showstart To $showend GUICtrlSetState($idx, $GUI_SHOW) Next EndFunc ;==>GUIChangeItems < -------------------------------------------------------------------------------- *GUICtrlCreateUpdown* +---------------------+~ | GUICtrlCreateUpdown |~ +---------------------+~ Creates an UpDown control for the GUI. > GUICtrlCreateUpdown ( inputcontrolID [,style] ) < Parameters~ inputcontrolID -------------- The controlID of the input control in which the updown control will be created. style ----- [optional] Defines the style of the control. See GUI Control Styles Appendix. default (-1) : $UDS_ALIGNRIGHT. forced style : $UDS_SETBUDDYINT and $UDS_ALIGNRIGHT if no align defined. Return Value~ Success ------- Returns the identifier (controlID) of the new control. Failure ------- Returns 0. Remarks~ To use the values specified above you must #include in your script. Max and min value can be set with GUICtrlSetLimit. By default Windows increases the value when clicking the upper arrow button. Default height resizing is done according to the one of the related input control. Related~ |GUICtrlCreateInput|, |GUICtrlSetData|, |GUICtrlSetLimit| Example~ > #include #include Opt('MustDeclareVars', 1) Example() Func Example() Local $title, $input, $updown, $msg $title = "My GUI UpDown" GUICreate($title, -1, -1, -1, -1, $WS_SIZEBOX) $input = GUICtrlCreateInput("2", 10, 10, 50, 20) $updown = GUICtrlCreateUpdown($input) ; Attempt to resize input control GUICtrlSetPos($input, 10, 10, 100, 40) GUISetState() ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd MsgBox(0, "Updown", GUICtrlRead($input)) EndFunc ;==>Example < -------------------------------------------------------------------------------- *GUICtrlDelete* +---------------+~ | GUICtrlDelete |~ +---------------+~ Deletes a control. > GUICtrlDelete ( controlID ) < Parameters~ controlID ----- The control identifier (controlID) as returned by a GUICtrlCreate... function. Return Value~ Success ------- Returns 1. Failure ------- Returns 0. Remarks~ For context menu controls see GUICtrlCreateContextMenu remarks. Related~ |GUICreate|, GUICtrlCreateXXX, |GUICtrlCreateContextMenu| Example~ > #include Opt('MustDeclareVars', 1) Example() Func Example() Local $date, $del, $msg GUICreate("My GUI delete control", 200, 200, 800, 200) $date = GUICtrlCreateDate("1953/04/25", 10, 10, 185, 20) $del = GUICtrlCreateButton("Delete control", 50, 50, 70, 20) GUISetState() ; Run the GUI until the dialog is closed Do $msg = GUIGetMsg() If $msg = $del Then GUICtrlDelete($date) GUICtrlDelete($del) EndIf Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example < -------------------------------------------------------------------------------- *_IE_Example* +-------------+~ | _IE_Example |~ +-------------+~ Display a new browser window pre-loaded with documents to be used in IE.au3 examples or your own testing > #include _IE_Example ( [$s_module = "basic"] ) < Parameters~ $s_module --------- [optional] specifies which module to run basic = (Default) simple HTML page with text, links and images form = simple HTML page with multiple form elements frameset = simple HTML page with frames iframe = simple HTML page with iframes table = simple HTML page with tables Return Value~ Success ------- Returns an object variable pointing to an InternetExplorer.Application object Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 5 ($_IEStatus_InvalidValue) = Invalid Value @Extended: Contains invalid parameter number Remarks~ This function displays browser windows pre-populated with HTML and HTML elements that are used throughout the helpfile and IE.au3 examples. You are also encouraged to use them to experiment with the IE.au3 function set. Related~ |_IE_Introduction| Example~ > ; ******************************************************* ; Example 1 - Create browser windows with each of the example pages displayed. ; The object variable returned can be used just as the object ; variables returned by _IECreate or _IEAttach ; ******************************************************* ; #include $oIE_basic = _IE_Example ("basic") $oIE_form = _IE_Example ("form") $oIE_table = _IE_Example ("table") $oIE_frameset = _IE_Example ("frameset") $oIE_iframe = _IE_Example ("iframe") < -------------------------------------------------------------------------------- *_IE_Introduction* +------------------+~ | _IE_Introduction |~ +------------------+~ Display introductory information about IE.au3 in a new browser window > #include _IE_Introduction ( [$s_module = "basic"] ) < Parameters~ $s_module [optional] specifies which module to run basic = (Default) basic introduction Return Value~ Success ------- Returns an object variable pointing to an InternetExplorer.Application object Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 5 ($_IEStatus_InvalidValue) = Invalid Value @Extended: Contains invalid parameter number Remarks~ The AutoIt Helpfile does not currently allow UDFs to have general documentation that covers a series of functions, but rather UDF documentation is focused on individual functions. This function is intended to provide that general documentation. It will grow over time. Related~ |_IE_Example| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the basic IE.au3 introductory text displayed ; ******************************************************* ; #include $oIE = _IE_Introduction ("basic") < -------------------------------------------------------------------------------- *_IE_VersionInfo* +-----------------+~ | _IE_VersionInfo |~ +-----------------+~ Returns an array of information about the IE.au3 version > #include _IE_VersionInfo ( ) < Parameters~ None. Return Value~ Success ------- Returns an array ($IEAU3VersionInfo) $IEAU3VersionInfo[0] = Release Type (T=Test or V=Production) $IEAU3VersionInfo[1] = Major Version $IEAU3VersionInfo[2] = Minor Version $IEAU3VersionInfo[3] = Sub Version $IEAU3VersionInfo[4] = Release Date (YYYYMMDD) $IEAU3VersionInfo[5] = Display Version (e.g. V2.1-0) Failure ------- None Remarks~ The array contents make it easy to determine of the UDF version is higher or lower than a required version. Related~ None. Example~ > ; ******************************************************* ; Example 1 - Retrieve and display IE.au3 version information ; ******************************************************* ; #include $aVersion = _IE_VersionInfo () MsgBox(0, "IE.au3 Version", $aVersion[5] & " released " & $aVersion[4]) < -------------------------------------------------------------------------------- *_IEAction* +-----------+~ | _IEAction |~ +-----------+~ Perform any of a set of simple actions on the Browser. > #include _IEAction ( ByRef $o_object, $s_action ) < Parameters~ $o_object Object variable of an InternetExplorer.Application $s_action Action selection (see remarks) Return Value~ Success ------- Returns 1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 5 ($_IEStatus_InvalidValue) = Invalid Value @Extended: Contains invalid parameter number Remarks~ Action Description "back" Navigates backward one item in the history list. "blur" Causes the element to lose focus, but does not set focus on the next element in the tab order. "click" Simulates a click on the specified element. "copy" Copies the current selection to the clipboard. "cut" Copies the current selection to the clipboard and then deletes it. "delete" Deletes the current selection. "disable" Disables the specified element. "enable" Enables the specified element. "focus" Causes the element to receive focus. "forward" Navigates forward one item in the history list. "home" Navigates to the current home or start page. "invisible" Sets an object state to hidden. "paste" Overwrites the contents of the clipboard on the current selection. "print" Opens the print dialog box so the user can print the current page. "printdefault" Print directly to default printer (no dialog) "quit" Closes the object. "refresh" Refreshes the current document. "saveas" Opens a dialog box to save the current Web page to a file. "search" Navigates to the current search page. "selectall" Selects the entire document. "stop" Cancels any pending navigation or download operation and stops any dynamic page elements, such as background sounds and animations. "unselect" Clears the current selection. "visible" Sets an object state to visible. Related~ |_IEPropertySet|, |_IELoadWait| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the "form" example, get a reference ; to the submit button by name and "click" it. This technique ; of submitting forms is useful because many forms rely on JavaScript ; code and "onClick" events on their submit button making _IEFormSubmit() ; not perform as expected ; ******************************************************* ; #include $oIE = _IE_Example ("form") $oSubmit = _IEGetObjByName ($oIE, "submitExample") _IEAction ($oSubmit, "click") _IELoadWait ($oIE) ; ******************************************************* ; Example 2 - Same as Example 1, except instead of using click, give the element focus ; and then use ControlSend to send Enter. Use this technique when the ; browser-side scripting associated with a click action prevents control ; from being automatically returned to your code. ; ******************************************************* ; #include $oIE = _IE_Example ("form") $oSubmit = _IEGetObjByName ($oIE, "submitExample") $hwnd = _IEPropertyGet($oIE, "hwnd") _IEAction ($oSubmit, "focus") ControlSend($hwnd, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "{Enter}") ; Wait for Alert window, then click on OK WinWait("Windows Internet Explorer", "ExampleFormSubmitted") ControlClick("Windows Internet Explorer", "ExampleFormSubmitted", "[CLASS:Button; TEXT:OK; Instance:1;]") _IELoadWait ($oIE) < -------------------------------------------------------------------------------- *_IEAttach* +-----------+~ | _IEAttach |~ +-----------+~ Attach to the specified instance of Internet Explorer where the search string sub-string matches (based on the selected mode). > #include _IEAttach ( $s_string [, $s_mode = "Title" [, $i_instance = 1]] ) < Parameters~ $s_string --------- String to search for (for "embedded" or "dialogbox", use Title sub-string or HWND of window) $s_mode ------- [optional] specifies search mode Title = (Default) sub-string of main document title WindowTitle = sub-string of full window title (instead of document title) URL = sub-string or url of the current page Text = sub-string in text from the body of the current page HTML = sub-string in html from the body of the current page HWND = hwnd of the browser window Embedded = title sub-string or hwnd of of the window embedding the control DialogBox = title sub-string or hwnd of modal/modeless dialogbox Instance = $s_string is ignored, one browser reference returned (by matching instance number) from all available browser instances $i_instance ----------- [optional] 1-based index into group of browsers or embedded browsers matching $s_string and $s_mode. See Remarks. Return Value~ Success ------- Returns an object variable pointing to the InternetExplorer Object for all but Embedded and DislogBox modes which return a Window Object Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 5 ($_IEStatus_InvalidValue) = Invalid Value 7 ($_IEStatus_NoMatch) = No Match @Extended: Contains invalid parameter number Remarks~ _IEAttach provides the "dialogbox" parameter to attach to modal and modeless dialogs created by the browser. It is important to note that not all dialogs created through browser interaction can be attached to and controlled in this way. Many of these dialogs are actually standard windows and can be controlled through the traditional AutoIt window functions. A reliable way to tell the difference between these types of windows is to use the "AutoIt Window Info" tool to examine it -- if the window contains a control called "Internet Explorer_Server" then you can attach to it with this function, if it does not it is a standard window and traditional AutoIt windows functions must be used to control it. HyperTextApplication (.hta) windows may be attached to using the "embedded" option. The advanced Window Title selection syntax available to the standard Win* functions may be used in place of a title sub-string for the modes "dialogbox" and "embedded". Use of "$i_instance" with the "embedded" mode: used to return a reference to a specific instance of a WebBrowser and is particularly useful when more than one exists in a particular window. If you pass a window title in $s_string using embedded mode, only the first window matching that title will be used. If the WebBrowser control you desire is in another window you must pass the HWnd of that window rather than the title, or use the advanced Window Title selection syntax available to the standard Win* functions. Use of "$i_instance" with all modes other than "embedded": used to return a browser reference from a groups of all windows that match the criteria from $s_string and $s_mode. Instance order for DialogBox mode determined by the order returned by WinList() matching the title. For all other modes the Instance order is determined by the Shell.Windows collection. "$i_instance" values > 1 are set to 1 and a warning message is displayed when used with "hwnd" mode or with "DialogBox" mode when an HWnd is passed in $s_string. DialogBox and Embedded modes can be used to attach to standard browser windows, but the object returned is that if the top level Window in the browser and not the InternetExplorer object. Window objects do not offer access to all of the attributes of the InternetExplorer object (e.g. status text, address bar etc.). As well, if you attempt to use a function like _IENavigate on such an object you may receive COM errors due to the way that IE7 has implemented Tabs. It may be useful to find browser instances in this way, but it is recommended that you immediately use _IEAttach using one of the other modes and using information that you may have obtained from the Window object in order to get a reference to the associated InternetExplorer object. Related~ |_IECreate|, |_IECreateEmbedded|, |_IEQuit| Example~ > ; ******************************************************* ; Example 1 - Attach to a browser with "AutoIt" in its title, display the URL ; ******************************************************* ; #include $oIE = _IEAttach ("AutoIt") MsgBox(0, "The URL", _IEPropertyGet ($oIE, "locationurl")) ; ******************************************************* ; Example 2 - Attach to a browser with "The quick brown fox" ; in the text of it's top-level document ; ******************************************************* ; #include $oIE = _IEAttach ("The quick brown fox", "text") ; ******************************************************* ; Example 3 - Attach to a browser control embedded in another window ; ******************************************************* ; #include $oIE = _IEAttach ("A Window Title", "embedded") ; ******************************************************* ; Example 4 - Attach to the 3rd browser control embedded in another window ; Use the advanced window title syntax to use the 2nd window ; with the string 'ICQ' in the title ; ******************************************************* ; #include $oIE = _IEAttach ("[REGEXPTITLE:ICQ; INSTANCE:2]", "embedded", 3) ; ******************************************************* ; Example 5 - Create an array of object references to all current browser instances ; The first array element will contain the number of instances found ; ******************************************************* ; #include Dim $aIE[1] $aIE[0] = 0 $i = 1 While 1 $oIE = _IEAttach ("", "instance", $i) If @error = $_IEStatus_NoMatch Then ExitLoop ReDim $aIE[$i + 1] $aIE[$i] = $oIE $aIE[0] = $i $i += 1 WEnd MsgBox(0, "Browsers Found", "Number of browser instances in the array: " & $aIE[0]) < -------------------------------------------------------------------------------- *_IEBodyReadHTML* +-----------------+~ | _IEBodyReadHTML |~ +-----------------+~ Returns the HTML inside the tag of the document. > #include _IEBodyReadHTML ( ByRef $o_object ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window or Frame object Return Value~ Success ------- Returns HTML included in the of the document Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type @Extended: Contains invalid parameter number Remarks~ This function uses the .innerHTML property of the document Body. .innerHTML is available for nearly all DOM elements using _IEPropertyGet. Related~ |_IEBodyReadText|, |_IEBodyWriteHTML|, |_IEPropertyGet|, |_IEDocInsertHTML|, |_IEDocInsertText|, |_IEDocReadHTML| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the basic example, ready the body HTML, ; append new HTML to the original and write it back to the browser ; ******************************************************* ; #include $oIE = _IE_Example ("basic") $sHTML = _IEBodyReadHTML ($oIE) $sHTML = $sHTML & "

Big RED text!" _IEBodyWriteHTML ($oIE, $sHTML) < -------------------------------------------------------------------------------- *_IEBodyReadText* +-----------------+~ | _IEBodyReadText |~ +-----------------+~ Returns the Text inside the tag of the document. > #include _IEBodyReadText ( ByRef $o_object ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window or Frame object Return Value~ Success ------- Returns the Text included in the of the document Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type @Extended: Contains invalid parameter number Remarks~ This function uses the .innerText property of the document Body. .innerText is available for nearly all DOM elements and is a fast convenient method of parsing out just the text in a document using _IEPropertyGet. Related~ |_IEBodyReadHTML|, |_IEBodyWriteHTML|, |_IEPropertyGet| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the basic example, read the body Text ; (the content with all HTML tags removed) and display it in a MsgBox ; ******************************************************* ; #include $oIE = _IE_Example ("basic") $sText = _IEBodyReadText ($oIE) MsgBox(0, "Body Text", $sText) < -------------------------------------------------------------------------------- *_IEBodyWriteHTML* +------------------+~ | _IEBodyWriteHTML |~ +------------------+~ Replaces the HTML inside the tag of the document. > #include _IEBodyWriteHTML ( ByRef $o_object, $s_html ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window or Frame object $s_html ------- The HTML string to write to the document Return Value~ Success ------- Returns -1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 1 ($_IEStatus_GeneralError) = General Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 6 ($_IEStatus_LoadWaitTimeout) = Load Wait Timeout 8 ($_IEStatus_AccessIsDenied) = Access Is Denied 9 ($_IEStatus_ClientDisconnected) = Client Disconnected @Extended: Contains invalid parameter number Remarks~ You may use _IEBodyReadHTML to read the current HTML contents of the document body, manipulat that string and then write it back with _IEBodyWriteHTML. You may also use _IEDocInsertHTML, _IEDocInsertText and the innerHTML, innerText, outerHTML and outerText features of _IEPropertyGet and _IEPropertySet to control specific elements without rewriting large blocks of text. Related~ |_IEBodyReadHTML|, |_IEBodyReadText|, |_IEDocInsertHTML|, |_IEDocInsertText|, |_IEPropertyGet|, |_IEPropertySet|, |_IELoadWait| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the iFrame example, get a reference ; to the iFrame with a name of "iFrameTwo" and replace its body HTML ; ******************************************************* ; #include $oIE = _IE_Example ("iframe") $oFrame = _IEFrameGetObjByName ($oIE, "iFrameTwo") _IEBodyWriteHTML ($oFrame, "Hello iFrame!") < -------------------------------------------------------------------------------- *_IECreate* +-----------+~ | _IECreate |~ +-----------+~ Create an Internet Explorer Browser Window. > #include _IECreate ( [$s_Url = "about:blank" [, $f_tryAttach = 0 [, $f_visible = 1 [, $f_wait = 1 [, $f_takeFocus = 1]]]]] ) < Parameters~ $s_Url ------ [optional] specifies the Url to navigate to upon creation $f_tryAttach ------------ [optional] specifies whether to try to attach to an existing window 0 = (Default) do not try to attach 1 = Try to attach to an existing window $f_visible ---------- [optional] specifies whether the browser window will be visible 0 = Browser Window is hidden 1 = (Default) Browser Window is visible $f_wait [optional] specifies whether to wait for page to load before returning 0 = Return immediately, not waiting for page to load 1 = (Default) Wait for page load to complete before returning $f_takeFocus ------------ [optional] specifies whether to bring the attached window to focus 0 = Do not bring window into focus 1 = (Default) bring window into focus Return Value~ Success ------- Returns an object variable pointing to an InternetExplorer.Application object Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 1 ($_IEStatus_GeneralError) = General Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 6 ($_IEStatus_LoadWaitTimeout) = Load Wait Timeout 8 ($_IEStatus_AccessIsDenied) = Access Is Denied 9 ($_IEStatus_ClientDisconnected) = Client Disconnected @Extended: Set to true (1) or false (0) depending on the success of $f_tryAttach Remarks~ When using tryAttach, a No Match error will be displayed to the console from _IEAttach. This can be controlled with _IEErrorNotify. When opening a local HyperTextApplication (.hta) file, Internet Explorer will open a new browser process for it that will not be accessible through the object variable returned by _IECreate. To control this new browser you must use _IEAttach with the "embedded" option. New security in Windows Vista causes a new browser window to be created when a browser is instructed to navigate to a URL in a different security zone. This occurs as well with the initial creation and navigation initiated with _IECreate. The new window is a new browser instance and the previous browser object variable no longer points to it. There are several workarounds: 1) add #RequireAdmin to your code (this is required even if the account is part of the Administrator's Group and will propmt for credentials if necessary), 2) use _IEAttach to connect to the new browser window 3) add the target website to the Trusted Sites security zone in IE, 4) turn off "Protected Mode" in IE, or 5) disable UAC. Care must be taken to understand the implications of disabling IE security features when accessing untrusted sites. Related~ |_IEAttach|, |_IECreateEmbedded|, |_IEQuit|, |_IENavigate|, |_IELoadWait| Example~ > ; ******************************************************* ; Example 1 - Create a browser window and navigate to a website ; ******************************************************* ; #include $oIE = _IECreate ("www.autoitscript.com") ; ******************************************************* ; Example 2 - Create new browser windows pointing to each of 3 different URLs ; if one does not already exist ($f_tryAttach = 1) ; do not wait for the page loads to complete ($f_wait = 0) ; ******************************************************* ; #include _IECreate ("www.autoitscript.com", 1, 1, 0) _IECreate ("my.yahoo.com", 1, 1, 0) _IECreate ("www.google.com", 1, 1, 0) ; ******************************************************* ; Example 3 - Attempt to attach to an existing browser displaying a particular website URL ; Create a new browser and navigate to that site if one does not already exist ; ******************************************************* ; #include $oIE = _IECreate ("www.autoitscript.com", 1) ; Check @extended return value to see if attach was successful If @extended Then MsgBox(0, "", "Attached to Existing Browser") Else MsgBox(0, "", "Created New Browser") EndIf ; ******************************************************* ; Example 4 - Create an empty browser window and populate it with custom HTML ; ******************************************************* ; #include $oIE = _IECreate () $sHTML = "

Hello World!

" _IEBodyWriteHTML ($oIE, $sHTML) ; ******************************************************* ; Example 5 - Create an invisible browser window, navigate to a website, ; retrieve some information and Quit ; ******************************************************* ; #include $oIE = _IECreate ("http://sourceforge.net", 0, 0) ; Display the innerText on an element on the page with a name of "sfmarquee" $oMarquee = _IEGetObjByName ($oIE, "sfmarquee") MsgBox(0, "SourceForge Information", $oMarquee.innerText) _IEQuit ($oIE) ; ******************************************************* ; Example 6 - Create a browser window attached to a new instance of iexplore.exe ; This is often necessary in order to get a new session cookie context ; (session cookies are shared among all browser instances sharing the same iexplore.exe) ; ******************************************************* ; #include ShellExecute ("iexplore.exe", "about:blank") WinWait ("Blank Page") $oIE = _IEAttach ("about:blank", "url") _IELoadWait ($oIE) _IENavigate ($oIE, "www.autoitscript.com") < -------------------------------------------------------------------------------- *_IECreateEmbedded* +-------------------+~ | _IECreateEmbedded |~ +-------------------+~ Create a Webbrowser object suitable for embedding in an AutoIt GUI with GuiCtrlCreateObj(). > #include _IECreateEmbedded ( ) < Parameters~ None. Return Value~ Success ------- Returns a Webbrowser object reference Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 1 ($_IEStatus_GeneralError) = General Error Remarks~ No actions can be performed on this object until it has been embedded into a parent application (e.g. you cannot perform an _IENavigate). Because of this restriction, the browser is not automatically navigated to 'about:blank' as is a browser created with _IECreate. You must therefore use _IENavigate to navigate this browser to 'about:blank' after it has been embedded into the parent application and before you attempt any operations that rely on having a document loaded (e.g. _IEBodyWriteHTML). There are several properties related to an InternetExplorer object (e.g. returned by _IECreate) that do not apply to this object. These include status text, addressbar and others that may exist for a browser, but do not exist for an embedded control. You may have object visibility issues unless you use the Windows style $WS_CLIPCHILDREN in GUICreate(). _IEQuit cannot be used with this object. The object will be destroyed when its parent GUI is destroyed. Related~ |GUICreate|, |GUICtrlCreateObj|, |_IEAttach|, |_IECreate|, |_IENavigate| Example~ > ; ******************************************************* ; Example 1 - Trap COM errors so that 'Back' and 'Forward' ; outside of history bounds does not abort script ; (expect COM errors to be sent to the console) ; ******************************************************* ; #include #include #include _IEErrorHandlerRegister () $oIE = _IECreateEmbedded () GUICreate("Embedded Web control Test", 640, 580, _ (@DesktopWidth - 640) / 2, (@DesktopHeight - 580) / 2, _ $WS_OVERLAPPEDWINDOW + $WS_VISIBLE + $WS_CLIPSIBLINGS + $WS_CLIPCHILDREN) $GUIActiveX = GUICtrlCreateObj($oIE, 10, 40, 600, 360) $GUI_Button_Back = GUICtrlCreateButton("Back", 10, 420, 100, 30) $GUI_Button_Forward = GUICtrlCreateButton("Forward", 120, 420, 100, 30) $GUI_Button_Home = GUICtrlCreateButton("Home", 230, 420, 100, 30) $GUI_Button_Stop = GUICtrlCreateButton("Stop", 340, 420, 100, 30) GUISetState() ;Show GUI _IENavigate ($oIE, "http://www.autoitscript.com") ; Waiting for user to close the window While 1 $msg = GUIGetMsg() Select Case $msg = $GUI_EVENT_CLOSE ExitLoop Case $msg = $GUI_Button_Home _IENavigate ($oIE, "http://www.autoitscript.com") Case $msg = $GUI_Button_Back _IEAction ($oIE, "back") Case $msg = $GUI_Button_Forward _IEAction ($oIE, "forward") Case $msg = $GUI_Button_Stop _IEAction ($oIE, "stop") EndSelect WEnd GUIDelete() Exit < -------------------------------------------------------------------------------- *_IEDocGetObj* +--------------+~ | _IEDocGetObj |~ +--------------+~ Given any DOM object, returns a reference to the associated document object. > #include _IEDocGetObj ( ByRef $o_object ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window, Frame or any DOM object Return Value~ Success ------- Returns an object variable pointing to the Document object Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type @Extended: Contains invalid parameter number Remarks~ Given any DOM object (e.g. Browser, Window, Frame, iFrame, Document or Document Element) this will return a reference to the associated document object. It is particularly useful when writing generalized functions when you cannot control the type of object that will be passed in. Related~ None. Example~ > ; ******************************************************* ; Example 1 - Open a browser to the AutoIt Homepage, get a reference ; to the document object and display a document attribute ; ******************************************************* ; #include $oIE = _IECreate ("http://www.autoitscript.com") $oDoc = _IEDocGetObj ($oIE) MsgBox(0, "Document Created Date", $oDoc.fileCreatedDate) < -------------------------------------------------------------------------------- *_IEDocInsertHTML* +------------------+~ | _IEDocInsertHTML |~ +------------------+~ Inserts HTML Text in or around an element. > #include _IEDocInsertHTML ( ByRef $o_object, $s_string [, $s_where = "beforeend"] ) < Parameters~ $o_object --------- Object variable pointing to a document element. $s_string --------- The string containing the HTML text to insert. $s_where -------- [optional] specifies the string insertion point beforebegin = Inserts string immediately before the object. afterbegin = Inserts string after the start of the object but before all other content in the object. beforeend = (Default) Inserts string immediately before the end of the object but after all other content in the object. afterend = Inserts string immediately after the end of the object. Return Value~ Success ------- Returns 1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 5 ($_IEStatus_InvalidValue) = Invalid Value @Extended: Contains invalid parameter number Remarks~ The innerHTML, outerHTML, innerText and outerText features of _IEPropertySet can be used to dynamically manipulate inserted content. Related~ |_IEDocInsertText|, |_IEPropertyGet|, |_IEPropertySet|, |_IEBodyReadHTML|, |_IEBodyWriteHTML|, |_IEDocReadHTML|, |_IEHeadInsertEventScript| Example~ > ; ******************************************************* ; Example 1 - Insert HTML at the top and bottom of a document ; ******************************************************* ; #include $oIE = _IECreate("http://www.autoitscript.com") $oBody = _IETagNameGetCollection($oIE, "body", 0) _IEDocInsertHTML($oBody, "

This HTML is inserted After Begin

", "afterbegin") _IEDocInsertHTML($oBody, "

This HTML is inserted Before End

", "beforeend") ; ******************************************************* ; Example 2 - Open a browser with the basic example page, insert HTML ; in and around the DIV tag named "IEAu3Data" and display Body HTML ; ******************************************************* ; $oIE = _IE_Example ("basic") $oDiv = _IEGetObjByName($oIE, "IEAu3Data") _IEDocInsertHTML($oDiv, "(HTML beforebegin)", "beforebegin") _IEDocInsertHTML($oDiv, "(HTML afterbegin)", "afterbegin") _IEDocInsertHTML($oDiv, "(HTML beforeend)", "beforeend") _IEDocInsertHTML($oDiv, "(HTML afterend)", "afterend") ConsoleWrite(_IEBodyReadHTML($oIE) & @CRLF) ; ******************************************************* ; Example 3 - Advanced example ; Insert a clock and a referrer string at the top of every page, even when you ; browse to a new location. Uses _IEDocInsertText, _IEDocInsertHTML and ; _IEPropertySet features "innerhtml" and "referrer" ; ******************************************************* ; #include $oIE = _IECreate("http://www.autoitscript.com") AdlibRegister("UpdateClock", 1000) ; Update clock once per second ; idle as long as the browser window exists While WinExists(_IEPropertyGet($oIE, "hwnd")) Sleep(10000) WEnd Exit Func UpdateClock() Local $curTime = "Current Time is: " & @HOUR & ":" & @MIN & ":" & @SEC ; _IEGetObjByName is expected to return a NoMatch error after navigation ; (before DIV is inserted), so temporarily turn off notification _IEErrorNotify(False) Local $oAutoItClock = _IEGetObjByName($oIE, "AutoItClock") If Not IsObj($oAutoItClock) Then ; Insert DIV element if it wasn't found ; ; Get reference to BODY, insert DIV, get reference to DIV, update time $oBody = _IETagNameGetCollection($oIE, "body", 0) _IEDocInsertHTML($oBody, "
", "afterbegin") $oAutoItClock = _IEGetObjByName($oIE, "AutoItClock") _IEPropertySet($oAutoItClock, "innerhtml", $curTime) ; ; Check referrer string, if not blank insert after clock _IELoadWait($oIE) $sReferrer = _IEPropertyGet($oIE, "referrer") If $sReferrer Then _IEDocInsertText($oAutoItClock, _ " Referred by: " & $sReferrer, "afterend") Else _IEPropertySet($oAutoItClock, "innerhtml", $curTime) ; update time EndIf _IEErrorNotify(True) EndFunc < -------------------------------------------------------------------------------- *_IEDocInsertText* +------------------+~ | _IEDocInsertText |~ +------------------+~ Inserts Text in or around an element. > #include _IEDocInsertText ( ByRef $o_object, $s_string [, $s_where = "beforeend"] ) < Parameters~ $o_object --------- Object variable pointing to a document element. $s_string --------- The string containing the text to insert. $s_where -------- [optional] specifies the string insertion point beforebegin = Inserts string immediately before the object. afterbegin = Inserts string after the start of the object but before all other content in the object. beforeend = (Default) Inserts string immediately before the end of the object but after all other content in the object. afterend = Inserts string immediately after the end of the object. Return Value~ Success ------- Returns 1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 5 ($_IEStatus_InvalidValue) = Invalid Value @Extended: Contains invalid parameter number Remarks~ In the text to be inserted includes HTML tags, they are first converted so that they display as text. The innerHTML, outerHTML, innerText and outerText features of _IEPropertySet can be used to dynamically manipulate inserted content. Related~ |_IEDocInsertHTML|, |_IEPropertyGet|, |_IEPropertySet|, |_IEBodyReadHTML|, |_IEBodyWriteHTML|, |_IEDocReadHTML|, |_IEHeadInsertEventScript| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the basic example page, insert text ; in and around the first Paragraph tag and display Body HTML ; ******************************************************* ; #include $oIE = _IE_Example ("basic") $oP = _IETagNameGetCollection($oIE, "p", 0) _IEDocInsertText($oP, "(Text beforebegin)", "beforebegin") _IEDocInsertText($oP, "(Text afterbegin)", "afterbegin") _IEDocInsertText($oP, "(Text beforeend)", "beforeend") _IEDocInsertText($oP, "(Text afterend)", "afterend") ConsoleWrite(_IEBodyReadHTML($oIE) & @CRLF) ; ******************************************************* ; Example 2 - Insert HTML at the top and bottom of a document ; ******************************************************* ; #include $oIE = _IE_Example ("basic") $oBody = _IETagNameGetCollection($oIE, "body", 0) _IEDocInsertText($oBody, "This Text is inserted After Begin", "afterbegin") _IEDocInsertText($oBody, "Notice that Tags are before display", "beforeend") ; ******************************************************* ; Example 3 - Advanced example ; Insert a clock and a referrer string at the top of every page, even when you ; browse to a new location. Uses _IEDocInsertText, _IEDocInsertHTML and ; _IEPropertySet features "innerhtml" and "referrer" ; ******************************************************* ; #include $oIE = _IECreate("http://www.autoitscript.com") AdlibRegister("UpdateClock", 1000) ; Update clock once per second ; idle as long as the browser window exists While WinExists(_IEPropertyGet($oIE, "hwnd")) Sleep(10000) WEnd Exit Func UpdateClock() Local $curTime = "Current Time is: " & @HOUR & ":" & @MIN & ":" & @SEC ; _IEGetObjByName is expected to return a NoMatch error after navigation ; (before DIV is inserted), so temporarily turn off notification _IEErrorNotify(False) Local $oAutoItClock = _IEGetObjByName($oIE, "AutoItClock") If Not IsObj($oAutoItClock) Then ; Insert DIV element if it wasn't found ; ; Get reference to BODY, insert DIV, get reference to DIV, update time $oBody = _IETagNameGetCollection($oIE, "body", 0) _IEDocInsertHTML($oBody, "
", "afterbegin") $oAutoItClock = _IEGetObjByName($oIE, "AutoItClock") _IEPropertySet($oAutoItClock, "innerhtml", $curTime) ; ; Check referrer string, if not blank insert after clock _IELoadWait($oIE) $sReferrer = _IEPropertyGet($oIE, "referrer") If $sReferrer Then _IEDocInsertText($oAutoItClock, _ " Referred by: " & $sReferrer, "afterend") Else _IEPropertySet($oAutoItClock, "innerhtml", $curTime) ; update time EndIf _IEErrorNotify(True) EndFunc < -------------------------------------------------------------------------------- *_IEDocReadHTML* +----------------+~ | _IEDocReadHTML |~ +----------------+~ Returns the full HTML source of a document. > #include _IEDocReadHTML ( ByRef $o_object ) < Parameters~ $o_object ----- Object variable of an InternetExplorer.Application, Window or Frame object Return Value~ Success ------- Returns the HTML included in the of the document, including the and tags Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type @Extended: Contains invalid parameter number Remarks~ This function returns the document source after any client-side modifications (e.g. by AutoIt or by client-side JavaScript). It may therefore be different than what is shown by the browser View Source or by _INetGetSource. Related~ |_IEDocWriteHTML|, |_IEBodyReadHTML|, |_INetGetSource|, |_IEDocInsertHTML|, |_IEDocInsertText| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the basic example, read the document HTML ; (all HTML including the and script) and display it in a MsgBox ; ******************************************************* ; #include $oIE = _IE_Example ("basic") $sHTML = _IEDocReadHTML ($oIE) MsgBox(0, "Document Source", $sHTML) < -------------------------------------------------------------------------------- *_IEDocWriteHTML* +-----------------+~ | _IEDocWriteHTML |~ +-----------------+~ Replaces the HTML for the entire document. > #include _IEDocWriteHTML ( ByRef $o_object, $s_html ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window or Frame object $s_html ------- The HTML string to write to the document Return Value~ Success ------- Returns -1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 1 ($_IEStatus_GeneralError) = General Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 6 ($_IEStatus_LoadWaitTimeout) = Load Wait Timeout 8 ($_IEStatus_AccessIsDenied) = Access Is Denied 9 ($_IEStatus_ClientDisconnected) = Client Disconnected @Extended: Contains invalid parameter number Remarks~ This function completely replaces the content of the document in a browser or a frame. It can be used to create a new page with custom HTML and JavaScript. It is sometimes necessary to refresh the page after writing with _IEAction($oIE, "refresh") (e,g, after creating a FRAMESET). Related~ |_IEDocReadHTML|, |_IELoadWait| Example~ > ; ******************************************************* ; Example 1 - Create an empty browser, write customer HTML to it - in this case a ; FRAMESET - and then update the contents of each of the frames ; ******************************************************* ; #include $oIE = _IECreate () $sHTML = "" $sHTML &= "" & @CR $sHTML &= "" & @CR $sHTML &= "_IE_Example('frameset')" & @CR $sHTML &= "" & @CR $sHTML &= "" & @CR $sHTML &= " " & @CR $sHTML &= " " & @CR $sHTML &= " " & @CR $sHTML &= " " & @CR $sHTML &= " " & @CR $sHTML &= "" & @CR $sHTML &= "" _IEDocWriteHTML ($oIE, $sHTML) _IEAction ($oIE, "refresh") Local $oFrameTop = _IEFrameGetObjByName ($oIE, "Top") Local $oFrameMenu = _IEFrameGetObjByName ($oIE, "Menu") Local $oFrameMain = _IEFrameGetObjByName ($oIE, "Main") _IEBodyWriteHTML ($oFrameTop, '$oFrameTop = _IEFrameGetObjByName($oIE, "Top")') _IEBodyWriteHTML ($oFrameMenu, '$oFrameMenu = _IEFrameGetObjByName($oIE, "Menu")') _IEBodyWriteHTML ($oFrameMain, '$oFrameMain = _IEFrameGetObjByName($oIE, "Main")') < -------------------------------------------------------------------------------- *_IEErrorHandlerDeRegister* +---------------------------+~ | _IEErrorHandlerDeRegister |~ +---------------------------+~ Disable a registered user COM error handler > #include _IEErrorHandlerDeRegister ( ) < Parameters~ None. Return Value~ Success ------- Returns 1 Failure ------- None Remarks~ See remarks for _IEErrorHandlerRegister. Related~ |_IEErrorHandlerRegister| Example~ > ; ******************************************************* ; Example 1 - Register and later deregister a custom error handler ; ******************************************************* ; #include ; Register a customer error handler _IEErrorHandlerRegister ("MyErrFunc") ; Do something ; Deregister the customer error handler _IEErrorHandlerDeregister () ; Do something else Exit Func MyErrFunc() $HexNumber = Hex($oIEErrorHandler.number, 8) MsgBox(0, "", "We intercepted a COM Error !" & @CRLF & _ "Number is: " & $HexNumber & @CRLF & _ "Windescription is: " & $oIEErrorHandler.windescription) SetError(1) ; something to check for when this function returns EndFunc ;==>MyErrFunc < -------------------------------------------------------------------------------- *_IEErrorHandlerRegister* +-------------------------+~ | _IEErrorHandlerRegister |~ +-------------------------+~ > #include _IEErrorHandlerRegister ( [$s_functionName = "__IEInternalErrorHandler"] ) < Parameters~ $s_functionName --------------- [optional] String variable with the name of a user-defined COM error handler, defaults to the internal COM error handler in this UDF Return Value~ Success ------- Returns 1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 1 ($_IEStatus_GeneralError) = General Error @Extended: Contains invalid parameter number Remarks~ Important: When using your own error handler, the Error Object variable used MUST be named $oIEErrorHandler (see example). AutoIt has the ability to trap COM errors and pass them through a custom error handler using the ObjEvent function. There is a problem with this for UDF writers however because only a single COM error handler can be in use at a time. For the UDF to use a COM error handler it must first deregister the user error handler, install its own and then put the user handler back in place. Unfortunately, by default, the UDF has no way to access the handle of the user error handler. Using this routine you can register your COM error handler in a way that IE.au3 can gracefully remove and reinstate it when it needs to. You may either point to your own custom error handler or you may use the one developed for IE.au3 (the default). Using the default IE.au3 error handler you will also get some nice diagnostic information written to the console and some global variables that contain information about the trapped errors. If you instantiate your own COM error handler without using this routine IE.au3 will not be able to trap some COM errors and you may experience some abrupt script terminations as a result. If you use the default error handler (__IEInternalErrorHandler), the following global variables are set for you to reference: $IEComErrorNumber, $IEComErrorNumberHex, $IEComErrorDescription, $IEComErrorScriptline, $IEComErrorWinDescription, $IEComErrorSource, $IEComErrorHelpFile, $IEComErrorHelpContext, $IEComErrorLastDllError, $IEComErrorComObj and $IEComErrorOutput You may control the display of COM error messages to the console with _IEErrorNotify. Related~ |_IEErrorHandlerDeRegister,| |_IEErrorNotify| Example~ > ; ******************************************************* ; Example 1 - Register and later deregister a custom and the default IE.au3 error handler ; ******************************************************* ; #include ; Register a customer error handler _IEErrorHandlerRegister ("MyErrFunc") ; Do something ; Deregister the customer error handler _IEErrorHandlerDeregister () ; Do something else ; Register the default IE.au3 COM Error Handler _IEErrorHandlerRegister () ; Do more work Exit Func MyErrFunc() ; Important: the error object variable MUST be named $oIEErrorHandler $ErrorScriptline = $oIEErrorHandler.scriptline $ErrorNumber = $oIEErrorHandler.number $ErrorNumberHex = Hex($oIEErrorHandler.number, 8) $ErrorDescription = StringStripWS($oIEErrorHandler.description, 2) $ErrorWinDescription = StringStripWS($oIEErrorHandler.WinDescription, 2) $ErrorSource = $oIEErrorHandler.Source $ErrorHelpFile = $oIEErrorHandler.HelpFile $ErrorHelpContext = $oIEErrorHandler.HelpContext $ErrorLastDllError = $oIEErrorHandler.LastDllError $ErrorOutput = "" $ErrorOutput &= "--> COM Error Encountered in " & @ScriptName & @CR $ErrorOutput &= "----> $ErrorScriptline = " & $ErrorScriptline & @CR $ErrorOutput &= "----> $ErrorNumberHex = " & $ErrorNumberHex & @CR $ErrorOutput &= "----> $ErrorNumber = " & $ErrorNumber & @CR $ErrorOutput &= "----> $ErrorWinDescription = " & $ErrorWinDescription & @CR $ErrorOutput &= "----> $ErrorDescription = " & $ErrorDescription & @CR $ErrorOutput &= "----> $ErrorSource = " & $ErrorSource & @CR $ErrorOutput &= "----> $ErrorHelpFile = " & $ErrorHelpFile & @CR $ErrorOutput &= "----> $ErrorHelpContext = " & $ErrorHelpContext & @CR $ErrorOutput &= "----> $ErrorLastDllError = " & $ErrorLastDllError MsgBox(0,"COM Error", $ErrorOutput) SetError(1) Return EndFunc ;==>MyErrFunc < -------------------------------------------------------------------------------- *_IEErrorNotify* +----------------+~ | _IEErrorNotify |~ +----------------+~ Specifies whether IE.au3 automatically notifies of Warnings and Errors (to the console) > #include _IEErrorNotify ( [$f_notify = -1] ) < Parameters~ $f_notify --------- [optional] specifies whether notification should be on or off -1 = (Default) return current setting True = Turn On False = Turn Off Return Value~ Success ------- If $f_notify = -1, returns the current notification setting, else returns 1 Failure ------- Returns 0 Remarks~ IE.au3 writes diagnostic information, warnings and errors to the console by default. This information can readily be seen when using the SciTe editor to run your scripts. This function allows you to turn this functionality on or off. Related~ |_IEErrorHandlerRegister| Example~ > ; ******************************************************* ; Example 1 - Check the current status of _IEErrorNotify, turn it off if on, on if off ; ******************************************************* ; #include If _IEErrorNotify () Then MsgBox(0, "_IEErrorNotify Status", "Notification is ON, turning it OFF") _IEErrorNotify (False) Else MsgBox(0, "_IEErrorNotify Status", "Notification is OFF, turning it ON") _IEErrorNotify (True) EndIf < -------------------------------------------------------------------------------- *_IEFormElementCheckBoxSelect* +------------------------------+~ | _IEFormElementCheckBoxSelect |~ +------------------------------+~ Set the value of a specified form element. > #include _IEFormElementCheckBoxSelect ( ByRef $o_object, $s_string [, $s_name = "" [, $f_select = 1 [, $s_mode = "byValue" [, $f_fireEvent = 1]]]] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Form object $s_string --------- Value used to match element - treatment based on $s_mode $s_name ------- [optional] Name or Id of checkbox(es) $f_select --------- [optional] specifies whether element should be checked or unchecked -1 = Return checked state 0 = Uncheck the element 1 = (Default) Check the element $s_mode ------- [optional] specify search mode byValue = (Default) value of the checkbox you wish to select byIndex = 0-based index of checkbox you wish to select $f_fireEvent ------------ [optional] specifies whether to fire OnChange and OnClick events after changing value 0 = do not fire OnChange or OnClick event after setting value 1 = (Default) fire OnChange and OnClick events after setting value Return Value~ Success ------- If $f_select = -1, returns the current checked state, else returns 1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 5 ($_IEStatus_InvalidValue) = Invalid Value 7 ($_IEStatus_NoMatch) = No Match @Extended: Contains invalid parameter number Remarks~ The $f_fireEvent parameter is significant only if the form element has an onChange event associated with it. $s_Name is optional for this function. If it is omitted, the function will operate on a collection of all elements in the form. If specified, the function will operate on a collection of elements with that name. Related~ |_IEFormElementOptionSelect|, |_IEFormElementRadioSelect|, |_IEFormElementGetValue|, |_IEFormElementSetValue| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the form example, get reference to form, select and ; deselect the checkboxes byValue. Since $s_Name is not specified, operate ; on the collection of all elements in the form ; Note: You will likely need to scroll down on the page to see the changes ; ******************************************************* ; #include $oIE = _IE_Example ("form") $oForm = _IEFormGetObjByName ($oIE, "ExampleForm") For $i = 1 To 5 _IEFormElementCheckboxSelect ($oForm, "gameBasketball", "", 1, "byValue") Sleep(1000) _IEFormElementCheckboxSelect ($oForm, "gameFootball", "", 1, "byValue") Sleep(1000) _IEFormElementCheckboxSelect ($oForm, "gameTennis", "", 1, "byValue") Sleep(1000) _IEFormElementCheckboxSelect ($oForm, "gameBaseball", "", 1, "byValue") Sleep(1000) _IEFormElementCheckboxSelect ($oForm, "gameBasketball", "", 0, "byValue") Sleep(1000) _IEFormElementCheckboxSelect ($oForm, "gameFootball", "", 0, "byValue") Sleep(1000) _IEFormElementCheckboxSelect ($oForm, "gameTennis", "", 0, "byValue") Sleep(1000) _IEFormElementCheckboxSelect ($oForm, "gameBaseball", "", 0, "byValue") Sleep(1000) Next ; ******************************************************* ; Example 2 - Open a browser with the form example, get reference to form, select and ; deselect the checkboxes byIndex. Since $s_Name is not specified, operate ; on the collection of all elements in the form ; Note: You will likely need to scroll down on the page to see the changes ; ******************************************************* ; #include $oIE = _IE_Example ("form") $oForm = _IEFormGetObjByName ($oIE, "ExampleForm") For $i = 1 To 5 _IEFormElementCheckboxSelect ($oForm, 3, "", 1, "byIndex") Sleep(1000) _IEFormElementCheckboxSelect ($oForm, 2, "", 1, "byIndex") Sleep(1000) _IEFormElementCheckboxSelect ($oForm, 1, "", 1, "byIndex") Sleep(1000) _IEFormElementCheckboxSelect ($oForm, 0, "", 1, "byIndex") Sleep(1000) _IEFormElementCheckboxSelect ($oForm, 3, "", 0, "byIndex") Sleep(1000) _IEFormElementCheckboxSelect ($oForm, 2, "", 0, "byIndex") Sleep(1000) _IEFormElementCheckboxSelect ($oForm, 1, "", 0, "byIndex") Sleep(1000) _IEFormElementCheckboxSelect ($oForm, 0, "", 0, "byIndex") Sleep(1000) Next ; ******************************************************* ; Example 3 - Open a browser with the form example, get reference to form, select and ; deselect the checkboxes byIndex in the group that shares the name checkboxG2Example ; Note: You will likely need to scroll down on the page to see the changes ; ******************************************************* ; #include $oIE = _IE_Example ("form") $oForm = _IEFormGetObjByName ($oIE, "ExampleForm") For $i = 1 To 5 _IEFormElementCheckboxSelect ($oForm, 0, "checkboxG2Example", 1, "byIndex") Sleep(1000) _IEFormElementCheckboxSelect ($oForm, 1, "checkboxG2Example", 1, "byIndex") Sleep(1000) _IEFormElementCheckboxSelect ($oForm, 0, "checkboxG2Example", 0, "byIndex") Sleep(1000) _IEFormElementCheckboxSelect ($oForm, 1, "checkboxG2Example", 0, "byIndex") Sleep(1000) Next < -------------------------------------------------------------------------------- *_IEFormElementGetCollection* +-----------------------------+~ | _IEFormElementGetCollection |~ +-----------------------------+~ Returns a collection object variable representing all Form Elements within a given Form. > #include _IEFormElementGetCollection ( ByRef $o_object [, $i_index = -1] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Form object $i_index -------- [optional] specifies whether to return a collection or indexed instance 0 or positive integer returns an indexed instance -1 = (Default) returns a collection Return Value~ Success ------- Returns an object variable containing the Form Elements collection, @EXTENDED = form element count Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 5 ($_IEStatus_InvalidValue) = Invalid Value 7 ($_IEStatus_NoMatch) = No Match @Extended: Contains invalid parameter number Remarks~ None. Related~ |_IEFormElementGetObjByName,| |_IEFormElementGetValue,| |_IEFormElementSetValue,| |_IEFormSubmi|t Example~ > ; ******************************************************* ; Example 1 - Get a reference to a specific form element by 0-based index. ; In this case, submit a query to the Google search engine ; ******************************************************* ; #include $oIE = _IECreate ("http://www.google.com") $oForm = _IEFormGetCollection ($oIE, 0) $oQuery = _IEFormElementGetCollection ($oForm, 2) _IEFormElementSetValue ($oQuery, "AutoIt IE.au3") _IEFormSubmit ($oForm) < -------------------------------------------------------------------------------- *_IEFormElementGetObjByName* +----------------------------+~ | _IEFormElementGetObjByName |~ +----------------------------+~ Returns an object reference to a Form Element by name. > #include _IEFormElementGetObjByName ( ByRef $o_object, $s_name [, $i_index = 0] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Form object $s_name ------- Specifies the name of the Form Element you wish to match $i_index -------- [optional] If the Form Element name occurs more than once, specifies instance by 0-based index 0 (Default) or positive integer returns an indexed instance -1 returns a collection of the specified Form Elements Return Value~ Success ------- Returns an object variable pointing to the Form Element object, @EXTENDED = form count Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 7 ($_IEStatus_NoMatch) = No Match @Extended: Contains invalid parameter number Remarks~ If the desired form element does not have a name or ID, _IEFormElementGetCollection to get a reference by index Related~ |_IEFormElementGetCollection|, |_IEFormElementGetValue|, |_IEFormElementSetValue|, |_IEFormSubmit| Example~ > ; ******************************************************* ; Example 1 - Get a reference to a specific form element by name. ; In this case, submit a query to the Google search engine ; ******************************************************* ; #include $oIE = _IECreate ("http://www.google.com") $oForm = _IEFormGetObjByName ($oIE, "f") $oQuery = _IEFormElementGetObjByName ($oForm, "q") _IEFormElementSetValue ($oQuery, "AutoIt IE.au3") _IEFormSubmit ($oForm) < -------------------------------------------------------------------------------- *_IEFormElementGetValue* +------------------------+~ | _IEFormElementGetValue |~ +------------------------+~ Returns the value of a given Form Element. > #include _IEFormElementGetValue ( ByRef $o_object ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Form Element object Return Value~ Success ------- Returns the string value of the given Form Element Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type @Extended: Contains invalid parameter number Remarks~ See remarks for _IEFormElementSetValue. Related~ |_IEFormElementSetValue|, |_IEFormElementGetCollection|, |_IEFormElementGetObjByName|, |_IEFormElementOptionSelect|, |_IEFormElementCheckboxSelect|, |_IEFormElementRadioSelect| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the form example, set the value of a text ; form element, retrieve and display the value from the element ; ******************************************************* ; #include $oIE = _IE_Example ("form") $oForm = _IEFormGetObjByName ($oIE, "ExampleForm") $oText = _IEFormElementGetObjByName ($oForm, "textExample") $IEAu3Version = _IE_VersionInfo () _IEFormElementSetValue ($oText, $IEAu3Version[5]) MsgBox(0, "Form Element Value", _IEFormElementGetValue ($oText)) < -------------------------------------------------------------------------------- *_IEFormElementOptionSelect* +----------------------------+~ | _IEFormElementOptionSelect |~ +----------------------------+~ Set the value of a specified form element. > #include _IEFormElementOptionSelect ( ByRef $o_object, $s_string [, $f_select = 1 [, $s_mode = "byValue" [, $f_fireEvent = 1]]] ) < Parameters~ $o_object --------- Form Element Object of type "Select Option" $s_string --------- Value used to match element - treatment based on $s_mode $f_select --------- [optional] specifies whether element should be selected or deselected -1 = Return selected state 0 = Deselect the element 1 = (Default) Select the element $s_mode ------- [optional] specifies search mode byValue = (Default) value of the option you wish to select byText = text of the option you wish to select byIndex = 0-based index of option you wish to select $f_fireEvent ------------ [optional] specifies whether to fire OnChange and OnClick events after changing value 0 = do not fire OnChange or OnClick event after setting value 1 = (Default) fire OnChange and OnClick events after setting value Return Value~ Success ------- If $f_select = -1, returns the current selected state, else returns 1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 5 ($_IEStatus_InvalidValue) = Invalid Value 7 ($_IEStatus_NoMatch) = No Match @Extended: Contains invalid parameter number Remarks~ The $f_fireEvent parameter is significant only if the form element has an onChange event associated with it. Related~ |_IEFormElementCheckBoxSelect|, |_IEFormElementRadioSelect|, |_IEFormElementGetValue|, |_IEFormElementSetValue| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the form example, get reference to form, get reference ; to select element, cycle 10 times selecting options byValue, byText and byIndex ; Note: You will likely need to scroll down on the page to see the changes ; ******************************************************* ; #include $oIE = _IE_Example ("form") $oForm = _IEFormGetObjByName ($oIE, "ExampleForm") $oSelect = _IEFormElementGetObjByName ($oForm, "selectExample") For $i = 1 To 10 _IEFormElementOptionSelect ($oSelect, "Freepage", 1, "byText") Sleep(1000) _IEFormElementOptionSelect ($oSelect, "midipage.html", 1, "byValue") Sleep(1000) _IEFormElementOptionSelect ($oSelect, 0, 1, "byIndex") Sleep(1000) Next ; ******************************************************* ; Example 2 - Open a browser with the form example, get reference to form, get reference ; to select multiple element, cycle 5 times selecting and then deselecting ; options byValue, byText and byIndex. ; Note: You will likely need to scroll down on the page to see the changes ; ******************************************************* ; #include $oIE = _IE_Example ("form") $oForm = _IEFormGetObjByName ($oIE, "ExampleForm") $oSelect = _IEFormElementGetObjByName ($oForm, "multipleSelectExample") For $i = 1 To 5 _IEFormElementOptionSelect ($oSelect, "Carlos", 1, "byText") Sleep(1000) _IEFormElementOptionSelect ($oSelect, "Name2", 1, "byValue") Sleep(1000) _IEFormElementOptionSelect ($oSelect, 5, 1, "byIndex") Sleep(1000) _IEFormElementOptionSelect ($oSelect, "Carlos", 0, "byText") Sleep(1000) _IEFormElementOptionSelect ($oSelect, "Name2", 0, "byValue") Sleep(1000) _IEFormElementOptionSelect ($oSelect, 5, 0, "byIndex") Sleep(1000) Next ; ******************************************************* ; Example 3 - Open a browser with the form example, get reference to form, get reference ; to select element, check to see if the option "Freepage" is selected and ; report result. Repeat for the option with index 0 and for the option ; with value of 'midipage.html' ; Note: You will likely need to scroll down on the page to see the changes ; ******************************************************* ; #include $oIE = _IE_Example ("form") $oForm = _IEFormGetObjByName ($oIE, "ExampleForm") $oSelect = _IEFormElementGetObjByName ($oForm, "selectExample") If _IEFormElementOptionSelect ($oSelect, "Freepage", -1, "byText") Then MsgBox(0, "Option Selected", "Option Freepage is selected") Else MsgBox(0, "Option Selected", "Option Freepage is Not selected") EndIf If _IEFormElementOptionSelect ($oSelect, 0, -1, "byIndex") Then MsgBox(0, "Option Selected", "The First (index 0) option is selected") Else MsgBox(0, "Option Selected", "The First (index 0) option is Not selected") EndIf If _IEFormElementOptionSelect ($oSelect, "midipage.html", -1, "byValue") Then MsgBox(0, "Option Selected", "The option with value 'midipage.html' is selected") Else MsgBox(0, "Option Selected", "The option with value 'midipage.html' is NOT selected") EndIf < -------------------------------------------------------------------------------- *_IEFormElementRadioSelect* +---------------------------+~ | _IEFormElementRadioSelect |~ +---------------------------+~ Set the value of a specified form element. > #include _IEFormElementRadioSelect ( ByRef $o_object, $s_string , $s_name [, $f_select = 1 [, $s_mode = "byValue" [, $f_fireEvent = 1]]] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Form object $s_string --------- Value used to match element - treatment based on $s_mode $s_name ------- Name or Id of Radio Group $f_select --------- [optional] specifies whether element should be selected or deselected -1 = Return selected state 0 = Unselect the element 1 = (Default) Select the element $s_mode ------- [optional] specifies search mode byValue = (Default) value of the radio you wish to select byIndex = 0-based index of radio you wish to select $f_fireEvent ------------ [optional] specifies whether to fire OnChange and OnClick events after changing value 0 = do not fire OnChange or OnClick event after setting value 1 = (Default) fire OnChange and OnClick events after setting value Return Value~ Success ------- If $f_select = -1, returns the current selected state, else returns 1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 5 ($_IEStatus_InvalidValue) = Invalid Value 7 ($_IEStatus_NoMatch) = No Match @Extended: Contains invalid parameter number Remarks~ The $f_fireEvent parameter is significant only if the form element has an onChange event associated with it. $s_Name is a mandatory parameter for this function. Radio buttons are operated upon in groups sharing the same name. No more than one element within a group may be selected at a given time - when one item is selected, all others are deselected. Related~ |_IEFormElementOptionSelect|, |_IEFormElementCheckBoxSelect|, |_IEFormElementGetValue|, |_IEFormElementSetValue| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the form example, get reference to form, select ; each radio button byValue, then deselect the last item leaving none selected. ; Note: You will likely need to scroll down on the page to see the changes ; ******************************************************* ; #include $oIE = _IE_Example ("form") $oForm = _IEFormGetObjByName ($oIE, "ExampleForm") For $i = 1 To 5 _IEFormElementRadioSelect ($oForm, "vehicleAirplane", "radioExample", 1, "byValue") Sleep(1000) _IEFormElementRadioSelect ($oForm, "vehicleTrain", "radioExample", 1, "byValue") Sleep(1000) _IEFormElementRadioSelect ($oForm, "vehicleBoat", "radioExample", 1, "byValue") Sleep(1000) _IEFormElementRadioSelect ($oForm, "vehicleCar", "radioExample", 1, "byValue") Sleep(1000) _IEFormElementRadioSelect ($oForm, "vehicleCar", "radioExample", 0, "byValue") Sleep(1000) Next ; ******************************************************* ; Example 2 - Open a browser with the form example, get reference to form, select ; each radio button byIndex, then deselect the last item leaving none selected. ; Note: You will likely need to scroll down on the page to see the changes ; ******************************************************* ; #include $oIE = _IE_Example ("form") $oForm = _IEFormGetObjByName ($oIE, "ExampleForm") For $i = 1 To 5 _IEFormElementRadioSelect ($oForm, 3, "radioExample", 1, "byIndex") Sleep(1000) _IEFormElementRadioSelect ($oForm, 2, "radioExample", 1, "byIndex") Sleep(1000) _IEFormElementRadioSelect ($oForm, 1, "radioExample", 1, "byIndex") Sleep(1000) _IEFormElementRadioSelect ($oForm, 0, "radioExample", 1, "byIndex") Sleep(1000) _IEFormElementRadioSelect ($oForm, 0, "radioExample", 0, "byIndex") Sleep(1000) Next < -------------------------------------------------------------------------------- *_IEFormElementSetValue* +------------------------+~ | _IEFormElementSetValue |~ +------------------------+~ Set the value of a specified Form Element. > #include _IEFormElementSetValue ( ByRef $o_object, $s_newvalue [, $f_fireEvent = 1] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Form Element object $s_newvalue ----------- The new value to be set into the Form Element $f_fireEvent ------------ [optional] specifies whether to fire an OnChange event after changing value 0 = Do not fire OnChange or OnClick event after setting value 1 = (Default) fire OnChange and OnClick event after setting value Return Value~ Success ------- Returns 1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type @Extended: Contains invalid parameter number Remarks~ While all Form Elements have a value, only text oriented elements use their value attribute in an obvious fashion (type text, textarea, hidden, password and file). The value of other form elements does not affect what is displayed in the user interface, but rather the value that is returned by the element when it is selected or activated. See _IEFormElementOptionSelect, _IEFormElementCheckboxSelect, _IEFormElementRadioSelect and _IEFormImageClick for more information. Note: You cannot use _IEFormElementSetValue to set the value of an INPUT TYPE=FILE element. Browser security restrictions prevent this element from being scripted. See the example below for a workaround. Related~ |_IEFormElementGetValue|, |_IEFormElementGetCollection|, |_IEFormElementGetObjByName|, |_IEFormElementOptionSelect|, |_IEFormElementCheckboxSelect|, |_IEFormElementRadioSelect| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the form example, set the value of a text form element ; ******************************************************* ; #include $oIE = _IE_Example ("form") $oForm = _IEFormGetObjByName ($oIE, "ExampleForm") $oText = _IEFormElementGetObjByName ($oForm, "textExample") _IEFormElementSetValue ($oText, "Hey! This works!") ; ******************************************************* ; Example 2 - Get a reference to a specific form element and set its value. ; In this case, submit a query to the Google search engine ; ******************************************************* ; #include $oIE = _IECreate ("http://www.google.com") $oForm = _IEFormGetObjByName ($oIE, "f") $oQuery = _IEFormElementGetObjByName ($oForm, "q") _IEFormElementSetValue ($oQuery, "AutoIt IE.au3") _IEFormSubmit ($oForm) ; ******************************************************* ; Example 3 - Login to Hotmail ; ******************************************************* ; #include ; Create a browser window and navigate to hotmail $oIE = _IECreate ("http://www.hotmail.com") ; get pointers to the login form and username, password and signin fields $o_form = _IEFormGetObjByName ($oIE, "f1") $o_login = _IEFormElementGetObjByName ($o_form, "login") $o_password = _IEFormElementGetObjByName ($o_form, "passwd") $o_signin = _IEFormElementGetObjByName ($o_form, "SI") $username = "your username here" $password = "your password here" ; Set field values and submit the form _IEFormElementSetValue ($o_login, $username) _IEFormElementSetValue ($o_password, $password) _IEAction ($o_signin, "click") ; ******************************************************* ; Example 4 - Set the value of an INPUT TYPE=FILE element ; (security restrictions prevent using _IEFormElementSetValue) ; ******************************************************* ; #include $oIE = _IE_Example("form") $oForm = _IEFormGetObjByName($oIE, "ExampleForm") $oInputFile = _IEFormElementGetObjByName($oForm, "fileExample") ; Assign input focus to the field and then send the text string _IEAction($oInputFile, "focus") Send("C:\myfile.txt") ; ******************************************************* ; Example 5 - Set the value of an INPUT TYPE=FILE element ; Same as previous example, but with invisible window ; (security restrictions prevent using _IEFormElementSetValue) ; ******************************************************* ; #include $oIE = _IE_Example("form") ; Hide the browser window to demonstrate sending text to invisible window _IEAction($oIE, "invisible") $oForm = _IEFormGetObjByName($oIE, "ExampleForm") $oInputFile = _IEFormElementGetObjByName($oForm, "fileExample") ; Assign input focus to the field and then send the text string _IEAction($oInputFile, "focus") $hIE = _IEPropertyGet($oIE, "hwnd") ControlSend($hIE, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "C:\myfile.txt") MsgBox(0, "Success", "Value set to C:\myfile.txt") _IEAction($oIE, "visible") < -------------------------------------------------------------------------------- *_IEFormGetCollection* +----------------------+~ | _IEFormGetCollection |~ +----------------------+~ Returns a collection object variable representing the Forms in the document or a single form by index. > #include _IEFormGetCollection ( ByRef $o_object [, $i_index = -1] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window, Frame or iFrame object $i_index -------- [optional] specifies whether to return a collection or indexed instance 0 or positive integer returns an indexed instance -1 = (Default) returns a collection Return Value~ Success ------- Returns an object variable with a collection of all forms in the document, @EXTENDED = form count Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 5 ($_IEStatus_InvalidValue) = Invalid Value 7 ($_IEStatus_NoMatch) = No Match @Extended: Contains invalid parameter number Remarks~ None. Related~ |_IEFormGetObjByName|, |_IEFormReset|, |_IEFormSubmit| Example~ > ; ******************************************************* ; Example 1 - Get a reference to a specific form by 0-based index, ; in this case the first form on the page ; ******************************************************* ; #include $oIE = _IECreate ("http://www.google.com") $oForm = _IEFormGetCollection ($oIE, 0) $oQuery = _IEFormElementGetCollection ($oForm, 1) _IEFormElementSetValue ($oQuery, "AutoIt IE.au3") _IEFormSubmit ($oForm) ; ******************************************************* ; Example 2 - Get a reference to the collection of forms on a page, ; and then loop through them displaying information for each ; ******************************************************* ; #include $oIE = _IECreate ("http://www.autoitscript.com") $oForms = _IEFormGetCollection ($oIE) MsgBox(0, "Forms Info", "There are " & @extended & " forms on this page") For $oForm In $oForms MsgBox(0, "Form Info", $oForm.name) Next ; ******************************************************* ; Example 3 - Get a reference to the collection of forms on a page, ; and then loop through them displaying information for each ; demonstrating use of form index ; ******************************************************* ; #include $oIE = _IECreate ("http://www.autoitscript.com") $oForms = _IEFormGetCollection ($oIE) $iNumForms = @extended MsgBox(0, "Forms Info", "There are " & $iNumForms & " forms on this page") For $i = 0 to $iNumForms - 1 $oForm = _IEFormGetCollection ($oIE, $i) MsgBox(0, "Form Info", $oForm.name) Next < -------------------------------------------------------------------------------- *_IEFormGetObjByName* +---------------------+~ | _IEFormGetObjByName |~ +---------------------+~ Returns an object reference to a Form by name. > #include _IEFormGetObjByName ( ByRef $o_object, $s_name [, $i_index = 0] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window or Frame object $s_name ------- Specifies the name of the Form you wish to match $i_index -------- [optional] If Form name occurs more than once, specifies instance by 0-based index 0 (Default) or positive integer returns an indexed instance -1 returns a collection of the specified Forms Return Value~ Success ------- Returns an object variable pointing to the Form object, @EXTENDED = form count Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 7 ($_IEStatus_NoMatch) = No Match @Extended: Contains invalid parameter number Remarks~ If the desired form does not have a name or ID, _IEFormGetCollection to get a reference by index Related~ |_IEFormGetCollection|, |_IEFormReset|, |_IEFormSubmit| Example~ > ; ******************************************************* ; Example 1 - Get a reference to a specific form by name. In this case, submit a query ; to the Google search engine. Note that the names of the form and form ; elements can be found by viewing the page HTML source ; ******************************************************* ; #include $oIE = _IECreate ("http://www.google.com") $oForm = _IEFormGetObjByName ($oIE, "f") $oQuery = _IEFormElementGetObjByName ($oForm, "q") _IEFormElementSetValue ($oQuery, "AutoIt IE.au3") _IEFormSubmit ($oForm) < -------------------------------------------------------------------------------- *_IEFormImageClick* +-------------------+~ | _IEFormImageClick |~ +-------------------+~ Simulate a mouse click on an . Match by sub-string match of alt text, name or src. > #include _IEFormImageClick ( ByRef $o_object, $s_linkText [, $s_mode = "src" [, $i_index = 0 [, $f_wait = 1]]] ) < Parameters~ $o_object --------- Object variable of any DOM element (will be converted to the associated document object) $s_linkText ----------- Value used to match element - treatment based on $s_mode $s_mode ------- [optional] specifies search mode src = (Default) match the url of the image name = match the name of the image alt = match the alternate text of the image $i_index -------- [optional] If the img text occurs more than once, specifies which instance you want by 0-based index $f_wait ------- [optional] specifies whether to wait for page to load before returning 0 = Return immediately, not waiting for page to load 1 = (Default) Wait for page load to complete before returning Return Value~ Success ------- Returns -1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 1 ($_IEStatus_GeneralError) = General Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 5 ($_IEStatus_InvalidValue) = Invalid Value 6 ($_IEStatus_LoadWaitTimeout) = Load Wait Timeout 7 ($_IEStatus_NoMatch) = No Match 8 ($_IEStatus_AccessIsDenied) = Access Is Denied 9 ($_IEStatus_ClientDisconnected) = Client Disconnected @Extended: Contains invalid parameter number Remarks~ The form element is handled differently from all others. It is not recognized by Internet Explorer as a member of the form element collection and this function therefore gives you other means of getting a reference to it within the document using src, name or alt strings. Regardless of the object passed to this function, it looks for the form element within the full document context. Related~ |_IEImgClick|, |_IEImgGetCollection|, |_IELoadWait| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the form example, click on the ; form element with matching alt text ; ******************************************************* ; #include $oIE = _IE_Example ("form") _IEFormImageClick ($oIE, "AutoIt Homepage", "alt") ; ******************************************************* ; Example 2 - Open a browser with the form example, click on the ; form element with matching img source URL (sub-string) ; ******************************************************* ; #include $oIE = _IE_Example ("form") _IEFormImageClick ($oIE, "autoit_6_240x100.jpg", "src") ; ******************************************************* ; Example 3 - Open a browser with the form example, click on the ; form element with matching name ; ******************************************************* ; #include $oIE = _IE_Example ("form") _IEFormImageClick ($oIE, "imageExample", "name") < -------------------------------------------------------------------------------- *_IEFormReset* +--------------+~ | _IEFormReset |~ +--------------+~ > #include _IEFormReset ( ByRef $o_object ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Form object Return Value~ Success ------- Returns 1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type @Extended: Contains invalid parameter number Remarks~ None. Related~ |_IEFormSubmit|, |_IEFormGetObjByName|, |_IEFormGetCollection| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the form example, fill in a form field and ; reset the form back to default values ; ******************************************************* ; #include $oIE = _IE_Example ("form") $oForm = _IEFormGetObjByName ($oIE, "ExampleForm") $oText = _IEFormElementGetObjByName ($oForm, "textExample") _IEFormElementSetValue ($oText, "Hey! It works!") _IEFormReset ($oForm) < -------------------------------------------------------------------------------- *_IEFormSubmit* +---------------+~ | _IEFormSubmit |~ +---------------+~ Submit a specified Form. > #include _IEFormSubmit ( ByRef $o_object [, $f_wait = 1] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Form object $f_wait ------- [optional] specifies whether to wait for page to load before returning 0 = Return immediately, not waiting for page to load 1 = (Default) Wait for page load to complete before returning Return Value~ Success ------- Returns -1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 1 ($_IEStatus_GeneralError) = General Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 6 ($_IEStatus_LoadWaitTimeout) = Load Wait Timeout 8 ($_IEStatus_AccessIsDenied) = Access Is Denied 9 ($_IEStatus_ClientDisconnected) = Client Disconnected @Extended: Contains invalid parameter number Remarks~ For many HTML forms it is not sufficient to use _IEFormSubmit() because there is often custom JavaScript tied to an onClick event for its Submit button. In these cases you'll need to simulate a click of the submit button instead of using _IEFormSubmit(). See the example for the "click" action of _IEAction(). As well, some form processing relies on the "value" of the submit button being passed along with the rest of the form data (often when there is more than one submit button in the form and they are designed to trigger different results). This function will not result in a submit button value being passed. The solution is to use the "click" action of _IEAction() as above. If you experience trouble with the automatic _IELoadWait called by default, please set $f_wait parameter to 0 and call _IELoadWait from your script, passing it the InternetExplorer object. Related~ |_IEFormReset|, |_IEFormGetObjByName|, |_IEFormGetCollection|, |_IEFormElementGetObjByName|, |_IEFormElementGetCollection|, |_IELoadWait| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the form example, fill in a form field and submit the form ; ******************************************************* ; #include $oIE = _IE_Example ("form") $oForm = _IEFormGetObjByName ($oIE, "ExampleForm") $oText = _IEFormElementGetObjByName ($oForm, "textExample") _IEFormElementSetValue ($oText, "Hey! It works!") _IEFormSubmit ($oForm) ; ******************************************************* ; Example 2 - Get a reference to a specific form element and set its value. ; In this case, submit a query to the Google search engine ; ******************************************************* ; #include $oIE = _IECreate ("http://www.google.com") $oForm = _IEFormGetObjByName ($oIE, "f") $oQuery = _IEFormElementGetObjByName ($oForm, "q") _IEFormElementSetValue ($oQuery, "AutoIt IE.au3") _IEFormSubmit ($oForm) ; ******************************************************* ; Example 3 - Get a reference to a specific form element and set its value. ; Call _IELoadWait manually if the default _IELoadWait experiences trouble. ; ******************************************************* ; #include $oIE = _IECreate ("http://www.google.com") $oForm = _IEFormGetObjByName ($oIE, "f") $oQuery = _IEFormElementGetObjByName ($oForm, "q") _IEFormElementSetValue ($oQuery, "AutoIt IE.au3") _IEFormSubmit ($oForm, 0) _IELoadWait($oIE) < -------------------------------------------------------------------------------- *_IEFrameGetCollection* +-----------------------+~ | _IEFrameGetCollection |~ +-----------------------+~ Returns a collection object containing the frames in a FrameSet or the iFrames on a normal page or a single Frame or iFrame by index. > #include _IEFrameGetCollection ( ByRef $o_object [, $i_index = -1] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window or Frame object $i_index -------- [optional] specifies whether to return a collection or indexed instance 0 or positive integer returns an indexed instance -1 = (Default) returns a collection Return Value~ Success ------- Returns an object variable containing the Frames collection, @EXTENDED = Frame count Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 5 ($_IEStatus_InvalidValue) = Invalid Value 7 ($_IEStatus_NoMatch) = No Match @Extended: Contains invalid parameter number Remarks~ Although MSDN documents the return value for this function as a collection object, it cannot be looped through with a For...Next loop like a standard collection object. You must instead step through the collection by index - see example. Related~ |_IEIsFrameSet|, |_IEFrameGetObjByName| Example~ > ; ******************************************************* ; Example 1 - Open frameset example, get collection of frames ; and loop through them displaying their source URL's ; ******************************************************* ; #include $oIE = _IE_Example ("frameset") $oFrames = _IEFrameGetCollection ($oIE) $iNumFrames = @extended For $i = 0 to ($iNumFrames - 1) $oFrame = _IEFrameGetCollection ($oIE, $i) MsgBox(0, "Frame Info", _IEPropertyGet ($oFrame, "locationurl")) Next < -------------------------------------------------------------------------------- *_IEFrameGetObjByName* +----------------------+~ | _IEFrameGetObjByName |~ +----------------------+~ Returns an object reference to a Frame or iFrame by name. > #include _IEFrameGetObjByName ( ByRef $o_object, $s_name ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window or Frame object $s_name ------- Name of the Frame you wish to match Return Value~ Success ------- Returns an object variable pointing to the Window object in a Frame, @EXTENDED = Frame count Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 7 ($_IEStatus_NoMatch) = No Match @Extended: Contains invalid parameter number Remarks~ The object returned by this function is a window object which allows access to the document contained within. You may also want to access the frame or iframe tag and its properties - to do this, use _IETagNameGetCollection. Related~ |_IEFrameGetCollection| Example~ > ; ******************************************************* ; Example 1 - Open iFrame example, get a reference to the iFrame ; with a name of "iFrameTwo" and replace its body HTML ; ******************************************************* ; #include $oIE = _IE_Example ("iframe") $oFrame = _IEFrameGetObjByName ($oIE, "iFrameTwo") _IEBodyWriteHTML ($oFrame, "Hello iFrame!") _IELoadWait ($oFrame) < -------------------------------------------------------------------------------- *_IEGetObjById* +---------------+~ | _IEGetObjById |~ +---------------+~ Returns an object variable by id or name. > #include _IEGetObjById ( ByRef $o_object, $s_Id) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window or Frame object $s_Id ----- Specifies id or name of the object you wish to match Return Value~ Success ------- Returns an object variable pointing to the specified Object Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 7 ($_IEStatus_NoMatch) = No Match Remarks~ This function will return an object reference to any object in the document with a specified id or name. DOM elements can have Name or ID attributes or both. A specific ID can be assigned to only a single element while a specific Name can be assigned to multiple elements. In Internet Explorer, the Name and ID namespaces are shared. Related~ |_IEGetObjByName| Example~ > ; ******************************************************* ; Example 1 - Open a browser to the basic example, get an object reference ; to the DIV element with the ID "line1". Display the innerText ; of this element to the console. ; ******************************************************* ; #include $oIE = _IE_Example ("basic") $oDiv = _IEGetObjById ($oIE, "line1") ConsoleWrite(_IEPropertyGet($oDiv, "innertext") & @CRLF) < -------------------------------------------------------------------------------- *_IEGetObjByName* +-----------------+~ | _IEGetObjByName |~ +-----------------+~ Returns an object variable by name or id. > #include _IEGetObjByName ( ByRef $o_object, $s_Id [, $i_index = 0] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window or Frame object $s_Id ----- Specifies name or id of the object you wish to match $i_index -------- [optional] If name of id occurs more than once, specifies instance by 0-based index 0 (Default) or positive integer returns an indexed instance -1 returns a collection of the specified objects Return Value~ Success ------- Returns an object variable pointing to the specified Object, @EXTENDED = specified object count Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 7 ($_IEStatus_NoMatch) = No Match @Extended: Contains invalid parameter number Remarks~ This function will return an object reference to any object in the document with a specified name or id. DOM elements can have Name or ID attributes or both. A specific ID can be assigned to only a single element while a specific Name can be assigned to multiple elements. In Internet Explorer, the Name and ID namespaces are shared. Related~ |_IEGetObjById| Example~ > ; ******************************************************* ; Example 1 - Open a browser to the form example, get an object reference ; to the element with the name "ExampleForm". In this case the ; result is identical to using $oForm = _IEFormGetObjByName($oIE, "ExampleForm") ; ******************************************************* ; #include $oIE = _IE_Example ("form") $oForm = _IEGetObjByName ($oIE, "ExampleForm") < -------------------------------------------------------------------------------- *_IEHeadInsertEventScript* +--------------------------+~ | _IEHeadInsertEventScript |~ +--------------------------+~ Inserts a Javascript into the Head of the document. > #include _IEHeadInsertEventScript ( ByRef $o_object, $s_htmlFor, $s_event, $s_script ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window or Frame object $s_htmlFor ---------- The HTML element for event monitoring (e.g. "document", "window" or an element ID) $s_event -------- The event to monitor (e.g. "onclick" or "oncontextmenu") $s_script --------- Javascript string to be executed Return Value~ Success ------- Returns 1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type @Extended: Contains invalid parameter number Remarks~ Using ObjEvent, AutoIt is able to be notified of events via COM, but it manages them asynchronously (rather than synchronously as they are handled in the browser context). This routine allows you to inject code that is managed inside the browser context. Note that elements that do not have an ID assigned can still be used by obtaining their "uniqueID" property with _IEPropertyGet Related~ |_IEDocInsertHTML|, |_IEPropertyGet|, |_IEDocInsertText| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the basic example page, insert an ; event script into the head of the document that creates ; a JavaScript alert when someone clicks on the document ; ******************************************************* ; #include $oIE = _IE_Example ("basic") _IEHeadInsertEventScript ($oIE, "document", "onclick", "alert('Someone clicked the document!');") ; ******************************************************* ; Example 2 - Open a browser with the basic example page, insert an ; event script into the head of the document that creates ; a JavaScript alert when someone tries to right-click on the ; document and then the event script returns "false" to prevent ; the right-click context menu from appearing ; ******************************************************* ; #include $oIE = _IE_Example ("basic") _IEHeadInsertEventScript ($oIE, "document", "oncontextmenu", "alert('No Context Menu');return false") ; ******************************************************* ; Example 3 - Open a browser with the basic example page, insert an ; event script into the head of the document that creates a ; JavaScript alert when we are about to navigate away from the ; page and presents the option to cancel the operation. ; ******************************************************* ; #include $oIE = _IE_Example ("basic") _IEHeadInsertEventScript ($oIE, "window", "onbeforeunload", _ "alert('Example warning follows...');return 'Pending changes may be lost';") _IENavigate($oIE, "www.autoitscript.com") ; ******************************************************* ; Example 4 - Open a browser with the basic example page, insert an ; event script into the head of the document that prevents ; selection of text in the document ; ******************************************************* ; #include $oIE = _IE_Example() _IEHeadInsertEventScript ($oIE, "document", "ondrag", "return false;") _IEHeadInsertEventScript ($oIE, "document", "onselectstart", "return false;") ; ******************************************************* ; Example 5 - Open a browser with the AutoIt homepage, insert an ; event script into the head of the document that prevents ; navigation when any link is clicked and log the URL of the ; clicked link to the console ; ******************************************************* ; #include $oIE = _IECreate("http://www.autoitscript.com") $oLinks = _IELinkGetCollection($oIE) For $oLink in $oLinks $sLinkId = _IEPropertyGet($oLink, "uniqueid") _IEHeadInsertEventScript($oIE, $sLinkId, "onclick", "return false;") ObjEvent($oLink, "_Evt_") Next While 1 Sleep(100) WEnd Func _Evt_onClick() Local $o_link = @COM_EventObj ConsoleWrite($o_link.href & @CRLF) EndFunc < -------------------------------------------------------------------------------- *_IEImgClick* +-------------+~ | _IEImgClick |~ +-------------+~ Simulate a mouse click on an image. Match by sub-string match of alt text, name, or src. > #include _IEImgClick ( ByRef $o_object, $s_linkText [, $s_mode = "src" [, $i_index = 0 [, $f_wait = 1]]] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window or Frame object $s_linkText ----------- Text to match the content of the attribute specified in $s_mode $s_mode ------- [optional] specifies search mode src = (Default) match the url of the image name = match the name of the image alt = match the alternate text of the image $i_index -------- [optional] If the img text occurs more than once, specify which instance you want by 0-based index $f_wait ------- [optional] specifies whether to wait for page to load before returning 0 = Return immediately, not waiting for page to load 1 = (Default) Wait for page load to complete before returning Return Value~ Success ------- Returns -1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 1 ($_IEStatus_GeneralError) = General Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 5 ($_IEStatus_InvalidValue) = Invalid Value 6 ($_IEStatus_LoadWaitTimeout) = Load Wait Timeout 7 ($_IEStatus_NoMatch) = No Match 8 ($_IEStatus_AccessIsDenied) = Access Is Denied 9 ($_IEStatus_ClientDisconnected) = Client Disconnected @Extended: Contains invalid parameter number Remarks~ None. Related~ |_IEImgGetCollection|, |_IEFormImageClick|, |_IELoadWait| Example~ > ; ******************************************************* ; Example 1 - Click on IMG by Alt text ; ******************************************************* ; #include $oIE = _IE_Example ("basic") _IEImgClick ($oIE, "AutoIt Homepage Image", "alt") ; ******************************************************* ; Example 2 - Click on IMG by name ; ******************************************************* ; #include $oIE = _IE_Example ("basic") _IEImgClick ($oIE, "AutoItImage", "name") ; ******************************************************* ; Example 3 - Click on IMG by src sub-string ; ******************************************************* ; #include $oIE = _IE_Example ("basic") _IEImgClick ($oIE, "autoit_6_240x100.jpg", "src") ; ******************************************************* ; Example 4 - Click on IMG by full src string ; ******************************************************* ; #include $oIE = _IE_Example ("basic") _IEImgClick ($oIE, "http://www.autoitscript.com/images/autoit_6_240x100.jpg") < -------------------------------------------------------------------------------- *_IEImgGetCollection* +---------------------+~ | _IEImgGetCollection |~ +---------------------+~ Returns a collection object variable representing the IMG tags in the document or a single image by index. > #include _IEImgGetCollection ( ByRef $o_object [, $i_index = -1] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window, Frame or iFrame object $i_index -------- [optional] specifies whether to return a collection or indexed instance 0 or positive integer returns an indexed instance -1 = (Default) returns a collection Return Value~ Success ------- Returns an object variable with a collection of all IMG tags in the document, @EXTENDED = img count Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 5 ($_IEStatus_InvalidValue) = Invalid Value 7 ($_IEStatus_NoMatch) = No Match @Extended: Contains invalid parameter number Remarks~ None. Related~ |_IEFormImageClick|, |_IEImgClick| Example~ > ; ******************************************************* ; Example 1 - Create browser at AutoIt homepage, get a reference to ; the 6th Image on the page (note: the first image is index 0) ; and display information about it ; ******************************************************* ; #include $oIE = _IECreate ("http://www.autoitscript.com/") $oImg = _IEImgGetCollection ($oIE, 5) $sInfo = "Src: " & $oImg.src & @CR $sInfo &= "FileName: " & $oImg.nameProp & @CR $sInfo &= "Height: " & $oImg.height & @CR $sInfo &= "Width: " & $oImg.width & @CR $sInfo &= "Border: " & $oImg.border MsgBox(0, "4th Image Info", $sInfo) ; ******************************************************* ; Example 2 - Create browser at AutoIt homepage, get Img collection ; and display src URL for each ; ******************************************************* ; #include $oIE = _IECreate ("http://www.autoitscript.com/") $oImgs = _IEImgGetCollection ($oIE) $iNumImg = @extended MsgBox(0, "Img Info", "There are " & $iNumImg & " images on the page") For $oImg In $oImgs MsgBox(0, "Img Info", "src=" & $oImg.src) Next < -------------------------------------------------------------------------------- *_IEIsFrameSet* +---------------+~ | _IEIsFrameSet |~ +---------------+~ Checks to see if the specified Window contains a FrameSet. > #include _IEIsFrameSet ( ByRef $o_object ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window or Frame object Return Value~ Success ------- Returns 1 if the object references a FrameSet page Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type @Extended: Contains invalid parameter number Remarks~ _IEFrameGetCollection does not specify whether the referenced frames are part of a FrameSet or whether they are iFrames. If frames exist on a page and this function return False, then the frames are iFrames. Related~ |_IEFrameGetCollection| Example~ > ; ******************************************************* ; Example 1 - Display the frameset example, get frame collection, ; check number of frames, display number of frames or iFrames present ; ******************************************************* ; #include $oIE = _IE_Example ("frameset") $oFrames = _IEFrameGetCollection ($oIE) $iNumFrames = @extended If $iNumFrames > 0 Then If _IEIsFrameSet ($oIE) Then MsgBox(0, "Frame Info", "Page contains " & $iNumFrames & " frames in a FrameSet") Else MsgBox(0, "Frame Info", "Page contains " & $iNumFrames & " iFrames") EndIf Else MsgBox(0, "Frame Info", "Page contains no frames") EndIf < -------------------------------------------------------------------------------- *_IELinkClickByIndex* +---------------------+~ | _IELinkClickByIndex |~ +---------------------+~ Simulate a mouse click on a link by 0-based index (in source order). > #include _IELinkClickByIndex ( ByRef $o_object, $i_index [, $f_wait = 1] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window or Frame object $i_index -------- 0-based index of the link you wish to match $f_wait ------- [optional] specifies whether to wait for page to load before returning 0 = Return immediately, not waiting for page to load 1 = (Default) Wait for page load to complete before returning Return Value~ Success ------- Returns -1 Failure -------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 1 ($_IEStatus_GeneralError) = General Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 6 ($_IEStatus_LoadWaitTimeout) = Load Wait Timeout 7 ($_IEStatus_NoMatch) = No Match 8 ($_IEStatus_AccessIsDenied) = Access Is Denied 9 ($_IEStatus_ClientDisconnected) = Client Disconnected @Extended: Contains invalid parameter number Remarks~ Not all elements that appear to be links actually are. It is common practice to attach onClick JavaScript events to other DOM elements to simulate the behavior of links. To activate such elements, use "click" with _IEAction. Related~ |_IELinkClickByText|, |_IELoadWait| Example~ > ; ******************************************************* ; Example 1 - Open browser with basic example, click on the 3rd ; link on the page (note: the first link is index 0) ; ******************************************************* ; #include $oIE = _IE_Example ("basic") _IELinkClickByIndex ($oIE, 2) < -------------------------------------------------------------------------------- *_IELinkClickByText* +--------------------+~ | _IELinkClickByText |~ +--------------------+~ Simulate a mouse click on a link with text sub-string matching the string provided. > #include _IELinkClickByText ( ByRef $o_object, $s_linkText [, $i_index = 0[, $f_wait = 1]] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window or Frame object $s_linkText ----------- Text displayed on the web page for the desired link to click $i_index -------- [optional] If the link text occurs more than once, specify which instance you want by 0-based index $f_wait ------- [optional] specifies whether to wait for page to load before returning 0 = Return immediately, not waiting for page to load 1 = (Default) Wait for page load to complete before returning Return Value~ Success ------- Returns -1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 1 ($_IEStatus_GeneralError) = General Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 6 ($_IEStatus_LoadWaitTimeout) = Load Wait Timeout 7 ($_IEStatus_NoMatch) = No Match 8 ($_IEStatus_AccessIsDenied) = Access Is Denied 9 ($_IEStatus_ClientDisconnected) = Client Disconnected @Extended: Contains invalid parameter number Remarks~ Not all elements that appear to be links actually are. It is common practice to attach onClick JavaScript events to other DOM elements to simulate the behavior of links. To activate such elements, use "click" with _IEAction. Related~ |_IELinkClickByIndex|, |_IELoadWait| Example~ > ; ******************************************************* ; Example 1 - Open browser with basic example, click on the link ; with text "user forum" ; ******************************************************* ; #include $oIE = _IE_Example ("basic") _IELinkClickByText ($oIE, "user forum") ; ******************************************************* ; Example 2 - Open browser to the AutoIt homepage, loop through the links ; on the page and click on the link with text "wallpaper" ; using a sub-string match. ; ******************************************************* ; #include $oIE = _IECreate("http://www.autoitscript.com") $sMyString = "wallpaper" $oLinks = _IELinkGetCollection($oIE) For $oLink in $oLinks $sLinkText = _IEPropertyGet($oLink, "innerText") If StringInStr($sLinkText, $sMyString) Then _IEAction($oLink, "click") ExitLoop EndIf Next < -------------------------------------------------------------------------------- *_IELinkGetCollection* +----------------------+~ | _IELinkGetCollection |~ +----------------------+~ Returns a collection object containing all links in the document or a single link by index. > #include _IELinkGetCollection ( ByRef $o_object [, $i_index = -1] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window or Frame object $i_index -------- [optional] specifies whether to return a collection or indexed instance 0 or positive integer returns an indexed instance -1 = (Default) returns a collection Return Value~ Success ------- Returns an object collection of all links in the document, @EXTENDED = link count Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 5 ($_IEStatus_InvalidValue) = Invalid Value 7 ($_IEStatus_NoMatch) = No Match @Extended: Contains invalid parameter number Remarks~ Not all elements that appear to be links actually are. It is common practice to attach onClick JavaScript events to other DOM elements to simulate the behavior of links. To activate such elements, use "click" with _IEAction. Related~ None. Example~ > ; ******************************************************* ; Example 1 - Open browser with basic example, get link collection, ; loop through items and display the associated link URL references ; ******************************************************* ; #include $oIE = _IE_Example ("basic") $oLinks = _IELinkGetCollection ($oIE) $iNumLinks = @extended MsgBox(0, "Link Info", $iNumLinks & " links found") For $oLink In $oLinks MsgBox(0, "Link Info", $oLink.href) Next < -------------------------------------------------------------------------------- *_IELoadWait* +-------------+~ | _IELoadWait |~ +-------------+~ Wait for a browser page load to complete before returning. > #include _IELoadWait ( ByRef $o_object [, $i_delay = 0 [, $i_timeout = -1]] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application or DOM element $i_delay -------- [optional] Milliseconds to wait before checking status $i_timeout ---------- [optional] Period of time to wait before exiting function (default = 300000 ms aka 5 min) Return Value~ Success ------- Returns 1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 1 ($_IEStatus_GeneralError) = General Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 6 ($_IEStatus_LoadWaitTimeout) = Load Wait Timeout 8 ($_IEStatus_AccessIsDenied) = Access Is Denied 9 ($_IEStatus_ClientDisconnected) = Client Disconnected @Extended: Contains invalid parameter number Remarks~ Several IE.au3 functions call _IELoadWait() automatically (e.g. _IECreate(), _IENavigate() etc.). Most functions that do this also allow you to turn this off with a $f_wait parameter if you do not want the wait or if you want to call it yourself. When document objects or DOM elements are passed to _IELoadWait, it will check the readyState of the container elements up to and including the parentWindow. Browser scripting security restrictions may sometimes prevent _IELoadWait from guaranteeing that a page is fully loaded and can occasionally result in untrapped errors. In these cases you may need to avoid calling _IELoadWait and attempt to employ other methods of insuring that the page load has completed. These methods might include using a Sleep command, examining browser status bar text and other methods. When using functions that call _IELoadWait for objects other than the InternetExplorer (browser) object, you may also be successful by calling _IELoadWait for the browser yourself (e.g. _IELoadWait($oIE)). The most common causes of trouble are page redirects and cross-site scripting security restrictions associated with frames. Page re-writing techniques employed by some applications (e.g. Gmail) can also cause trouble here. Related~ |_IELoadWaitTimeout|, |_IECreate|, |_IENavigate|, |_IEFormSubmit|, |_IELinkClickByText|, |_IELinkClickByIndex|, |_IEImgClick|, |_IEFormImageClick|, |_IEBodyWriteHTML|, |_IEDocWriteHTML|, |_IEAction| Example~ > ; ******************************************************* ; Example 1 - Open the AutoIt forum page, tab to the "View new posts" ; link and activate the link with the enter key. ; Then wait for the page load to complete before moving on. ; ******************************************************* ; #include $oIE = _IECreate ("http://www.autoitscript.com/forum/index.php") Send("{TAB 12}") Send("{ENTER}") _IELoadWait ($oIE) < -------------------------------------------------------------------------------- *_IELoadWaitTimeout* +--------------------+~ | _IELoadWaitTimeout |~ +--------------------+~ Retrieve or set the current value in milliseconds _IELoadWait will try before timing out. > #include _IELoadWaitTimeout ( [$i_timeout = -1] ) < Parameters~ $i_timeout ---------- [optional] retrieve or specify the number of milliseconds 0 or positive integer sets timeout to this value -1 = (Default) returns the current timeout value (stored in global variable $__IELoadWaitTimeout) Return Value~ Success ------- If $i_timeout = -1, returns the current timeout value, else returns 1 Failure ------- None Remarks~ There is no way to completely disable the Timeout value. You can functionally do this however by setting it to a very large positive integer. The initial timeout value is 30000 ms (5 minutes). Related~ |_IELoadWait| Example~ > ; ******************************************************* ; Example 1 - Obtain current timeout value ; ******************************************************* ; #include $iCurrentTimeout = _IELoadWaitTimeout () ; ******************************************************* ; Example 2 - Set timeout to 1 minute (60000 milliseconds) ; ******************************************************* ; #include _IELoadWaitTimeout (60000) < -------------------------------------------------------------------------------- *_IENavigate* +-------------+~ | _IENavigate |~ +-------------+~ Directs an existing browser window to navigate to the specified URL. > #include _IENavigate ( ByRef $o_object, $s_url [, $f_wait = 1] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window or Frame object $s_url ------ URL to navigate to (e.g. "http://www.autoitscript.com") $f_wait ------- [optional] specifies whether to wait for page to load before returning 0 = Return immediately, not waiting for page to load 1 = (Default) Wait for page load to complete before returning Return Value~ Success ------- Returns -1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 1 ($_IEStatus_GeneralError) = General Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 6 ($_IEStatus_LoadWaitTimeout) = Load Wait Timeout 8 ($_IEStatus_AccessIsDenied) = Access Is Denied 9 ($_IEStatus_ClientDisconnected) = Client Disconnected @Extended: Contains invalid parameter number Remarks~ This function always returns a value of -1. This is because the navigate method has no useful return value and therefore nothing can be implied from it. You will need to employ other methods to determine success or failure of the navigation. New security in Windows Vista causes a new browser window to be created when a browser is instructed to navigate to a URL in a different security zone. This occurs as well with the initial creation and navigation initiated with _IECreate. The new window is a new browser instance and the previous browser object variable no longer points to it. There are several workarounds: 1) add #RequireAdmin to your code (this is required even if the account is part of the Administrator's Group and will propmt for credentials if necessary), 2) use _IEAttach to connect to the new browser window 3) add the target website to the Trusted Sites security zone in IE, 4) turn off "Protected Mode" in IE, or 5) disable UAC. Care must be taken to understand the implications of disabling IE security features when accessing untrusted sites. Related~ |_IECreate|, |_IECreateEmbedded|, |_IELoadWait| Example~ > ; ******************************************************* ; Example 1 - Create a browser window and navigate to a website, ; wait 5 seconds and navigate to another ; wait 5 seconds and navigate to another ; ******************************************************* ; #include $oIE = _IECreate ("www.autoitscript.com") Sleep(5000) _IENavigate ($oIE, "http://www.autoitscript.com/forum/index.php?") Sleep(5000) _IENavigate ($oIE, "http://www.autoitscript.com/forum/index.php?showforum=9") ; ******************************************************* ; Example 2 - Create a browser window and navigate to a website, ; do not wait for page load to complete before moving to next line ; ******************************************************* ; #include $oIE = _IECreate ("www.autoitscript.com", 0) MsgBox(0, "_IENavigate()", "This code executes immediately") < -------------------------------------------------------------------------------- *_IEPropertyGet* +----------------+~ | _IEPropertyGet |~ +----------------+~ Returns a select property of the Browser or DOM element. > #include _IEPropertyGet ( ByRef $o_object, $s_property ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application or DOM element $s_property ----------- Property selection (see remarks) Return Value~ Success ------- Value of selected Property Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 5 ($_IEStatus_InvalidValue) = Invalid Value @Extended: Contains invalid parameter number Remarks~ Further information can be found at MSDN. The following tables provide a description of each property available for use. Some properties to DOM elements, others to the browser. Browser Properties Property Description ------------------ -------------------- "addressbar" Retrieves a Boolean value indicating whether the browser address bar is visible or hidden. "browserx" Retrieves the x-coordinate of the top left corner of a document element, relative to the browser. "browsery" Retrieves the y-coordinate of the top left corner of a document element, relative to the browser. "busy" Retrieves a Boolean value indicating whether the object is engaged in a navigation or downloading operation. "contenteditable" Retrieves a Boolean value that indicates whether the object can be edited with mouse and keyboard. "fullscreen" Retrieves a Boolean value that indicates whether the browser is in full-screen or normal window mode. "height" Retrieves the height of the browser main window or a document element. "hwnd" Retrieves the handle of the Internet Explorer main window. Can be used in most AutoIt Win* functions. "innerhtml" Retrieves the rendered HTML of an element excluding the beginning and ending element tags. "innertext" Retrieves the rendered Text (but not any tags) of an element. Typically identical to outertext. "isdisabled" Retrieves the value indicating whether the user can interact with the object. "left" Retrieves the screen coordinate of the left edge of the main window of the object. "locationname" Retrieves the name of the resource that Internet Explorer is currently displaying. "locationurl" Retrieves the URL of the resource that Internet Explorer is currently displaying. "menubar" Retrieves a Boolean value that indicates whether the browser menu bar is visible. "offline" Retrieves a Boolean value that indicates whether the browser is currently operating in offline mode. "outertext" Retrieves the rendered Text (but not any tags) of an element. Typically identical to innertext. "outerhtml" Retrieves the rendered HTML of an element including the beginning and ending element tags. "readystate" Retrieves the ready state of the object. "referrer" Retrieves a string of the URL of the page from which the current page was accessed (but only if accessed via a link on that page, else the string is null). "resizable" Retrieves a value that indicates whether the object can be resized. "screenx" Retrieves the x-coordinate of the top left corner of a document object or the browser, relative to the screen. "screeny" Retrieves the y-coordinate of the top left corner of a document object or the browser, relative to the screen. "silent" Retrieves a value that indicates whether the browser can show dialog boxes. "statusbar" Retrieves a value that indicates whether the status bar for the object is visible. "statustext" Retrieves the text in the status bar for the object. "theatermode" Retrieves a Boolean value indicating whether the browser is in Theater Mode. In theater mode, the browser main window fills the entire screen and displays a toolbar with a minimal set of navigational buttons. "title" Retrieves the document title. Note that this is different than the window title which typically starts with the document title, but has additional text specified in the windows registry appended to it. "toolbar" Retrieves a Boolean value indicating whether the tool bar of the browser is visible or hidden. "top" Retrieves the screen coordinate of the top edge of the main window of the object. "visible" Retrieves a value that indicates whether the object is visible or hidden. "width" Retrieves the width of the browser main window or a document element. "uniqueid" Retrieves an ID assigned by the DOM that is unique among all elements. This can be used in any context that requires an element ID. ClientInfo Properties Property Description --------------------- -------------------- "appcodename" Retrieves the code name of the browser (the property has a default value of Mozilla). "appminorversion" Retrieves the application's minor version value. "appname" Retrieves the name of the browser (the property has a default value of Microsoft Internet Explorer). "appversion" Retrieves the platform and version of the browser. "browserlanguage" Retrieves the current browser language (the value will be one of these Language Codes). "cookieenabled" Retrieves whether client-side persistent cookies are enabled in the browser. Persistent cookies are those that are stored on the client-side computer. "cpuclass" Retrieves a string denoting the CPU class (the return values can be found here). "javaenabled" Returns whether Java is enabled. "online" Retrieves a value indicating whether the system is in global offline mode. "platform" Retrieves the name of the user's operating system (the return values can be found here). "systemlanguage" Retrieves the default language used by the operating system (the value will be one of these Language Codes). "useragent" Retrieves a string equivalent to the HTTP user-agent request header. "userlanguage" Retrieves the operating system's natural language setting (the value will be one of these Language Codes). "vcard" Returns an array containing each attribute in the userProfile object (a list of attributes can be found here). The return is a two dimentional array, where the first dimention has two elements. The first element (0) contains the attribute names, the second element (1) contains the corresponding values. The second dimention has 29 elements (0 to 28). Related~ |_IEPropertySet|, |_IEBodyReadHTML|, |_IEBodyReadText|, |_IEBodyWriteHTML|, |_IEDocInsertHTML|, |_IEDocInsertText|, |_IEHeadInsertEventScript| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the basic example, check to see if the ; addressbar is visible, if it is turn it off, if it is not turn it on ; ******************************************************* ; #include $oIE = _IE_Example ("basic") If _IEPropertyGet ($oIE, "addressbar") Then MsgBox(0, "AddressBar Status", "AddressBar Visible, turning it off") _IEPropertySet ($oIE, "addressbar", False) Else MsgBox(0, "AddressBar Status", "AddressBar Invisible, turning it on") _IEPropertySet ($oIE, "addressbar", True) EndIf ; ******************************************************* ; Example 2 - Open a browser with the form example and get a reference to the form ; textarea element. Get the coordinates and dimensions of the text area, ; outline its shape with the mouse and come to rest in the center ; ******************************************************* ; $oIE = _IE_Example("form") $oForm = _IEFormGetObjByName($oIE, "ExampleForm") $oTextArea = _IEFormElementGetObjByName($oForm, "textareaExample") ; Get coordinates and dimensions of the textarea $iScreenX = _IEPropertyGet($oTextArea, "screenx") $iScreenY = _IEPropertyGet($oTextArea, "screeny") $iBrowserX = _IEPropertyGet($oTextArea, "browserx") $iBrowserY = _IEPropertyGet($oTextArea, "browserY") $iWidth = _IEPropertyGet($oTextArea, "width") $iHeight = _IEPropertyGet($oTextArea, "height") ; Outline the textarea with the mouse, come to rest in the center MouseMove($iScreenX, $iScreenY) MouseMove($iScreenX + $iWidth, $iScreenY) MouseMove($iScreenX + $iWidth, $iScreenY + $iHeight) MouseMove($iScreenX, $iScreenY + $iHeight) MouseMove($iScreenX, $iScreenY) MouseMove($iScreenX + $iWidth/2, $iScreenY + $iHeight/2) < -------------------------------------------------------------------------------- *_IEPropertySet* +----------------+~ | _IEPropertySet |~ +----------------+~ Set a select property of the Browser or DOM element. > #include _IEPropertySet ( ByRef $o_object, $s_property, $newvalue ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application $s_property ----------- Property selection (see remarks) $newvalue --------- The new value to be set into the Browser Property Return Value~ Success ------- Returns 1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 5 ($_IEStatus_InvalidValue) = Invalid Value @Extended: Contains invalid parameter number Remarks~ Further information can be found at MSDN. The following table provide a description of each property available for use. Some properties to DOM elements, others to the browser. Browser Properties Property Description ------------------ -------------------- "addressbar" Specifies whether the address bar of the object is visible or hidden. "contenteditable" Specifies a Boolean value that indicates whether the object can be edited with mouse and keyboard. "height" Specifies the height of the browser main window. "innerhtml" Sets the rendered HTML of an element excluding the beginning and ending element tags. "innertext" Sets the rendered Text (but not any tags) of an element. Typically identical to outertext. "left" Specifies the screen coordinate of the left edge of the browser main window. "menubar" Specifies a Boolean value that indicates whether the browser menu bar is visible. "offline" Specifies a Boolean value that indicates whether the browser is currently operating in offline mode. "outertext" Sets the rendered Text (but not any tags) of an element. Typically identical to innertext. "outerhtml" Sets the rendered HTML of an element including the beginning and ending element tags. "resizable" Specifies a Boolean value that indicates whether the object can be resized. "silent" Specifies a Boolean value that indicates whether the browser can show dialog boxes. "statusbar" Specifies a value that indicates whether the browser status bar is visible. "statustext" Specifies the text in the browser status bar. "theatermode" Specifies a Boolean value indicating whether the browser is in Theater Mode. In theater mode, the browser main window fills the entire screen and displays a toolbar with a minimal set of navigational buttons. "title" Sets the document title. Note that this is different than the window title which typically starts with the document title, but has additional text specified in the windows registry appended to it. "toolbar" Specifies a Boolean value indicating whether the tool bar of the browser is visible or hidden. "top" Specifies the screen coordinate of the top edge of the browser main window. "width" Specifies the width of the browser main window. Related~ |_IEPropertyGet|, |_IEAction|, |_IEBodyWriteHTML|, |_IEDocInsertHTML|, |_IEDocInsertText| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the basic example, check to see if the ; addressbar is visible, if it is not turn it on. Then change ; the text displayed in the statusbar ; ******************************************************* ; #include $oIE = _IE_Example ("basic") If Not _IEPropertyGet ($oIE, "statusbar") Then _IEPropertySet ($oIE, "statusbar", True) _IEPropertySet ($oIE, "statustext", "Look What I can Do") Sleep(1000) _IEPropertySet ($oIE, "statustext", "I can change the status text") < -------------------------------------------------------------------------------- *_IEQuit* +---------+~ | _IEQuit |~ +---------+~ Close the browser and remove the object reference to it. > #include _IEQuit ( ByRef $o_object ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application Return Value~ Success ------- Returns 1 Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type @Extended: Contains invalid parameter number Remarks~ _IEQuit is particularly important when creating or working with invisible instances of Internet Explorer. When AutoIt exits when working with visible instances of a browser, the browser continues to run and the visible window is left for the user to manage. When the browser instance is invisible however, when AutoIt exits the browser process is left running and there is no user interface to interact with and an orphan Iexplore.exe process is left running on the system. It is therefore good practice to call _IEQuit whenever the browser process is not needed after the script exists. _IEQuit is not allowed with embedded browser objects created with _IECreateEmbedded. The browser processes associated with those objects will close when their parent GUI window is destroyed. Related~ |_IEAttach|, |_IECreate| Example~ > ; ******************************************************* ; Example 1 - Create an invisible browser window, navigate to a ; website, retrieve some information and Quit ; ******************************************************* ; #include $oIE = _IECreate ("http://sourceforge.net", 0, 0) ; Display the innerText on an element on the page with a name of "sfmarquee" $oMarquee = _IEGetObjByName ($oIE, "sfmarquee") MsgBox(0, "SourceForge Information", $oMarquee.innerText) _IEQuit ($oIE) < -------------------------------------------------------------------------------- *_IETableGetCollection* +-----------------------+~ | _IETableGetCollection |~ +-----------------------+~ Returns a collection object variable representing all the tables in a document or a single table by index. > #include _IETableGetCollection ( ByRef $o_object [, $i_index = -1] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window or Frame object $i_index -------- [optional] specifies whether to return a collection or indexed instance 0 or positive integer returns an indexed instance -1 = (Default) returns a collection Return Value~ Success ------- Returns an object collection of all tables in the document, @EXTENDED = table count Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 5 ($_IEStatus_InvalidValue) = Invalid Value 7 ($_IEStatus_NoMatch) = No Match @Extended: Contains invalid parameter number Remarks~ None. Related~ |_IETableWriteToArray| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the table example, get a reference to the first table ; on the page (index 0) and read its contents into a 2-D array ; ******************************************************* ; #include $oIE = _IE_Example ("table") $oTable = _IETableGetCollection ($oIE, 0) $aTableData = _IETableWriteToArray ($oTable) ; ******************************************************* ; Example 2 - Open a browser with the table example, get a reference to the ; table collection and display the number of tables on the page ; ******************************************************* ; #include $oIE = _IE_Example ("table") $oTable = _IETableGetCollection ($oIE) $iNumTables = @extended MsgBox(0, "Table Info", "There are " & $iNumTables & " tables on the page") < -------------------------------------------------------------------------------- *_IETableWriteToArray* +----------------------+~ | _IETableWriteToArray |~ +----------------------+~ Reads the contents of a Table into an array. > #include _IETableWriteToArray ( ByRef $o_object [, $f_transpose] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Table object $f_transpose ------------ [optional] Boolean value specifying whether to swap the rows and columns in the output array Return Value~ Success ------- Returns a 2-dimensional array containing the contents of the Table Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type @Extended: Contains invalid parameter number Remarks~ When table cells span multiple columns or rows, blank array elements are added to properly align the results. Data in spanning cells will be in the left or uppermost array elements. Tables are often nested in HTML documents. If all of your data is unexpectedly returned in a single array element, you may need to reference a more deeply nested table to this function. Related~ |_IETableGetCollection| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the table example, get a reference to the second table ; on the page (index 1) and read its contents into a 2-D array ; ******************************************************* ; #include $oIE = _IE_Example ("table") $oTable = _IETableGetCollection ($oIE, 1) $aTableData = _IETableWriteToArray ($oTable) ; ******************************************************* ; Example 2 - Same as Example 1, except transpose the output array and display ; the results with _ArrayDisplay() ; ******************************************************* ; #include #include $oIE = _IE_Example ("table") $oTable = _IETableGetCollection ($oIE, 1) $aTableData = _IETableWriteToArray ($oTable, True) _ArrayDisplay($aTableData) < -------------------------------------------------------------------------------- *_IETagNameAllGetCollection* +----------------------------+~ | _IETagNameAllGetCollection |~ +----------------------------+~ Returns a collection object all elements in the document or document hierarchy in source order or a single element by index. > #include _IETagNameAllGetCollection ( ByRef $o_object [, $i_index = -1] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window, Frame, iFrame or any object in the DOM $i_index -------- [optional] specifies whether to return a collection or indexed instance 0 or positive integer returns an indexed instance -1 = (Default) returns a collection Return Value~ Success ------- Returns an object variable containing the Tag collection, @EXTENDED = Tag count Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 5 ($_IEStatus_InvalidValue) = Invalid Value 7 ($_IEStatus_NoMatch) = No Match @Extended: Contains invalid parameter number Remarks~ The DOM is hierarchical, so if the object passed is the document object, all elements in the document are returned. If the object passed in is an object inside the document (e.g. a TABLE object), then only the elements inside that object are returned. Related~ |_IETagNameGetCollection| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the basic example, get the collection ; of all elements and display the tagname and innerText of each ; ******************************************************* ; #include $oIE = _IE_Example ("basic") $oElements = _IETagNameAllGetCollection ($oIE) For $oElement In $oElements MsgBox(0, "Element Info", "Tagname: " & $oElement.tagname & @CR & "innerText: " & $oElement.innerText) Next < -------------------------------------------------------------------------------- *_IETagNameGetCollection* +-------------------------+~ | _IETagNameGetCollection |~ +-------------------------+~ Returns a collection object of all elements in the object with the specified TagName or a single element by index. > #include _IETagNameGetCollection ( ByRef $o_object, $s_TagName [, $i_index = -1] ) < Parameters~ $o_object --------- Object variable of an InternetExplorer.Application, Window, Frame, iFrame or any object in the DOM $s_TagName ---------- TagName of collection to return (e.g. IMG, TR etc.) $i_index -------- [optional] specifies whether to return a collection or indexed instance 0 or positive integer returns an indexed instance -1 = (Default) returns a collection Return Value~ Success ------- Returns an object variable containing the specified Tag collection, @EXTENDED = specified Tag count Failure ------- Returns 0 and sets @ERROR @Error: 0 ($_IEStatus_Success) = No Error 3 ($_IEStatus_InvalidDataType) = Invalid Data Type 4 ($_IEStatus_InvalidObjectType) = Invalid Object Type 5 ($_IEStatus_InvalidValue) = Invalid Value 7 ($_IEStatus_NoMatch) = No Match @Extended: Contains invalid parameter number Remarks~ The DOM is hierarchical, so if the object passed is the document object, the specified elements in the document are returned. If the object passed is an object inside the document (e.g. a TABLE object), then only the specified elements inside that object are returned. Related~ |_IETagNameAllGetCollection| Example~ > ; ******************************************************* ; Example 1 - Open a browser with the form example, get the collection ; of all INPUT tags and display the formname and type of each ; ******************************************************* ; #include $oIE = _IE_Example ("form") $oInputs = _IETagNameGetCollection ($oIE, "input") For $oInput In $oInputs MsgBox(0, "Form Input Type", "Form: " & $oInput.form.name & " Type: " & $oInput.type) Next < ---------------------------------------------------------------------- *StringInStr* +-------------+~ | StringInStr |~ +-------------+~ Checks if a string contains a given substring. > StringInStr ( " string ", " substring " [, casesense [, occurrence [, start [, count ]]]] ) < Parameters~ string~ ------ The string to evaluate. substring~ --------- The substring to search for. casesense [optional]~ -------------------- Flag to indicate if the operations should be case sensitive. 0 = not case sensitive, using the user's locale (default) 1 = case sensitive 2 = not case sensitive, using a basic/faster comparison occurrence [optional] Which occurrence of the substring to find in the string. Use a negative occurrence to search from the right side. The default value is 1 (finds first occurrence). start [optional]~ ---------------- The starting position of the search. count [optional]~ ---------------- The number of characters to search. This effectively limits the search to a portion of the full string. See remarks. Return Value~ Success~ ------- Returns the position of the substring. Failure~ ------- Returns 0 if substring not found. @Error 0 - Normal operation 1 - Invalid "start" or "occurence" parameter given. Remarks~ The first character position is 1. The count parameter must be longer than the substring being searched for. The count parameter (combined with the start parameter) effectively limits the search to a substring of the full string. The following two statements are equivalent: > StringInStr("the string to search", "string", 0, 1, 1, 11) StringInStr(StringMid("the string to search", 1, 11), "string") < Related~ |StringCompare|, |StringLeft|, |StringLen|, |StringLower|, |StringMid|, |StringRight|, |StringTrimLeft|, |StringTrimRight|, |StringUpper|, |StringRegExp|, |StringSplit| Example~ > $result = StringInStr("I am a String", "RING") MsgBox(0, "Search result:", $result) $location = StringInStr("How much wood could a woodchuck chuck is a woodchuck could chuck wood?", "wood", 0, 3) ; Find the 3rd occurance of "wood" < -------------------------------------------------------------------------------- *StringIsAlNum* +---------------+~ | StringIsAlNum |~ +---------------+~ Checks if a string contains only alphanumeric characters. > StringIsAlNum ( "string" ) < Parameters~ string ------ The string to check Return Value~ Success ------- 1. Failure ------- 0 if string contains non-alphanumeric characters. Remarks~ Keep in mind that any whitespace will cause StringIsAlNum() to return 0. Related~ |StringIsAlpha|, |StringIsASCII|, |StringIsDigit|, |StringIsLower|, |StringIsSpace|, |StringIsUpper|, |StringIsXDigit|, |StringLower|, |StringUpper| Example~ > #include Local $sString = "This is a sentence with whitespace." ; Check whether this string contains only alphanumeric characters. If StringIsAlNum($sString) Then MsgBox($MB_SYSTEMMODAL, "", "The variable contains only alphanumeric characters.") Else MsgBox($MB_SYSTEMMODAL, "", "The variable does not contain alphanumeric characters.") EndIf < -------------------------------------------------------------------------------- *StringIsAlpha* +---------------+~ | StringIsAlpha |~ +---------------+~ Checks if a string contains only alphabetic characters. > StringIsAlpha ( "string" ) < Parameters~ string ------ The string to check Return Value~ Success ------- 1. Failure ------- 0 if string contains non-alphabetic characters. Remarks~ Keep in mind that any whitespace will cause StringIsAlpha() to return 0. Related~ |StringIsAlNum|, |StringIsASCII|, |StringIsDigit|, |StringIsLower|, |StringIsSpace|, |StringIsUpper|, |StringIsXDigit|, |StringLower|, |StringUpper| Example~ > #include Local $sString = "This is a sentence with whitespace." ; Check whether this string contains only alphabetic characters. If StringIsAlpha($sString) Then MsgBox($MB_SYSTEMMODAL, "", "The variable contains only alphabetic characters.") Else MsgBox($MB_SYSTEMMODAL, "", "The variable does not contain alphabetic characters.") EndIf < -------------------------------------------------------------------------------- *StringIsASCII* +---------------+~ | StringIsASCII |~ +---------------+~ Checks if a string contains only ASCII characters in the range 0x00 - 0x7f (0 - 127). > StringIsASCII ( "string" ) < Parameters~ string The string to check Return Value~ Success ------- 1. Failure ------- 0 if string contains extended ASCII characters. Related~ |StringIsAlNum|, |StringIsAlpha|, |StringIsDigit|, |StringIsLower|, |StringIsSpace|, |StringIsUpper|, |StringIsXDigit|, |StringLower|, |StringUpper| Example~ > #include Local $sString = "This is a sentence with whitespace." ; Check whether this string contains only ASCII characters. If StringIsASCII($sString) Then MsgBox($MB_SYSTEMMODAL, "", "The variable contains ASCII characters.") Else MsgBox($MB_SYSTEMMODAL, "", "The variable does not contain ASCII characters.") EndIf < -------------------------------------------------------------------------------- *StringIsDigit* +---------------+~ | StringIsDigit |~ +---------------+~ Checks if a string contains only digit (0-9) characters. > StringIsDigit ( "string" ) < Parameters~ string ------ The string to check Return Value~ Success ------- 1. Failure ------- 0 if string contains non-digits. Remarks~ See examples. Related~ |StringIsAlNum|, |StringIsAlph|, |StringIsASCII|, |StringIsInt|, |StringIsLower|, |StringIsSpace|, |StringIsUpper|, |StringIsXDigit| Example~ > #include MsgBox($MB_SYSTEMMODAL, "", "Is the string 42 a digit: " & StringIsDigit("42") & @CRLF & _ ; Returns 1, as the string contains only digit (0-9) characters. "Is the string 00 a digit: " & StringIsDigit("00") & @CRLF & _ ; Returns 1, as the string contains only digit (0-9) characters. "Is the string 1.0 a digit: " & StringIsDigit("1.0") & @CRLF & _ ; Returns 0, due to the decimal point. "Is the number 1.0 a digit: " & StringIsDigit(1.0) & @CRLF & _ ; Returns 1, due to the number to string conversion. "Is the string 1+2 a digit: " & StringIsDigit("1+2") & @CRLF) ; Returns 0, as the + (plus) symbol is present in the string. < -------------------------------------------------------------------------------- *StringIsFloat* +---------------+~ | StringIsFloat |~ +---------------+~ Checks if a string is a floating point number. > StringIsFloat ( "string" ) < Parameters~ string ------ The string or expression to check. Return Value~ Success ------- 1. Failure ------- 0 if not floating point format. Remarks~ A string is a float if it contains at least one decimal digit and exactly one period; the only other character allowed is an optional plus or minus at the beginning. (StringIsFloat() does not accept a comma character as the decimal point even if the computer Locale settings use that symbol.) If parameter is not a string, its value is converted to a string. See examples. Related~ |IsFloat|, |StringIsInt| Example~ > #include MsgBox($MB_SYSTEMMODAL, "", "Is the string 1.5 a floating point number: " & StringIsFloat("1.5") & @CRLF & _ ; Returns 1, due to the decimal point. "Is the string 7. a floating point number: " & StringIsFloat("7.") & @CRLF & _ ; Returns 1, due to the decimal point. "Is the string 3/4 a floating point number: " & StringIsFloat("3/4") & @CRLF & _ ; Returns 0, as the string 3 / (forward slash) 4 is not a floating point number. "Is the number 1.0 a floating point number: " & StringIsFloat(1.0) & @CRLF & _ ; Returns 1, due to the number to string conversion as well as the decimal point. "Is the string 2 a floating point number: " & StringIsFloat("2") & @CRLF) ; Returns 0, due to 2 being an integer. < -------------------------------------------------------------------------------- *StringIsInt* +-------------+~ | StringIsInt |~ +-------------+~ Checks if a string is an integer. > StringIsInt ( "string" ) < Parameters~ string The string to check. Return Value~ Success ------- 1. Failure ------- 0 if string cannot be an integer. Remarks~ StringIsInt() also returns 1 for non-string integer expressions; however, StringIsInt() returns 0 for hexadecimal expressions such as "4ff0". The only punctuation allowed is either a plus or a minus at the beginning of the string. Related~ |IsInt|, |StringIsDigit|, |StringIsFloat| Example~ > #include MsgBox($MB_SYSTEMMODAL, "", "Is the string +42 an integer: " & StringIsInt("+42") & @CRLF & _ ; Returns 1, due to the + (plus) symbol being at the beginning of the string. "Is the string -00 an integer: " & StringIsInt("-00") & @CRLF & _ ; Returns 1, due to the - (minus) symbol being at the beginning of the string. "Is the string 1.0 an integer: " & StringIsInt("1.0") & @CRLF & _ ; Returns 0, due to the decimal point. "Is the number 1.0 an integer: " & StringIsInt(1.0) & @CRLF & _ ; Returns 1, due to the number to string conversion. "Is the string 1+2 an integer: " & StringIsInt("1+2") & @CRLF) ; Returns 0, as the + (plus) symbol is not at the beginning of the string. < -------------------------------------------------------------------------------- *StringIsLower* +---------------+~ | StringIsLower |~ +---------------+~ Checks if a string contains only lowercase characters. > StringIsLower ( "string" ) < Parameters~ string ------ The string to check Return Value~ Success ------- 1. Failure ------- 0 if string contains non-lowercase characters. Remarks~ Note that digits/punctuation/whitespace will cause StringIsLower() to return 0. Related~ |StringIsAlNum|, |StringIsAlpha|, |StringIsASCII|, |StringIsDigit|, |StringIsSpace|, |StringIsUpper|, |StringIsXDigit|, |StringLower|, |StringUpper| Example~ > #include Local $sString = "lowercase" ; Check whether this string contains only lowercase characters. If StringIsLower($sString) Then MsgBox($MB_SYSTEMMODAL, "", "The variable is a lowercase string") Else MsgBox($MB_SYSTEMMODAL, "", "The variable is not a lowercase string") EndIf < -------------------------------------------------------------------------------- *StringIsSpace* +---------------+~ | StringIsSpace |~ +---------------+~ Checks if a string contains only whitespace characters. > StringIsSpace ( "string" ) < Parameters~ string ------ The string to check Return Value~ Success ------- 1. Failure ------- 0 if string contains non-whitespace characters. Remarks~ Whitespace includes Chr(9) thru Chr(13) which are HorizontalTab, LineFeed, VerticalTab, FormFeed, and CarriageReturn. Whitespace also includes the null string ( Chr(0) ) and the standard space ( Chr(32) ). Related~ |StringIsAlNum|, |StringIsAlpha|, |StringIsASCII|, |StringIsDigit|, |StringIsLower|, |StringIsUpper|, |StringIsXDigit|, |StringLower|, |StringStripCR|, |StringStripWS|, |StringUpper| Example~ > #include Local $sString = " " & @CRLF & @CRLF & Chr(11) & @TAB & " " & @CRLF ; Check whether this string contains only whitespace characters. If StringIsSpace($sString) Then MsgBox($MB_SYSTEMMODAL, "", "The variable contains only whitespace characters.") Else MsgBox($MB_SYSTEMMODAL, "", "The variable does not contain whitespace characters.") EndIf < -------------------------------------------------------------------------------- *StringIsUpper* +---------------+~ | StringIsUpper |~ +---------------+~ Checks if a string contains only uppercase characters. > StringIsUpper ( "string" ) < Parameters~ string ------ The string to check Return Value~ Success ------- 1. Failure ------- 0 if string contains non-uppercase characters. Remarks~ Note that digits/punctuation/whitespace will cause StringIsUpper() to return 0. Related~ |StringIsAlNum|, |StringIsAlpha|, |StringIsASCII|, |StringIsDigit|, |StringIsLower|, |StringIsSpace|, |StringIsXDigit|, |StringLower|, |StringUpper| Example~ > #include Local $sString = "UPPERCASESTRING" ; Check whether this string contains only uppercase characters. If StringIsUpper($sString) Then MsgBox($MB_SYSTEMMODAL, "", "The variable is an uppercase string") Else MsgBox($MB_SYSTEMMODAL, "", "The variable is not an uppercase string") EndIf < -------------------------------------------------------------------------------- *StringIsXDigit* +----------------+~ | StringIsXDigit |~ +----------------+~ Checks if a string contains only hexadecimal digit (0-9, A-F) characters. > StringIsXDigit ( "string" ) < Parameters~ string ------ The string to check Return Value~ Success ------- 1. Failure ------- 0 if string contains non-hexadecimal characters. Remarks~ Valid characters are 0123456789abcdefABCDEF. Note that a string containing whitespace or the "0x" prefix will cause StringIsXDigit() to return 0. Related~ |StringIsAlNum|, |StringIsAlpha|, |StringIsASCII|, |StringIsDigit|, |StringIsLower|, |StringIsSpace|, |StringIsUpper|, |StringLower|, |StringUpper| Example~ > #include MsgBox($MB_SYSTEMMODAL, "", "Is the string 42 a hexadecimal digit: " & StringIsXDigit("42") & @CRLF & _ ; Returns 1, as the string contains only hexadecimal (0-9, A-F) characters. "Is the string 00 a hexadecimal digit: " & StringIsXDigit("00") & @CRLF & _ ; Returns 1, as the string contains only hexadecimal (0-9, A-F) characters. "Is the string 1.0 a hexadecimal digit: " & StringIsXDigit("1.0") & @CRLF & _ ; Returns 0, due to the decimal point. "Is the number 1.0 a hexadecimal digit: " & StringIsXDigit(1.0) & @CRLF & _ ; Returns 1, due to the number to string conversion. "Is the string 'A string' a hexadecimal digit: " & StringIsXDigit("A string.") & @CRLF) ; Returns 0, due to the string containing whitespace. < -------------------------------------------------------------------------------- *StringLeft* +------------+~ | StringLeft |~ +------------+~ Returns a number of characters from the left-hand side of a string. > StringLeft ( "string", count ) < Parameters~ string ------ The string to evaluate. count ----- The number of characters to get. Return Value~ Returns a string containing the leftmost count characters of the string. Remarks~ If count exceeds string length, the entire string is returned. If count is negative, an empty string is returned. Related~ |StringCompare|, |StringInStr|, |StringLen|, |StringLower|, |StringMid|, |StringReplace|, |StringRight|, |StringSplit|, |StringTrimLeft|, |StringTrimRight|, |StringUpper| Example~ > #include Local $sString = StringLeft("This is a sentence with whitespace.", 5) ; Retrieve 5 characters from the left of the string. MsgBox($MB_SYSTEMMODAL, "", "The 5 leftmost characters are: " & $sString) < -------------------------------------------------------------------------------- *StringLen* +-----------+~ | StringLen |~ +-----------+~ Returns the number of characters in a string. > StringLen ( "string" ) < Parameters~ string ------ The string to evaluate. Return Value~ Returns the length of the string. Remarks~ A numeric expression is automatically evaluated and converted to a string. Related~ |StringCompare|, |StringInStr|, |StringLeft|, |StringLower|, |StringMid|, |StringReplace|, |StringRight|, |StringSplit|, |StringTrimLeft|, |StringTrimRight|, |StringUpper| Example~ > #include ; Retrieve the length of a string. ; If the string is using only ASCII characters, then the length is equal to the size in bytes e.g. 10 characters is 10 bytes. Local $iLength = StringLen("This is a sentence with whitespace.") MsgBox($MB_SYSTEMMODAL, "", "The length of this string is " & $iLength & " characters.") < -------------------------------------------------------------------------------- *StringLower* +-------------+~ | StringLower |~ +-------------+~ Converts a string to lowercase. > StringLower ( "string" ) < Parameters~ string ------ The string to convert. Return Value~ Returns the string converted to lowercase. Related~ |StringCompare|, |StringInStr|, |StringIsAlNum|, |StringIsAlpha|, |StringIsASCII|, |StringIsLower|, |StringIsSpace|, |StringIsUpper|, |StringIsXDigit|, |StringLeft|, |StringLen|, |StringMid|, |StringReplace|, |StringRight|, |StringSplit|, |StringTrimLeft|, |StringTrimRight|, |StringUpper| Example~ > #include Local $sString = StringLower("This is a string") ; Convert the following string to lowercase. MsgBox($MB_SYSTEMMODAL, "", "StringLower returned: " & $sString) < -------------------------------------------------------------------------------- *StringMid* +-----------+~ | StringMid |~ +-----------+~ Extracts a number of characters from a string. > StringMid ( "string", start [, count = -1] ) < Parameters~ string ------ The string to evaluate. start ----- The character position to start. (1 = first character) count ----- [optional] The number of characters to extract. By default the entire remainder of the string. Return Value~ Returns the extracted string. Remarks~ If start is out-of-bounds, an empty string is returned. If start is valid but count is out-of-bounds, the entire remainder of the string is returned. Related~ |StringCompare|, |StringInStr|, |StringLeft|, |StringLen|, |StringLower|, |StringReplace|, |StringRight|, |StringSplit|, |StringTrimLeft|, |StringTrimRight|, |StringUpper| Example~ > #include ; Retrieve 5 characters from the 10th position in the string. Local $sString = StringMid("This is a sentence with whitespace.", 10, 5) MsgBox($MB_SYSTEMMODAL, "", $sString) < -------------------------------------------------------------------------------- *_StringProper* +---------------+~ | _StringProper |~ +---------------+~ Changes a string to proper case, same as the =Proper function in Excel > #include _StringProper ( $sString ) < Parameters~ $sString -------- Input string Return Value~ Success ------- a proper string. Failure ------- an empty string. Remarks~ This function will capitalize every character following a non-alpha character. Related~ |StringLower()|, |StringUpper()| Example~ > #include #include ; Will return : Somebody Lastnames MsgBox($MB_SYSTEMMODAL, '', _StringProper("somebody lastnames")) ; Will return : Some.Body Last(Name) MsgBox($MB_SYSTEMMODAL, '', _StringProper("SOME.BODY LAST(NAME)")) Exit < -------------------------------------------------------------------------------- *StringRegExp* +--------------+~ | StringRegExp |~ +--------------+~ Check if a string fits a given regular expression pattern. > StringRegExp ( "test", "pattern" [, flag = 0 [, offset = 1]] ) < Parameters~ test ----- The subject string to check pattern ------- The regular expression to match. flag ----- [optional] A number to indicate how the function behaves. See below for details. The default is 0. offset ------ [optional] The string position to start the match (starts at 1). The default is 1. Flag Values $STR_REGEXPMATCH (0) Returns 1 (match) or 0 (no match). (Default). $STR_REGEXPARRAYMATCH (1) Return array of matches. $STR_REGEXPARRAYFULLMATCH (2) Return array of matches including the full match (Perl / PHP style). $STR_REGEXPARRAYGLOBALMATCH (3) Return array of global matches. $STR_REGEXPARRAYGLOBALFULLMATCH (4) Return an array of arrays containing global matches including the full match (Perl / PHP style). Constants are defined in StringConstants.au3. Return Value~ Flag = $STR_REGEXPMATCH (0) : @error / Meaning~ 2 : Bad pattern. @extended = offset of error in pattern. Flag = $STR_REGEXPARRAYMATCH (1) or $STR_REGEXPARRAYFULLMATCH (2) : 0: Array is valid. Check @extended for next offset 1 : Array is invalid. No matches. 2 : Bad pattern, array is invalid. @extended = offset of error in pattern. Flag = $STR_REGEXPARRAYGLOBALMATCH (3) or $STR_REGEXPARRAYGLOBALFULLMATCH (4) : @error / Meaning 0: Array is valid. 1: Array is invalid. No matches. 2: Bad pattern, array is invalid. @extended = offset of error in pattern. Remarks~ The flag parameter can have one of 5 values ($STR_REGEXPMATCH (0) through $STR_REGEXPARRAYGLOBALFULLMATCH (4)). $STR_REGEXPMATCH (0) returns 1 (true) or 0 (false) if the pattern was found or not. $STR_REGEXPARRAYMATCH (1) $STR_REGEXPARRAYFULLMATCH (2) find the first match and return captured groups in an array; when the pattern has no capturing groups, the first match is returned in the array. $STR_REGEXPARRAYGLOBALMATCH (3) $STR_REGEXPARRAYGLOBALFULLMATCH (4) fill the array with all matching instances. $STR_REGEXPARRAYFULLMATCH (2) and $STR_REGEXPARRAYGLOBALFULLMATCH (4) include the full matching text as the first element of the return array, not just the captured groups as with flag $STR_REGEXPARRAYMATCH (1) and $STR_REGEXPARRAYGLOBALMATCH (3). Regular expression notation is a compact way of specifying a pattern for subject strings that can be searched and from which specific parts can be extracted by StringRegExp() or replaced when using StringRegExpReplace(). More precisely, the regular expression engine tries to match a pattern (a kind of programmatic format) with a subject string, both from left to right. Should a mismatch occur, the engines tries to backtrack (return to successively previous states) as much as needed, expecting that the rest of the pattern will match as well. Backtracking is a fundamental feature of regular expression engines and one that every novice programmer already understand and uses daily. It is like leaving a specific mark on every fork in the road and going back to the last untried path when the choosen path turns out to be a dead end: you backtrack as needed until you find the right point (match success) or explore every path without reaching your goal (match failure). Searching a given filename with optional wildcards inside a directory tree is no different. AutoIt uses the PCRE engine. PCRE means "Perl-Compatible Regular Expressions" and is the most comprehensive open-source engine available. This implementation includes Unicode Category Properties (UCP) support, which allows fine-grain processing of most human languages. However to maintain compatibility with previous versions and keep matching speed at its best, the UCP support is not enabled by default. You can enable it by prepending the string (*UCP) at the very start of your pattern. When enabled, the UCP setting changes the extend of a number of regular expression elements, as documented below where applicable. This page is only a summary for the most used pattern elements. For full in-depth discussion of regular expressions as implemented in AutoIt, refer to the complete description of PCRE patterns. Unless you are already familiar with regular expressions you will probably need to read several parts of this summary more than once to grasp how they work and inter-relate. Caution: bad regular expressions can produce a quasi-infinite loop hogging the CPU, and can even cause a crash. Global settings~ These settings are only recognized at the start of the pattern and affect it globally. Newline conventions~ Newline sequences affect where the ^ and $ anchors match and what \N and . do not match. By default the newline sequence is @CRLF as an unbreakable sequence or lone @CR or @LF. The default can be changed by prepending one of the following sequence at the start of a pattern.(*CR) Carriage return (@CR). (*LF) Line feed (@LF). (*CRLF) Carriage return immediately followed by linefeed (@CRLF). (*ANYCRLF) Any of @CRLF, @CR or @LF. This is the default newline convention. (*ANY) Any Unicode newline sequence: @CRLF, @LF, VT, FF, @CR or \x85. What \R matches~ (*BSR_ANYCRLF) By default \R matches @CRLF, @CR or @LF only. (*BSR_UNICODE) Changes \R to match any Unicode newline sequence: @CRLF, @LF, VT, FF, @CR or \x85. PCRE patterns may contain options, which are enclosed in (? ) sequences. Options can be grouped together: "(?imx)". Options following an hyphen are negated: "(?im-sx)". Options appearing outside a group affect the remaining of the pattern from that point onwards. Options appearing inside a group affect that group only. Options loose their special meaning inside a character class, where they are treated literally. (?i) Caseless: matching becomes case-insensitive from that point on. By default, matching is case-sensitive. When UCP is enabled casing applies to the entire Unicode plane 0, else applies by default to ASCII letters A-Z and a-z only. (?m) Multiline: ^ and $ match at newline sequences within data. By default, multiline is off. (?s) Single-line or DotAll: . matches anything including a newline sequence. By default, DotAll is off hence . does not match a newline sequence. (?U) Ungreedy: quantifiers become lazy (non-greedy) from that point on. By default, matching is greedy - see below for further explanation. (?x) eXtended: whitespaces outside character classes are ignored and # starts a comment up to the next solid newline in pattern. Meaningless whitespaces between components make regular expressions much more readable. By default, whitespaces match themselves and # is a literal character. Characters~ Regular expressions patterns consist of literal Unicode text parts which match themselves, intermixed with regular expression specifiers or options. Specifiers and options use a few metacharacters which have a special meaning by themselves or introduce special pattern elements described in the tables below. In literal parts, alphanumeric characters always stand for themselves: the pattern "literal part with ????" matches exactly the string "literal part with ????" ("????" means "chinese text".) Some non-alphanumeric characters called metacharacters have special behavior, discussed thereafter. Representing some characters literally~ The special sequences below are used to represent certain characters literally. \a Represents "alarm", the BEL character (Chr(7)). \cX Represents "control-X", where X is any 7-bit ASCII character. For example, "\cM" represents ctrl-M, same as \x0D or \r (Chr(13)). \e Represents the "escape" control character (Chr(27)). Not to be confused with the escaping of a character! \f Represents "formfeed" (Chr(12)). \n Represents "linefeed" (@LF, Chr(10)). \r Represents "carriage return" (@CR, Chr(13)). \t Represents "tab" (@TAB, Chr(9)). \ddd Represents character with octal code ddd, OR backreference to capturing group number ddd in decimal. For example, ([a-z])\1 would match a doubled letter. Best avoided as it can be ambiguous! Favor the hex representations below. \xhh Represents Unicode character with hex codepoint hh: "\x7E" represents a tilde, "~". \x{hhhh} Represents Unicode character with hex codepoint hhhh: "\x{20AC}" represents the Euro symbol, "€" (ChrW(0x20AC)). \x where x is non-alphanumeric, stands for a literal x. Used to represent metacharacters literally: "\.\[" represents a dot followed by a left square bracket, ".[". \Q ... \E Verbatim sequence: metacharacters loose their special meaning between \Q and \E: "\Q(.)\E" matches "(.)" and is equivalent to, but more readable than, "\(\.\)". Metacharacters~ PCRE metacharacters are \ . ^ $ | [ ( { * + ? # which have one or more special meaning, depending on context. To insert a literal metacharacter, precede it by adding a backslash (this is called escaping (or quoting) a character): "\$" means the dollar character. Metacharacters will be discussed in separate sections where their behavior or meaning belong. Character types~ . Matches any single character except, by default, a newline sequence. Matches newlines as well when option (?s) is active. \d Matches any decimal digit (any Unicode decimal digit in any language when UCP is enabled). \D Matches any non-digit. \h Matches any horizontal whitespace character (see table below). \H Matches any character that is not a horizontal whitespace character. \N Matches any character except a newline sequence regardless of option (?s). \p{ppp} Only when UCP is enabled: matches any Unicode character having the property ppp. E.g. "\b\p{Cyrillic}+" matches any cyrillic word; "\p{Sc}" matches any currency symbol. See reference documentation for details. \P{ppp} Only when UCP is enabled: matches any Unicode character not having the property ppp. \R Matches any Unicode newline sequence by default, or the currently active (*BSR_...) setting. By default \R matches "(?>\r\n|\n|\r)" where "(?>...)" is an atomic group, making the sequence "\r\n" (@CRLF) unbreakable. \s Matches any whitespace character (see table below). \S Matches any non-whitespace character. \v Matches any vertical whitespace character (see table below). \V Matches any character that is not a vertical whitespace character. \w Matches any "word" character: any digit, any letter or underscore "_" (any Unicode digit, any Unicode letter in any language or underscore "_" when UCP is enabled). \W Matches any non-word character. \X Only when UCP is enabled: matches any Unicode extended grapheme cluster - an unbreakable sequence of codepoints which represent a single character for the user. As a consequence \X may match more than one character in the subject string, contrary to all other sequences in this table. Horizontal whitespace characters matched by \h~ \h is equivalent to "[\x09 \xA0]" by default (or "[\x09 \xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{202F}\x{205F}\x{3000}]" when UCP is enabled.) This set is: Horizontal tab (HT), Space, Non-break space (adding: Ogham space mark, Mongolian vowel separator, En quad, Em quad, En space, Em space, Three-per-em space, Four-per-em space, Six-per-em space, Figure space, Punctuation space, Thin space, Hair space, Narrow no-break space, Medium mathematical space, Ideographic space when UCP is enabled.) Vertical whitespace characters matched by \v~ \v is equivalent to "[\x0A-\x0D]" by default (or "[\x0A-\x0D\x{0085}\x{2028}\x{2029}]" when UCP is enabled.) This set is: Linefeed (LF), Vertical tab (VT), Form feed (FF), Carriage return (CR) (adding: Next line (NEL), Line separator, Paragraph separator when UCP is enabled.) Whitespace characters matched by \s~ \s is equivalent to "[\h\x0A\x0C\x0D]". This set is: all characters in \h plus Linefeed (LF), Form feed (FF), Carriage return (CR). Whitespace characters matched by [[:space:]]~ [[:space:]] is equivalent to "\s". This set is: all characters in \s plus Vertical tab (VT). Character classes and POSIX classes~ Character classes~ A character classes defines a set of allowed (resp. disallowed) characters, which the next character in subject is expected to match (resp. not to match). Inside a character classes, most metacharacters loose their meaning (like $ . or *) or mean something else (like ^). [ ... ] Matches any character in the explicit set: "[aeiou]" matches any lowercase vowel. A contiguous (in Unicode codepoint increasing order) set can be defined by putting an hyphen between the starting and ending characters: "[a-z]" matches any lowercase ASCII letter. To include a hyphen (-) in a set, put it as the first or last character of the set or escape it (\-). Notice that the pattern "[A-z]" is not the same as "[A-Za-z]": the former is equivalent to "[A-Z\[\\\]^_`a-z]". To include a closing bracket in a set, use it as the first character of the set or escape it: "[][]" and "[\[\]]" will both match either "[" or "]". Note that in a character class, only \d, \D, \h, \H, \p{}, \P{}, \s, \Q...\E, \S, \v, \V, \w, \W, and \x sequences retain their special meaning, while \b means the backspace character (Chr(8)). [^ ... ] Matches any character not in the set: "[^0-9]" matches any non-digit. To include a caret (^) in a set, put it after the beginning of the set or escape it (\^). POSIX classes~ These are named sets specifications to be used themselves within a character class: "[z[:digit:]w-y]" is the same as "[w-z0-9]". To negate a POSIX character class, put a caret (^) after the first colon: "[[:^digit:]]". When UCP is enabled, several POSIX classes extend to some Unicode character subset, else they are by default restricted to 7-bit ASCII. [:alnum:] ASCII letters and digits (same as [^\W_] or [A-Za-z0-9]). When UCP is enabled: Unicode letters and digits (same as [^\W_] or \p{Xan}). [:alpha:] ASCII letters (same as [^\W\d_] or [A-Za-z]). When UCP is enabled: Unicode letters (same as [^\W\d_] or \p{L}). [:ascii:] ASCII characters (same as [\x00-\x7F]). [:blank:] Space or Tab (@TAB) (same as \h or [\x09\x20]). When UCP is enabled: Unicode horizontal whitespaces (same as \h). [:cntrl:] ASCII control characters (same as Chr(0) ... Chr(31) and Chr(127)). [:digit:] ASCII decimal digits (same as \d or [0-9]). When UCP is enabled: Unicode decimal digits (same as \d or \p{Nd}). [:graph:] ASCII printing characters, excluding space (same as Chr(33) ... Chr(126)). [:lower:] ASCII lowercase letters (same as [a-z]). When UCP is enabled: Unicode lowercase letters (same as \p{Ll}). [:print:] ASCII printing characters, including space (same as Chr(32) ... Chr(126)). [:punct:] ASCII punctuation characters, [:print:] excluding [:alnum:] and space, (33-47, 58-64, 91-96, 123-126). [:space:] ASCII white space (same as [\h\x0A-\x0D]). [:space:] is not quite the same as \s: it includes VT, Chr(11)). [:upper:] ASCII uppercase letters (same as [A-Z]). When UCP is enabled: Unicode uppercase letters (same as \p{Lu}). [:word:] ASCII "Word" characters (same as \w or [[:alnum:]_]). When UCP is enabled: Unicode "word" characters (same as \w or [[:alnum:]_] or \p{Xwd}). [:xdigit:] Hexadecimal digits (same as [0-9A-Fa-f]). Groups are used to delimit subpatterns and are the building blocks of powerful expressions. Groups can be either capturing or not and may be nested irrespective of their nature, except comments groups. A regular expression can contain up to 65535 capturing groups. Option letters (discussed above) can be conveniently inserted between the "?" and the ":" of non-capturing groups: "(?-i:[aeiou]{5})" matches 5 lowercase vowels. In this case options are local to the group. ( ... ) Capturing group. The elements in the group are treated in order and can be repeated as a block. E.g. "(ab)+c" will match "abc" or "ababc", but not "abac". Capturing groups remember the text they matched for use in backreferences and they populate the optionally returned array. They are numbered starting from 1 in the order of appearance of their opening parenthesis. Capturing groups may also be treated as subroutines elsewhere in the pattern, possibly recursively. (? ... ) Named capturing group. Can be later referenced by name as well as by number. Avoid using the name "DEFINE" (see "conditional patterns"). (?: ... ) Non-capturing group. Does not record the matching characters in the array and cannot be re-used as backreference. (?| ... ) Non-capturing group with reset. Resets capturing group numbers in each top-level alternative it contains: "(?|(Mon)|(Tue)s|(Wed)nes|(Thu)rs|(Fri)|(Sat)ur|(Sun))day" matches a weekday name and captures its abbreviation in group number 1. (?> ... ) Atomic non-capturing group: locks and never backtracks into (gives back from) what has been matched (see also Quantifiers and greediness below). Atomic groups, like possessive quantifiers, are always greedy. (?# ... ) Comment group: always ignored (but may not contain a closing parenthesis, hence comment groups are not nestable). Quantifiers (or repetition specifiers) specify how many of the preceding character, class, reference or group are expected to match. Optional greediness qualifiers denote how aggressively the repetition will behave. For instance "\d{3,5}" will match at least 3 and no more than 5 decimal digits. By default, patterns are "greedy", which means that quantifiers * + ? {...} will match the longest string which doesn't cause the rest of the pattern to fail. Greediness can be inverted for the entire pattern by giving option (?U) at the head of the pattern, or locally by placing a question mark following a quantifier. Non-greedy (lazy) repetitions will match the smallest string that still allows the rest of the pattern to match. E.g. given the subject "aaab", the pattern "(a*)([ab]+)" will capture "aaa" then "b", but "(?U)(a*)([ab]+)" will capture "" then "a": indeed, capturing an empty string is good enough to satisfy the lazy "(a*)" and capturing "a" matches the lazy "([ab]+)" subpattern. Possessive quantifiers are atomic and greedy. In fact they are a short notation for simple atomic groups. "\d++" is a shorthand notation for "(?>\d+)" and its behavior is "match a complete sequence of one or more digits, but never give back any". As a consequence "\d++(\d)" can never match since the last digit (in bold) is already matched and locked by "\d++". This is in contrast with simple greediness, where "\d+(\d)" will first match a complete sequence of digits with "\d+", but then backtrack the last one to allow "(\d)" to capture it. There are two reasons for using an atomic group or a possessive quantifier: either for matching a sequence of characters that may also appear individually (e.g. "\r\n" in the definition of \R), or for forcing a quick failure in certain situations involving unbounded repetitions, where the engine would normally spend a very long time trying a huge number of grouping combinations before failing. ? 0 or 1, greedy. ?+ 0 or 1, possessive. ?? 0 or 1, lazy. * 0 or more, greedy. *+ 0 or more, possessive. *? 0 or more, lazy. + 1 or more, greedy. ++ 1 or more, possessive. +? 1 or more, lazy. {x} exactly x. {x,y} at least x and no more than y, greedy. {x,y}+ at least x and no more than y, possessive. {x,y}? at least x and no more than y, lazy. {x,} x or more, greedy. {x,}+ x or more, possessive. {x,}? x or more, lazy. X|Y Matches either subpattern X or Y: "ac|dc|ground" matches "ac" or "dc" or "ground". Backreferences~ permit reuse of the content of a previously captured group. \n References a previous capturing group by its absolute number. WARNING: if no group number n exists, it evaluates as the character with value n provided n is a valid octal value, else errors out. Due to this ambiguity, this form is not recommended. Favor the next forms for a safe semantic. \gn References a previous capturing group by its absolute number. \g{n} References a previous capturing group by its absolute number. Similar to above but clearly delimits where n ends: useful when the following character(s) is(are) digits. \g-n References a previous capturing group by its relative number. \k References a previous capturing group by its name. References to subroutines~ Capturing groups are subpatterns that can be invoked (possibly recursively) exactly like subroutines in a programming language. The subpattern is simply re-run at the current matching point. See reference documentation for details and examples. (?R) or (?0) Recurses into the entire regular expression. (?n) Calls subpattern by absolute number. (?+n) Calls subpattern by relative number. (?-n) Calls subpattern by relative number. (?&name) Calls subpattern by name. Anchors~ and assertions are tests that do not change the matching position and therefore do not consume nor capture anything. Anchors test the position of the current matching point. ^ Outside a character class, the caret matches at the start of the subject text, and also just after a non-final newline sequence if option (?m) is active. By default the newline sequence is @CRLF. Inside a character class, a leading ^ complements the class (excludes the characters listed there). $ Outside a character class, the dollar matches at the end of the subject text, and also just before a newline sequence if option (?m) is active. Inside a character class, $ means itself, a dollar sign. \A Matches only at the absolute beginning of subject string, irrespective of the multiline option (?m). Will never match if offset is not 1. \G Matches when the current position is the first matching position in subject. \z Matches only at end of subject string, irrespective of the multiline option (?m). \Z Matches only at end of subject string, or before a newline sequence at the end, irrespective of the multiline option (?m). Assertions~ test the character(s) preceding (look-behind), at (word boundary) or following (look-ahead) the current matching point. \b Matches at a "word" boundary, i.e. between characters not both \w or \W. See \w for the meaning of "word". Inside a character class, \b means "backspace" (Chr(8)). \B Matches when not at a word boundary. (?=X) Positive look-ahead: matches when the subpattern X matches starting at the current position. (?!X) Negative look-ahead: matches when the subpattern X does not match starting at the current position. (?<=X) Positive look-behind: matches when the subpattern X matches characters preceding the current position. Pattern X must match a fixed-length string, i.e. may not use any undefinite quantifier * + or ?. (?) Tests whether the capturing group with name name matched. (R) Tests whether any kind of recursion occured. (Rn) Tests whether the most recent recursion was for capturing group with absolute number n. (R&name) Tests whether the most recent recursion was for capturing group with name name. (DEFINE) Used without no-pattern, permits definition of a subroutine useable from elsewhere. "(?x) (?(DEFINE) (? 2[0-4]\d | 25[0-5] | 1\d\d | [1-9]?\d) )" defines a subroutine named "byte" which matches any component of an IPv4 address. Then an actual address can be matched by "\b (?&byte) (\.(?&byte)){3} \b". (assertion) Here assertion is one of positive or negative, look-ahead or look-behind assertion. These options, escapes and constructs are simply mentioned here; see reference documentation for detail on why, when and how to use them, if at all. Uncommon settings and options~ (?J) Enables duplicate group or subroutine names (not discussed further here). (?X) Causes some out-of-context sequences to raise an error, instead of being benign. (*J) Enables Javascript compatibility (not discussed further here). (*LIMIT_MATCH=n) Limits number of matches to n. (*LIMIT_RECURSION=n) Limits recursion to n levels. (*NO_START_OPT) Disables several optimizations (not discussed further here). Backtracking control~ (*ACCEPT) Forces an immediate match success in the current subroutine or top-level pattern. (*FAIL) or (*F) Forces an immediate match failure. (*MARK:name) or (*:name) (See reference documentation.) (*COMMIT) (See reference documentation.) (*PRUNE) (See reference documentation.) (*PRUNE:name) (See reference documentation.) (*SKIP) (See reference documentation.) (*SKIP:name) (See reference documentation.) (*THEN) (See reference documentation.) (*THEN:name) (See reference documentation.) 1. When UCP is active, case sense matching applies to the full Unicode plane 0. There are also a small number of many-to-one mappings in Unicode, like the Greek lowercase letter sigma; these are supported by PCRE with UCP enabled. 2. Alternate forms of several escapes exist for compatibility with Perl, Ruby, Python, JavaScript, .NET and other engines. Do not use constructs not listed here: some will simply not work, some will supply wrong results, some will cause severe issues or merely crash. 3. The default newline convention is the unbreakable sequence @CRLF or a separate @CR or @LF. Similarly \R matches the same set. Know your data! If you know that your subjects use separate @LF or @CR to mean something else than a newline, you may have to change the newline convention and/or the matching of \R (see "Settings"). See also the Regular Expression tutorial, in which you can run a script to test your regular expression(s). Related~ |StringInStr|, |StringRegExpReplace| Example~ Option 1, using offset parameter > #include #include Local $aArray = 0, _ $iOffset = 1 While 1 $aArray = StringRegExp('a b c', '(?i)(.*?)', $STR_REGEXPARRAYMATCH, $iOffset) If @error Then ExitLoop $iOffset = @extended For $i = 0 To UBound($aArray) - 1 MsgBox($MB_SYSTEMMODAL, "RegExp Test with Option 1 - " & $i, $aArray[$i]) Next WEnd Option 2, single return, php/preg_match() style > #include #include Local $aArray = StringRegExp('a b c', '(?i)(.*?)', $STR_REGEXPARRAYFULLMATCH) For $i = 0 To UBound($aArray) - 1 MsgBox($MB_SYSTEMMODAL, "RegExp Test with Option 2 - " & $i, $aArray[$i]) Next < Option 3, global return, old AutoIt style > #include #include Local $aArray = StringRegExp('a b c', '(?i)(.*?)', $STR_REGEXPARRAYGLOBALMATCH) For $i = 0 To UBound($aArray) - 1 MsgBox($MB_SYSTEMMODAL, "RegExp Test with Option 3 - " & $i, $aArray[$i]) Next < Option 4, global return, php/preg_match_all() style > #include #include Local $aArray = StringRegExp('F1oF2oF3o', '(F.o)*?', $STR_REGEXPARRAYGLOBALFULLMATCH) Local $aMatch = 0 For $i = 0 To UBound($aArray) - 1 $aMatch = $aArray[$i] For $j = 0 To UBound($aMatch) - 1 MsgBox($MB_SYSTEMMODAL, "RegExp Test with Option 4 - " & $i & ',' & $j, $aMatch[$j]) Next Next < -------------------------------------------------------------------------------- *Tutorial__Regular_Expression* *tutorial__regular_expression* +-------------------------------+~ | Tutorial - Regular Expression |~ +-------------------------------+~ Here's a smallish guide on unraveling the seeming mysteries of StringRegExp(). > StringRegExp( "test" , "pattern" [, flag ] ) < "test" = The string to search through for matches. "pattern" = A string consisting of certain key characters that let the function know PRECISELY what you want to match. No ifs, ands, or buts.. it's a match or it isn't. flag [optional] = Tells the function if you just want to know if the "pattern" is found, or if you want it to return the first match, or if you want it to return all the matches in the "test" string. The Very Basics~ As you may have figured out, the "pattern" string is the only difficult part of calling a StringRegExp() (forthwith: SRE). I find it best to think of patterns as telling the function to match a string character by character. There are different ways to find a certain character: If you want to match the string "test", that should be simple enough. You want to tell SRE to first search the string for a "t". If it finds one, then it assumes it has a match, and the rest of the pattern is used to try to prove that what it's found is not a match. So, if the next character is an "e", it could still be a match. Let's say the next letter is an "x". SRE knows immediately that it hasn't found a match because the third character you tell it to look for is an "s". Example 1~ > #include MsgBox($MB_OK, "SRE Example 1 Result", StringRegExp("text", 'test')) In this example, the message box should read "0", which means the pattern "test" was not found in the test string "text". I know this seems pretty simple, but now you know why it wasn't found. < The next way of specifying a pattern is by using a set ("[ ... ]"). You can equate a set to the logic function "OR". Let's use the previous Example. We want to find either the string "test" or the string "text". So, the way I start looking for a pattern is to think like SRE would think: The first character I want to match is "t", then the letter "e", this is the same for both strings we want to match. Now we want to match "s" OR "x", so we can use a set as a substitute: "[sx]" means match an "s" or an "x". Then the last letter is a "t" again. Example 2~ > #include MsgBox($MB_OK, "SRE Example 2 Result", StringRegExp("text", 'te[sx]t')) MsgBox($MB_OK, "SRE Example 2 Result", StringRegExp("test", 'te[sx]t')) < These should both provide the result "1", because the pattern should match both "test" and "text". You can also specify how many times to match each character by using "{number of matches}" or you can specify a range by using "{min, max}". The first example below is redundant, but shows what I mean: Example 3~ > #include MsgBox($MB_OK, "SRE Example 3 Result", StringRegExp("text", 't{1}e{1}[sx]{1}t{1}')) MsgBox($MB_OK, "SRE Example 3 Result", StringRegExp("aaaabbbbcccc", 'b{4}')) < The Not-So Basics~ Right now you're probably thinking "Isn't this just a glorified StringInStr() function?". Well, using a "flag" value of 0, most of the time you're right. But SRE is much more powerful than that. As you use SRE's more and more, you'll find you might know less and less about the type of pattern you are looking for. There are ways to be less and less specific about each character you wish to specify in the pattern. Take, for example, a line from an inventory log file: "There were 18 sheets left in the ream of paper." You want to find the number of remaining sheets. Well, you can't use StringInStr() because you aren't looking for "18", you're looking for "????", where ? could be any digit. Here's how I would assemble this pattern. Look at what you do and do not know about what you want to find: 1) You know that it will ALWAYS contain nothing but digits. 2) You know that it will SOMETIMES be 2 characters long. 2a) You know that a full ream of paper is 500 sheets. 2b) You know that the minimum number of sheets is 0. 3) You know that it will ALWAYS be between 1 and 3 characters long. 4) You know that there are no other digits in the test string. At this point, I'd like to introduce the FLAG value of "1" and the grouping characters "()". The flag value of "1" means that SRE will not only match your pattern, but also return an array, with each element of the array consisting of a captured "group" of characters. So without veering off course too much, take this example: Example 4~ > #include #include Local $aResult = StringRegExp("This is a test example", '(test)', $STR_REGEXPARRAYMATCH) If Not @error Then MsgBox($MB_OK, "SRE Example 4 Result", $aResult[0]) EndIf $aResult = StringRegExp("This is a test example", '(te)(st)', $STR_REGEXPARRAYMATCH) If Not @error Then MsgBox($MB_OK, "SRE Example 4 Result", $aResult[0] & "," & $aResult[1]) EndIf < So, first the pattern must match somewhere in the test string. If it does, then SRE is told to "capture" any groups ("()") and store them in the return array. You can use multiple captures, as demonstrated by the second piece of code in Example 4. Ok, back to the log file. Now that we know how to "capture" text, let's construct our pattern: Since you know what you're looking for is digits, there are 3 ways to specify "match any digit": "[:digit:]", "[0-9]", and "\d". The first is probably the easiest to understand. There are a few classes (digit, alnum, space, etc. Check the help file for a full list) you can use to specify sets of characters, one of them being digit. "[0-9]" just specifies a range of all the digits 0 through 9. "\d" is just a special character that means the same as the first two. There is no difference between the three, and with all SRE's there are usually at least a couple ways to construct any pattern. So, first we know we want to capture the digits, so indicate that with the opening parentheses "(". Next, we know we want to capture between 1 and 3 characters, all consisting of digits, so our pattern now looks like "([0-9]{1,3}". And finally close it off with the closing parentheses to indicate the end of our group: "([0-9]{1,3})". Let's try it: Example 5~ > #include #include Local $aResult = StringRegExp("There were 18 sheets left in the ream of paper.", _ '([0-9]{1,3})', $STR_REGEXPARRAYMATCH) If Not @error Then MsgBox($MB_OK, "SRE Example 5 Result", $aResult[0]) EndIf < There you go, the message box correctly displays "18". Next we need to cover non-capturing groups. The way you indicate these groups is by opening the group with "(?:" instead of just "(". Let's say your log file says "You used 36 of 279 pages." Now if you run Example 5's SRE on this, you'll come up with "36" instead of "279". Now what I like to do here is just determine what's different between the numbers. One that jumps out at me is that the second number is always followed by a space and then the word "pages". We could just modify our previous pattern to be "([0-9]{1,3} pages)", but what if our script is just looking for the starting amount of pages, without " pages" tacked onto the end of the number? Here's where you can use a non-capturing group to accomplish this. Example 6~ > #include #include Local $aResult = StringRegExp("You used 36 of 279 pages.", '([0-9]{1,3})(?: pages)', $STR_REGEXPARRAYMATCH) If Not @error Then MsgBox($MB_OK, "SRE Example 6 Result", $aResult[0]) EndIf < This could get lengthy, but mostly I just wanted to lay out the foundation for how regular expressions work, and mainly how SRE "thinks". A few things to keep in mind: - Remember to think about the pattern one character at a time - The StringRegExp() function finds the first character in the pattern, then it's your job to provide enough evidence to "prove" whether or not it truly is a match. Example 6 is a good display of this. - Remember [ ... ] means OR ([xyz] match an "x", a "y", OR a "z") If you have any other questions, consult the help file first! It explains in detail all of the nitty gritty syntax that comes along with SRE's. One thing to look at in particular is the section on "Repeating Characters". It can make your pattern more readable by substituting certain characters for ranges. For example: "*" is equivalent to {0,} or the range from 0 to any number of characters. Good luck, Regular Expressions can greatly decrease the length of your code, and make it easier to modify later. Corrections and feedback are welcome! Resources~ Wikipedia Article - Regular Expressions - Thanks blindwig. The 30 Minute Regex Tutorial - by Jim Hollenhorst. GUI for testing various StringRegExp() patterns - Thanks steve8tch. Credit: w0uter -------------------------------------------------------------------------------- *StringAddCR* +-------------+~ | StringAddCR |~ +-------------+~ Takes a string and prefixes all linefeed characters ( Chr(10) ) with a carriage return character ( Chr(13) ). > StringAddCR ( "string" ) < Parameters~ string ------ The string to convert. Return Value~ Returns the string with all instances of linefeed characters ( @LF ) prefixed with a carriage return character ( @CR ). Related~ |StringReplace|, |StringStripCR| Example~ > #include ; Add the carriage return charcter to all the line feed characters in the string. Local $sString = StringAddCR("This is a sentence " & @LF & "with " & Chr(10) & "whitespace.") MsgBox($MB_SYSTEMMODAL, "", $sString) < -------------------------------------------------------------------------------- *_StringBetween* +----------------+~ | _StringBetween |~ +----------------+~ Find strings between two string delimiters > #include _StringBetween ( $sString, $sStart, $sEnd [, $iMode = $STR_ENDISSTART [, $bCase = False]] ) < Parameters~ $sString -------- The string to search. $sStart ------- The beginning of the string to find. Passing an empty string starts at the beginning $sEnd ----- The end of the string to find. Passing an empty string searches from $sStart to end of string $iMode ------ [optional] Search mode when $sStart = $sEnd $STR_ENDISSTART (0) the $sEnd string at the end of a match starts the next possible match (default) $STR_ENDNOTSTART (1) a further instance of the $sStart starts the next match $bCase ------ [optional] False (default setting) = case-insensitive. True = case-sensitive. Return Value~ Success ------- a 0-based array - element [0] contains the first found string. Failure ------- sets the @error flag to non-zero. @error ------ 1 - No strings found. Example~ > #include #include Example() Func Example() ; Create an array of all the values between "[" and "]". Local $aArray = _StringBetween("[18][20][3][5][500][60]", "[", "]") ; Display the results in _ArrayDisplay. _ArrayDisplay($aArray, "Default Search") ; Create an array of all the values between "|" and "|" - note $sStart and $sEnd are identical Local $sString = "-----|Both Modes|$STR_ENDISSTART only|Both Modes|-----" ; Mode $STR_ENDISSTART - default - $sEnd is next $sStart $aArray = _StringBetween($sString, "|", "|") ; Display the results in _ArrayDisplay. _ArrayDisplay($aArray, "$STR_ENDISSTART") ; Mode $STR_ENDNOTSTART - $sEnd is not next $sStart $aArray = _StringBetween($sString, "|", "|", $STR_ENDNOTSTART) ; Display the results in _ArrayDisplay. _ArrayDisplay($aArray, "$STR_ENDNOTSTART") EndFunc ;==>Example < -------------------------------------------------------------------------------- *StringCompare* +---------------+~ | StringCompare |~ +---------------+~ Compares two strings with options. > StringCompare ( "string1", "string2" [, casesense = 0] ) < Parameters~ string1 ------- The first string to evaluate. string2 ------- The second string to evaluate. casesense --------- [optional] Flag to indicate if the operations should be case sensitive. $STR_NOCASESENSE (0) = not case sensitive, using the user's locale (default) $STR_CASESENSE (1) = case sensitive $STR_NOCASESENSEBASIC (2) = not case sensitive, using a basic/faster comparison Constants are defined in StringConstants.au3. Return Value~ 0: string1 and string2 are equal > 0: string1 is greater than string2 < 0: string1 is less than string2 Related~ |StringInStr|, |StringLeft|, |StringLen|, |StringLower|, |StringMid|, |StringRight|, |StringTrimLeft|, |StringTrimRight|, |StringUpper| Example~ > #include #include Local $sStr1 = "Tiësto" Local $sStr2 = "TIËSTO" ; Compare two strings without using case sensitivity. Local $iCmp = StringCompare($sStr1, $sStr2) MsgBox($MB_SYSTEMMODAL, "", _ "Comparing '" & $sStr1 & "' To '" & $sStr2 & "'" & @CRLF & _ "StringCompare Result (mode $STR_NOCASESENSE): " & $iCmp) ; Compare two strings with using case sensitivity. $iCmp = StringCompare($sStr1, $sStr2, $STR_CASESENSE) MsgBox($MB_SYSTEMMODAL, "", _ "Comparing '" & $sStr1 & "' To '" & $sStr2 & "'" & @CRLF & _ "StringCompare Result (mode $STR_CASESENSE): " & $iCmp) ; Compare two strings without using case sensitivity. $iCmp = StringCompare($sStr1, $sStr2, $STR_NOCASESENSEBASIC) MsgBox($MB_SYSTEMMODAL, "", _ "Comparing '" & $sStr1 & "' To '" & $sStr2 & "'" & @CRLF & _ "StringCompare Result (mode $STR_NOCASESENSEBASIC): " & $iCmp) < -------------------------------------------------------------------------------- *_StringExplode* +----------------+~ | _StringExplode |~ +----------------+~ Splits up a string into substrings depending on the given delimiters as PHP Explode v5 > #include _StringExplode ( $sString, $sDelimiter [, $iLimit = 0] ) < Parameters~ $sString -------- String to be split $sDelimiter ----------- Delimiter to split on (split is performed on entire string, not individual characters) $iLimit ------- [optional] Maximum elements to be returned =0 : (default) Split on every instance of the delimiter >0 : Split until limit, last element will contain remaining portion of the string <0 : Split on every instance, removing limit count from end of the array Return Value~ Returns an array containing the exploded strings. Remarks~ Use negative limit values to remove the first possible elements. Example~ > #include #include Local $sText = "one##two##three##four##five##six##seven##eight" Local $aArray1 = _StringExplode($sText, "##", 0) _ArrayDisplay($aArray1, "StringExplode 0") ; DISPLAYED ; [0] = one ; [1] = two ; [2] = three ; [3] = four ; [4] = five ; [5] = six ; [6] = seven ; [7] = eight Local $aArray2 = _StringExplode($sText, "##", 4) _ArrayDisplay($aArray2, "StringExplode 4") ; DISPLAYED ; [0] = one ; [1] = two ; [2] = three ; [3] = four ; [4] = five##six##seven##eight Local $aArray3 = _StringExplode($sText, "##", -3) _ArrayDisplay($aArray3, "StringExplode -3") ; DISPLAYED ; [0] = one ; [1] = two ; [2] = three ; [3] = four ; [4] = five < -------------------------------------------------------------------------------- *StringFormat* +--------------+~ | StringFormat |~ +--------------+~ Returns a formatted string (similar to the C sprintf() function). > StringFormat ( "format control", var1 [, ... var32] ) < Parameters~ format ------ control The format and flags to use (see Remarks). var1...var32 ------------ Up to 32 variables that will be output according to the "format control". Return Value~ Returns the formatted string according to "format control" parameter. Remarks~ To prevent buffer overflow, each "variable" is limited to 65535 characters. Escape characters can be contain in the "format control" such as \n (@LF), \r (@CR), \t (@TAB]. So if you want to have a "\" you need to use \\, samething for "%" %%. "variable format" is; %[flags] [width] [.precision] type If a format specification is invalid, the behaviour is undefined. If you specify invalid input you can in special circumstances create unhandled exception and cause program termination. Width Specification~ The second optional field of the format specification is the width specification. The width argument is a nonnegative decimal integer controlling the minimum number of characters printed. If the number of characters in the output value is less than the specified width, blanks are added to the left or the right of the values — depending on whether the – flag (for left alignment) is specified — until the minimum width is reached. If width is prefixed with 0, zeros are added until the minimum width is reached (not useful for left-aligned numbers). The width specification never causes a value to be truncated. If the number of characters in the output value is greater than the specified width, or if width is not given, all characters of the value are printed (subject to the precision specification). Type Specification~ Type Variable type Output format d, i Integer Signed decimal integer. o Integer Unsigned octal integer. u Integer Unsigned decimal integer. x Integer Unsigned hexadecimal integer, using "abcdef". X Integer Unsigned hexadecimal integer, using "ABCDEF". e Float Signed value having the form [ - ]d.dddd e [sign]ddd where d is a single decimal digit, dddd is one or more decimal digits, ddd is exactly three decimal digits, and sign is + or -. E Float Identical to the e format except that E rather than e introduces the exponent. f Float Signed value having the form [ - ]dddd.dddd, where dddd is one or more decimal digits. The number of digits before the decimal point depends on the magnitude of the number, and the number of digits after the decimal point depends on the requested precision. g Float Signed value printed in f or e format, whichever is more compact for the given value and precision. The e format is used only when the exponent of the value is less than -4 or greater than or equal to the precision argument. Trailing zeros are truncated, and the decimal point appears only if one or more digits follow it. G Float Identical to the g format, except that E, rather than e, introduces the exponent (where appropriate). s String String. Flag Specification~ Flag Meaning Default - Left align the result within the given field width. Right align. + Prefix the output value with a sign (+ or -) if the output value is of a signed type. Sign appears only for negative signed values (-). 0 If width is prefixed with 0, zeros are added until the minimum width is reached. If 0 and - appear, the 0 is ignored. If 0 is specified with an integer format (i, u, x, X, o, d) the 0 is ignored. No padding. Blank Prefix the output value with a blank if the output value is signed and positive; the blank is ignored if both the blank and + flags appear. No blank appears. # When used with the o, x, or X format, the # flag prefixes any nonzero output value with 0, 0x, or 0X, respectively. No blank appears. # When used with the e, E, or f format, the # flag forces the output value to contain a decimal point in all cases. Decimal point appears only if digits follow it. # When used with the g or G format, the # flag forces the output value to contain a decimal point in all cases and prevents the truncation of trailing zeros. Ignored when used with d, i, u, or s. Decimal point appears only if digits follow it. Trailing zeros are truncated. Precision Specification~ The third optional field of the format specification is the precision specification. It specifies a nonnegative decimal integer, preceded by a period (.), which specifies the number of characters to be printed, the number of decimal places, or the number of significant digits (see Table below). Unlike the width specification, the precision specification can cause either truncation of the output value or rounding of a floating-point value. If precision is specified as 0 and the value to be converted is 0, the result is no characters output, as shown below: StringFormat( "%.0d", 0 ); /* No characters return */ How Precision Values Affect Type~ Type Meaning Default d, i, u, o, x, X The precision specifies the minimum number of digits to be printed. If the number of digits in the argument is less than precision, the output value is padded on the left with zeros. The value is not truncated when the number of digits exceeds precision. Default precision is 1. e, E The precision specifies the number of digits to be printed after the decimal point. The last printed digit is rounded. Default precision is 6; if precision is 0 or the period (.) appears without a number following it, no decimal point is printed. f The precision value specifies the number of digits after the decimal point. If a decimal point appears, at least one digit appears before it. The value is rounded to the appropriate number of digits. Default precision is 6; if precision is 0, or if the period (.) appears without a number following it, no decimal point is printed. g, G The precision specifies the maximum number of significant digits printed. Six significant digits are printed, with any trailing zeros truncated. s The precision specifies the maximum number of characters to be printed. Characters in excess of precision are not printed. Characters are printed until a null character is encountered. Example~ > Example() Func Example() Local $iInt_Unsigned = 43951789 Local $iInt_Negative = -43951789 ConsoleWrite(@CRLF & "Numeric Formats" & @CRLF) PrintFormat($iInt_Unsigned, "%d", "standard positive integer with no sign", 1) ; 43951789 PrintFormat($iInt_Negative, "%d", "standard negative integer with sign", 1) ; -43951789 PrintFormat($iInt_Unsigned, "%i", "standard integer", 1) ; 43951789 PrintFormat($iInt_Unsigned, "%09i", "9 digits with leading zero", 1) ; 043951789 PrintFormat($iInt_Unsigned, "%e", "scientific notation") ; 4.395179e+007 PrintFormat($iInt_Unsigned, "%u", "unsigned integer with positive integer", 1) ; 43951789 PrintFormat($iInt_Negative, "%u", "unsigned integer with negative integer", 1) ; 4251015507 PrintFormat($iInt_Unsigned, "%f", "floating point") ; 43951789.000000 PrintFormat($iInt_Unsigned, "%.2f", "floating point with 2 digits after decimal point", 1) ; 43951789.00 PrintFormat($iInt_Unsigned, "%o", "octal", 1) ; 247523255 PrintFormat($iInt_Unsigned, "%s", "string", 1) ; 43951789 PrintFormat($iInt_Unsigned, "%x", "hexadecimal (lower-case)", 1) ; 29ea6ad PrintFormat($iInt_Unsigned, "%X", "hexadecimal (upper-case)", 1) ; 29EA6AD PrintFormat($iInt_Unsigned, "%+d", "sign specifier on a positive integer", 1) ; +43951789 PrintFormat($iInt_Negative, "%+d", "sign specifier on a negative integer", 1) ; -43951789 Local $sString = "string" Local $sString_Long = "longstring" ConsoleWrite(@CRLF & "String Formats - [ ] used to show beginning/end of string" & @CRLF) PrintFormat($sString, "[%s]", "standard string", 1) ; [string] PrintFormat($sString, "[%10s]", "10 chars right justified with added spaces") ; [ string] PrintFormat($sString, "[%-10s]", "10 chars left justified with added spaces") ; [string ] PrintFormat($sString_Long, "[%10.8s]", "right justified but precision 8 so truncated") ; [ longer s] PrintFormat($sString_Long, "[%-10.8s]", "left justifed but precision 8 so truncated") ; [longer s ] PrintFormat($sString, "[%010s]", "10 chars with leading zero") ; [0000string] ConsoleWrite(@CRLF & "Date Format - each % uses a new parameter" & @CRLF) ConsoleWrite('"%02i\%02i\%04i" 0n (1, 9, 2013) => ' & StringFormat("%02i\%02i\%04i", 1, 9, 2013) & @CRLF & @CRLF) EndFunc ;==>Example Func PrintFormat($vVar, $sFormat, $sExplan, $iTab = 0) ConsoleWrite('"' & $sFormat & '" on ' & $vVar & @TAB & ' => ' & StringFormat($sFormat, $vVar)) If $iTab Then ConsoleWrite(@TAB) ConsoleWrite(@TAB & " ; " & $sExplan & @CRLF) EndFunc ;==>PrintFormat -------------------------------------------------------------------------------- *StringFromASCIIArray* +----------------------+~ | StringFromASCIIArray |~ +----------------------+~ Converts an array of ASCII codes to a string. > StringFromASCIIArray ( array,[start = 0 [, end = -1 [, encoding = 0]]] ) < Parameters~ array ----- The array of ASCII codes to convert to characters. start ----- [optional] The 0-based index to start processing from (Default: 0). end ----- [optional] The 0-based index to end processing at (Default: UBound($aArray)). Note that the character at this index is NOT included in the output. encoding -------- [optional] The array contains values in the specified character set: $SE_UTF16 (0) = UTF-16 (Default) $SE_ANSI (1) = ANSI $SE_UTF8 (2) = UTF-8 Constants are defined in StringConstants.au3. Return Value~ Success ------- a string with character representations of the ASCII codes. Failure ------- an empty string and sets the @error flag to non-zero. @error ------ 1 = Input is not an array. 2 = Invalid start index. Remarks~ The returned string may contain embedded Chr(0) but will still be a string type. Most string functions will stop at the first Chr(0) found, however, if access to the entire contents of the string is required then the StringToBinary() function can convert it into a BinaryString preserving all the data. If you attempt to create an array manually (As opposed to using an array returned from StringToASCIIArray()) then the codes in the array must be specified in UNICODE. Related~ |StringToASCIIArray| Example~ > #include #include ; Required for _ArrayDisplay() only. Example() Func Example() ; Convert the string to an ASCII array. Local $aArray = StringToASCIIArray("This is a sentence with whitespace.") ; Display the array to see that it contains the ASCII values for each character in the string. _ArrayDisplay($aArray) ; Convert the array into a string. Local $sString = StringFromASCIIArray($aArray) ; Display the string to see that it matches the original string initially converted to an array. MsgBox($MB_SYSTEMMODAL, "", $sString) EndFunc ;==>Example < -------------------------------------------------------------------------------- *_StringInsert* +---------------+~ | _StringInsert |~ +---------------+~ Inserts a string within another string > #include _StringInsert ( $sString, $sInsertString, $iPosition ) < Parameters~ $sString -------- Original string $sInsertString -------------- String to be inserted $iPosition ---------- Position to insert string (negatives values count from right hand side) Return Value~ Success ------- a new modified string. Failure ------- the original string and sets the @error flag to non-zero. @error ------ 1 - Invalid position Remarks~ Use negative position values to insert string from the right hand side. Example~ > #include ; Inserts three "moving" underscores and prints them to the console. For $i = -20 To 20 ConsoleWrite($i & @TAB & _StringInsert("Supercalifragilistic", "___", $i) & @CRLF) Next < -------------------------------------------------------------------------------- *StringRegExpReplace* +---------------------+~ | StringRegExpReplace |~ +---------------------+~ Replace text in a string based on regular expressions. > StringRegExpReplace ( "test", "pattern", "replace" [, count = 0] ) < Parameters~ test ----- The string to check pattern ------- The regular expression to compare. See StringRegExp for pattern definition characters. replace ------- The text to replace the regular expression matching text with. To insert matched group text, \0 - \9 (or $0 - $9) can be used as back-references. (See remarks) count ----- [optional] The number of times to execute the replacement in the string. The default is 0. Use 0 for global replacement. Return Value~ Success ------- an updated string based on regular expressions. Check @extended for the number of replacements performed. Failure ------- sets the @error flag to non-zero. @error ------ 2 = Pattern invalid. @extended = offset of error in pattern. Remarks~ To separate back-reference replacements from actual (replaced) numbers, wrap them with curly braces, i.e: "${1}5". If a "\" needs to be in the replaced string it must be doubled. This is a consequence of the back-references mechanism. The "\" and "$" replacement formats are the only valid back-references formats supported. See also the Regular Expression tutorial, in which you can run a script to test your regular expression(s). Related~ |StringRegExp|, |StringReplace| Example~ > #include Test1() Test2() Test3() ; This example demonstrates a basic replacement. It replaces the vowels aeiou ; with the @ character. Func Test1() Local $sInput = "Where have all the flowers gone, long time passing?" Local $sOutput = StringRegExpReplace($sInput, "[aeiou]", "@") Display($sInput, $sOutput) EndFunc ;==>Test1 ; The following example demonstrates using back-references to change the date ; from MM/DD/YYYY to DD.MM.YYYY Func Test2() Local $sInput = 'some text1 12/31/2009 01:02:03 some text2' & @CRLF & _ 'some text3 02/28/2009 11:22:33 some text4' Local $sOutput = StringRegExpReplace($sInput, '(\d{2})/(\d{2})/(\d{4})', ' $2.$1.$3 ') Display($sInput, $sOutput) EndFunc ;==>Test2 ; The following example demonstrates the need to double backslash Func Test3() Local $sInput = '%CommonProgramFiles%\Microsoft Shared\' Local $sOutput = StringRegExpReplace($sInput, '%([^%]*?)%', 'C:\\WINDOWS\\Some Other Folder$') Display($sInput, $sOutput) EndFunc ;==>Test3 Func Display($sInput, $sOutput) ; Format the output. Local $sMsg = StringFormat("Input:\t%s\n\nOutput:\t%s", $sInput, $sOutput) MsgBox($MB_SYSTEMMODAL, "Results", $sMsg) EndFunc ;==>Display < -------------------------------------------------------------------------------- *_StringRepeat* +---------------+~ | _StringRepeat |~ +---------------+~ Repeats a string a specified number of times > #include _StringRepeat ( $sString, $iRepeatCount ) < Parameters~ $sString -------- String to repeat $iRepeatCount ------------- Number of times to repeat the string Return Value~ Success ------- a string with specified number of repeats. Failure ------- an empty string and sets the @error flag to non-zero. @error ------ 1 - One of the parameters is invalid Example~ > #include #include ; Repeat the string "+-" forty times. MsgBox($MB_SYSTEMMODAL, '', _StringRepeat("+-", 40)) < -------------------------------------------------------------------------------- *StringReplace* +---------------+~ | StringReplace |~ +---------------+~ Replaces substrings in a string. > StringReplace ( "string", "searchstring/start", "replacestring" [, occurrence = 0 [, casesense = 0]] ) < Parameters~ string ------ The string to evaluate. searchstring/start ------------------ The substring to search for or the character position to start the replacement. replacestring ------------- The replacement string. occurrence ---------- [optional] The number of times to replace the searchstring. Use a negative occurrence to replace from the right side. 0 = all searchstrings will be replaced (default) casesense --------- [optional] Flag to indicate if the operations should be case sensitive. $STR_NOCASESENSE (0) = not case sensitive, using the user's locale (default) $STR_CASESENSE (1) = case sensitive $STR_NOCASESENSEBASIC (2) = not case sensitive, using a basic/faster comparison Constants are defined in StringConstants.au3. Return Value~ Returns the new string with the number of replacements performed stored in the @extended macro. Remarks~ By default or if the occurrence is positive the search/replace is performed left-to-right. Thus, StringReplace("aaa", "aa", "bb") returns "bba" If the start method is used the occurrence and casesense parameters are ignored. The function will replace the characters in "string", starting at the requested position, with the characters in "replacestring" - as many characters will be replaced as are in "replacestring". However, if there are not enough characters in "string" for the entire "replacestring" to be inserted an empty string is returned and @error is set to 1. Related~ |StringAddCR|, |StringLeft|, |StringLen|, |StringLower|, |StringMid|, |StringRight|, |StringStripWS|, |StringTrimLeft|, |StringTrimRight|, |StringUpper| Example~ > #include ; Replace a blank space (' ') with a - (minus) character. Local $sString = StringReplace("This is a sentence with whitespace.", " ", "-") Local $iReplacements = @extended MsgBox($MB_SYSTEMMODAL, "", $iReplacements & " replacements were made and the new string is:" & @CRLF & @CRLF & $sString) < -------------------------------------------------------------------------------- *StringReverse* +---------------+~ | StringReverse |~ +---------------+~ Reverses the contents of the specified string. > StringReverse ( "string" [, flag = 0] ) < Parameters~ string ------ The string to reverse. flag ----- [optional] Changes the way the string is reversed $STR_UTF16 (0) = reversed in full UTF-16 mode. (default) $STR_UCS2 (1) = a much faster method - only use if using UCS-2 text. Constants are defined in "StringConstants.au3". Return Value~ Returns a reversed string. Related~ |StringCompare|, |StringInStr|, |StringLen|, |StringLower|, |StringMid|, |StringReplace|, |StringRight|, |StringSplit|, |StringTrimLeft|, |StringTrimRight|, |StringUpper| Example~ > #include ; Reverse the string esreveR. MsgBox($MB_SYSTEMMODAL, "", StringReverse("esreveR")) < -------------------------------------------------------------------------------- *StringRight* +-------------+~ | StringRight |~ +-------------+~ Returns a number of characters from the right-hand side of a string. > StringRight ( "string", count ) < Parameters~ string ------ The string to evaluate. count ----- The number of characters to get. Return Value~ Returns a string containing the rightmost count characters of the string. Remarks~ If count exceeds string length, the entire string is returned. If count is negative, an empty string is returned. Related~ |StringCompare|, |StringInStr|, |StringLeft|, |StringLen|, |StringLower|, |StringMid|, |StringReplace|, |StringSplit|, |StringTrimLeft|, |StringTrimRight|, |StringUpper| Example~ > #include Local $sString = StringRight("This is a sentence with whitespace.", 5) ; Retrieve 5 characters from the right of the string. MsgBox($MB_SYSTEMMODAL, "", "The 5 rightmost characters are: " & $sString) < -------------------------------------------------------------------------------- *StringSplit* +-------------+~ | StringSplit |~ +-------------+~ Splits up a string into substrings depending on the given delimiters. > StringSplit ( "string", "delimiters" [, flag = 0] ) < Parameters~ string ------ The string to evaluate. delimiters ---------- One or more characters to use as delimiters (case sensitive). flag ----- [optional] Changes how the string split works, add multiple flag values together if required: $STR_CHRSPLIT (0) = each character in the delimiter string will mark where to split the string (default) $STR_ENTIRESPLIT (1) = entire delimiter string is needed to mark the split $STR_NOCOUNT (2) = disable the return count in the first element - effectively makes the array 0-based (must use UBound() to get the size of the array in this case). Constants are defined in StringConstants.au3. Return Value~ Returns an array, by default the first element ($aArray[0]) contains the number of strings returned, the remaining elements ($aArray[1], $aArray[2], etc.) contain the delimited strings. If the flag parameter is set to $STR_NOCOUNT (2) then the count is not returned in the first element. If no delimiters were found then the @error flag is set to 1: If flag is not equal to $STR_NOCOUNT, $aArray[0] is set to 1 and the full string is returned in $aArray[1]. If flag is equal to $STR_NOCOUNT, the full string is returned in $aArray[0]. Remarks~ If you use an empty string "" for the delimiters, each character will be returned as an element. If the delimiter string contains several characters function behaviour depends on the flag setting. If set to $STR_CHRSPLIT the string will be split at every instance of each of the individual characters in the delimiter - if set to $STR_ENTIRESPLIT then the string will only be split when the entire delimiter string is encountered. See second example below. Note that the macro @CRLF is actually a 2 character string, so unless the flag parameter to $STR_ENTIRESPLIT extra blank lines will be generated as the string is split on both @CR and @LF. StringSplit() is very useful as an alternative to StringInStr() as well as a means to populate an array. Related~ |StringInStr|, |StringLeft|, |StringLen|, |StringLower|, |StringMid|, |StringRight|, |StringTrimLeft|, |StringTrimRight|, |StringUpper| Example~ Example 1 > #include Example() Func Example() Local $aDays = StringSplit("Mon,Tues,Wed,Thur,Fri,Sat,Sun", ",") ; Split the string of days using the delimiter "," and the default flag value. #cs The array returned will contain the following values: $aDays[1] = "Mon" $aDays[2] = "Tues" $aDays[3] = "Wed" ... $aDays[7] = "Sun" #ce For $i = 1 To $aDays[0] ; Loop through the array returned by StringSplit to display the individual values. MsgBox($MB_SYSTEMMODAL, "", "$aDays[" & $i & "] - " & $aDays[$i]) Next EndFunc ;==>Example < Example 2 > #include #include Example() Func Example() Local $sText = "This\nline\ncontains\nC-style breaks." ; Define a variable with a string of text. Local $aArray = StringSplit($sText, '\n', $STR_ENTIRESPLIT) ; Pass the variable to StringSplit and using the delimiter "\n". ; Note that flag parameter is set to $STR_ENTIRESPLIT (1) as it would split at \ or n otherwise. #cs The array returned will contain the following values: $aArray[1] = "This" $aArray[2] = "line" ... $aArray[4] = "C-style breaks." #ce For $i = 1 To $aArray[0] ; Loop through the array returned by StringSplit to display the individual values. MsgBox($MB_SYSTEMMODAL, "", "$aArray[" & $i & "] - " & $aArray[$i]) Next EndFunc ;==>Example < Example 3 > #include #include Example() Func Example() Local $sText = "This\nline\ncontains\nC-style breaks." ; Define a variable with a string of text. ; Pass the variable to StringSplit and using the delimiter "\n". ; Note that flag parameter is set to $STR_ENTIRESPLIT (1) as it would split at \ or n otherwise. MsgBox($MB_SYSTEMMODAL, "", StringSplit($sText, '\n', $STR_ENTIRESPLIT)[2]) ; Directly access the array index by using array access on expression. #cs An internal temporary array is used to return a string that may contain one of the following values: $aArray[1] = "This" $aArray[2] = "line" ... $aArray[4] = "C-style breaks." #ce EndFunc ;==>Example < -------------------------------------------------------------------------------- *StringStripCR* +---------------+~ | StringStripCR |~ +---------------+~ Removes all carriage return values ( Chr(13) ) from a string. > StringStripCR ( "string" ) < Parameters~ string ------ The string to convert. Return Value~ Returns the string with all instances of the @CR character ( Chr(13) ) removed. Related~ |StringAddCR|, |StringIsSpace|, |StringStripWS| Example~ > #include ; A string with carriage return characters. Local $sString = "This is a sentence " & @CR & "with " & Chr(13) & "whitespace." ; Strip all carriage return characters in the string. Local $sStrippedString = StringStripCR($sString) ; Display the before and after string. MsgBox($MB_SYSTEMMODAL, "", "Before: " & $sString & @CRLF & @CRLF & "After: " & $sStrippedString) < -------------------------------------------------------------------------------- *StringStripWS* +---------------+~ | StringStripWS |~ +---------------+~ Strips the white space in a string. > StringStripWS ( "string", flag ) < Parameters~ string ------ The string to strip. flag ----- Flag to indicate the type of stripping that should be performed (add the flags together for multiple operations): $STR_STRIPLEADING (1) = strip leading white space $STR_STRIPTRAILING (2) = strip trailing white space $STR_STRIPSPACES (4) = strip double (or more) spaces between words $STR_STRIPALL (8) = strip all spaces (over-rides all other flags) Constants are defined in StringConstants.au3. Return Value~ Returns the new string stripped of the requested white space. Remarks~ Whitespace includes Chr(9) thru Chr(13) which are HorizontalTab, LineFeed, VerticalTab, FormFeed, and CarriageReturn. Whitespace also includes the null string ( Chr(0) ) and the standard space ( Chr(32) ). To strip single spaces between words, use the function StringReplace(). Related~ |StringIsSpace|, |StringReplace|, |StringStripCR| Example~ > #include #include ; Strip leading and trailing whitespace as well as the double spaces (or more) in between the words. Local $sString = StringStripWS(" This is a sentence with whitespace. ", $STR_STRIPLEADING + $STR_STRIPTRAILING + $STR_STRIPSPACES) MsgBox($MB_SYSTEMMODAL, "", $sString) < -------------------------------------------------------------------------------- *_StringTitleCase* +------------------+~ | _StringTitleCase |~ +------------------+~ Changes a string to a title case string > #include _StringTitleCase ( $sString ) < Parameters~ $sString -------- Input string Return Value~ Success ------- a titlecased string. Failure ------- an empty string. Remarks~ This function will capitalize the first character of every word. Does not support unicode strings. Related~ |_StringProper| Example~ > #include #include Local $sString = "'she's all 'that' I, wAnt (" & '1st "disk" of 2)' MsgBox($MB_SYSTEMMODAL, '', 'Original string: ' & $sString & @CRLF & _ ; Display the orginal and titlecased string. 'Titlecased string: ' & _StringTitleCase($sString) & @CRLF) < -------------------------------------------------------------------------------- *StringToASCIIArray* +--------------------+~ | StringToASCIIArray |~ +--------------------+~ Converts a string to an array containing the ASCII code of each character. > StringToASCIIArray ( "string",[start = 0 [, end [, encoding = 0]]] ) < Parameters~ "string" -------- The string to convert to an array of ASCII codes. start ----- [optional] The 0-based position to start processing from (Default: 0). end ----- [optional] The 0-based position to end processing at (Default: StringLen("string")). encoding -------- [optional] The returned array will contain values in the specified character set: $SE_UTF16 (0) = UTF-16 (Default) $SE_ANSI (1) = ANSI $SE_UTF8 (2) = UTF-8 Constants are defined in StringConstants.au3. Return Value~ Success ------- an array where each element is the UNICODE code of the character at the corresponding position. Failure ------- an empty string. Remarks~ The string may contain embedded Chr(0). These will appear in the returned array as well as any data past them. Processing only stops when the end of the string is reached or the user specified end. In order to convert binary data to an array using this function it must first be converted to a string with the BinaryToString() function. Related~ |BinaryToString|, |StringFromASCIIArray| Example~ > #include #include ; Required for _ArrayDisplay() only. Example() Func Example() ; Convert the string to an ASCII array. Local $aArray = StringToASCIIArray("This is a sentence with whitespace.") ; Display the array to see that it contains the ASCII values for each character in the string. _ArrayDisplay($aArray) ; Convert the array into a string. Local $sString = StringFromASCIIArray($aArray) ; Display the string to see that it matches the original string initially converted to an array. MsgBox($MB_SYSTEMMODAL, "", $sString) EndFunc ;==>Example < -------------------------------------------------------------------------------- *StringToBinary* +----------------+~ | StringToBinary |~ +----------------+~ Converts a string into binary data. > StringToBinary ( expression [, flag = 1] ) < Parameters~ expression ---------- An expression to convert into binary data. flag ----- [optional] Changes how the string is stored as binary: $SB_ANSI (1) = string data is ANSI (default) $SB_UTF16LE (2) = string data is UTF16 Little Endian $SB_UTF16BE (3) = string data is UTF16 Big Endian $SB_UTF8 (4) = string data is UTF8 Constants are defined in StringConstants.au3. Return Value~ Returns a binary variant. Remarks~ See "Unicode Support" for a detailed description. Related~ |Binary|, |BinaryToString|, |IsBinary|, |String| Example~ > #include #include Example() Func Example() ; Define the string that will be converted later. ; NOTE: This string may show up as ?? in the help file and even in some editors. ; This example is saved as UTF-8 with BOM. It should display correctly in editors ; which support changing code pages based on BOMs. Local Const $sString = "Hello - ??" ; Temporary variables used to store conversion results. $dBinary will hold ; the original string in binary form and $sConverted will hold the result ; afte it's been transformed back to the original format. Local $dBinary = Binary(""), $sConverted = "" ; Convert the original UTF-8 string to an ANSI compatible binary string. $dBinary = StringToBinary($sString) ; Convert the ANSI compatible binary string back into a string. $sConverted = BinaryToString($dBinary) ; Display the resulsts. Note that the last two characters will appear ; as ?? since they cannot be represented in ANSI. DisplayResults($sString, $dBinary, $sConverted, "ANSI") ; Convert the original UTF-8 string to an UTF16-LE binary string. $dBinary = StringToBinary($sString, $SB_UTF16LE) ; Convert the UTF16-LE binary string back into a string. $sConverted = BinaryToString($dBinary, $SB_UTF16LE) ; Display the resulsts. DisplayResults($sString, $dBinary, $sConverted, "UTF16-LE") ; Convert the original UTF-8 string to an UTF16-BE binary string. $dBinary = StringToBinary($sString, $SB_UTF16BE) ; Convert the UTF16-BE binary string back into a string. $sConverted = BinaryToString($dBinary, $SB_UTF16BE) ; Display the resulsts. DisplayResults($sString, $dBinary, $sConverted, "UTF16-BE") ; Convert the original UTF-8 string to an UTF-8 binary string. $dBinary = StringToBinary($sString, $SB_UTF8) ; Convert the UTF8 binary string back into a string. $sConverted = BinaryToString($dBinary, $SB_UTF8) ; Display the resulsts. DisplayResults($sString, $dBinary, $sConverted, "UTF8") EndFunc ;==>Example ; Helper function which formats the message for display. It takes the following parameters: ; $sOriginal - The original string before conversions. ; $dBinary - The original string after it has been converted to binary. ; $sConverted- The string after it has been converted to binary and then back to a string. ; $sConversionType - A human friendly name for the encoding type used for the conversion. Func DisplayResults($sOriginal, $dBinary, $sConverted, $sConversionType) MsgBox($MB_SYSTEMMODAL, "", "Original:" & @CRLF & $sOriginal & @CRLF & @CRLF & "Binary:" & @CRLF & $dBinary & @CRLF & @CRLF & $sConversionType & ":" & @CRLF & $sConverted) EndFunc ;==>DisplayResults < -------------------------------------------------------------------------------- *_StringToHex* +--------------+~ | _StringToHex |~ +--------------+~ Convert a string to a hex string > #include _StringToHex ( $sString ) Parameters~ $sString -------- String to be converted. Return Value~ Success ------- a hex string. Failure ------- an empty string. Related~ |_HexToString| Example~ > #include #include Local $sString = "This is a sample string" Local $sHex = _StringToHex($sString) ; Convert the string to a hex string. MsgBox($MB_SYSTEMMODAL, "", "Original String: " & $sString & @CRLF & " Hex: " & $sHex) $sString = _HexToString($sHex) ; Convert the hex string back to the original string. MsgBox($MB_SYSTEMMODAL, "", "Original Hex: " & $sHex & @CRLF & "String: " & $sString) < -------------------------------------------------------------------------------- *StringTrimLeft* +----------------+~ | StringTrimLeft |~ +----------------+~ Trims a number of characters from the left hand side of a string. > StringTrimLeft ( "string", count ) < Parameters~ string ------ The string to evaluate. count ----- The number of characters to trim. Return Value~ Returns the string trimmed by count characters from the left. Remarks~ If count is out-of-bounds, an empty string is returned. StringTrimLeft($str, $n) is functionally equivalent to StringRight($str, StringLen($str) - $n) Related~ |StringCompare|, |StringInStr|, |StringLeft|, |StringLen|, |StringLower|, |StringMid|, |StringReplace|, |StringRight|, |StringSplit|, |StringTrimRight|, |StringUpper| Example~ > #include Local $sString = StringTrimLeft("This is a sentence with whitespace.", 5) ; Remove the 5 leftmost characters from the string. MsgBox($MB_SYSTEMMODAL, "", $sString) < -------------------------------------------------------------------------------- *StringTrimRight* +-----------------+~ | StringTrimRight |~ +-----------------+~ Trims a number of characters from the right hand side of a string. > StringTrimRight ( "string", count ) < Parameters~ string ------ The string to evaluate. count ----- The number of characters to trim. Return Value~ Returns the string trimmed by count characters from the right. Remarks~ If count is out-of-bounds, an empty string is returned. StringTrimRight($str, $n) is functionally equivalent to StringLeft($str, StringLen($str) - $n) Related~ |StringCompare|, |StringInStr|, |StringLeft|, |StringLen|, |StringLower|, |StringMid|, |StringReplace|, |StringRight|, |StringSplit|, |StringTrimLeft|, |StringUpper| Example~ > #include Local $sString = StringTrimRight("This is a sentence with whitespace.", 5) ; Remove the 5 rightmost characters from the string. MsgBox($MB_SYSTEMMODAL, "", $sString) < -------------------------------------------------------------------------------- *StringUpper* +-------------+~ | StringUpper |~ +-------------+~ Converts a string to uppercase. > StringUpper ( "string" ) < Parameters~ string ------ The string to convert. Return Value~ Returns the string converted to uppercase. Related~ |StringCompare|, |StringInStr|, |StringIsAlNum|, |StringIsAlpha|, |StringIsASCII|, |StringIsLower|, |StringIsSpace|, |StringIsUpper|, |StringIsXDigit|, |StringLeft|, |StringLen|, |StringLower|, |StringMid|, |StringReplace|, |StringRight|, |StringSplit|, |StringTrimLeft|, |StringTrimRight| Example~ > #include Local $sString = StringUpper("This is a string") ; Convert the following string to uppercase. MsgBox($MB_SYSTEMMODAL, "", "StringUpper returned: " & $sString) < -------------------------------------------------------------------------------- *Number* +--------+~ | Number |~ +--------+~ Returns the numeric representation of an expression. > Number ( expression [, flag = 0] ) < Parameters~ expression ---------- An expression to convert into a number. flag ----- [optional] Defines behavior. Can be one of the following: $NUMBER_AUTO (0) = (default) the result is auto-sized integer. See remarks. $NUMBER_32BIT (1) = the result is 32bit integer. $NUMBER_64BIT (2) = the result is 64bit integer. $NUMBER_DOUBLE (3) = the result is double. Constants are defined in "AutoItConstants.au3". Return Value~ Returns a number. Remarks~ If you pass number, function outputs the input. A string beginning with letters has a numeric value of zero. A string beginning with digits has non-numeric characters stripped at the from the first one. Valid characters for Double numbers does not start the stripping. Default behavior results in auto-sized integer. If input value after conversion is within the range of 32bit integer the result is 32bit integer. If not the result is 64bit integer. Both are signed. Related~ |Binary|, |Ceiling|, |Floor|, |HWnd|, |Int|, |Ptr|, |Round|, |String| Example~ > #include Local $bNumber1 = Number(1 + 2 + 10) ; Returns 13. Local $bNumber2 = Number("3.14") ; Returns 3.14. Local $bNumber3 = Number("24/7") ; Returns 24. Local $bNumber4 = Number("tmp3") ; Returns 0 as this is a string. Local $bNumber5 = Number("1,000,000") ; Returns 1 as it strips everything after and including the first comma. MsgBox($MB_SYSTEMMODAL, "", "The following values were converted to a numeric value:" & @CRLF & _ $bNumber1 & @CRLF & $bNumber2 & @CRLF & $bNumber3 & @CRLF & $bNumber4 & @CRLF & $bNumber5) < -------------------------------------------------------------------------------- *Binary* +--------+~ | Binary |~ +--------+~ Returns the binary representation of an expression. > Binary ( expression ) < Parameters~ expression ---------- An expression to convert into binary/byte data. Return Value~ Returns a Binary variant. Remarks~ See language datatypes for a detailed description. Related~ |BinaryLen|, |BinaryMid|, |BinaryToString|, |Int|, |IsBinary|, |Number|, |StringToBinary| Example~ > #include Local $dBinary = Binary("0x00204060") ; Convert the string to binary. MsgBox($MB_SYSTEMMODAL, "", "Returns 1 as the variable is binary: " & IsBinary($dBinary)) < -------------------------------------------------------------------------------- *BinaryLen* +-----------+~ | BinaryLen |~ +-----------+~ Returns the number of bytes in a binary variant. > BinaryLen ( binary ) < Parameters~ binary ------ The binary data to evaluate. Return Value~ Returns the length of the binary data in bytes. Related~ |Binary,| |BinaryMid| Example~ > #include Local $dBinary = Binary("0x10203040") ; Create binary data from a string. MsgBox($MB_SYSTEMMODAL, "", "The length of the binary is: " & BinaryLen($dBinary)) < -------------------------------------------------------------------------------- *BinaryMid* +-----------+~ | BinaryMid |~ +-----------+~ BinaryMid~ Extracts a number of bytes from a binary variant. > BinaryMid ( binary, start [, count] ) < Parameters~ binary ------ The binary data to evaluate. start ----- The byte position to start. (1 = first byte) count ----- [optional] The number of bytes to extract. By default the entire remainder of the binary data. Return Value~ Returns the extracted binary data. Remarks~ If start is out-of-bounds, an empty binary variant is returned. If start is valid but count is out-of-bounds, the entire remainder of the binary data is returned. Related~ |Binary|, |BinaryLen| Example~ > #include Local $dBinary = Binary("0x10203040") ; Create binary data from a string. Local $dExtract = BinaryMid($dBinary, 2, 2) MsgBox($MB_SYSTEMMODAL, "", "The 2nd and 3rd bytes are: " & $dExtract) < -------------------------------------------------------------------------------- *BinaryToString* +----------------+~ | BinaryToString |~ +----------------+~ Converts a binary variant into a string. > BinaryToString ( expression [, flag = 1] ) < Parameters~ expression ---------- An expression to convert into a string. flag ----- [optional] Changes how the binary data is converted: $SB_ANSI (1) = binary data is ANSI (default) $SB_UTF16LE (2) = binary data is UTF16 Little Endian $SB_UTF16BE (3) = binary data is UTF16 Big Endian $SB_UTF8 (4) = binary data is UTF8 Constants are defined in StringConstants.au3. Return Value~ Success ------- the string representation of the binary data. Failure ------- an empty string and sets the @error flag to non-zero. @error: 1 = Input string had zero length. 2 = Input string had an odd number of bytes but was supposed to be UTF16 (must contain an even number of bytes to be valid UTF16). Remarks~ Unlike String() which returns a hexadecimal representation of binary data, this function will assume the binary data is a string value and convert it appropriately. See "Unicode Support" for a detailed description. Related~ |Binary|, |IsBinary|, |String|, |StringToASCIIArray|, |StringToBinary| Example~ > #include #include Example() Func Example() ; Define the string that will be converted later. ; NOTE: This string may show up as ?? in the help file and even in some editors. ; This example is saved as UTF-8 with BOM. It should display correctly in editors ; which support changing code pages based on BOMs. Local Const $sString = "Hello - ??" ; Temporary variables used to store conversion results. $dBinary will hold ; the original string in binary form and $sConverted will hold the result ; afte it's been transformed back to the original format. Local $dBinary = Binary(""), $sConverted = "" ; Convert the original UTF-8 string to an ANSI compatible binary string. $dBinary = StringToBinary($sString) ; Convert the ANSI compatible binary string back into a string. $sConverted = BinaryToString($dBinary) ; Display the resulsts. Note that the last two characters will appear ; as ?? since they cannot be represented in ANSI. DisplayResults($sString, $dBinary, $sConverted, "ANSI") ; Convert the original UTF-8 string to an UTF16-LE binary string. $dBinary = StringToBinary($sString, $SB_UTF16LE) ; Convert the UTF16-LE binary string back into a string. $sConverted = BinaryToString($dBinary, $SB_UTF16LE) ; Display the resulsts. DisplayResults($sString, $dBinary, $sConverted, "UTF16-LE") ; Convert the original UTF-8 string to an UTF16-BE binary string. $dBinary = StringToBinary($sString, $SB_UTF16BE) ; Convert the UTF16-BE binary string back into a string. $sConverted = BinaryToString($dBinary, $SB_UTF16BE) ; Display the resulsts. DisplayResults($sString, $dBinary, $sConverted, "UTF16-BE") ; Convert the original UTF-8 string to an UTF-8 binary string. $dBinary = StringToBinary($sString, $SB_UTF8) ; Convert the UTF8 binary string back into a string. $sConverted = BinaryToString($dBinary, $SB_UTF8) ; Display the resulsts. DisplayResults($sString, $dBinary, $sConverted, "UTF8") EndFunc ;==>Example ; Helper function which formats the message for display. It takes the following parameters: ; $sOriginal - The original string before conversions. ; $dBinary - The original string after it has been converted to binary. ; $sConverted- The string after it has been converted to binary and then back to a string. ; $sConversionType - A human friendly name for the encoding type used for the conversion. Func DisplayResults($sOriginal, $dBinary, $sConverted, $sConversionType) MsgBox($MB_SYSTEMMODAL, "", "Original:" & @CRLF & $sOriginal & @CRLF & @CRLF & "Binary:" & @CRLF & $dBinary & @CRLF & @CRLF & $sConversionType & ":" & @CRLF & $sConverted) EndFunc ;==>DisplayResults < -------------------------------------------------------------------------------- *IsArray* +---------+~ | IsArray |~ +---------+~ Checks if a variable is an array type. > IsArray ( variable ) < Parameters~ variable -------- The variable/expression to check. Return Value~ Success ------- 1. Failure ------- 0 if parameter is not an array variable. Remarks~ Can be useful to validate array/non-array parameters to user-defined functions. See language datatypes for a detailed description. Related~ |IsBinary|, |IsBool|, |IsFloat|, |IsHWnd|, |IsInt|, |IsNumber|, |IsPtr|, |IsString|, |VarGetType| Example~ > #include Example() Func Example() ; Run Notepad Run("notepad.exe") ; Wait 10 seconds for the Notepad window to appear. Local $hWnd = WinWait("[CLASS:Notepad]", "", 10) ; Retrieve the position and size of the Notepad window by passing the handle to WinGetPos. Local $aPos = WinGetPos($hWnd) ; Check if the variable is an array. If IsArray($aPos) Then MsgBox($MB_SYSTEMMODAL, "", "Window height: " & $aPos[3]) Else MsgBox($MB_SYSTEMMODAL, "", "An error occurred.") EndIf ; Close the Notepad window using the handle returned by WinWait. WinClose($hWnd) EndFunc ;==>Example < -------------------------------------------------------------------------------- *IsBinary* +----------+~ | IsBinary |~ +----------+~ Checks if a variable or expression is a binary type. > IsBinary ( expression ) < Parameters~ expression ---------- The variable or expression to check. Return Value~ Success ------- 1. Failure ------- 0 if expression is not binary type. Remarks~ See language datatypes for a detailed description. Related~ |Binary|, |BinaryToString|, |IsArray|, |IsBool|, |IsFloat|, |IsHWnd|, |IsInt|, |IsNumber|, |IsString|, |StringToBinary|, |VarGetType| Example~ > #include Local $dBinary = Binary("0x00204060") Local $sString = "0x00204060" MsgBox($MB_SYSTEMMODAL, "", "Returns 1 as the variable is binary: " & IsBinary($dBinary)) MsgBox($MB_SYSTEMMODAL, "", "Returns 0 as the variable is a string: " & IsBinary($sString)) < -------------------------------------------------------------------------------- *IsFloat* +---------+~ | IsFloat |~ +---------+~ Checks if the value of a variable or expression has a fractional component. > IsFloat ( variable ) < Parameters~ variable -------- The variable or expression to check. Return Value~ Success ------- 1 - Fractional component Failure ------- 0 - No fractional component Remarks~ The function will return 0 if the value is a float with no fractional component (e.g. 1.000). See language datatypes for a detailed description. Related~ |IsArray|, |IsBinary|, |IsBool|, |IsHWnd|, |IsInt|, |IsNumber|, |IsPtr|, |IsString|, |StringIsFloat|, |VarGetType| Example~ > #include Example() Func Example() Local $bIsFloat1 = IsFloat(3.14159) ; Returns 1 Local $bIsFloat2 = IsFloat(3.000) ; Returns 0 as the value is an integer i.e. 3 Local $bIsFloat3 = IsFloat(1 / 2 - 5) ; Returns 1 Local $bIsFloat4 = IsFloat(1.5e3) ; Returns 0 as 1.5e3 is equal to 1500. Local $bIsFloat5 = IsFloat("12.345") ; Returns 0 as the value is a string. MsgBox($MB_SYSTEMMODAL, "", "IsFloat: " & @CRLF & _ $bIsFloat1 & @CRLF & $bIsFloat2 & @CRLF & $bIsFloat3 & @CRLF & $bIsFloat4 & @CRLF & $bIsFloat5) EndFunc ;==>Example < -------------------------------------------------------------------------------- *IsBool* +--------+~ | IsBool |~ +--------+~ Checks if a variable's base type is boolean. > IsBool ( variable ) < Parameters~ variable -------- The variable/expression to check. Return Value~ Success ------- 1. Failure ------- 0 if expression is not boolean type. Remarks~ See language datatypes for a detailed description. Related~ |IsArray|, |IsBinary|, |IsFloat|, |IsHWnd|, |IsInt|, |IsNumber|, |IsPtr|, |IsString|, |VarGetType| Example~ > #include Local $bBoolean = True If IsBool($bBoolean) Then MsgBox($MB_SYSTEMMODAL, "", "The variable is boolean") Else MsgBox($MB_SYSTEMMODAL, "", "The variable is not boolean") EndIf < -------------------------------------------------------------------------------- *IsHWnd* +--------+~ | IsHWnd |~ +--------+~ Checks if a variable's base type is a pointer and window handle. > IsHWnd ( variable ) < Parameters~ variable -------- The variable/expression to check. Return Value~ Success ------- 1 if the expression is a pointer type AND a valid window handle. Failure ------- 0 if expression is not a pointer OR not a valid window handle. Remarks~ See language datatypes for a detailed description. Related~ |GUICtrlGetHandle|, |IsArray|, |IsBinary|, |IsBool|, |IsFloat|, |IsInt|, |IsNumber|, |IsPtr|, |IsString|, |VarGetType| Example~ > #include Example() Func Example() ; Run Notepad Run("notepad.exe") ; Wait 10 seconds for the Notepad window to appear. Local $hWnd = WinWait("[CLASS:Notepad]", "", 10) ; Test if the window was found and display the results. If IsHWnd($hWnd) Then MsgBox($MB_SYSTEMMODAL, "", "It's a valid HWND") Else MsgBox($MB_SYSTEMMODAL, "", "It's not a valid HWND") EndIf EndFunc ;==>Example < -------------------------------------------------------------------------------- *IsInt* +-------+~ | IsInt |~ +-------+~ Checks if the value of a variable or expression has no fractional component. > IsInt ( variable ) < Parameters~ variable -------- The variable/expression to check. Return Value~ Success ------- 1 - No fractional component Failure ------- 0 - Fractional component Remarks~ The function will return 1 if the value is a float with no fractional component (e.g. 1.000). See language datatypes for a detailed description. Related~ |IsArray|, |IsBinary|, |IsBool|, |IsFloat|, |IsHWnd|, |IsNumber|, |IsPtr|, |IsString|, |StringIsInt|, |VarGetType| Example~ > #include Example() Func Example() Local $bIsInt1 = IsInt(-12345) ; Returns 1 Local $bIsInt2 = IsInt(3.0000) ; Returns 1 Local $bIsInt3 = IsInt("5432") ; Returns 0 as the value is a string. Local $bIsInt4 = IsInt(7.5 - 4.5) ; Returns 1 since it evaluates to integer 3 MsgBox($MB_SYSTEMMODAL, "", "IsInt: " & @CRLF & _ $bIsInt1 & @CRLF & $bIsInt2 & @CRLF & $bIsInt3 & @CRLF & $bIsInt4) EndFunc ;==>Example < -------------------------------------------------------------------------------- *IsNumber* +----------+~ | IsNumber |~ +----------+~ Checks if a variable's base type is numeric. > IsNumber ( variable ) < Parameters~ variable -------- The variable/expression to check. Return Value~ Success ------- 1. Failure ------- 0 if expression is not numeric type. Remarks~ A number can be an integer/whole number or a fractional/floating-point. If the variable is a numeric value represented as a string, then IsNumber() will return 0. See language datatypes for a detailed description. Related~ |IsArray|, |IsBinary|, |IsBool|, |IsFloat|, |IsHWnd|, |IsInt|, |IsPtr|, |IsString| Example~ > #include Local $iLife = 42 If IsNumber($iLife) Then MsgBox($MB_SYSTEMMODAL, "", "The variable is a number") Else MsgBox($MB_SYSTEMMODAL, "", "The variable is not a number") EndIf < -------------------------------------------------------------------------------- *IsPtr* +-------+~ | IsPtr |~ +-------+~ Checks if a variable's base type is a pointer. > IsPtr ( variable ) < Parameters~ variable -------- The variable/expression to check. Return Value~ Success ------- 1 if the expression is a pointer type. Failure ------- 0 if expression is not pointer type. Remarks~ See language datatypes for a detailed description. Related~ |IsArray|, |IsBool|, |IsFloat|, |IsHWnd|, |IsInt|, |IsNumber|, |IsString|, |Ptr| Example~ > #include Example() Func Example() ; Run Notepad Run("notepad.exe") ; Wait 10 seconds for the Notepad window to appear. Local $hWnd = WinWait("[CLASS:Notepad]", "", 10) ; Test if $hWnd is a valid pointer and display the results. If IsPtr($hWnd) Then MsgBox($MB_SYSTEMMODAL, "", "It's a valid Ptr") Else MsgBox($MB_SYSTEMMODAL, "", "It's not a valid Ptr") EndIf ; Close the Notepad window using the handle returned by WinWait. WinClose($hWnd) EndFunc ;==>Example < -------------------------------------------------------------------------------- *IsString* +----------+~ | IsString |~ +----------+~ Checks if a variable is a string type. > IsString ( variable ) < Parameters~ variable -------- The variable/expression to check. Return Value~ Success ------- 1. Failure ------- 0 if expression is not string type. Remarks~ See language datatypes for a detailed description. Related~ |IsArray|, |IsBinary|, |IsBool|, |IsFloat|, |IsHWnd|, |IsInt|, |IsNumber|, |IsPtr|, |String|, |VarGetType| Example~ > #include Local $sString = "This is a string" If IsString($sString) Then MsgBox($MB_SYSTEMMODAL, "", "The variable is a string") Else MsgBox($MB_SYSTEMMODAL, "", "The variable is not a string") EndIf < -------------------------------------------------------------------------------- *String* +--------+~ | String |~ +--------+~ Returns the string representation of an expression. > String ( expression ) < Parameters~ expression ---------- An expression to convert into a string. Return Value~ Returns a string. Remarks~ Maximum string length is 2147483647 characters (but keep in mind that no line in an AutoIt script can exceed 4095 characters.) Related~ |BinaryToString|, |Chr|, |ChrW|, |HWnd|, |Int|, |IsString|, |Number|, |Ptr|, |StringToBinary| Example~ > #include Local $sString = String(10) ; The expression passed to String will return a string representation, currently 10 is a number. MsgBox($MB_SYSTEMMODAL, "", "$sString contains the value: " & $sString & " and IsString returns: " & IsString($sString)) < -------------------------------------------------------------------------------- *Int* +-----+~ | Int |~ +-----+~ Returns the integer (whole number) representation of an expression. > Int ( expression [, flag = 0] ) < Parameters~ expression ---------- An expression to convert into an integer. flag ----- [optional] Defines behavior. Can be one of the following: $NUMBER_AUTO (0) = (default) the result is auto-sized integer. See remarks. $NUMBER_32BIT (1) = string is interpreted as a 32bit integer $NUMBER_64BIT (2) = string is interpreted as a 64bit integer Constants are defined in "AutoItConstants.au3". Return Value~ Returns an integer. Remarks~ Default behavior is that if the result is within range of 32bit integer then 32bit integer is returned. If not, 64bit integer is returned. Both are signed. Fractional portions are truncated, so Int(1.999999) returns 1 Int(0/0) returns -9223372036854775807, if you were wondering. This function makes minor corrections to floating point numbers to account for the imprecise nature of floating point numbers. For example, the floating point expression 0.7 + 0.2 + 0.1 produces a floating point number that is not quite 1.0. Int() corrects for this anomaly, however, certain extremely rare circumstances may lead to Int() returning an unexpected value (the odds of getting an unexpected value are less than if Int() did not attempt any correction at all). Related~ |Binary|, |Ceiling|, |Floor|, |HWnd|, |Mod|, |Number|, |Ptr|, |Round|, |String| Example~ > #include ; Assign a Local variable the int representation of 10.793. Local $iInt = Int(10.793) ; Display the result. MsgBox($MB_SYSTEMMODAL, "", $iInt) < -------------------------------------------------------------------------------- *Mod* +-----+~ | Mod |~ +-----+~ Performs the modulus operation. > Mod ( value1, value2 ) < Parameters~ value1 ------ The dividend. value2 ------ The divisor. Return Value~ Success ------- the remainder when value1 is divided by value2. Failure ------- -1. #IND if the divisor is zero. Remarks~ This function guarantees that Mod(dividend, divisor) = dividend - Int(dividend / divisor) * divisor. This function does not guarantee that dividend or divisor can be represented, specifically with floating point numbers. If integers are passed this function does an integral modulo operation. Otherwise it falls back to a floating point operation which per the previous remark means it may not produce the expected output. Related~ |Int| Example~ > #include Example() Func Example() ; Assign a Local variable the number 18. Local $iNb = 18 ; If the mudulus operation of $iNb by 2 equals to 0 then $iNb is even. If Mod($iNb, 2) = 0 Then MsgBox($MB_SYSTEMMODAL, "", $iNb & " is an even number.") Else MsgBox($MB_SYSTEMMODAL, "", $iNb & " is an odd number.") EndIf ; Assign a Local variable the modulus operation of 4 by 7. Local $iMod1 = Mod(4, 7) ; 4%7 = 4 because the divisor > dividend ; Display the result. MsgBox($MB_SYSTEMMODAL, "", $iMod1) ; Assign a Local variable the modulus operation of 1 by 3/4. Local $iMod2 = Mod(1, 3 / 4) ; 1%(3/4) = 0.25 because the divisor is a float ; Display the result. MsgBox($MB_SYSTEMMODAL, "", $iMod2) EndFunc ;==>Example < -------------------------------------------------------------------------------- *Round* +-------+~ | Round |~ +-------+~ Returns a number rounded to a specified number of decimal places. > Round ( expression [, decimalplaces] ) < Parameters~ expression ---------- Any valid numeric expression. decimalplaces ------------- [optional] Number indicating how many places to the right of the decimal are included in the rounding. If omitted, Round returns an integer. Return Value~ Returns rounded number. Remarks~ The decimalplaces parameter can be negative which allows you to round to the ones, tens, hundred, etc. place. Note that up to fifteen digits of a number are displayed, and note that decimalplaces will never pad a number with trailing zeros. Related~ |Ceiling|, |Floor|, |Int|, |Number|, |Random| Example~ Example 1 > #include Local $iRound1 = Round(-1.582, 1) ; Returns -1.6. Local $iRound2 = Round(3.1415, 9) ; No change is made. Local $iRound3 = Round(123.5, -1) ; Returns 120 MsgBox($MB_SYSTEMMODAL, "", "The following values were rounded: " & @CRLF & _ $iRound1 & @CRLF & $iRound2 & @CRLF & $iRound3) < Example 2 > #include Example() Func Example() ; Assign a Local variable an Array which will contain the rounded numbers. Local $aRound[5] $aRound[0] = Round(-1.582, 1) ; Returns -1.6. $aRound[1] = Round(3.1415, 9) ; Returns 3.1415 $aRound[2] = Round(123.5, -1) ; Returns 120. $aRound[3] = Round(123.5) ; Returns 124. $aRound[4] = Round(50) ; Returns 50. ; Display the results. For $i = 0 To UBound($aRound) - 1 MsgBox($MB_SYSTEMMODAL, "", "Round" & $i & ": " & $aRound[$i] & @CRLF) Next EndFunc ;==>Example < -------------------------------------------------------------------------------- *Ceiling* +---------+~ | Ceiling |~ +---------+~ Returns a number rounded up to the next integer. > Ceiling ( expression ) < Parameters~ expression ---------- Any valid numeric expression. Return Value~ Returns the rounded number. Related~ |Floor|, |Int|, |Number|, |Round| Example~ > #include Example() Func Example() ; Assign a Local variable an array containing the numbers. Local $aNumber[8] = [4.8, 4.5, 4.3, 4, -4.8, -4.5, -4.3, -4] ; Assign a Local variable a string which will contain the results. Local $sResults = "" ; Loop through the array: calculate the ceiling and format the result. For $i = 0 To 7 $sResults &= "Ceiling(" & $aNumber[$i] & ") = " & Ceiling($aNumber[$i]) & @CRLF & ($i = 3 ? @CRLF : "") Next ; Display the results. MsgBox($MB_SYSTEMMODAL, "", $sResults) EndFunc ;==>Example < -------------------------------------------------------------------------------- *Chr* +-----+~ | Chr |~ +-----+~ Returns a character corresponding to an ASCII code. > Chr ( ASCIIcode ) < Parameters~ ASCIIcode --------- An ASCII code in the range 0-255 (e.g., 65 returns the capital letter A). Return Value~ Success ------- a string containing the ASCII representation of the given code. Failure ------- an empty string and sets the @error flag to 1 if the ASCIIcode is greater than 255. Remarks~ See the ASCII Character Code table for a complete list of available values. Chr(48) == "0", Chr(57) == "9", Chr(65) == "A", Chr(90) == "Z", Chr(97) == "a", Chr(122) == "z", etc. Related~ |Asc|, |AscW|, |ChrW|, |String| Example~ > #include Local $sText = "" For $i = 65 To 90 $sText = $sText & Chr($i) ; Or $sText &= Chr($i) can be used as well. Next MsgBox($MB_SYSTEMMODAL, "Uppercase alphabet", $sText) ; Display the characters between 65 to 90. < -------------------------------------------------------------------------------- *ChrW* +------+~ | ChrW |~ +------+~ Returns a character corresponding to a unicode code. > ChrW ( UNICODEcode ) < Parameters~ UNICODEcode ----------- A unicode code in the range 0-65535 (e.g., 65 returns the capital letter A). Return Value~ Success ------- a string containing the representation of the given code. Failure ------- an empty string and sets the @error flag to non-zero if the UNICODE value is greater than 65535. Remarks~ See the ASCII Character Code table for a complete list of available values. Related~ |Asc|, |AscW|, |Chr|, |String| Example~ > #include Local $sText = "" For $i = 256 To 512 $sText = $sText & ChrW($i) ; Or $sText &= ChrW($i) can be used as well. Next MsgBox($MB_SYSTEMMODAL, "Unicode chars 256 to 512", $sText) ; Display the unicode characters between 256 to 512. < -------------------------------------------------------------------------------- *Asc* +-----+~ | Asc |~ +-----+~ Returns the ASCII code of a character. > Asc ( "char" ) < Parameters~ char ----- The character to get the code for. If a string is used, the code for the first character is given. Return Value~ Returns the ASCII code of the specified char. Remarks~ See the ASCII Character Code table for a complete list of available values. Asc("0") == 48, Asc("9") == 57, Asc("A") == 65, Asc("Z") == 90, Asc("a") == 97, Asc("z") == 122, etc. Related~ |AscW|, |Chr|, |ChrW| Example~ > #include Local $iCode = Asc("A") MsgBox($MB_SYSTEMMODAL, "", "ASCII code for A: " & $iCode) < -------------------------------------------------------------------------------- *AscW* +------+~ | AscW |~ +------+~ Returns the unicode code of a character. > AscW ( "char" ) < Parameters~ char ----- The character to get the code for. If a string is used, the code for the first character is given. Return Value~ Returns the unicode code of the specified char. Remarks~ See the ASCII Character Code table for a complete list of available values. See "Unicode Support" for a detailed description. Related~ |Asc|, |Chr|, |ChrW| Example~ > #include Local $iCode = AscW("ß") MsgBox($MB_SYSTEMMODAL, "", "Unicode code for ß: U+" & Hex($iCode, 6)) < -------------------------------------------------------------------------------- *_FileReadToArray* +------------------+~ | _FileReadToArray |~ +------------------+~ Reads the specified file into a 1D or 2D array > #include _FileReadToArray ( $sFilePath, ByRef $vReturn [, $iFlags = $FRTA_COUNT [, $sDelimiter = ""]] ) < Parameters~ $sFilePath ---------- Path and filename of the file to be read. $vReturn -------- Variable to hold returned data - does not need to be an array. $iFlags ------- [optional] Add multiple values together as required $FRTA_NOCOUNT (0) - array is 0-based use UBound() to get size $FRTA_COUNT (1) - array count in the first element. (default) $FRTA_INTARRAYS (2) - Create "array of arrays" - see remarks $FRTA_ENTIRESPLIT (4) - Use entire delimiter string as split point (default each character defines a split point) $sDelimiter ----------- [optional] Used to further split each line of the file - e.g. reading CSV files into a 2D array Return Value~ Success ------- 1 and $vReturn holds an array. Failure ------- 0, @error flag set to non-zero and $vReturn is set to 0. @error: 1 - Error opening specified file 2 - Unable to split the file 3 - File lines have different numbers of fields (only if $FRTA_INTARRAYS flag not set) 4 - No delimiters found (only if $FRTA_INTARRAYS flag not set) Remarks~ If a delimiter is not specified the function returns a 1D array with each element holding a line of the file - line endings can be any mix of @CR, @LF and @CRLF. When a delimiter is specified the function tries to further split each line of the file - how this is done depends on the setting of the $FRTA_INTARRAYS flag. If the flag is not set and each line has the same number of fields split by the delimiter then a 2D array is created, but if this is not the case then @error is set to 3 and no array is returned. If the $FRTA_INTARRAYS flag is set the function creates a 1D array where each element is a further array holding the fields of the line split on the delimiter - the lines do not need to have the same number of fields. See example below. If the delimiter is more than a single character then the $FRTA_ENTIRESPLIT flag setting determines the split method. Related~ |_FileWriteFromArray| Example~ Example 1 > #include #include #include Example() Func Example() Local $aRetArray, $sFilePath = @TempDir & "\Test.txt" ; Create 1D array Local $aArray[] = ["0", "1", "2", "3", "4"] ; Write it to file _FileWriteFromArray($sFilePath, $aArray, Default, Default, @CRLF) Sleep(1000) ; Re-read it - with count _FileReadToArray($sFilePath, $aRetArray) _ArrayDisplay($aRetArray, "1D array - count", Default, 8) ; Re-read it - without count _FileReadToArray($sFilePath, $aRetArray, $FRTA_NOCOUNT) _ArrayDisplay($aRetArray, "1D array - no count", Default, 8) ; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ; Create "square" 2D array Local $aArray[][] = [ _ ["00", "01", "02", "03"], _ ["10", "11", "12", "13"], _ ["20", "21", "22", "23"], _ ["30", "31", "32", "33"]] _ArrayDisplay($aArray, "Original", Default, 8) ; Write it to file _FileWriteFromArray($sFilePath, $aArray, Default, Default, ",") Sleep(1000) ; Re-read it - with count _FileReadToArray($sFilePath, $aRetArray, Default, ",") _ArrayDisplay($aRetArray, "2D array - count", Default, 8) ; Re-read it - without count _FileReadToArray($sFilePath, $aRetArray, $FRTA_NOCOUNT, ",") _ArrayDisplay($aRetArray, "2D array - no count", Default, 8) ; Read into "array of arrays" with count _FileReadToArray($sFilePath, $aRetArray, $FRTA_COUNT + $FRTA_INTARRAYS, ",") _ArrayDisplay($aRetArray, "Array of arrays - count", Default, 8) ; Now look inside the arrays inside the returned array _ArrayDisplay($aRetArray[1], "Array 1 inside RetArray - count", Default, 8) ; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ; Rewrite 2D array with multiple delimiters _FileWriteFromArray($sFilePath, $aArray, Default, Default, ":|") Sleep(1000) ; Re-read with each delimiter acting as a split point _FileReadToArray($sFilePath, $aRetArray, $FRTA_NOCOUNT, ":|") _ArrayDisplay($aRetArray, "Split on each character", Default, 8) ; Re-read with whole delimiter acting as a split point _FileReadToArray($sFilePath, $aRetArray, $FRTA_NOCOUNT + $FRTA_ENTIRESPLIT, ":|") _ArrayDisplay($aRetArray, "Split on full delimiter", Default, 8) FileDelete($sFilePath) EndFunc ;==>Example < Example 2 > #include #include #include Example() Func Example() ; Define a variable to pass to _FileReadToArray. Local $aArray = 0 ; Read the current script file into an array using the variable defined previously. ; $iFlag is specified as 0 in which the array count will not be defined. Use UBound() to find the size of the array. If Not _FileReadToArray(@ScriptFullPath, $aArray, 0) Then MsgBox($MB_SYSTEMMODAL, "", "There was an error reading the file. @error: " & @error) ; An error occurred reading the current script file. EndIf ; Display the array in _ArrayDisplay. _ArrayDisplay($aArray) EndFunc ;==>Example < -------------------------------------------------------------------------------- *_FileCountLines* +-----------------+~ | _FileCountLines |~ +-----------------+~ Returns the number of lines in the specified file > #include _FileCountLines ( $sFilePath ) < Parameters~ $sFilePath ---------- Path and filename of the file to be read Return Value~ Success ------- the number of lines in the file. Failure ------- 0 and sets the @error flag to non-zero. @error: 1 - File cannot be opened or found. Remarks~ It does not count a final @LF as a line. Example~ > #include #include Local $iCountLines = _FileCountLines(@ScriptFullPath) ; Retrieve the number of lines in the current script. MsgBox($MB_SYSTEMMODAL, "", "There are " & $iCountLines & " lines in this file.") < -------------------------------------------------------------------------------- *_FileCreate* +-------------+~ | _FileCreate |~ +-------------+~ Creates or zero's out the length of the file specified > #include _FileCreate ( $sFilePath ) < Parameters~ $sFilePath ---------- Path and filename of the file to be created. Return Value~ Success ------- 1. Failure ------- 0 and sets the @error flag to non-zero. @error: 1 - Error opening specified file 2 - File could not be written to Example~ > #include #include If Not _FileCreate("error.log") Then MsgBox($MB_SYSTEMMODAL, "Error", " Error Creating/Resetting log. error:" & @error) EndIf < -------------------------------------------------------------------------------- *_FileListToArray* +------------------+~ | _FileListToArray |~ +------------------+~ Lists files and\or folders in a specified folder (Similar to using Dir with the /B Switch) > #include _FileListToArray ( $sFilePath [, $sFilter = "*" [, $iFlag = $FLTA_FILESFOLDERS [, $bReturnPath = False]]] ) < Parameters~ $sFilePath ---------- Folder to generate filelist for. $sFilter -------- [optional] the filter to use, default is *. (* and ? wildcards accepted - See Remarks) $iFlag ------ [optional] specifies whether to return files folders or both $FLTA_FILESFOLDERS (0) = (Default) Return both files and folders $FLTA_FILES (1) = Return files only $FLTA_FOLDERS (2) = Return Folders only Constants are defined in FileConstants.au3 $bReturnPath [optional] If True the full path is appended to the file\folder path, otherwise it is relative to the $sFilePath folder. Default is False. Return Value~ Success ------- A one-dimensional array. $aArray[0] = Number of Files\Folders returned $aArray[1] = 1st File\Folder $aArray[2] = 2nd File\Folder $aArray[3] = 3rd File\Folder $aArray[n] = nth File\Folder Failure ------- sets the @error flag to non-zero. @error: 1 - Folder not found or invalid 2 - Invalid $sFilter 3 - Invalid $iFlag 4 - No File(s) Found Remarks~ This function uses the Windows OS to return subfolders matching the specified filter. This works perfectly for simple filters, using a complex filter with multiple wildcards may return some unexpected results (for example *test*.* will match both testX and testX.X subfolders). If this occurs, the _FileListToArrayRec() function might be better suited as it compares all subfolders to the specified filter using a RegEx, although the time taken to run the function can be noticeably greater See FileFindFirstFile() for a discussion about wildcards. Related~ |_FileListToArrayRec| Example~ Example 1 > #include #include #include Example() Func Example() ; List all the files and folders in the desktop directory using the default parameters. Local $aFileList = _FileListToArray(@DesktopDir, "*") If @error = 1 Then MsgBox($MB_SYSTEMMODAL, "", "Path was invalid.") Exit EndIf If @error = 4 Then MsgBox($MB_SYSTEMMODAL, "", "No file(s) were found.") Exit EndIf ; Display the results returned by _FileListToArray. _ArrayDisplay($aFileList, "$aFileList") EndFunc ;==>Example < Example 2 > #include #include #include Example() Func Example() ; List all the files and folders in the desktop directory using the default parameters and return the full path. Local $aFileList = _FileListToArray(@DesktopDir, Default, Default, True) If @error = 1 Then MsgBox($MB_SYSTEMMODAL, "", "Path was invalid.") Exit EndIf If @error = 4 Then MsgBox($MB_SYSTEMMODAL, "", "No file(s) were found.") Exit EndIf ; Display the results returned by _FileListToArray. _ArrayDisplay($aFileList, "$aFileList") EndFunc ;==>Example < -------------------------------------------------------------------------------- *_FileListToArrayRec* +---------------------+~ | _FileListToArrayRec |~ +---------------------+~ Lists files and\or folders in specified path with optional recursion to defined level and result sorting > #include _FileListToArrayRec ( $sFilePath [, $sMask = "*" [, $iReturn = $FLTAR_FILESFOLDERS [, $iRecur = $FLTAR_NORECUR [, $iSort = $FLTAR_NOSORT [, $iReturnPath = $FLTAR_RELPATH]]]]] ) < Parameters~ $sFilePath ---------- Initial path used to generate filelist. If path ends in \ then folders will be returned with an ending \ If path lengths > 260 chars, prefix path with "\\?\" - return paths are not affected $sMask ------ [optional] Filter for result. Multiple filters must be separated by ";" Use "|" to separate 3 possible sets of filters: "Include|Exclude|Exclude_Folders" Include = Files/Folders to include (default = "*" [all]) Exclude = Files/Folders to exclude (default = "" [none]) Exclude_Folders = only used if $iRecur = 1 AND $iReturn <> 2 to exclude defined folders (default = "" [none]) $iReturn -------- [optional] Specifies whether to return files, folders or both and omit those with certain attributes $FLTAR_FILESFOLDERS (0) - (Default) Return both files and folders $FLTAR_FILES (1) - Return files only $FLTAR_FOLDERS (2) - Return Folders only Add one or more of the following to $iReturn to omit files/folders with that attribute + $FLTAR_NOHIDDEN (4) - Hidden files and folders + $FLTAR_NOSYSTEM (8) - System files and folders + $FLTAR_NOLINK (16) - Link/junction folders $iRecur ------- [optional] Specifies whether to search recursively in subfolders and to what level $FLTAR_NORECUR (0) - Do not search in subfolders (Default) $FLTAR_RECUR (1) - Search in all subfolders (unlimited recursion) Negative integer - Search in subfolders to specified depth $iSort ------ [optional] Sort results in alphabetical and depth order $FLTAR_NOSORT (0) - Not sorted (Default) $FLTAR_SORT (1) - Sorted $FLTAR_FASTSORT (2) - Sorted with faster algorithm (assumes files in folder returned sorted - requires NTFS and not guaranteed) $iReturnPath ------------ [optional] Specifies displayed path of results $FLTAR_NOPATH (0) - File/folder name only $FLTAR_RELPATH (1) - Relative to initial path (Default) $FLTAR_FULLPATH (2) - Full path included Return Value~ Success: a one-dimensional array made up as follows: [0] = Number of Files/Folders returned [1] = 1st File/Folder [2] = 2nd File/Folder ... [n] = nth File\Folder Failure: an empty string and sets the @error flag to 1 with @extended set as follows: 1 - Path not found or invalid 2 - Invalid Include parameter 3 - Invalid Exclude parameter 4 - Invalid Exclude_Folders parameter 5 - Invalid $iReturn parameter 6 - Invalid $iRecur parameter 7 - Invalid $iSort parameter 8 - Invalid $iReturnPath parameter 9 - No files/folders found Remarks~ If the files and/or folders to be returned are all within the same folder and can be specified with a single simple filter the _FileListToArray() function might be better suited as it is considerably faster. Include/Exclude/Exclude_Folders logic: Non-recursive: Include/Exclude: Files and/or folders Exclude_Folders: Ignored Recursive: Include/Exclude: $iReturn = $FLTAR_FILESFOLDERS/$FLTAR_FILES - Files only $iReturn = $FLTAR_FOLDERS - Folders only Exclude_Folders: $iReturn = $FLTAR_FILESFOLDERS/$FLTAR_FILES - Folders only $iReturn = $FLTAR_FOLDERS - Ignored Sorting the results will significantly increase the time required for the UDF to return the array Despite the name, this UDF is iterative, not recursive. Constants are defined in FileConstants.au3 Related~ |_FileListToArray| Example~ > #include ; Only required to display the arrays #include #include Example() Func Example() Local $sAutoItDir = StringLeft(@AutoItExe, StringInStr(@AutoItExe, "\", Default, -1)) If StringRight($sAutoItDir, 5) = "beta\" Then $sAutoItDir = StringTrimRight($sAutoItDir, 5) EndIf ConsoleWrite($sAutoItDir & @CRLF) ; A sorted list of all files and folders in the AutoIt installation Local $aArray = _FileListToArrayRec($sAutoItDir, "*", $FLTAR_FILESFOLDERS, $FLTAR_RECUR, $FLTAR_SORT) _ArrayDisplay($aArray, "Sorted tree") ; And now ignoring the "Include" folder $aArray = _FileListToArrayRec($sAutoItDir, "*||include", $FLTAR_FILESFOLDERS, $FLTAR_RECUR, $FLTAR_SORT) _ArrayDisplay($aArray, "No 'Include' folder") ; A sorted list of all but the .exe files in the \AutoIt3 folder $aArray = _FileListToArrayRec($sAutoItDir, "*|*.exe", $FLTAR_FILES, $FLTAR_NORECUR, $FLTAR_SORT) _ArrayDisplay($aArray, "Non .EXE files") ; And here are the .exe files we left out last time $aArray = _FileListToArrayRec($sAutoItDir, "*.exe", $FLTAR_FILES) _ArrayDisplay($aArray, ".EXE Files") ; A test for all folders and .exe files only throughout the folder tree, omitting folders beginning with I (Icons and Include) $aArray = _FileListToArrayRec($sAutoItDir, "*.exe||i*", $FLTAR_FILESFOLDERS, $FLTAR_RECUR, $FLTAR_SORT) _ArrayDisplay($aArray, "Recur with filter") ; Look for icon files - but exlude the "Icons" folder $aArray = _FileListToArrayRec($sAutoItDir, "*.ico||ic*", $FLTAR_FILES, $FLTAR_RECUR, $FLTAR_SORT) If @error Then MsgBox($MB_SYSTEMMODAL, "Ooops!", "No ico files found") Else _ArrayDisplay($aArray, "Icon files not in 'Icons' folder") EndIf ; And to show that the filter applies to files AND folders when not recursive $aArray = _FileListToArrayRec($sAutoItDir, "*.exe", $FLTAR_FILESFOLDERS, $FLTAR_NORECUR, $FLTAR_SORT) _ArrayDisplay($aArray, "Non-recur with filter") ; The filter also applies to folders when recursively searching for folders $aArray = _FileListToArrayRec($sAutoItDir, "Icons", $FLTAR_FOLDERS, $FLTAR_RECUR, $FLTAR_SORT) _ArrayDisplay($aArray, "Folder recur with filter") ; Note the exlude_folder parameter is ignored when looking for folders - "Icons" will be excluded but "Include" will still be there $aArray = _FileListToArrayRec($sAutoItDir, "*|ic*|i*", $FLTAR_FOLDERS, $FLTAR_RECUR, $FLTAR_SORT) _ArrayDisplay($aArray, "'Icons' out - 'Include' in") ; The root of C:\Windows showing hidden/system folders $aArray = _FileListToArrayRec("C:\Windows\", "*", $FLTAR_FOLDERS) _ArrayDisplay($aArray, "Show hidden folders") ; The root of C:\Windows omitting hidden/system folders $aArray = _FileListToArrayRec("C:\Windows\", "*", $FLTAR_FOLDERS + $FLTAR_NOHIDDEN + $FLTAR_NOSYSTEM) _ArrayDisplay($aArray, "Hide hidden folders") EndFunc ;==>Example < -------------------------------------------------------------------------------- *_FilePrint* +------------+~ | _FilePrint |~ +------------+~ Prints a plain text file > #include _FilePrint ( $sFilePath [, $iShow = @SW_HIDE] ) < Parameters~ $sFilePath ---------- The file to print. $iShow ------ [optional] The state of the window. (default = @SW_HIDE) Return Value~ Success ------- 1. Failure ------- 0 and sets the @error flag to non-zero. Remarks~ Uses the ShellExecute function of shell32.dll. Example~ > #include #include Local $sFilePath = FileOpenDialog("Print File", "", "Text Documents (*.txt)", 1) If @error Then Exit Local $iIsPrinted = _FilePrint($sFilePath) If $iIsPrinted Then MsgBox($MB_SYSTEMMODAL, "", "The file was printed.") Else MsgBox($MB_SYSTEMMODAL, "", "Error: " & @error & @CRLF & "The file was not printed.") EndIf < -------------------------------------------------------------------------------- *_FileWriteFromArray* +---------------------+~ | _FileWriteFromArray |~ +---------------------+~ Writes an array to a specified file > #include _FileWriteFromArray ( $sFilePath, Const ByRef $aArray [, $iBase = Default [, $iUBound = Default [, $sDelimiter = "|"]]] ) < Parameters~ $sFilePath ---------- Path of the file to write to, or a file handle returned by FileOpen(). $aArray ------- The array to be written to the specified file. $iBase ------ [optional] Start array index to read, normally set to 0 or 1. Default is 0. $iUbound -------- [optional] Set to the last record you want to write to the File. Default is the whole array. $sDelimiter ----------- [optional] Delimiter character(s) for 2-dimension arrays. Default is "|". Return Value~ Success ------- 1. Failure ------- 0 and sets the @error flag to non-zero. @error: 1 - Error opening specified file 2 - $aArray is not an array 3 - Error writing to file 4 - $aArray is not a 1D or 2D array 5 - Start index is greater than the $iUbound parameter Remarks~ If a string path is provided, the file will be overwritten and closed. To use other write modes, like append or Unicode formats, open the file with FileOpen() first and pass the file handle instead. If a file handle is passed, the file will still be open after writing. Related~ |_FileReadToArray| Example~ > #include ; List all the files in the current script directory. Local $aScriptDir = _FileListToArray(@ScriptDir) ; Create a file in the users %TEMP% directory. Local $sFilePath = @TempDir & "\Examples.txt" ; Write array to a file by passing the file name. _FileWriteFromArray($sFilePath, $aScriptDir, 1) ; Display the file. ShellExecute($sFilePath) < -------------------------------------------------------------------------------- *_FileWriteToLine* +------------------+~ | _FileWriteToLine |~ +------------------+~ Writes text to a specific line in a file > #include _FileWriteToLine ( $sFilePath, $iLine, $sText [, $bOverWrite = False] ) < Parameters~ $sFilePath ---------- The file to write to $iLine ------ The line number to write to $sText ------ The text to write $bOverWrite ----------- [optional] True - will overwrite the old line False - (default) will not overwrite Return Value~ Success ------- 1. Failure ------- 0 and sets the @error flag to non-zero. @error: 1 - File has fewer lines than $iLine 2 - File does not exist 3 - Error when opening file 4 - $iLine is invalid 5 - $iOverWrite is invalid 6 - $sText is invalid Remarks~ If _FileWriteToLine() is called with $iOverWrite as 1 and $sText as "", it will delete the line. Example~ > #include ; Example: Write to line 3 of c:\temp\test.txt REPLACING line 3 _FileWriteToLine("c:\temp\test.txt", 3, "my replacement for line 3", True) ; Example: Write to line 3 of c:\temp\test.txt NOT REPLACING line 3 _FileWriteToLine("c:\temp\test.txt", 3, "my insertion", False) < -------------------------------------------------------------------------------- *_Array1DToHistogram* +---------------------+~ | _Array1DToHistogram |~ +---------------------+~ Transform a 1D array to Histogram > #include _Array1DToHistogram ( $aArray [, $iSizing = 100] ) < Parameters~ $aArray ------- Array to transform $iSizing -------- [optional] Allows to zoom the histogram. Default = 100 percent Return Value~ Success ------- the array transformed. Failure ------- sets the @error flag to non-zero. @error: 1 - $aArray is not a 1D array Remarks~ Right alignment of negative values is not perfect due to non fixed font usage. Example~ Example 1 > #include Local $aNEW[] = [0, -80, -49, -44, 80, 100, 8, 7, 6, 5, 4, 3, 2, 1] Local $aArray = _Array1DToHistogram($aNEW, 125) _ArrayDisplay($aArray, "_Array1DToHistogram") < Example 2 > #include Local $iLimit = 500 Local $aValues[51] Local $t, $n For $i = 1 To $iLimit $t = TimerInit() Sleep(10) $n = Round(TimerDiff($t)) $aValues[$n] += 1 Next Local $aArray = _Array1DToHistogram($aValues) _ArrayDisplay($aArray, "_Array1DToHistogram", "10:20") < -------------------------------------------------------------------------------- *_ArrayAdd* +-----------+~ | _ArrayAdd |~ +-----------+~ Adds a specified value at the end of an existing 1D or 2D array > #include _ArrayAdd ( ByRef $aArray, $vValue [, $iStart = 0 [, $sDelim_Item = "|" [, $sDelim_Row = @CRLF [, $iForce = $ARRAYFILL_FORCE_DEFAULT]]]] ) Parameters~ $aArray ------- Array to modify $vValue ------- Value(s) to add - can be a single item, a delimited string or an array $iStart ------- [optional] Column in which addition is to begin (2D array only) $sDelim_Item ------------ [optional] Delimiter used if a string is to be split into items $sDelim_Row ----------- [optional] Delimiter used if a string is to be split into rows (2D only) $iForce ------- [optional] Maintains default behaviour, ARRAYFILL_FORCE_DEFAULT (0) Forces $vValue addition as a single item, $ARRAYFILL_FORCE_SINGLEITEM (1) Or forces datatype for all added items $ARRAYFILL_FORCE_INT (2) $ARRAYFILL_FORCE_NUMBER (3) $ARRAYFILL_FORCE_PTR (4) $ARRAYFILL_FORCE_HWND (5) $ARRAYFILL_FORCE_STRING (6) See Remarks for more details Return Value~ Success ------- the index of last added item. Failure ------- -1 and sets the @error flag to non-zero. @error: 1 - $aArray is not an array 2 - $aArray is not a 1 or 2 dimensional array 3 - $vValue has too many columns to fit into $aArray 4 - $iStart outside array bounds (2D only) 5 - Number of dimensions for $avArray and $vValue arrays do not match Remarks~ Addition mode depends on $vValue type, but using $iForce can affect this. Default behaviour is as follows: 1D arrays: Single item - adds 1 element $sDelim_Item delimited string - adds as many elements as items 0-based 1D array - adds as many elements as items 2D arrays: $sDelim_Item delimited string - adds 1 row, columns filled if enough items $sDelim_Row delimited string - adds as many rows as items, only 1 column filled $sDelim_Item & Row delimited string - adds rows and items, depending on split points 0-based 2D array - adds as many rows/columns as in array An empty string ("") is added if there are insufficient items specified in $vValue. Excess items are ignored. Setting the $iForce parameter can change the default insertion behaviour or amend the datatype for added items. It can be set as follows: - $ARRAYFILL_FORCE_DEFAULT (default): - Items are split as described above. Single items and array elements retain their datatypes - delimited strings are added as strings. - $ARRAYFILL_FORCE_SINGLEITEM: - If $aArray is 1D, $vValue is added as a single element. - if $aArray is 2D the parameter is ignored. - $ARRAYFILL_FORCE_INT, $ARRAYFILL_FORCE_NUMBER, $ARRAYFILL_FORCE_PTR, $ARRAYFILL_FORCE_HWND, $ARRAYFILL_FORCE_STRING - If $vValue is a single item, it is forced into the defined datatype - by default it would retain its existing datatype. - If $vValue is a delimited string, all items are forced into the specified datatype - by default they would be added to the array as strings. If different datatypes are required for the items they must be passed as an array. - If $vValue is an array, the parameter is ignored and the array elements are added retaining their existing datatypes. If $iForce is set to any other value it is ignored. Related~ |_ArrayConcatenate|, |_ArrayDelete|, |_ArrayInsert|, |_ArrayPop|, |_ArrayPush| Example~ Example 1 > #include #include Local $aArray_Base[2] = ["Org Item 0", "Org item 1"] _ArrayDisplay($aArray_Base, "1D - Base array") ; Add a single item Local $aArray = $aArray_Base Local $sSingleFill = "New Item 2" _ArrayAdd($aArray, $sSingleFill) _ArrayDisplay($aArray, "1D - Single") ; Add a delimited string - each item adds new element $aArray = $aArray_Base Local $sFill = "" For $i = 1 To 5 $sFill &= "New Item " & $i + 1 & "|" Next $sFill = StringTrimRight($sFill, 1) MsgBox($MB_SYSTEMMODAL, "Delimited string to add", $sFill) _ArrayAdd($aArray, $sFill) _ArrayDisplay($aArray, "1D - Delim string") ; Add a 1D array - each element adds new element $aArray = $aArray_Base Local $aFill[5] For $i = 0 To 4 $aFill[$i] = "New Item " & $i + 2 Next _ArrayDisplay($aFill, "Array to add") _ArrayAdd($aArray, $aFill) _ArrayDisplay($aArray, "1D - 1D array") < Example 2 > #include Local $aArray, $sFill Local $aArray_Base[2][2] = [["Item 0 - 0", "Item 0 - 1"], ["Item 1 - 0", "Item 1 - 1"]] _ArrayDisplay($aArray_Base, "2D - Base array") ; Add item delimited string $aArray = $aArray_Base $sFill = "New Item 2 - 0|New Item 2 - 1" _ArrayAdd($aArray, $sFill) _ArrayDisplay($aArray, "2D - Item delimited") ; Add row delimited string - load in col 1 $aArray = $aArray_Base $sFill = "New Item 2 - 1" & @CRLF & "New Item 3 - 1" _ArrayAdd($aArray, $sFill, 1) _ArrayDisplay($aArray, "2D - Row Delimited") ; Add item & row delimited string $aArray = $aArray_Base $sFill = "New Item 2 - 0|New Item 2 - 1" & @CRLF & "New Item 3 - 0|New Item 3 - 1" _ArrayAdd($aArray, $sFill) _ArrayDisplay($aArray, "2D - Item & row Delimited") ; Add a 2D array $aArray = $aArray_Base Local $aFill[2][2] = [["New Item 2 - 1", "New Item 2 - 2"], ["New Item 3 - 1", "New Item 3 - 2"]] _ArrayAdd($aArray, $aFill) _ArrayDisplay($aArray, "2D - 2D Array") ; Add a 2D array - Single item/column - load in col 1 $aArray = $aArray_Base Local $aFill[2][1] = [["New Item 2 - 1"], ["New Item 3 - 1"]] _ArrayAdd($aArray, $aFill, 1) _ArrayDisplay($aArray, "2D - 2D Array") < Example 3 > #include #include Local $aArray_Base[2] = ["Org Item 0", "Org item 1"] Local $aArray Local $sFill = "" For $i = 2 To 6 $sFill &= $i & "|" ; Note variables added as number datatype here Next $sFill = StringTrimRight($sFill, 1) MsgBox($MB_SYSTEMMODAL, "Delimited string to add", $sFill) ; Add items by delimited string $aArray = $aArray_Base _ArrayAdd($aArray, $sFill) _ArrayDisplay($aArray, "Converted to string") ; But converted to string datatype when inserted MsgBox($MB_SYSTEMMODAL, "Result", "Data:" & @TAB & $aArray[6] & @CRLF & "Datatype:" & @TAB & VarGetType($aArray[6])) ; Add items by delimited string $aArray = $aArray_Base ; Now force datatype to Number _ArrayAdd($aArray, $sFill, Default, Default, Default, $ARRAYFILL_FORCE_NUMBER) _ArrayDisplay($aArray, "Forced to number") ; And datatype is forced to required type MsgBox($MB_SYSTEMMODAL, "Result", "Data:" & @TAB & $aArray[6] & @CRLF & "Datatype:" & @TAB & VarGetType($aArray[6])) < -------------------------------------------------------------------------------- *_ArrayBinarySearch* +--------------------+~ | _ArrayBinarySearch |~ +--------------------+~ Uses the binary search algorithm to search through a 1D or 2D array > #include _ArrayBinarySearch ( Const ByRef $aArray, $vValue [, $iStart = 0 [, $iEnd = 0 [, $iColumn = 0]]] ) < Parameters~ $aArray ------- Array to search $vValue ------- Value to find $iStart ------- [optional] Index of array to start searching at $iEnd ----- [optional] Index of array to stop searching at $iColumn -------- [optional] Column of array to search Return Value~ Success ------- the index that value was found at. Failure ------- -1 and sets the @error flag to non-zero. @error: 1 - $aArray is not an array 2 - $vValue outside of array min/max values 3 - $vValue was not found in array 4 - $iStart is greater than $iEnd 5 - $aArray is not a 1D or 2D array 6 - $aArray is empty 7 - $iColumn outside array bounds Remarks~ When performing a binary search on an array of items, the array (specified column if 2D) MUST be sorted before the search is done. Otherwise undefined results will be returned. Related~ |_ArrayFindAll|, |_ArraySearch| Example~ Example 1 > #include #include Local $iIndex Local $aArray[5][2] For $i = 0 To 4 For $j = 0 To 1 $aArray[$i][$j] = "#" & $i & $j Next Next _ArrayDisplay($aArray, "Array") ; Search col 0 $iIndex = _ArrayBinarySearch($aArray, "#10", 0, 0, 0) MsgBox($MB_SYSTEMMODAL, "Index", $iIndex) ; Search col 1 $iIndex = _ArrayBinarySearch($aArray, "#31", 0, 0, 1) MsgBox($MB_SYSTEMMODAL, "Index", $iIndex) < Example 2 > ; using an array returned by StringSplit() #include #include Local $avArray = StringSplit("a,b,d,c,e,f,g,h,i", ",") ; sort the array to be able to do a binary search _ArraySort($avArray, 0, 1) ; start at index 1 to skip $avArray[0] ; display sorted array _ArrayDisplay($avArray, "$avArray AFTER _ArraySort()") ; start at index 1 to skip $avArray[0] Local $iKeyIndex = _ArrayBinarySearch($avArray, "c", 1) If Not @error Then MsgBox($MB_SYSTEMMODAL, 'Entry found', ' Index: ' & $iKeyIndex) Else MsgBox($MB_SYSTEMMODAL, 'Entry Not found', ' Error: ' & @error) EndIf < -------------------------------------------------------------------------------- *_ArrayColDelete* +-----------------+~ | _ArrayColDelete |~ +-----------------+~ Deletes a specified column from a 2D array > #include _ArrayColDelete ( ByRef $aArray, $iColumn [, $bConvert = False] ) < Parameters~ $aArray ------- Array to modify $iColumn -------- Column to delete $bConvert --------- [optional] If True then if only one column remains the array is converted to 1D Return Value~ Success ------- the number of columns remaining. Failure ------- -1 and sets the @error flag to non-zero. @error: 1 - $aArray is not an array 2 - $aArray is not a 2D array 3 - $iColumn is outside array bounds Related~ |_ArrayColInsert| Example~ > #include Local $aArray[4][3] For $i = 0 To 3 For $j = 0 To 2 $aArray[$i][$j] = $i & $j Next Next _ArrayDisplay($aArray, "Original") _ArrayColDelete($aArray, 2) _ArrayDisplay($aArray, "Col 2 Deleted") ; Copy 2 col array Local $aArray_2Col = $aArray ; Default 1 column left as 2D array _ArrayColDelete($aArray, 0) _ArrayDisplay($aArray, "Col 0 del - 2D array") ; Convert 1 column array to 1D _ArrayColDelete($aArray_2Col, 0, True) _ArrayDisplay($aArray_2Col, "Col 0 del - 1D array") < -------------------------------------------------------------------------------- *_ArrayColInsert* +-----------------+~ | _ArrayColInsert |~ +-----------------+~ Inserts a specified column into a 1D or 2D array > #include _ArrayColInsert ( ByRef $aArray, $iColumn ) < Parameters~ $aArray ------- Array to modify $iColumn -------- Column to insert - if array is 1D it is automatically converted to 2D Return Value~ Success ------- the number of columns remaining. Failure ------- -1 and sets the @error flag to non-zero. @error: 1 - $aArray is not an array 2 - $aArray is not a 1D or 2D array 3 - $iColumn is less than 0 or greater than upper array bound plus 1 Related~ |_ArrayColDelete| Example~ > #include Local $aArray[4] = [0, 1, 2, 3] _ArrayDisplay($aArray, "Original") _ArrayColInsert($aArray, 0) ; Now a 2D array _ArrayDisplay($aArray, "Col 0 inserted") _ArrayColInsert($aArray, 1) _ArrayDisplay($aArray, "Col 1 inserted") _ArrayColInsert($aArray, 3) _ArrayDisplay($aArray, "Col 3 inserted") < -------------------------------------------------------------------------------- *_ArrayCombinations* +--------------------+~ | _ArrayCombinations |~ +--------------------+~ Returns an array of the combinations of a set of elements from a selected 1D array > #include _ArrayCombinations ( Const ByRef $aArray, $iSet [, $sDelimiter = ""] ) < Parameters~ $aArray ------- The Array to use $iSet ----- Size of the combinations set $sDelimiter ----------- [optional] String result separator, default is "" for none Return Value~ Success ------- an array of Combinations The first element ($aArray[0]) contains the number of strings returned. The remaining elements ($aArray[1], $aArray[2], etc.) contain the Combinations. Failure ------- sets the @error flag to non-zero. @error: 1 - The Input Must be an Array 2 - $aArray is not a 1D array Remarks~ The input array must be 0-based, i.e. no counter in $aArray[0]. Based on an algorithm by Kenneth H. Rosen. Related~ |_ArrayPermute| Example~ > ; Declare a 1-dimensional array, and create an array showing the Possible Combinations #include Local $aArray[5] = [1, 2, 3, 4, 5] For $i = 1 To UBound($aArray) Local $aArrayCombo = _ArrayCombinations($aArray, $i, ",") _ArrayDisplay($aArrayCombo, "iSet = " & $i) Next < -------------------------------------------------------------------------------- *_ArrayConcatenate* +-------------------+~ | _ArrayConcatenate |~ +-------------------+~ Concatenate two arrays - either 1D or 2D with the same number of columns > #include _ArrayConcatenate ( Const ByRef $aArrayTarget, ByRef $aArraySource [, $iStart = 0] ) < Parameters~ $aArrayTarget ------------- The array to which the source array will be concatenated $aArraySource ------------- The array to concatenate to the target array $iStart ------- [optional] index of the first Source array entry (Default = 0) Return Value~ Success ------- the number of elemets/rows in the new target array Failure ------- -1 and sets the @error flag to non-zero. @error: 1 - $aArrayTarget is not an array 2 - $aArraySource is not an array 3 - $aArrayTarget is not a 1D or 2D array 4 - $aArrayTarget and $aArraySource 1D/2D mismatch 5 - $aArrayTarget and $aArraySource column number mismatch (2D only) 6 - $iStart outside array bounds Remarks~ The $iStart parameter is useful when concatenating arrays which have a count in the [0] element. Related~ |_ArrayAdd| Example~ > #include Local $aArrayTarget[5] = ["0", "1", "2", "3", "4"] Local $aArraySource[5] = ["5", "6", "7", "8", "9"] _ArrayDisplay($aArrayTarget, "1D Target") _ArrayDisplay($aArraySource, "1D Source") _ArrayConcatenate($aArrayTarget, $aArraySource) _ArrayDisplay($aArrayTarget, "1D Target and Source concatenated") Local $aArrayTarget[4][3] For $i = 0 To 3 For $j = 0 To 2 $aArrayTarget[$i][$j] = $i & $j Next Next Local $aArraySource[4][3] For $i = 0 To 3 For $j = 0 To 2 $aArraySource[$i][$j] = (4 + $i) & $j Next Next _ArrayDisplay($aArrayTarget, "2D Target") _ArrayDisplay($aArraySource, "2D Source") _ArrayConcatenate($aArrayTarget, $aArraySource) _ArrayDisplay($aArrayTarget, "2D Target and Source concatenated") < -------------------------------------------------------------------------------- *_ArrayDelete* +--------------+~ | _ArrayDelete |~ +--------------+~ Deletes the specified element(s) from the specified 1D or 2D array > #include _ArrayDelete ( ByRef $aArray, $vRange ) < Parameters~ $aArray ------- Array to modify $vRange ------- Element(s) to delete - either a single index, a range string or a 1D array with a count in the [0] element (see example for details) Return Value~ Success ------- the new size of the array (see remarks) Failure ------- -1 and sets the @error flag to non-zero. @error: 1 - $aArray is not an array 2 - $aArray is not a 1D or 2D array 3 - $vRange is not a valid range string 4 - $vRange is not a 1D array or has only 1 element 5 - $vRange content is outside array bounds Remarks~ $vRange ------- can be a string containing the rows which are to be deleted. It can be a single number or a range denoted by the first and last lines separated by a hyphen (-) - multiple items are separated by a semi-colon (;). $vRange can also be a 1D array listing all rows to be deleted with the count in the [0] element]. In either case, the rows need not be in ascending order and can be duplicated. Related~ |_ArrayAdd|, |_ArrayInsert| Example~ > #include Local $aArray[5] = [0, 1, 2, 3, 4] _ArrayDisplay($aArray, "Original") _ArrayDelete($aArray, 2) _ArrayDisplay($aArray, "Element 2 deleted") Local $aArray_Base[25][4] For $i = 0 To 24 For $j = 0 To 3 $aArray_Base[$i][$j] = $i & "-" & $j Next Next ; Single row $aArray = $aArray_Base _ArrayDisplay($aArray, "BEFORE deletion") _ArrayDelete($aArray, 7) _ArrayDisplay($aArray, "SINGLE ROW deleted") ; Range string $aArray = $aArray_Base Local $sRange = "0;11-15;24" _ArrayDisplay($aArray, "BEFORE deletion") _ArrayDelete($aArray, $sRange) ConsoleWrite(" " & @error & @CRLF) _ArrayDisplay($aArray, "RANGE STRING deleted") ; 1D array $aArray = $aArray_Base Local $aDel[4] = [3, 5, 11, 13] _ArrayDisplay($aArray, "BEFORE deletion") _ArrayDelete($aArray, $aDel) _ArrayDisplay($aArray, "RANGE ARRAY deleted") < -------------------------------------------------------------------------------- *_ArrayDisplay* +---------------+~ | _ArrayDisplay |~ +---------------+~ Displays a 1D or 2D array in a ListView > #include _ArrayDisplay ( Const ByRef $aArray [, $sTitle = "ArrayDisplay" [, $sArrayRange = "" [, $iFlags = 0 [, $vUser_Separator = Default [, $sHeader = Default [, $iMax_ColWidth = Default [, $iAlt_Color = Default [, $hUser_Function = ""]]]]]]]] ) < Parameters~ $aArray ------- Array to display $sTitle ------- [optional] Title for dialog. Default = "ArrayDisplay". $sArrayRange ------------ [optional] Range of rows/columns to display. Default ("") = entire array. (See below for details) $iFlags ------- [optional] Determine UDF options. Add required values together 0 = (default) Column text alignment - left 1 = Transposes the array 2 = Column text alignment - right 4 = Column text alignment - center 8 = Verbose - display MsgBox on error and splash screens during processing of large arrays 16 = Only 'Copy' buttons displayed 32 = No buttons displayed 64 = No 'Row' column displayed $vUser_Separator ---------------- [optional] Sets column display option when copying data to clipboard. Character = Delimiter between columns. Number = Fixed column width - longer items will be truncated. Default = Current separator character (usually "|"). $sHeader -------- [optional] Column names in header (string of names separated by current separator character - usually "|"). Default see Remarks. $iMax_Colwidth -------------- [optional] Max width to which a ListView column will expand to show content. Default = 350 pixels. $iAlt_Color ----------- [optional] ListView alternate rows set to defined color. Default = all rows ListView background color. $hUser_Function --------------- [optional] A variable assigned to the user defined function to run. Default = none. See remarks. Return Value~ Success ------- 1 Failure ------- 0 and @error flag set as follows: @error: 1 - $aArray is not an array 2 - $aArray has too many dimensions (only 1D and 2D supported) Remarks~ If the function is passed a non-array variable or an array of more than 2 dimensions the function returns an error and the script continues. If the "verbose" parameter is set in $iFlags a MsgBox will be displayed which offers the chance to exit the script immediately or to continue the script with the normal error return. Only 65525 rows of an array can be displayed - this is an AutoIt limitation on the total number of controls that can be displayed in a GUI - and an abitrary display limit of 250 columns has also been set. If the user tries to display an array larger than these limits an "*" is added to the truncated dimension value which will be displayed in red text. Note that using $iArrayRange to determine the elements to be displayed allows arrays larger than the display limits to be displayed in sections. The $sArrayRange parameter syntax is as follows:"7" Show rows 0-7 with all columns "7:" Show rows 7-end with all columns "|7" Show all rows with columns 0-7 "|7:" Show all rows with columns 7-end "7|7" Show rows 0-7 with columns 0-7 "5:7" Show rows 5-7 with all columns "|5:7" Show all rows with columns 5-7 "7|5:7" Show rows 0-7 with columns 5-7 "5:7|7" Show rows 5-7 with columns 0-7 "5:7|5:7" Show rows 5-7 with columns 5-7 Any column values are ignored for 1D arrays. $sHeader names (separated by the current separator character) will be used for as many columns as there are names. If no, or not enough, custom names are specified then the default header of "Row|Col0" for 1D arrays or "Row|Col0|Col1|...|Col n" for 2D is substituted. The 4 buttons at the bottom of the dialog have the following functions:Copy Data & Hdr/Row Copy the array or the selected row(s) to the clipboard adding full header and row identification. Copy Data Only Copy the array or the selected row(s) to the clipboard with no header or row identification. Run User Func Run the user-defined function passed in $sUser_Function. This function is entirely separate from the UDF and must be created and coded by the user to accept 2 (and only 2) parameters which will be provided by the UDF itself: the full array being displayed and a 1D array holding the selected rows indices with a count in the [0] element. These parameters can then be used inside the user function as required. The button is not displayed if no function is specified. Exit script Exit the script immediately. The $iFlags parameter enables some or all of these buttons to be hidden. If all buttons are displayed the array dimensions are displayed at lower left. They are in red text if any the following occur: row/column truncation, array transposition, or displaying only a range of elements - a tooltip displays the particular occurence(s). If the "verbose" parameter is set in $iFlags a splash dialog is displayed during initial processing when the array to display has more than 10000 elements. A similar dialog is displayed when the "Copy Data" buttons are used on a 10000+ element display - if this is likely to occur consideration should be given to using a "User Function" to store the array for later processing. An array element containing another array is displayed as {Array}. Example~ > #include #include Example() Func Example() ; Create 1D array to display Local $aArray_1D[5] = ["Item 0", "Item 1", "A longer Item 2 to show column expansion", "Item 3", "Item 4"] _ArrayDisplay($aArray_1D, "1D display") _ArrayDisplay($aArray_1D, "1D display transposed - 'Copy' buttons only", Default, 1 + 16) ; No buttons displayed ; Create 2D array to display Local $aArray_2D[75][255] For $i = 0 To UBound($aArray_2D) - 1 For $j = 0 To UBound($aArray_2D, 2) - 1 $aArray_2D[$i][$j] = "Item " & StringFormat("%02i", $i) & StringFormat("%02i", $j) Next Next _ArrayDisplay($aArray_2D, "2D display") ; Note columns truncated _ArrayDisplay($aArray_2D, "2D display transposed", Default, 1) ; Note all array elements displayed ReDim $aArray_2D[20][10] $aArray_2D[5][5] = "A longer item to show column expansion" _ArrayDisplay($aArray_2D, "Expanded column - custom titles - alternate line color - no buttons or 'Row' column", Default, 32 + 64, Default, "AA|BB|CC|DD|EE|FF|GG|HH|II|JJ", Default, 0xDDFFDD) ; Assign the user function to a variable to pass as a parameter Local $hUserFunction = _UserFunc $aArray_2D[5][5] = "Column alignment set to right" _ArrayDisplay($aArray_2D, "Range set - right align - copy column width - user function", "3:7|4:9", 2, 15, "AA|BB|CC|DD|EE|FF", Default, Default, $hUserFunction) _ArrayDisplay($aArray_2D, "Range set - right align - copy column width - transposed", "3:7|4:9", 3, 15, "AA|BB|CC|DD|EE|FF") ; Note no col names as transposed ; Create non-array variable to force error - MsgBox displayed as $iFlags set Local $vVar = 0 _ArrayDisplay($vVar, "MsgBox on Error", Default, 8) EndFunc ;==>Example ; Note that the user function MUST have TWO parameters even if you do not intend to use both of them Func _UserFunc($aArray_2D, $aSelected) ; But if a parameter is not used do this to prevent an Au3Check warning #forceref $aArray_2D _ArrayDisplay($aSelected, "Selected cols") EndFunc ;==>_UserFunc < -------------------------------------------------------------------------------- *_ArrayExtract* +---------------+~ | _ArrayExtract |~ +---------------+~ Extracts an array from the specified element(s) of a 1D or 2D array > #include _ArrayExtract ( Const ByRef $aArray [, $iStart_Row = -1 [, $iEnd_Row = -1 [, $iStart_Col = -1 [, $iEnd_Col = -1]]]] ) < Parameters~ $aArray ------- Array from which extraction should occur $iStart_Row ----------- [optional] First row of the extracted array $iEnd_Row --------- [optional] Last row of the extracted array $iStart_Col [optional] First column of the extracted array (2D only) $iEnd_Col [optional] Last column of the extracted array (2D only) Return Value~ Success ------- 1 Failure ------- -1 and sets the @error flag to non-zero. @error: 1 - $aArray is not an array 2 - $aArray is not a 1D or 2D array 3 - $iStart_Row or $iEnd_Row outside array bounds 4 - $iStart_Row greater then $iEnd_Row 5 - $iStart_Col or $iEnd_Col outside array bounds 6 - $iStart_Col greater then $iEnd_Col Related~ |_ArrayAdd|, |_ArrayInsert| Example~ > #include Local $aArray[4][4] For $i = 0 To 3 For $j = 0 To 3 $aArray[$i][$j] = $i & $j Next Next _ArrayDisplay($aArray, "Original") Local $aExtract = _ArrayExtract($aArray, 1, 2, 2, 3) _ArrayDisplay($aExtract, "Row 1-2 cols 2-3") < -------------------------------------------------------------------------------- *_ArrayFindAll* +---------------+~ | _ArrayFindAll |~ +---------------+~ Find the indices of all ocurrences of a search query between two points in a 1D or 2D array using _ArraySearch() > #include _ArrayFindAll ( Const ByRef $aArray, $vValue [, $iStart = 0 [, $iEnd = 0 [, $iCase = 0 [, $iCompare = 0 [, $iSubItem = 0 [, $bRow = False]]]]]] ) < Parameters~ $aArray ------- The array to search $vValue ------- What to search $aArray for $iStart ------- [optional] Index of array to start search $iEnd ----- [optional] Index of array to end search $iCase ------ [optional] If set to 1, search is case sensitive $iCompare --------- [optional] 0 Casting of variables to the same type (default), "string" = 0, "" = 0 or "0" = 0 match (If $iCase = 0) 1 executes a partial search 2 comparison match if variables have same type and same value 3 compares using a regular expression pattern provided as $vValue $iSubItem --------- [optional] Sub-index to search on in 2D arrays $bRow ----- [optional] If True then $iSubItem sets the row to search - False (default) searches columns Return Value~ Success ------- an array of all index numbers in array containing $vValue. Failure ------- sets the @error flag to non-zero (see _ArraySearch() description for @error). Remarks~ The values of $iCompare can not be combined together. Related~ |_ArrayBinarySearch|, |_ArraySearch| Example~ > #include Local $aArray[5] = [0, 1, 2, 1, 0] _ArrayDisplay($aArray, "1D array") Local $aiResult = _ArrayFindAll($aArray, 0) _ArrayDisplay($aiResult, "Found") Local $aArray[5][5] = [[0, 1, 2, 1, 0], _ [4, 5, 5, 4, 2], _ [4, 1, 3, 1, 3], _ [0, 3, 2, 1, 0], _ [1, 5, 5, 4, 1]] _ArrayDisplay($aArray, "2D array") Local $aResult = _ArrayFindAll($aArray, 0, Default, Default, Default, Default, 4) _ArrayDisplay($aResult, "Found in Column 4") $aResult = _ArrayFindAll($aArray, 1, Default, Default, Default, Default, 2, True) _ArrayDisplay($aResult, "Found in Row 2") < -------------------------------------------------------------------------------- *_ArrayInsert* +--------------+~ | _ArrayInsert |~ +--------------+~ Insert a new value at the specified position of a 1D or 2D array > #include _ArrayInsert ( ByRef $aArray, $vRange [, $vValue = "" [, $iStart = 0 [, $sDelim_Item = "|" [, $sDelim_Row = @CRLF [, $iForce = $ARRAYFILL_FORCE_DEFAULT]]]]] ) < Parameters~ $aArray ------- Array to modify $vRange ------- Position(s) at which to insert item(s) - see Remarks for format $vValue ------- [optional] Value(s) to add - can be a single variable, a delimited string or a 1D array $iStart ------- [optional] Column in which insert is to begin (2D array only) $sDelim_Item ------------ [optional] Delimiter used if a string is to be split into items $sDelim_Row ----------- [optional] Delimiter used if a string is to be split into rows (2D only) $iForce ------- [optional] Maintains default behaviour, $ARRAYFILL_FORCE_DEFAULT (0) Forces $vValue addition as a single item, $ARRAYFILL_FORCE_SINGLEITEM (1) Or forces datatype for all added items $ARRAYFILL_FORCE_INT (2) $ARRAYFILL_FORCE_NUMBER (3) $ARRAYFILL_FORCE_PTR (4) $ARRAYFILL_FORCE_HWND (5) $ARRAYFILL_FORCE_STRING (6) See Remarks for more details Return Value~ Success ------- the new size of the array. Failure ------- 0 and sets the @error flag to non-zero. @error: 1 - $aArray is not an array 2 - $aArray is not a 1D or 2D array 3 - $vRange incorrectly formatted (incorrect character or unordered) 4 - $vRange is not a 1D array or has only 1 element 5 - $vRange limits outside array bounds 6 - $iStart outside array bounds (2D only) 7 - $vValue not 2D array (2D only) 8 - $vValue has too many columns to fit into $aArray Remarks~ $vRange can be a string containing the rows above which a row is to to be inserted. It can be a single number or a range denoted by the first and last lines separated by a hyphen (-) - multiple items are separated by a semi-colon (;). $vRange can also be a 1D array containing the rows above which a row is to to be inserted with the count in the [0] element]. In either case, the rows must be in ascending order but can be duplicated. If $vValue is a delimited string all items are inserted into the array as strings. This can be over-ridden by using the $hDataType parameter which forces the items into the required datatype. Note that all items in the delimited string are converted - if the items are of different datatypes then they must be passed as an array so that their specific datatype is conserved. Insertion mode depends on $vValue type, but using $iForce can affect this. Default behaviour is as follows: 1D arrays: Single item - inserts 1 element containing $vValue $sDelim_Item delimited string - matches insertion lines to items in the string 0-based 1D array - matches insertion lines to elements in the array 2D arrays: Single item - inserts 1 row containing $vValue in the first column $sDelim_Item delimited string - inserts 1 row at first insertion line, columns filled if enough items $sDelim_Row delimited string - matches insertion lines to items in the string, only 1 column filled Double-delimited string - matches insertion lines to string split on $sDelim_Row, columns to string split on $sDelim_Item 0-based 2D array - matches insertion lines to rows in the array, columns to columns in the array An empty string ("") is added if there are insufficient items specified in $vValue. Excess items are ignored. Setting the $iForce parameter can change the default insertion behaviour or amend the datatype for added items. It can be set as follows: - $ARRAYFILL_FORCE_DEFAULT (default): - Items are split as described above. Single items and array elements retain their datatypes - delimited strings are added as strings. - $ARRAYFILL_FORCE_SINGLEITEM: - If $aArray is 1D, $vValue is inserted as a single element. - if $aArray is 2D the parameter is ignored. - $ARRAYFILL_FORCE_INT, $ARRAYFILL_FORCE_NUMBER, $ARRAYFILL_FORCE_PTR, $ARRAYFILL_FORCE_HWND, $ARRAYFILL_FORCE_STRING - If $vValue is a single item, it is forced into the defined datatype - by default it would retain its existing datatype. - If $vValue is a delimited string, all items are forced into the specified datatype - by default they would be inserted into the array as strings. If different datatypes are required for the items they must be passed as an array. - If $vValue is an array, the parameter is ignored and the array elements are inserted retaining their existing datatypes. If $iForce is set to any other value it is ignored. Related~ |_ArrayAdd|, |_ArrayDelete|, |_ArrayPop|, |_ArrayPush| Example~ Example 1 > #include Local $aArray_Base[10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] _ArrayDisplay($aArray_Base, "1D - Original") ; Insert single item Local $aArray = $aArray_Base _ArrayInsert($aArray, 2, "Insert above 2") _ArrayDisplay($aArray, "1D - Single item") ; Insert delimited string using range array $aArray = $aArray_Base Local $aRange[4] = [3, 3, 5, 9] Local $sFill = "Insert above 3|Insert above 5|Insert above 9" _ArrayInsert($aArray, $aRange, $sFill) _ArrayDisplay($aArray, "1D - Delim String") ; Insert 1D array using range string $aArray = $aArray_Base Local $aFill[4] = ["Insert above 2", "Insert above 6.1", "Insert above 6.2", "Insert above 7"] _ArrayInsert($aArray, "2;6;6;7", $aFill) _ArrayDisplay($aArray, "1D - 1D array") ; Insert 1D array as single item $aArray = $aArray_Base Local $aFill[4] = ["Insert 0", "Insert 1", "Insert 2", "Insert 3"] _ArrayInsert($aArray, "2", $aFill, Default, Default, Default, $ARRAYFILL_FORCE_SINGLEITEM) _ArrayDisplay($aArray, "1D - Single Item") _ArrayDisplay(($aArray)[2], "Internal array") Example 2 > #include Local $aArray_Base[10][3] For $i = 0 To 9 For $j = 0 To 2 $aArray_Base[$i][$j] = $i & " - " & $j Next Next _ArrayDisplay($aArray_Base, "2D - Original") ; Insert single item Local $aArray = $aArray_Base _ArrayInsert($aArray, 7, "Insert above 7-0") _ArrayDisplay($aArray, "2D - Single item") ; Insert single item in defined column $aArray = $aArray_Base _ArrayInsert($aArray, 3, "Insert above 3-1", 1) _ArrayDisplay($aArray, "2D - Defined column") ; Insert item delimited string - inserted as 1 row - other rows filled with "" $aArray = $aArray_Base Local $sFill = "Above 3-0|Above 3-1|Above 3-2" _ArrayInsert($aArray, "3;5;9", $sFill) _ArrayDisplay($aArray, "2D - Item delim string") ; Insert row delimited string using range array - inserted as 3 rows, other cols filled with "" $aArray = $aArray_Base Local $aRange[4] = [3, 3, 5, 9] $sFill = "Above 3-2" & @CRLF & "Above 5-2" & @CRLF & "Above 9-2" _ArrayInsert($aArray, $aRange, $sFill, 2) ; Insert in column 2 _ArrayDisplay($aArray, "2D - Item delim string") ; Insert item as row delimited string - inserted as 4 rows $aArray = $aArray_Base $sFill = "Above 3-0|3-1|3-2" & @CRLF & "Above 5a|5-1a|5-2a" & @CRLF & "Above 5b|5-1b|5-2b" & @CRLF & "Above 9|9-1|9-2" _ArrayInsert($aArray, "3;5;5;9", $sFill) _ArrayDisplay($aArray, "2D - Item & row delim string") ; Insert 2D array $aArray = $aArray_Base Local $aFill_1D[3][3] = [["Above 2", "2-1", "2-2"], ["Above 3", "3-1", "3-2"], ["Above 4", "4-1", "4-2"]] _ArrayInsert($aArray, "2-4", $aFill_1D) _ArrayDisplay($aArray, "2D - 2D Array") < Example 3 > #include #include Local $aArray_Base[2][2] = [["Org Item 0 - 0", "Org Item 0 - 1"], ["Org Item 1 - 0", "Org Item 1 - 1"]] Local $aArray Local $sFill = 1 & @CRLF & 2 ; Note added as number datatype here MsgBox($MB_SYSTEMMODAL, "Delimited string to add", $sFill) ; Add items by delimited string $aArray = $aArray_Base _ArrayInsert($aArray, "0;1", $sFill) _ArrayDisplay($aArray, "Converted to string") ; But converted to string datatype here MsgBox($MB_SYSTEMMODAL, "Result", "Data:" & @TAB & $aArray[2][0] & @CRLF & "Datatype:" & @TAB & VarGetType($aArray[2][0])) ; Add items by delimited string $aArray = $aArray_Base ; Now force datatype to be retained Local $hDataType = Number _ArrayInsert($aArray, "0;1", $sFill, Default, Default, Default, $ARRAYFILL_FORCE_NUMBER) _ArrayDisplay($aArray, "Forced to number") ; And datatype is retained MsgBox($MB_SYSTEMMODAL, "Result", "Data:" & @TAB & $aArray[2][0] & @CRLF & "Datatype:" & @TAB & VarGetType($aArray[2][0])) < -------------------------------------------------------------------------------- *_ArrayMax* +-----------+~ | _ArrayMax |~ +-----------+~ Returns the highest value held in a 1D or 2D array > #include _ArrayMax ( Const ByRef $aArray [, $iCompNumeric = 0 [, $iStart = -1 [, $iEnd = -1 [, $iSubItem = 0]]]] ) < Parameters~ $aArray ------- Array to search $iCompNumeric ------------- [optional] Comparison method: 0 - compare alphanumerically 1 - compare numerically $iStart ------- [optional] Index of array to start search $iEnd ----- [optional] Index of array to end search $iSubItem --------- [optional] Column of array to search Return Value~ Success ------- the maximum value in the array. Failure ------- sets the @error flag to non-zero (see _ArrayMaxIndex() description for @error). Related~ |_ArrayMaxIndex|, |_ArrayMin|, |_ArrayMinIndex|, |_ArrayUnique| Example~ > #include #include Local $aArray = StringSplit("4,2,06,8,12,5", ",") MsgBox($MB_SYSTEMMODAL, 'Max String value', _ArrayMax($aArray, 0, 1)) MsgBox($MB_SYSTEMMODAL, 'Max Numeric value', _ArrayMax($aArray, 1, 1)) Local $aArray[4][4] For $i = 0 To 3 For $j = 0 To 3 $aArray[$i][$j] = Random(0, 99, 1) Next Next _ArrayDisplay($aArray, "2D Array") MsgBox($MB_SYSTEMMODAL, 'Max Numeric value in column 2', _ArrayMax($aArray, 1, 0, 0, 2)) < -------------------------------------------------------------------------------- *_ArrayMaxIndex* +----------------+~ | _ArrayMaxIndex |~ +----------------+~ Returns the index where the highest value occurs in a 1D or 2D array > #include _ArrayMaxIndex ( Const ByRef $aArray [, $iCompNumeric = 0 [, $iStart = -1 [, $iEnd = -1 [, $iSubItem = 0]]]] ) < Parameters~ $aArray ------- Array to search $iCompNumeric ------------- [optional] Comparison method: 0 - compare alphanumerically 1 - compare numerically $iStart ------- [optional] Index of array to start search $iEnd ----- [optional] Index of array to end search $iSubItem ---------- [optional] Column of array to search Return Value~ Success ------- the index of the maximum value in the array. Failure ------- -1 and sets the @error flag to non-zero. @error: 1 - $aArray is not an array or is empty 2 - $aArray is not a 1D or 2D array 3 - $iStart or $iEnd outside array bounds 4 - $iStart is greater than $iEnd 5 - $aArray is empty 6 - $iSubItem outside array bounds Related~ |_ArrayMax|, |_ArrayMin|, |_ArrayMinIndex| Example~ > #include #include Local $aArray = StringSplit("4,2,06,8,12,5", ",") MsgBox($MB_SYSTEMMODAL, 'Max Index String value', _ArrayMaxIndex($aArray, 0, 1)) MsgBox($MB_SYSTEMMODAL, 'Max Index Numeric value', _ArrayMaxIndex($aArray, 1, 1)) Local $aArray[4][4] For $i = 0 To 3 For $j = 0 To 3 $aArray[$i][$j] = Random(0, 99, 1) Next Next _ArrayDisplay($aArray, "2D Array") MsgBox($MB_SYSTEMMODAL, 'Max Index Numeric value in column 2', _ArrayMaxIndex($aArray, 1, 0, 0, 2)) < -------------------------------------------------------------------------------- *_ArrayMin* +-----------+~ | _ArrayMin |~ +-----------+~ Returns the lowest value held in a 1D or 2D array > #include _ArrayMin ( Const ByRef $aArray [, $iCompNumeric = 0 [, $iStart = -1 [, $iEnd = -1 [, $iSubItem = 0]]]] ) < Parameters~ $aArray ------- Array to search $iCompNumeric ------------- [optional] Comparison method: 0 - compare alphanumerically 1 - compare numerically $iStart ------- [optional] Index of array to start search $iEnd ----- [optional] Index of array to end search $iSubItem --------- [optional] Column of array to search Return Value~ Success ------- the minimum value in the array. Failure ------- sets the @error flag to non-zero (see _ArrayMinIndex() description for @error). Related~ |_ArrayMax|, |_ArrayMaxIndex|, |_ArrayMinIndex|, |_ArrayUnique| Example~ > #include #include Local $aArray = StringSplit("4,2,06,8,12,5", ",") MsgBox($MB_SYSTEMMODAL, 'Min String value', _ArrayMin($aArray, 0, 1)) MsgBox($MB_SYSTEMMODAL, 'Min Numeric value', _ArrayMin($aArray, 1, 1)) Local $aArray[4][4] For $i = 0 To 3 For $j = 0 To 3 $aArray[$i][$j] = Random(0, 99, 1) Next Next _ArrayDisplay($aArray, "2D Array") MsgBox($MB_SYSTEMMODAL, 'Min Numeric value in column 2', _ArrayMin($aArray, 1, 0, 0, 2)) < -------------------------------------------------------------------------------- *_ArrayMinIndex* +----------------+~ | _ArrayMinIndex |~ +----------------+~ Returns the index where the lowest value occurs in a 1D or 2D array > #include _ArrayMinIndex ( Const ByRef $aArray [, $iCompNumeric = 0 [, $iStart = -1 [, $iEnd = -1 [, $iSubItem = 0]]]] ) < Parameters~ $aArray ------- Array to search $iCompNumeric ------------- [optional] Comparison method: 0 - compare alphanumerically 1 - compare numerically $iStart ------- [optional] Index of array to start search $iEnd ----- [optional] Index of array to end search $iSubItem --------- [optional] Column of array to search Return Value~ Success ------- the index of the minimum value in the array. Failure ------- -1 and sets the @error flag to non-zero. @error: 1 - $aArray is not an array or is empty 2 - $aArray is not a 1D or 2D array 3 - $iStart or $iEnd outside array bounds 4 - $iStart is greater than $iEnd 5 - $aArray is empty 6 - $iSubItem outside array bounds Related~ |_ArrayMax|, |_ArrayMaxIndex|, |_ArrayMin| Example~ > #include #include Local $aArray = StringSplit("4,2,06,8,12,5", ",") MsgBox($MB_SYSTEMMODAL, 'Min Index String value', _ArrayMinIndex($aArray, 0, 1)) MsgBox($MB_SYSTEMMODAL, 'Min Index Numeric value', _ArrayMinIndex($aArray, 1, 1)) Local $aArray[4][4] For $i = 0 To 3 For $j = 0 To 3 $aArray[$i][$j] = Random(0, 99, 1) Next Next _ArrayDisplay($aArray, "2D Array") MsgBox($MB_SYSTEMMODAL, 'Min Index Numeric value in column 2', _ArrayMinIndex($aArray, 1, 0, 0, 2)) < -------------------------------------------------------------------------------- *_ArrayPermute* +---------------+~ | _ArrayPermute |~ +---------------+~ Returns an array of the Permutations of all Elements in a 1D array > #include _ArrayPermute ( ByRef $aArray [, $sDelimiter = ""] ) < Parameters~ $aArray ------- The Array to get Permutations $sDelimiter ----------- [optional] String result separator, default is "" for none Return Value~ Success ------- an array of Permutations. $aArray[0] contains the number of strings returned. The remaining elements ($aArray[1], $aArray[2] ... $aArray[n]) contain the Permutations. Failure ------- sets the @error flag to non-zero. @error: 1 - The Input Must be an Array 2 - $aArray is not a 1 dimensional array Remarks~ The input array must be 0-based, i.e. no counter in $aArray[0]. Based on the algorithm by Alexander Bogomolny (http://www.bearcave.com/random_hacks/permute.html). Related~ |_ArrayCombinations| Example~ > ; Declare a 1-dimensional array, return an Array of permutations #include Local $aArray[4] = [1, 2, 3, 4] Local $aNewArray = _ArrayPermute($aArray, ",") ;Using Default Parameters _ArrayDisplay($aNewArray, "Array Permuted") < -------------------------------------------------------------------------------- *_ArrayPop* +-----------+~ | _ArrayPop |~ +-----------+~ Returns the last element of an array, deleting that element from the array at the same time > #include _ArrayPop ( ByRef $aArray ) < Parameters~ $aArray ------- Array to modify Return Value~ Success ------- the last element of the array (see remarks). Failure ------- sets the @error flag to non-zero. @error: 1 - The Input Must be an array 2 - $aArray is not a 1D array 3 - $aArray is empty Remarks~ If $aArray has one element left, it will be set to "" after _ArrayPop() is used on it. Related~ |_ArrayAdd|, |_ArrayDelete|, |_ArrayInsert|, |_ArrayPush| Example~ > #include #include Local $avArray[10] $avArray[0] = "JPM" $avArray[1] = "Holger" $avArray[2] = "Jon" $avArray[3] = "Larry" $avArray[4] = "Jeremy" $avArray[5] = "Valik" $avArray[6] = "Cyberslug" $avArray[7] = "Nutster" $avArray[8] = "JdeB" $avArray[9] = "Tylo" _ArrayDisplay($avArray, "$avArray BEFORE _ArrayPop()") While UBound($avArray) MsgBox($MB_SYSTEMMODAL, '_ArrayPop() return value', _ArrayPop($avArray)) _ArrayDisplay($avArray, "$avArray AFTER _ArrayPop()") WEnd < -------------------------------------------------------------------------------- *_ArrayPush* +------------+~ | _ArrayPush |~ +-------------+~ Add new values without increasing array size by inserting at the end the new value and deleting the first one or vice versa > #include _ArrayPush ( ByRef $aArray, $vValue [, $iDirection = 0] ) < Parameters~ $aArray ------- Array to modify $vValue ------- Value(s) to add (can be in an array) $iDirection ----------- [optional] Direction to push existing array elements: 0 = Slide left (adding at the end) 1 = Slide right (adding at the start) Return Value~ Success ------- 1. Failure ------- 0 and sets the @error flag to non-zero. @error: 1 - $aArray is not an array 2 - $vValue is an array larger than $aArray (so it can't fit) 3 - $aArray is not a 1D array Remarks~ This function is used for continuous updates of data in array, where in other cases a vast size of array would be created. It keeps all values inside the array (something like History), minus the first one or the last one depending on direction chosen. It is similar to the push command in assembly. Related~ |_ArrayAdd|, |_ArrayConcatenate|, |_ArrayDelete|, |_ArrayInsert|, |_ArrayPop| Example~ > #include Local $avArrayTarget[9] = [1, 2, 3, 4, 5, 6, 7, 8, 9] Local $avArraySource[2] = [100, 200] _ArrayDisplay($avArrayTarget, "$avArrayTarget BEFORE _ArrayPush()") _ArrayPush($avArrayTarget, $avArraySource) _ArrayDisplay($avArrayTarget, "$avArrayTarget AFTER _ArrayPush() array to end") _ArrayPush($avArrayTarget, $avArraySource, 1) _ArrayDisplay($avArrayTarget, "$avArrayTarget AFTER _ArrayPush() array to beginning") _ArrayPush($avArrayTarget, "Hello world!", 1) _ArrayDisplay($avArrayTarget, "$avArrayTarget AFTER _ArrayPush() string to beginning") < -------------------------------------------------------------------------------- *_ArrayReverse* +---------------+~ | _ArrayReverse |~ +---------------+~ Takes the given array and reverses the order in which the elements appear in a 1D array > #include _ArrayReverse ( ByRef $aArray [, $iStart = 0 [, $iEnd = 0]] ) < Parameters~ $aArray ------- Array to modify $iStart ------- [optional] Index of array to start modifying at $iEnd ----- [optional] Index of array to stop modifying at Return Value~ Success ------- 1. Failure ------- 0 and sets the @error flag to non-zero. @error: 1 - $aArray is not an array 2 - $iStart is greater than $iEnd 3 - $aArray is not a 1D array 4 - $aArray is empty Related~ |_ArraySwap| Example~ > #include Local $avArray[10] = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] _ArrayDisplay($avArray, "$avArray BEFORE _ArrayReverse()") _ArrayReverse($avArray) _ArrayDisplay($avArray, "$avArray AFTER _ArrayReverse()") _ArrayReverse($avArray, 3, 6) _ArrayDisplay($avArray, "$avArray AFTER _ArrayReverse() from index 3 to 6") < -------------------------------------------------------------------------------- *_ArraySearch* +--------------+~ | _ArraySearch |~ +--------------+~ Finds an entry within a 1D or 2D array. Similar to _ArrayBinarySearch(), except that the array does not need to be sorted > #include _ArraySearch ( Const ByRef $aArray, $vValue [, $iStart = 0 [, $iEnd = 0 [, $iCase = 0 [, $iCompare = 0 [, $iForward = 1 [, $iSubItem = -1 [, $bRow = False]]]]]]] ) < Parameters~ $aArray ------- The array to search $vValue ------- What to search $aArray for $iStart ------- [optional] Index of array to start searching at $iEnd ----- [optional] Index of array to stop searching at $iCase ------ [optional] If set to 1, search is case sensitive $iCompare --------- [optional] 0 Casting of variables to the same type (default), "string" = 0, "" = 0 or "0" = 0 match (If $iCase = 0) 1 executes a partial search 2 comparison match if variables have same type and same value 3 compares using a regular expression pattern provided as $vValue $iForward --------- [optional] If set to 0, searches the array from end to beginning (instead of beginning to end) $iSubItem --------- [optional] Sub-index to search on in 2D arrays $bRow ----- [optional] If True then $iSubItem sets the row to search - False (default) searches columns Return Value~ Success ------- the index that $vValue was found at. Failure ------- -1 and sets the @error flag to non-zero. @error: 1 - $aArray is not an array 2 - $aArray is not a 1D or 2D array 3 - $aArray is empty 4 - $iStart is greater than $iEnd 5 - Array not 2D and $bRow set True 6 - $vValue was not found in array Remarks~ This function is likely to be slower than _ArrayBinarySearch() but is useful when the array cannot be sorted before the search. The values of $iCompare can not be combined together. Related~ |_ArrayBinarySearch|, |_ArrayFindAll| Example~ Example 1 > #include #include Local $aArray[6][4] For $i = 0 To 5 For $j = 0 To 3 $aArray[$i][$j] = "#" & $i & $j Next Next _ArrayDisplay($aArray, "Looking for '#32'", Default, 8) ; Search by column (looking in col 2) Local $iIndex = _ArraySearch($aArray, "#32", 0, 0, 0, 0, 1, 2) MsgBox($MB_SYSTEMMODAL, "Found '#32'", "Column 2 on Row " & $iIndex) ; Search by row (looking in row 3) $iIndex = _ArraySearch($aArray, "#32", 0, 0, 0, 0, 1, 3, True) MsgBox($MB_SYSTEMMODAL, "Found '#32'", "Row 3 in Col " & $iIndex) < Example 2 > ; using a 2D array #include #include Local $avArray[6][2] = [ _ ["String0", "SubString0"], _ ["String1", "SubString1"], _ ["String2", "SubString2"], _ ["String3", "SubString3"], _ ["String4", "SubString4"], _ ["String5", "SubString5"]] _ArrayDisplay($avArray, "$avArray") Local $sSearch = InputBox("_ArraySearch() demo", "String to find?") If @error Then Exit Local $sColumn = InputBox("_ArraySearch() demo", "Column to search?") If @error Then Exit $sColumn = Int($sColumn) Local $iIndex = _ArraySearch($avArray, $sSearch, 0, 0, 0, 1, 1, $sColumn) If @error Then MsgBox($MB_SYSTEMMODAL, "Not Found", '"' & $sSearch & '" was not found on column ' & $sColumn & '.') Else MsgBox($MB_SYSTEMMODAL, "Found", '"' & $sSearch & '" was found in the array at position ' & $iIndex & ' on column ' & $sColumn & '.') EndIf < -------------------------------------------------------------------------------- *_ArrayShuffle* +---------------+~ | _ArrayShuffle |~ +---------------+~ Shuffles selected rows of 1D or 2D arrays - can be limited to a specific column in 2D arrays > #include _ArrayShuffle ( ByRef $aArray [, $iStart_Row = 0 [, $iEnd_Row = 0 [, $iCol = -1]]] ) < Parameters~ $aArray ------- Array to modify $iStart_Row ----------- [optional] Start row for shuffle - default first $iEnd_Row --------- [optional] End row for shuffle - default last $iCol ----- [optional] Specific column to shuffle (2D only) Return Value~ Success ------- 1. Failure ------- -1 and sets the @error flag to non-zero. @error: 1 - $aArray is not an array 2 - $aArray is not a 1D or 2D array 3 - $iStart or $iEnd outside array bounds 4 - $iStart greater than $iEnd 5 - $iColumn is outside array bounds Remarks~ The function uses the Fisher-Yates shuffle algorithm. Example~ > #include Local $aArray_Base[10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] _ArrayDisplay($aArray_Base, "1D - Original", Default, 8) Local $aArray = $aArray_Base _ArrayShuffle($aArray) _ArrayDisplay($aArray, "1D - Shuffled", Default, 8) $aArray = $aArray_Base _ArrayShuffle($aArray, 3, 8) _ArrayDisplay($aArray, "1D - Shuffled - 3-8 ", Default, 8) Local $aArray_Base[10][10] For $i = 0 To 9 For $j = 0 To 9 $aArray_Base[$i][$j] = $i Next Next _ArrayDisplay($aArray_Base, "2D - Original", Default, 8) $aArray = $aArray_Base _ArrayShuffle($aArray) _ArrayDisplay($aArray, "2D - Shuffled - All rows", Default, 8) $aArray = $aArray_Base _ArrayShuffle($aArray, 3, 8, 2) _ArrayDisplay($aArray, "2D - Shuffled - Col 2, 3-8", Default, 8) < -------------------------------------------------------------------------------- *_ArraySort* +------------+~ | _ArraySort |~ +------------+~ Sort a 1D or 2D array on a specific index using the dualpivotsort/quicksort/insertionsort algorithms > #include _ArraySort ( ByRef $aArray [, $iDescending = 0 [, $iStart = 0 [, $iEnd = 0 [, $iSubItem = 0 [, $iPivot = 0]]]]] ) < Parameters~ $aArray ------- Array to sort $iDescending ------------ [optional] If set to 1, sort in descending order $iStart ------- [optional] Index of array to start sorting (default 0 = first element or row) $iEnd ----- [optional] Index of array to stop sorting (default 0 = last element or row) $iSubItem --------- [optional] Sub-index to sort on in 2D arrays (default 0 = first column) $iPivot ------- [optional] Use pivot sort algorithm (default = quicksort) Return Value~ Success ------- 1. Failure ------- 0 and sets the @error flag to non-zero. @error: 1 - $aArray is not an array 2 - $iStart is greater than $iEnd 3 - $iSubItem is greater than subitem count 4 - $aArray is not a 1D or 2D array 5 - $aArray is empty 6 - $iPivot used with 2D array Remarks~ By default the UDF uses a QuickSort algorithm to sort the array. Setting the $iPivot parameter uses a DualPivotSort algorithm on 1D arrays - this can be significantly faster for large arrays (> 50 elements) - but sorting 2D arrays with this algorithm is very much slower and the UDF will return an error in this case. In both algorithms, relatively short arrays will be sorted using an insertion sort (< 15 elements with QuickSort; < 45 elements with Dual PivotSort). Note that there is no guarantee that a specific algorithm will be faster in a given case. Example~ Example 1 > ; using a 1D array #include Local $avArray[10] = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] _ArrayDisplay($avArray, "BEFORE _ArraySort()") _ArraySort($avArray) _ArrayDisplay($avArray, "AFTER QuickSort ascending") _ArraySort($avArray, 1) _ArrayDisplay($avArray, "AFTER QuickSort descending") _ArraySort($avArray, 0, 3, 6) _ArrayDisplay($avArray, "AFTER QuickSort from index 3 to 6") _ArraySort($avArray, 0, 0, 0, 0, 1) _ArrayDisplay($avArray, "AFTER DualPivotSort ascending") < Example 2 > ; using a 2D array #include Local $avArray[5][3] = [ _ [5, 20, 8], _ [4, 32, 7], _ [3, 16, 9], _ [2, 35, 0], _ [1, 19, 6]] _ArrayDisplay($avArray, "$avArray BEFORE _ArraySort()") _ArraySort($avArray, 0, 0, 0, 0) _ArrayDisplay($avArray, "$avArray AFTER _ArraySort() ascending column 0") _ArraySort($avArray, 0, 0, 0, 1) _ArrayDisplay($avArray, "$avArray AFTER _ArraySort() ascending column 1") _ArraySort($avArray, 0, 0, 0, 2) _ArrayDisplay($avArray, "$avArray AFTER _ArraySort() ascending column 2") < -------------------------------------------------------------------------------- *_ArraySwap* +------------+~ | _ArraySwap |~ +------------+~ Swaps elements of a 1D array and full or part rows/columns of a 2D array > #include _ArraySwap ( ByRef $aArray, $iIndex_1, $iIndex_2 [, $bCol = False [, $iStart = -1 [, $iEnd = -1]]] ) < Parameters~ $aArray ------- Array to modify $iIndex_1 --------- Index of first element (1D) or row/column (2D) to swap $iIndex_2 --------- Index of second element (1D) or row/column (2D) to swap $bCol ----- [optional] If True then for 2D array above parameters refer to rows; if False (default) above parameters refer to columns $iStart ------- [optional] Index in row/column to start swap (2D array only) $iEnd ----- [optional] Index in row/column to end swap (2D array only) Return Value~ Success ------- 1 Failure ------- -1 and sets the @error flag to non-zero. @error: 1 - $aArray is not an array 2 - $aArray is not a 1D or 2D array 3 - $iIndex_1 or $iIndex_2 is outside array bounds 4 - $iStart or $iEnd outside array bounds 5 - $iStart is greater than $iEnd Remarks~ Optional parameters ignored for 1D arrays. Related~ |_ArrayReverse| Example~ > #include Local $aArray[10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] _ArrayDisplay($aArray, "Original", Default, 8) _ArraySwap($aArray, 3, 7) _ArrayDisplay($aArray, "Swapped 3-7", Default, 8) Local $aArray_Base[10][10] For $i = 0 To 9 For $j = 0 To 9 $aArray_Base[$i][$j] = $i & " - " & $j Next Next _ArrayDisplay($aArray_Base, "Original", Default, 8) $aArray = $aArray_Base _ArraySwap($aArray, 3, 7) _ArrayDisplay($aArray, "Swapped Rows 3-7", Default, 8) $aArray = $aArray_Base _ArraySwap($aArray, 3, 7, False, 2, 5) _ArrayDisplay($aArray, "Swapped Rows 3-7, Cols 2-5", Default, 8) $aArray = $aArray_Base _ArraySwap($aArray, 3, 7, True) _ArrayDisplay($aArray, "Swapped Cols 3-7", Default, 8) $aArray = $aArray_Base _ArraySwap($aArray, 3, 7, True, 2, 5) _ArrayDisplay($aArray, "Swapped Cols 3-7, Rows 2-5", Default, 8) < -------------------------------------------------------------------------------- *_ArrayToClip* +--------------+~ | _ArrayToClip |~ +--------------+~ Sends the contents of a 1D or 2D array to the clipboard, each element separated by a specified delimiter > #include _ArrayToClip ( Const ByRef $aArray [, $sDelim_Col = "|" [, $iStart_Row = -1 [, $iEnd_Row = -1 [, $sDelim_Row = @CRLF [, $iStart_Col = -1 [, $iEnd_Col = -1]]]]]] ) < Parameters~ $aArray ------- Array to copy to clipboard $sDelim_Col ----------- [optional] Delimiter for elements of 1D array or columns of 2D array $iStart_Row ----------- [optional] Index of array row to start copy $iEnd_Row --------- [optional] Index of array row to stop copy $sDelim_Row ----------- [optional] Delimiter for rows of 2D array (2D only) $iStart_Col ----------- [optional] Index of array column to start copy (2D only) $iEnd_Col --------- [optional] Index of array column to stop copy (2D only) Return Value~ Success ------- 1. Failure ------- 0 and sets the @error flag to non-zero. @error: -1 - ClipPut() failed Other - See _ArrayToString() description for @error Related~ |_ArrayToString| Example~ > #include #include Local $aArray = StringSplit("A,B,C,D,E,F,G,H,I", ",") _ArrayDisplay($aArray, "1D Array") _ArrayToClip($aArray, " - ", Default, 1, 6) MsgBox($MB_SYSTEMMODAL, "_ArrayToClip() 1D Test", ClipGet()) Local $aArray[4][4] For $i = 0 To 3 For $j = 0 To 3 $aArray[$i][$j] = $i & $j Next Next _ArrayDisplay($aArray, "2D Array") _ArrayToClip($aArray, " :: ", Default, 1, 2, 1, 2) MsgBox($MB_SYSTEMMODAL, "_ArrayToClip() 2D Test", ClipGet()) < -------------------------------------------------------------------------------- *_ArrayToString* +----------------+~ | _ArrayToString |~ +----------------+~ Places the elements of a 1D or 2D array into a single string, separated by the specified delimiters > #include _ArrayToString ( Const ByRef $aArray [, $sDelim_Col = "|" [, $iStart_Row = -1 [, $iEnd_Row = -1 [, $sDelim_Row = @CRLF [, $iStart_Col = -1 [, $iEnd_Col = -1]]]]]] ) < Parameters~ $aArray ------- Array to convert to a string $sDelim_Col ----------- [optional] Delimiter for elements of 1D array or columns of 2D array $iStart_Row ----------- [optional] Index of array row to start copy $iEnd_Row --------- [optional] Index of array row to stop copy $sDelim_Row ----------- [optional] Delimiter for rows of 2D array (2D only) $iStart_Col ----------- [optional] Index of array column to start copy (2D only) $iEnd_Col --------- [optional] Index of array column to stop copy (2D only) Return Value~ Success ------- a string which combined selected elements separated by the delimiters. Failure ------- sets the @error flag to non-zero. @error: 1 - $aArray is not an array 2 - $aArray is not a 1D or 2D array 3 - $iStart_Row or $iEnd_Row outside array bounds 4 - $iStart_Row greater then $iEnd_Row 5 - $iStart_Col or $iEnd_Col outside array bounds 6 - $iStart_Col greater then $iEnd_Col Related~ |_ArrayToClip| Example~ > #include #include Local $aArray[20] For $i = 0 To 19 $aArray[$i] = $i Next _ArrayDisplay($aArray, "1D Array") MsgBox($MB_SYSTEMMODAL, "Items 1-7", _ArrayToString($aArray, @TAB, 1, 7)) Local $aArray[10][10] For $i = 0 To 9 For $j = 0 To 9 $aArray[$i][$j] = $i & "-" & $j Next Next _ArrayDisplay($aArray, "2D Array") MsgBox($MB_SYSTEMMODAL, "Rows 4-7, cols 2-5", _ArrayToString($aArray, " :: ", 4, 7, @CRLF, 2, 5)) < -------------------------------------------------------------------------------- *_ArrayTranspose* +-----------------+~ | _ArrayTranspose |~ +-----------------+~ Transposes a 1D or 2D array (swaps rows and columns) > #include _ArrayTranspose ( ByRef $aArray ) < Parameters~ $aArray ------- Array to modify Return Value~ Success ------- 1. Failure ------- 0 and sets the @error flag to non-zero. @error: 1 - $aArray is not a 1D or 2D array 2 - $aArray is not an array Related~ |_ArraySwap| Example~ > #include Local $aArray[3][2] = [[1, 2], [3, 4], [5, 6]] _ArrayDisplay($aArray, "Original") _ArrayTranspose($aArray) _ArrayDisplay($aArray, "Transposed") Local $aArray[5] = [1, 2, 3, 4, 5] _ArrayDisplay($aArray, "Original 1D") _ArrayTranspose($aArray) _ArrayDisplay($aArray, "Transposed to 2D") _ArrayTranspose($aArray) _ArrayDisplay($aArray, "Re-transposed to 1D") < -------------------------------------------------------------------------------- *_ArrayTrim* +------------+~ | _ArrayTrim |~ +------------+~ Trims a certain number of characters from all elements in a 1D or 2D array > #include _ArrayTrim ( ByRef $aArray, $iTrimNum [, $iDirection = 0 [, $iStart = 0 [, $iEnd = 0 [, $iSubItem = 0]]]] ) < Parameters~ $aArray ------- Array to modify $iTrimNum --------- Number of characters to remove $iDirection ----------- [optional] Direction to trim: 0 - trim left 1 - trim right $iStart ------- [optional] Index of array to start trim $iEnd ----- [optional] Index of array to stop trim $iSubItem --------- [optional] Column to trim Return Value~ Success ------- 1. Failure ------- 0 and sets the @error flag to non-zero. @error: 1 - $aArray is not an array 2 - $aArray is not an 1D or 2D array 3 - $iStart or $iEnd outside array bounds 4 - $iStart is greater than $iEnd 5 - $iSubItem outside array bounds Example~ > #include Local $aArray[5] = ["ab", "bc", "cd", "de", "ef"] _ArrayDisplay($aArray, "1D array") _ArrayTrim($aArray, 1, 1, 1, 3) _ArrayDisplay($aArray, "Trimmed right 1 char from items 1-3") Local $aArray[4][4], $iChr For $i = 0 To 3 For $j = 0 To 3 $iChr = Random(97, 121, 1) $aArray[$i][$j] = Chr($iChr) & Chr($iChr + 1) Next Next _ArrayDisplay($aArray, "2D array") _ArrayTrim($aArray, 1, 0, 1, 2, 3) _ArrayDisplay($aArray, "Trimmed left 1 char from col 2-3 in row 1-2") < -------------------------------------------------------------------------------- *_ArrayUnique* +--------------+~ | _ArrayUnique |~ +--------------+~ Returns the Elements from a column of a 1D or 2D array, removing all duplicates > #include _ArrayUnique ( Const ByRef $aArray [, $iColumn = 0 [, $iBase = 0 [, $iCase = 0 [, $iCount = $ARRAYUNIQUE_COUNT [, $iIntType = $ARRAYUNIQUE_AUTO]]]]] ) < Parameters~ $aArray ------- The Array to use $iColumn -------- [optional] 0-based column to be used - default 0. (2D only) $iBase ------ [optional] The array is 0-based or 1-based. Default 0 : 0-based. $iCase ------ [optional] Flag to indicate if the operations should be case sensitive. Default 0 : not case sensitive. $iCount ------- [optional] Flag to determine if [0] element holds the count of returned items (default) - see Remarks for details. $iIntType --------- [optional] Flag to change function algorithm - see Remarks for details. Return Value~ Success ------- a 1-dimensional array containing only the unique elements of that Column. Failure ------- sets the @error flag to non-zero. @error: 1 - $aArray is not an array or is an empty array. 2 - $aArray is not a 1D or 2D array 3 - Invalid $iBase or $iCase value 4 - Invalid $iCount value 5 - Invalid $iIntType value 6 - $iColumn ouside array bounds 7 - Mismatch of Int32 and Int64 items - requires $iIntType to be set Remarks~ Returns an array containing the unique elements. By default $iCount is set to $ARRAYUNIQUE_COUNT (1) and a count is placed in the [0] element. Setting $iCount to $ARRAYUNIQUE_NOCOUNT (0) returns a list without a count. The function can use a fast algorithm as long as the elements to be examined do not contain Int64 values (e.g. 64 bit integers, handles, pointers) - if these values are present then the function must use a slower algorithm. Setting the $iIntType parameter alters function behaviour as follows: $ARRAYUNIQUE_AUTO (0) (Default) : If first element not an integer runs fast algorithm - returns error if Int64 elements are found. : If first element is integer sets relevant FORCE32/64 value. $ARRAYUNIQUE_FORCE32 (1) : Forces all integers to Int32, runs fast algorithm - returns error if Int64 values are found. $ARRAYUNIQUE_FORCE64 (2) : Forces all integers to Int64, runs slow algorithm - returns error if Int32 values are found. $ARRAYUNIQUE_MATCH (3) : 0x00000123 and 0x0123 considered the same value, only first encountered returned - runs slow algorithm. $ARRAYUNIQUE_DISTINCT (4) : 0x00000123 and 0x0123 considered as distinct, both returned - runs slow algorithm. Using other than the default $ARRAYUNIQUE_AUTO setting is only required it is known or suspected that Int64 values will be examined. The requirement to use a slower algorithm when dealing with Int64 values is a limitation of the Scripting.Dictionary object used within the function, not of AutoIt itself. Related~ |_ArrayMax|, |_ArrayMin| Example~ Example 1 > #include Local $aArray[10] = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] ; Create a 1-dimensional array that contains duplicate values. _ArrayDisplay($aArray, "$aArray Initial") ; Display the current array. Local $aArrayUnique = _ArrayUnique($aArray) ; Use default parameters to create a unique array. _ArrayDisplay($aArrayUnique, "$aArray Unique") ; Display the unique array. < Example 2 > #include Local $aArray[6][2] = [[1, "A"], [2, "B"], [3, "C"], [1, "A"], [2, "B"], [3, "C"]] _ArrayDisplay($aArray, "2D array") ; Display the current array. Local $aArrayUnique = _ArrayUnique($aArray) ; Use default parameters to create a unique array of the first column. _ArrayDisplay($aArrayUnique, "$aArray first column") ; Display the unique array. $aArrayUnique = _ArrayUnique($aArray, 1) ; Create a unique array of the second column. _ArrayDisplay($aArrayUnique, "$aArray second column") ; Display the unique array. < -------------------------------------------------------------------------------- *#RequireAdmin* +---------------+~ | #RequireAdmin |~ +---------------+~ Specifies that the current script requires full administrator rights to run. Remarks~ This function was primarily aimed at allowing AutoIt scripts to work correctly with Windows User Account Control (UAC). For more details see AutoIt on Windows Vista. As this function launch a new process, some functions as ConsoleWrite() cannot be captured (SciTE will not display anything). In case system doesn't have elevation mechanism (e.g. disabled UAC) new process will run under the same user as the original. Related~ |IsAdmin| Example~ > #include #RequireAdmin If IsAdmin() Then MsgBox($MB_SYSTEMMODAL, "", "The script is running with admin rights.") < -------------------------------------------------------------------------------- *#include* +----------+~ | #include |~ +----------+~ Includes a file in the current script. > #include "[path\]filename" #include < Parameters~ filename --------- The filename of the current script to include. Path is optional. This must be a string--it cannot be a variable. If "..." is used, the filename is taken to be relative to the current script. If <...> is used the filename is taken to be relative to include library directory (usually C:\Program Files\AutoIt3\Include). The include library contains many pre-written user-functions for you to use! Remarks~ Other scripts can be included into an Autoit script using the #include command - these can be in either .au3 or .a3x format. The content of the included file is inserted into the script at the point of the #include command - in most cases this is the beginning of the script so that any variable or constant declarations within the included text are available to the rest of the script. If you include the same file containing a user defined function more than once you will get a "Duplicate function" error. When writing an include file that may be used in this way, make sure that the firstline contains #include-once to prevent that file from being included more than once. There is a special registry value that can be created at "HKEY_CURRENT_USER\Software\AutoIt v3\AutoIt" called "Include". It should be a REG_SZ (string) value. The contents of this value are a semi-colon delimited list of directories that should be searched for files when resolving #include's in addition to the standard locations. The search order used by AutoIt depends on which form of #include you use. The tables below show the order directories are searched using both forms. Using #include <>Standard library The path of the currently running interpreter with "\Include" appended is searched. User-defined libraries The registry value mentioned above is read and each directory is searched in the order they appear in. Script directory The directory of the currently executing script. Using #include "" (This is the reverse of #include <>).Script directory The directory of the currently executing script. User-defined libraries The registry value mentioned above is read and each directory is searched in the reverse order they appear in. Standard library The path of the currently running interpreter with "\Include" appended is searched. A note about using the /AutoIt3ExecuteScript option. Since the standard library is searched for in the current interpreter's directory, the standard library functions will not be found; that library will only be found when run through AutoIt3.exe. It's recommended that you compile a script to the .a3x format before attempting to run it with /AutoIt3ExecuteScript. Aut2Exe uses the same algorithm as AutoIt3.exe with the only difference being it looks for the Include sub-directory as being in a sibling directory to itself (..\Include). If Opt("TrayIconDebug",1) only 64 include files name can be displayed in the traytooltip. for the other no filename will be displayed. Related~ |#include-once| Example~ > #include "include-TIME.au3" MsgBox($MB_SYSTEMMODAL, "", "Example") #include Exit ; Running script.au3 will output two message boxes: ; one with 'Example', followed by one with the time. < -------------------------------------------------------------------------------- *#include-once* +---------------+~ | #include-once |~ +---------------+~ Specifies that the current file should only be included once. Remarks It is quite common to have the same "#include " line in several of the files included included in a script. If the same file were to be included several times, it is quite likely that this would generate a "Duplicate function" or "Cannot redeclare a Const" error. So when writing a script intended for use as an include file, add #include-once to prevent that file from being included more than once. Note that the #include-once line must be placed at the top of the script and before any other #include lines. It is not recommended to add a #include-once line to scripts which are not intended to be used as include files within other scripts. Related~ |#include| Example~ > #include-once when creating UDFs so the file isn't included multiple times ; if you call the same UDF in multiple files. #include-once #include ; Rename this file as IncludeFunc.au3 and place next to the main script. ; Then add #include "IncludeFunc.au3" at the top of the script. Func IncludeFunc() MsgBox($MB_SYSTEMMODAL, "", "This is an example of including a file.") EndFunc ;==>IncludeFunc < -------------------------------------------------------------------------------- *#NoTrayIcon* +-------------+~ | #NoTrayIcon |~ +-------------+~ Indicates that the AutoIt tray icon will not be shown when the script starts. Remarks~ It is possible to use Opt("TrayIconHide", 1) to remove the AutoIt tray icon but it will still be visible for a second when the script starts. Placing the #NoTrayIcon directive at the top of your script will stop the icon from being shown at startup. You may still turn the icon back on later in the script using Opt("TrayIconHide", 0) Related~ |TrayIconHide| (Option) Example~ > #NoTrayIcon #include Example() Func Example() ; Display a message box about the tray icon appearing once the OK button is selected. MsgBox($MB_SYSTEMMODAL, "", "The tray icon will display once OK is selected.") ; Display the tray icon. Opt("TrayIconHide", 0) ; Wait 5 seconds before closing the script. Sleep(5000) EndFunc ;==>Example < -------------------------------------------------------------------------------- *#OnAutoItStartRegister* +------------------------+~ | #OnAutoItStartRegister |~ +------------------------+~ Registers a function to be called when AutoIt starts. > #OnAutoItStartRegister "function" < Parameters~ function The name of the user function to call. Remarks~ The function cannot reference any variables defined in an #include. Related~ |OnAutoItExitRegister| Example~ > ; Register Example() and SomeFunc() to be called when AutoIt starts. #OnAutoItStartRegister "Example" #OnAutoItStartRegister "SomeFunc" Sleep(1000) Func Example() MsgBox(4096, "", "Function 'Example' is called first.") EndFunc ;==>Example Func SomeFunc() MsgBox(4096, "", "Function 'SomeFunc' is called second.") EndFunc ;==>SomeFunc < -------------------------------------------------------------------------------- *#comments-start* *#comments-end* +-----------------+~ | #comments-start |~ +-----------------+~ Specify that an entire section of script should be commented out. #comments-start ... ... #comments-end Remarks~ The #comments-start and #comments-end directives can be nested. You can also use the abbreviated keywords #cs and #ce. Additionally, the directives themselves can be commented out! Example~ > #include #comments-start MsgBox($MB_SYSTEMMODAL, "", "This won't display ") MsgBox($MB_SYSTEMMODAL, "", "nor will this.") #comments-end ; #cs MsgBox($MB_SYSTEMMODAL, "", "This will display if '#cs/#ce' are commented out.") ; #ce < -------------------------------------------------------------------------------- *RegWrite* +----------+~ | RegWrite |~ +----------+~ Creates a key or value in the registry. > RegWrite ( "keyname" [, "valuename", "type", value] ) < Parameters~ keyname ------- The registry key to write to. If no other parameters are specified this key will simply be created. valuename --------- [optional] The valuename to write to. type ----- [optional] Type of key to write: "REG_SZ", "REG_MULTI_SZ", "REG_EXPAND_SZ", "REG_DWORD", "REG_QWORD", or "REG_BINARY". value ----- [optional] The value to write. Return Value~ Success ------- 1. Failure ------- 0 and sets the @error flag to non-zero if error writing registry key or value. @error: 1 = unable to open requested key 2 = unable to open requested main key 3 = unable to remote connect to the registry -1 = unable to open requested value -2 = value type not supported Remarks~ A registry key must start with "HKEY_LOCAL_MACHINE" ("HKLM") or "HKEY_USERS" ("HKU") or "HKEY_CURRENT_USER" ("HKCU") or "HKEY_CLASSES_ROOT" ("HKCR") or "HKEY_CURRENT_CONFIG" ("HKCC"). When running on 64-bit Windows if you want to write a key or value specific to the 64-bit environment you have to suffix the HK... with 64 i.e. HKLM64. AutoIt supports registry keys of type REG_BINARY, REG_SZ, REG_MULTI_SZ, REG_EXPAND_SZ, REG_QWORD, and REG_DWORD. To access the (Default) value use "" (an empty string) for the valuename. When writing a REG_MULTI_SZ key you must separate each value with @LF. The value must NOT end with @LF unless you want an empty substring (see example). It is possible to access remote registries by using a keyname in the form "\\computername\keyname". To use this feature you must have the correct access rights. Related~ |RegDelete|, |RegEnumKey|, |RegEnumVal|, |RegRead| Example~ > ; Write a single REG_SZ value RegWrite("HKEY_CURRENT_USER\Software\Test", "TestKey", "REG_SZ", "Hello this is a test") ; Write the REG_MULTI_SZ value of "line1" and "line2" RegWrite("HKEY_CURRENT_USER\Software\Test", "TestKey1", "REG_MULTI_SZ", "line1" & @CRLF & "line2") ; Write the REG_MULTI_SZ value of "line1" RegWrite("HKEY_CURRENT_USER\Software\Test", "TestKey2", "REG_MULTI_SZ", "line1") ; always add and extra null string RegWrite("HKEY_CURRENT_USER\Software\Test", "TestKey3", "REG_MULTI_SZ", "line1" & @CRLF & "line2" & @CRLF) RegWrite("HKEY_CURRENT_USER\Software\Test", "TestKey4", "REG_MULTI_SZ", "line1" & @CRLF & @CRLF & "line2" & @CRLF) ; empty REG_MULTI_SZ RegWrite("HKEY_CURRENT_USER\Software\Test", "TestKey5", "REG_MULTI_SZ", "") ; create just the key RegWrite("HKEY_CURRENT_USER\Software\Test1") < -------------------------------------------------------------------------------- *RegDelete* +-----------+~ | RegDelete |~ +-----------+~ Deletes a key or value from the registry. > RegDelete ( "keyname" [, "valuename"] ) < Parameters~ keyname ------- The registry key to delete. valuename --------- [optional] The valuename to delete. Return Value~ Success ------- 1. Special: 0 if the key/value does not exist. Failure ------- 2 if error deleting key/value and sets the @error flag to non-zero. @error: 1 = unable to open requested key 2 = unable to open requested main key 3 = unable to remote connect to the registry -1 = unable to delete requested value -2 = unable to delete requested key/value Remarks~ A registry key must start with "HKEY_LOCAL_MACHINE" ("HKLM") or "HKEY_USERS" ("HKU") or "HKEY_CURRENT_USER" ("HKCU") or "HKEY_CLASSES_ROOT" ("HKCR") or "HKEY_CURRENT_CONFIG" ("HKCC"). When running on 64-bit Windows if you want to delete a key or value specific to the 64-bit environment you have to suffix the HK... with 64 i.e. HKLM64. To access the (Default) value use "" (an empty string) for the valuename. Deleting from the registry is potentially dangerous--please exercise caution! It is possible to access remote registries by using a keyname in the form "\\computername\keyname". To use this feature you must have the correct access rights. Related~ |RegEnumKey|, |RegEnumVal|, |RegRead|, |RegWrite| Example~ > RegDelete("HKEY_CURRENT_USER\Software\Test", "TestKey") RegWrite("HKEY_CURRENT_USER\Software\Test") RegWrite("HKEY_CURRENT_USER\Software\Test1") < -------------------------------------------------------------------------------- *RegEnumKey* +------------+~ | RegEnumKey |~ +------------+~ Reads the name of a subkey according to its instance. > RegEnumKey ( "keyname", instance ) < Parameters~ keyname ------- The registry key to read. instance -------- The 1-based key instance to retrieve Return Value~ Success ------- the requested subkey name. Failure ------- an empty string and sets the @error flag to non-zero. @error: 1 = unable to open requested key 2 = unable to open requested main key 3 = unable to remote connect to the registry -1 = unable to retrieve requested subkey (key instance out of range) Remarks~ A registry key must start with "HKEY_LOCAL_MACHINE" ("HKLM") or "HKEY_USERS" ("HKU") or "HKEY_CURRENT_USER" ("HKCU") or "HKEY_CLASSES_ROOT" ("HKCR") or "HKEY_CURRENT_CONFIG" ("HKCC"). When running on 64-bit Windows if you want to enum a key specific to the 64-bit environment you have to suffix the HK... with 64 i.e. HKLM64. Related~ |RegDelete|, |RegEnumVal|, |RegWrite| Example~ > #include Local $sSubKey = "" For $i = 1 To 10 $sSubKey = RegEnumKey("HKEY_LOCAL_MACHINE\SOFTWARE", $i) If @error Then ExitLoop MsgBox($MB_SYSTEMMODAL, "SubKey #" & $i & " under HKLM\SOFTWARE: ", $sSubKey) Next < -------------------------------------------------------------------------------- *RegEnumVal* +------------+~ | RegEnumVal |~ +------------+~ Reads the name of a value according to its instance. > RegEnumVal ( "keyname", instance ) < Parameters~ keyname ------- The registry key to read. instance -------- The 1-based value instance to retrieve Return Value~ Success ------- the requested registry value. @extended is set to the type of the value. Failure ------- sets the @error flag to non-zero. @error: 1 = unable to open requested key 2 = unable to open requested main key 3 = unable to remote connect to the registry -1 = unable to retrieve requested value name (value instance out of range) Remarks~ A registry key must start with "HKEY_LOCAL_MACHINE" ("HKLM") or "HKEY_USERS" ("HKU") or "HKEY_CURRENT_USER" ("HKCU") or "HKEY_CLASSES_ROOT" ("HKCR") or "HKEY_CURRENT_CONFIG" ("HKCC"). When running on 64-bit Windows if you want to enum a value specific to the 64-bit environment you have to suffix the HK... with 64 i.e. HKLM64. Related~ |RegDelete|, |RegEnumKey|, |RegWrite| Example~ > #include ; X64 running support Local $sWow64 = "" If @AutoItX64 Then $sWow64 = "\Wow6432Node" Local $sVar = "" For $i = 1 To 100 $sVar = RegEnumVal("HKEY_LOCAL_MACHINE\SOFTWARE" & $sWow64 & "\AutoIt v3\AutoIt", $i) If @error <> 0 Then ExitLoop MsgBox($MB_SYSTEMMODAL, "Value Name #" & $i & " under in AutoIt3 key", $sVar) Next < -------------------------------------------------------------------------------- *Dim__Global__Local__Const* +------------------------------+~ | Dim / Global / Local / Const |~ +------------------------------+~ Declare a variable, a constant, or create an array. Global | Local [Const] $variable [ = initializer ] Global | Local [Const] $aArray[subscript 1]...[subscript n] [ = initializer ] Parameters~ Const [optional] If present, the Const keyword creates a constant rather than a variable. $variable --------- The name of the variable/constant to declare. initializer The value that will be initially assigned to the variable. A Const must include the initializer. The initializer can be a function call. subscript The number of elements to create for the array dimension, indexed 0 to n-1. Remarks~ The Dim/Local/Global keywords perform similar functions: 1. Declare a variable before you use it (similar to VBScript) 2. Create an array Note: In AutoIt you can create a variable simply by assigning a value ($myvar = 0) but many people like to explicitly declare them. If AutoItSetOption("MustDeclareVars", 1) is active, then variables must be declared prior to use. You can also declare multiple variables on a single line: > Local $vVar_1, $vVar_2, $vVar_3 < And initialize the variables: > Local $vVar_1 = 10, $vVar_2 = "20", $vVar_3 = 30 < Creating constants can be done in a similar way: > Const $CONST_1 = 1, $CONST_2 = 2, $CONST_3 = 3 Global Const $PI = 3.14, $MEANING_OF_LIFE = 42 Local Const $iApples = 500 < Once created, you cannot change the value of a constant. Also, you cannot change an existing variable into a constant. To initialize an array, specify the values for each element inside square brackets, separated by commas. For multiple dimensions, nest the initializers. You can specify fewer elements in the initializer than declared, but not more. Function calls can also be placed in the initializers of an array. If the function call returns an array, then the one array element will contain that returned array. > Local $aArray_1[12] = [3, 7.5, "string"], $aArray_1[5] = [8, 4, 5, 9, 1] Local $aGrid[2][4] = [["Paul", "Jim", "Richard", "Louis"], [485.44, 160.68, 275.16, 320.00]] Global $aTest[5] = [3, 1, StringSplit("Abe|Jack|Bobby|Marty", "|"), Cos(0)] < The difference between Dim, Local and Global is the scope in which they are created: Dim = Local scope if the variable name doesn't already exist globally (in which case it reuses the global variable!) Global = Forces creation of the variable in the Global scope Local = Forces creation of the variable in the Local/Function scope You should use Local or Global, instead of Dim, to explicitly state which scope is desired for a variable/constant/array. When using variables, the local scope is checked first and then the global scope second. When creating arrays you are limited to up to 64 dimensions and/or a total of 16 million elements. A unique feature in AutoIt is the ability to copy arrays like this: > $mycopy = $myarray < In this case $mycopy will be an exact copy of $myarray and will have the same dimensions - no Dim statement is required to size the array first. If AutoItSetOption ( "MustDeclareVars", 1) is active then the variable $mycopy would still need to be declared first, but would not need to be sized. If the variable $mycopy was already an array or single value it will be erased before the copy takes place. To erase an array (maybe because it is a large global array and you want to free the memory), simply assign a single value to it: $aArray = 0 This will free the array and convert it back to the single value of 0. Declaring the same variable name again will erase all array values and reset the dimensions to the new definition. Declaring a variable with a simple value in the same scope will not change the value in the variable. If you declare a variable with the same name as a parameter, using Local inside a user function, an error will occur. Global can be used to assign to global variables inside a function, but if a local variable (or parameter) has the same name as a global variable, the local variable will be the only one used. It is recommended that local and global variables have distinct names. Related~ |AutoItSetOption|, |UBound|, |ReDim|, |Static| Example~ Example 1 > ; Example 1 - Declaring variables Local $i, $j = 23, $k Global $g_fPI = 3.14159, $g_iRADIUS Local $iDaysWorking = 5 ; Example 2 - Declaring arrays Global $g_aChessBoard[8][8] Local $aStates[2], $aWindowsStats[4] ; Example 3 - Declaring constant variables Const $iX1 = 11, $iY1 = 23, $iZ1 = 55 Global Const $PI = 3.14159, $E = 2.71828 Local Const $DAYS_WORKING = 5 < Example 2~ > #AutoIt3Wrapper_Au3Check_Parameters=-q -d -w- 3 -w- 6 ; Already declared var=off, warn when using Dim=off #include Dim $vVariableThatIsGlobal = "This is a variable that has ""Program Scope"" aka Global." MsgBox($MB_SYSTEMMODAL, "", "An example of why Dim can cause more problems than solve them.") Example() Func Example() ; That looks alright to me as it displays the following text: This is a variable that has "Program Scope" aka Global. MsgBox($MB_SYSTEMMODAL, "", $vVariableThatIsGlobal) ; Call some random function. Local $vReturn = SomeFunc() ; The Global variable ($vVariableThatIsGlobal) changed because I totally forgot I had a duplicate variable name in "SomeFunc". MsgBox($MB_SYSTEMMODAL, $vReturn, "The variable has now changed: " & $vVariableThatIsGlobal) EndFunc ;==>Example Func SomeFunc() ; This should create a variable in Local scope if the variable name doesn't already exist. ; For argument sake I totally forgot that I declared a variable already with the same name. ; Well I only want this to be changed in the function and not the variable at the top of the script. ; Should be OK right? Think again. Dim $vVariableThatIsGlobal = "" For $i = 1 To 10 $vVariableThatIsGlobal &= $i ; This will return 12345678910 totally wiping the previous contents of $vVariableThatIsGlobal. Next Return $vVariableThatIsGlobal EndFunc ;==>SomeFunc <