I want to create a new Tutorial for beginners. I am a complete autodidact coder and i want to get here some simple things in the right order. With helping others i can practice my coding. UNDER CONSTRUCTION

Finished Components

Commando-List sorted by Categories

SwissArmy Knife of (AHK) Coding

Structure Template v1.0

Under Construction

GUI

Basic Syntax Introduction - If Calls / Loops / Label

Good Code Structure - The art of Code AHK - My opionion to order the Code into logical sections / blocks. Starting usage to explain with the Template.

1.) Get a Editor with TexthiglightningNotepad++ and Scite is free software. Put the editor on the half of the screen and on the other side open your Browser or the AHK-Help File. Enough space to code and you got quick access if you need help.

STRUCTURE TEMPLATE to get things in the right order

I hope it helps to get the most used settings and give you a bit of orientation as a white sheet. The Setup is done in safe parameters that should prevent you to get mistakes that belong to the scriptsetup and not your code. As earlier you can handle the Outlay, as faster you can navigate inside the script. More time to learn the language. To hold a clear structure is really important. Nothing is more annoying, as to lose the plot. So you should the following little things. Sure its a bit work more to do. But in the end you save more time and make the code more readable for you and for the community if you need help.

use the Comment Function often - helps to learn and give you a visual hook

try to avoid Numbers and use Variables for them , if you have to change a value, you can do that for the complete script inside with one variable

Learn how to use Functions - Your Lazy and Smart. Use Functions. There will be functions you can use for many scripts. If you recognize that there are lines in your script obviously repeat. Try to write a function for the code. Modify and reuse the script will be happen soon. Believe me. If the most Code inside the script is done by functions. Youre on the right way.

Order your script segments with visual hooks. Paste in Lines that give you orientation in which section inside the code your are.

STill under progress but it includes many settings that should prevent you from some silly easy errors at the start. Just read the comments inside the Template. It depends a bit what kind or stuff you want to do. But there is some really interesting things for Beginner

#SingleInstance force allows you to restart the script without closing it. Really usefull and save a lot off clicks

ShortCut ALT + X Exit the Script - Should your Mousecursor run crazy or you cant close the script , this is your red button.

Its ok. But for beginners it a bit hard to understand and the many Question here in the Forum shows that its not really a good help is, how to code. The explanations for the commands are good but the examples are mostly not really good. But use the Index to get quick infos about the Command-Parameter. you gonna use these really often. Read the Tutorial. But IMO its not really helpfull. But it dont hurts your much if you do it. Take it as a advanced appendix from this Tutorial

Trial and Error

Without it, you wont get it. But this is how you learn. Every mistake your make, you can clear it out and learn from it. IMO i think that one of the fascinating and motivating thing in coding. Its really a pleasure if you found the little Comma that hang up your code. Or a missing Percentage sign. Try to find the mistake inside the code yourself. I see to many guys asking here for a really silly problem and they wanna have a ready solution for there Project. On this way you dont gonna learn the really interesting things with AHK. So keep it up and dont be shy to ask here if you really stuck somewhere.

Last edited by HinkerLoden on 01 Apr 2016, 03:54, edited 2 times in total.

It should be a introduction for beginners. So i really have to say some things about structure of every the Script language. Again, i try to keep it simple and the Hardcore Coders will say its not right. These 4 steps are allways present, even if you dont notice them. In Simple Things you dont really need them, but the normal case your structure will look this way. The Important thing is it, that you dont mix them together. I show you what thats how crucial that is and what to do to hold the script structure in shape.

COMPARE Comparisons in 99% handles with If-Calls. Compare 2 or more Inputs if active, are they fulfill the Values you want to do something. I think in most cases this should be the largest Part of your Script. I like it to integrate the If-Call inside a Timer. The Timer is like a constant Loop within a defined Rotation Time. So it is possible to do Switch Timers on an off. You can control the several Processes with a defined time you need. I recommend to do that right at the start up. I the practical case it working on this way really good.

TRANSFER - I really search for the right term here The comparison Value now maybe got the Value TRUE or FALSE. But you need to bring the Value in a Format you want to use in the upcoming Output. So you advice a specific Color or Coordinate on this you can you use.Transform the Value in the right Format you need. I separate this because many Compares are only need one Transfer. Mostly done by Functions. ( Example: Put the ColorValue and the CoordinateXY with the same Progress into a Ini File / Array . )

It really important to have that in mind. You have to prepare ( convert / format ) your upcoming Output.

OUTPUTAll Input Sources can turn into a Output. But you have the use the right commando for it. Usually done by :Mouse,Key(combinations), safe into file / txt / Ini / pic / etc, Sound, GUI

Maybe the interesting part for starters. To do all the clicks that make the life easier. But remind that it only a litle part at the end of the script.

I think here problem allready start. They explain Variables and mix right at begin "=" and ":=" Give it a go. But i try to Explain it on an other way to get the difference and especially the practical usage and how the syntax working.

First you have to think different of the learned Math in School.

Not think from Left to Right inside the Operations. The ahk Code work from Right to Left

Var1 + Var2 --> Output

Output <-- Var1 + Var2

Thats one important think what drives me Crazy at the begin. No one tell you here. But you really have to know it and so you prevent many mistakes and understand the code better.

And yes. Its not really correct here. But on this way it helps me to get the difference between this 2 basic important things. I try to create some easy rules for me to prevent the wrong usage with Assignments "=" and Expressions ":=". And with the Percentage Signs it can get very tricky. Keey the following in mind and it help you at the start.

USE OF = ( Assignments )

1_Variable = 1_Value

Only ONE Variable is addressed to ONE Value. No Operator used in Assignments

From the Official HelpAn expression can be used in a parameter that does not directly support it (except OutputVar parameters) by preceding the expression with a percent sign and a space or tab. In [v1.1.21+], this prefix can be used in the InputVar parameters of all commands except the traditional IF commands (use If (expression) instead). This technique is often used to access arrays. For example:

Functions give you a great flexibility and you can use them for your next project. Maybe with little changes. I not really noticed them a long time , but its really great and it make sense to understand the functions at the start. Functions are an universal instrument for many things. But the main thing is to automatic Codephrases. So its possible to do all the Code with no Functions.

There are a bunch of advantages if you use Functions inside the code:

But your Code is much shorter As bigger your script grow, as more this aspect gets important. Without lose the Overview so quick in case of that.

Modify the Task getting quite easy

Use the Functions for your next Project - So if you put energy and work in one Function you can mostly use them inside another Script.

Safe Time to Navigate inside the Code, Write the Code, Analyzing / debugging

I am know that the starter dont really need functions at the start. But as early you beginn with functions. As quicker you can understand the ahk syntax and you are able to understand the the Examples in the forum better.

Give a function a practical relation. You notice that you are doing the following Codelines again and again

1.)Get the Coordinates from the active Cursor position2.) Get the Color from the active Cursor position3.) Compare with 3 Colors If Found the Color4.) If Found - Wait between 1-2 seconds5.) Move the Cursor relative from the Position if the Search was sucessfull 50pixel Down and 50pixel Right. 6.) Output the WaitTime

Copy / Download it and paste it into your Editor. Add the upcoming Changes yourself to for the practice.

Output := X - Y ;a Task return Output ; Return end the Function a give back ONE Value , but you can do a return without set any Variable / Output Value}

Everything in the Braces is excecute if you put the Function FunctionName () in the Code. The Script dont stops and go ahead in the next Line.

Functions got there Limitations

Reminder:

Created Variables are only inside the Function Active

With return the Functions Stops

It is not possible to pass Clipboard, built-in variables, or environment variables to a function's ByRef parameter

Function give the only one Value back

avoid to use Label / Hotkey / Timer Inside a Function cause you cant get access outside of the function on it

Time to put something into a function. So we analyze first how many steps are done and where the code repeats.

1.)Get the Coordinates from the active Cursor position -1x2.) Get the Color from the active Cursor position - 1x3.) Compare with 3 Colors If Found the Color -3x4.) If Found - Wait between 1-2 seconds -3x5.) Move the Cursor relative from the Position if the Search was sucessfull 50pixel Down and 50pixel Right. 3x6.) Output the WaitTime -3x

So i paste it into the Example and adding a new Hotkey F12 to get the difference between the Stretched Code without the function and the Reduced Code with using FunctionRead the comments. (OLD Code without Functions --> F11 - Same Code Using Functions --> F12)

Function without Output / Input

If you dont want to Use Output or Input Variable. The Function is quite simple. There is nothing inside the Brackets. I take as an example a part from the Code above.

4.) If Found - Wait between 1-2 seconds -3x5.) Move the Cursor relative from the Position if the Search was sucessfull 50pixel Down and 50pixel Right. 3x

I know, its not the best example (cause we have some inputvariables and its possible to avoid the repeat to put it behind or in front of the comparison )- but i hope you get the point how the structure is how you integrate Functions in your code. And i want to build up on this example.

1.) F_Sleep_and_Move() Function is now only for the Settings inside the function. So we add these parameters as Inputs that we can use this function flexible for every Movement and every defined time to wait. So we create a the function: F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax)

F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax) ;Output Sleep Time

{

Random, Wait , WaitMin, WaitMaxSleep, % Wait

MouseMove, MoveX, MoveY, ,R

return Wait ; Output Value is the Variable behind return !

}

2.) We put the 3 First tasks into one Function - F_Compare_Color(X,Y,Colorinput,Colorname) and we enhance the Script with a string Input. There we can fill in the NameColor.

A String inside the Function Call need Quotation Marks

Example : F_Compare_Color(Color_Pink,"Pink")

1.)Get the Coordinates from the active Cursor position -1x2.) Get the Color from the active Cursor position - 1x3.) Compare with 3 Colors If Found the Color -3x

Now the final step. We modify the F_Compare_Color(Colorinput,Colorname) that we get the taken Coords out of the Function and the Color. So we get them out of the If you want to do get a Variable out of a Function you have use the ByRef Parameter

I only changed the Names inside, because i want to have OutputVars that describe my Output. The Value i give my ByRef Variables inside the function will create this variable (or override it) inside the code. So be careful here. Do not to choose a ByRef Variable what is allready is in use. (or you want to override it )

Hope you get it all. But you will say now. The Long code without Functions is easier. Right. It is. But there are now so many methods to modifiy this script. Reuse it in other Project and add additional task you want. I give you her some Task to modify the Script. Do it the with the use of functions and without it . You will notice quick the difference.

Why ? Because the Help file and online faq is really without any Structure. They took everything and Order it alphabetic. Ok - the Content is a bit structured. But i think it is now much better find Commandos you need for you task.

Exit Exits the current thread or(if the script isnot persistent andcontains no hotkeys) the entire script.

Critical Prevents the current thread from being interrupted by other threads,or enables it to be interrupted.Finally Ensures that a block of code is always executed after a Try statement finishes.Thread Sets the priority or interruptibility of threads. It can also temporarily disable all timers.

Catch Specifies the code to execute if an exception is raised during execution of a try statement.Throw Signals the occurrence of an error.This signal can be caught by a try-catch statement.Try Guards one or more statements (commands or expressions) against runtime errors and exceptions thrown by the throw command.

Loop(normal) Perform a series of commands repeatedly: either the specified number of times or until breakis encountered.Loop(files & folders) Retrieves the specified files or folders, one at a time.Loop(parse a string) Retrieves substrings (fields) from a string, one at a time.Loop(read file contents) Retrieves the lines in a text file, one at a time (performs better than FileReadLine).Loop(registry) Retrieves the contents of the specified registry subkey, one item at a time.

Continue Skips the rest of the current loop iteration and begins a new one. Valid inside any kind of loop While-loop Performs a series of commands repeatedly until the specified expression evaluates to false.Until Applies a condition to the continuation of a Loop or For-loop.

; IF

if(expression) Specifies the command(s) to perform if an expression evaluates to TRUE.If var [not]between Checks whether a variable's contents are numerically or alphabetically between two values (inclusive).

If var [not]in/contains MatchList Checks whether a variable's contents match one of the items in a list.If var is[not] type Checks whether a variable's contents are numeric, uppercase, etc.

IfEqual/ IfNotEqual Compares a variable to a value for equality. Synonymous with: if Var = Value | if Var <> Value.IfExist/FileExist() Checks for the existence of a file or folder.IfGreater/ IfGreaterOrEqual Compares a variable to a value. Synonymous with: if Var > Value | if Var >= ValueIfInString/InStr() Checks if a variable contains the specified string.IfLess/ IfLessOrEqual Compares a variable to a value. Synonymous with: if Var < Value | if Var <= Value.

For Repeats a series of commands once for each key-value pair in an object. Format Formats a variable number of input values according to a format string.Else Specifies the command(s) to perform if an IF-statement evaluates to FALSE. When more than one command is present, enclose them in a block (braces).

; ################# Label

; ################# OS and other Stuff

ListVars Displays the script's variables: their names and current contents.ListLines Displays the script lines most recently executed.Sort Arranges a variable's contents in alphabetical, numerical,or random order (optionally removing duplicates).

OnExit Specifies a subroutine to run automatically when the script exits.

Drive Ejects/retracts the tray in a CD or DVD drive,or sets a drive's volume label.DriveGet Retrieves various types of information about the computer's drive(s).DriveSpaceFree Retrieves the free disk space of a drive,in Megabytes.

IsByRef() Determines whether a ByRef parameter was supplied with a variable.IsFunc() Indicates whether a function may be called dynamically.IsLabel() Checks whether the given value exist as a label.IsObject() Determines whether a value is an object.

Trim Trims certain characters from the beginning and/or end of a string.InStr() Searches for a given occurrence of a string, from the leftor the right.

StringTrimLeft Removes a number of characters from the left-hand side of a string.StringTrimRight Removes a number of characters from the right-hand side of a string.

StringLeft Retrieves a number of characters from the left-hand side of a string.StringMid/SubStr()Retrieves one or more characters from the specified position in a string.StringRight Retrieves a number of characters from the right-hand side of a string.

WinActivate Activates the specified window (makes it foremost).WinActivateBottom Same as WinActivate except that it activates the bottommost (least recently active) matching window rather than the topmost.WinActive() Returns the Unique ID (HWND) of the active window if it matches the specified criteria.

WinGetTitle Retrieves the title of the specified window.WinGetText Retrieves the text from the specified window.WinGetPos Retrieves the position and size of the specified window.

DetectHiddenText Determines whether invisible text in a window is"seen"for the purpose of finding the window.This affects commands such as IfWinExist and WinActivate.DetectHiddenWindows Determines whether invisible windows are "seen" by the script.

StatusBarGetText Retrieves the text from a standard status bar control.StatusBarWait Waits until a window's status bar contains the specified string.

; ResizingWinMove Changes the position and/or size of the specified window.

WinMaximize Enlarges the specified window to its maximum size. WinMenuSelectItem Invokes a menu item from the menu bar of the specified window.WinMinimize Collapses the specified window into a button on the task bar. WinMinimizeAll Minimizes all windows.WinMinimizeAllUndo Reverses the effect of a previous

WinSet Makes a variety of changes to the specified window, such as "always on top"and transparency.WinSetTitle Changes the title of the specified window. WinShow Unhides the specified window.

; ###MenuGetHandle Retrieves the Win32 menu handle of a menu.MenuGetName Retrieves the name of a menu given a handle to its underlying Win32 menu.

; ################# GuiGui Creates and manages windows and controls. Such windows can be used as data entry forms or custom user interfaces.

; Create Popup Windows

MsgBox Displays the specified text in a small window containing one or more buttons (such as Yes and No).IfMsgBox Checks which button was pushed by the user during the most recent MsgBox command.PostMessage Places a message in the message queue of a window orcontrol.

; Create Popup Windows with Input

Input Waits for the user to type a string.InputBox Displays an input box to ask the user to enter a string.

; Read

GuiControlGet Retrieves various types of information about a controlin a GUI windowControlSend/ ControlSendRaw Sends simulated keystrokes to a window orcontrol.

GroupActivate Activates the next window in a window group that was defined with GroupAdd.GroupAdd Adds a window specification to a window group, creating the group if necessary.GroupClose Closes the active window if it was just activated byGroupActivateor GroupDeactivate. It then activates the next window in the series. It can also close all windows in a group.GroupDeactivate Similar to GroupActivate except activates the next window notin the group.

FileSelectFile Displays a standard dialog that allows the user to open or save file(s).FileSelectFolder Displays a standard dialog that allows the user to select a folder.

; Menu / ToolTip / Splashimage

Menu Creates, deletes, modifies and displays menus and menu items. Changes the tray icon and its tooltip. Controls whether the main window of a compiled script can be opened.

ToolTip Creates an always-on-top window anywhere on the screen.TrayTip Creates a balloon message window near the tray icon.#NoTrayIcon Disables the showing of a tray icon.

FileAppend Writes text to the end of a file (first creating the file, if necessary).FileCreateShortcut Creates a shortcut (.lnk) file.FileGetShortcut Retrieves information about a shortcut (.lnk) file, such as its target file.

FileSelectFile Displays a standard dialog that allows the user to open or save file(s).FileSelectFolder Displays a standard dialog that allows the user to select a folder.

FileSetAttrib Changes the attributes of one or more files or folders. Wildcards are supported.FileSetTime Changes the datetime stamp of one or more files or folders. Wildcards are supported.

; otherUrlDownloadToFile Downloads a file from the Internet.SplitPath Separates a file name or URL into its name, directory, extension,and drive.FileInstall Includes the specified file inside the compiled version of the script

; ################# Variable EnvUpdate Notifies the OS and all running applications that environment variable(s) have changed.

EnvAdd Sets a variable to the sum of itself plus the given value (can also add or subtract time from a date-time value). Synonymous with: Var += ValueEnvDiv Sets a variable to itself divided by the given value. Synonymous with: Var /= Value.EnvGet Retrieves an environment variable.EnvMult Sets a variable to itself times the given value. Synonymous with: Var *= Value.EnvSet Writes a value to a variable contained in the environment.EnvSub Sets a variable to itself minus the given value (can also compare date-time values). Synonymous with: Var -= Value.

Suspend Disables or enables all or selected hotkeys and hotstrings.ListHotkeys Displays the hotkeys in use by the current script, whether their subroutines are currently running,and whether ornot they use the keyboard or mouse hook.

SetKeyDelay Sets the delay that will occur after each keystroke sent by Send or ControlSend.SetCapslockState Sets the state of the Capslock key. Can also force the key to stay on or off.SetScrollLockState Sets the state of the Scrolllock key. Can also force the key to stay on or off.

SendLevel Controls which artificial keyboard and mouse events are ignored by hotkeys and hotstrings.SendMessage Sends a message to a window orcontroland waits for acknowledgement.

Hotkey Creates, modifies, enables,or disables a hotkey while the script is running. if Specifies the command(s) to perform if the comparison of a variable to a value evalutes to TRUE. When more than one command is present, enclose them in a block (braces).

GetKeyName()GetKeyVK()GetKeySC() Retrieves the name or text, virtual key code or scan code of a key. GetKeyState Checks if a keyboard key or mouse/joystick button isdownorup. Also retrieves joystick status.

KeyHistory Displays script info and a history of the most recent keystrokes and mouse clicks.KeyWait Waits for a key or mouse/joystick button to be released or pressed down.

; ################# Mouse

SetMouseDelay Sets the delay that will occur after each mouse movement orclick.SetNumlockState Sets the state of the Numlock key. Can also force the key to stay on or off.SetDefaultMouseSpeed Sets the mouse speed that will be used if unspecified inClickand MouseMove/Click/Drag.

MouseClick Clicks or holds down a mouse button,or turns the mouse wheel. NOTE: The Click command is generally more flexible and easier to use.

MouseClickDrag Clicks and holds the specified mouse button, moves the mouse to the destination coordinates, then releases the button.MouseGetPos Retrieves the current position of the mouse cursor,and optionally which window andcontrol it is hovering over.MouseMove Moves the mouse cursor.

Click Clicks a mouse button at the specified coordinates. It can also hold down a mouse button, turn the mouse wheel,or move the mouse.

; ################# Run /

Process Performs one of the following operations on a process: checks if it exists; changes its priority; closes it; waits for it to close. Progress Creates or updates a window containing a progress bar.

Run Runs an external program.RunAs Specifies a set of user credentials to use for all subsequent uses ofRunand RunWait.RunWait Runs an external program and waits until it finishes.

ComObjActive() Retrieves a registered COM object.ComObjArray() Creates a SAFEARRAY for use with COMComObjConnect() Connects a COM object's event sources to functions with a given prefix.ComObjCreate() Creates a COM object. ComObjEnwrap()/ ComObjUnwrap() Wraps/unwraps a COM object.ComObjError() Enables or disables notification of COM errors.ComObjFlags() Retrieves or changes flags which control a COM wrapper object's behaviour.ComObjGet() Returns a reference to an object provided by a COM component. ComObjMissing() Creates a "missing parameter" object to pass to a COM method. ComObjParameter() Wraps a value and type to pass as a parameter to a COM method.ComObjQuery() Queries a COM object for an interface or service.ComObjType() Retrieves type information from a COM object.ComObjValue() Retrieves the value or pointer stored in a COM wrapper object.

Cos() Returns the trigonometric cosine of Number.Sin() Returns the trigonometric sine of Number.Tan() Returns the trigonometric tangent of Number.

ASin() Returns the arcsine (the number whose sine is Number)in radians.ACos() Returns the arccosine (the number whose cosine is Number)in radians.ATan() Returns the arctangent (the number whose tangent is Number)in radians.

; Round

Round() If N is omitted or0, Number is rounded to the nearest integer. If N is positive number, Number is rounded to N decimal places. If N is negative, Number is rounded by N digits to the left of the decimal point.Ceil() Returns Number rounded up to the nearest integer (without any .00 suffix).Floor() Returns Number rounded down to the nearest integer (without any .00 suffix).

Exp() Returns e (which is approximately 2.71828182845905) raised to the Nth power.Sqrt() Returns the square root of Number.

NumGet() Returns the binary number stored at the specified address+offset.NumPut() Stores a number in binary format at the specified address+offset.

; ################# Script Enviroment

SetBatchLines Determines how fast a script will run (affects CPU utilization).

#NoEnv Avoids checking empty variables to see if they are environment variables (recommended for all new scripts).#Persistent Keeps a script permanently running (that is, until the user closes it or ExitApp is encountered).#SingleInstance Determines whether a script is allowed to run again when it is already running.

; ## Syntax modifiers#CommentFlag Changes the script's comment symbol from semicolon to some other string.#EscapeChar Changes the script's escape character (for example: backslash vs. accent).#HotkeyInterval Along with #MaxHotkeysPerInterval, specifies the rate of hotkey activations beyond which a warning dialog will be displayed.#HotkeyModifierTimeout Affects the behavior of hotkey modifiers:CTRL,ALT, WIN,andSHIFT.#Hotstring Changes hotstring options or ending characters.

#ErrorStdOut Sends any syntax error that prevents a script from launching to stdout rather than displaying a dialog.

#If Similar to #IfWinActive, but for arbitrary expressions.#IfTimeout Sets the maximum time that may be spent evaluating a single #If expression.#IfWinActive/ #IfWinExist Creates context-sensitive hotkeys and hotstrings. Such hotkeys perform a different action (or none at all) depending on the type of window that is active or exists.

#Include Causes the script to behave as though the specified file's contents are present at this exact position.#InputLevel Controls which artificial keyboard and mouse events are ignored by hotkeys and hotstrings.

#InstallKeybdHook Forces the unconditional installation of the keyboard hook. #InstallMouseHook Forces the unconditional installation of the mouse hook. #KeyHistory Sets the maximum number of keyboard and mouse events displayed by the KeyHistory window. You can set it to 0 to disable key history. #LTrim Enables or disables trimming of indentation in continuation sections.

OnMessage() Specifies a function to call automatically when the script receives the specified message.SetRegView Allows registry commands in a 32-bit script to access the 64-bit registry view and vice versa.

Last edited by HinkerLoden on 02 Apr 2016, 23:36, edited 3 times in total.

%Var%If a variable is enclosed in percent signs within an expression (e.g.%Var%), whatever that variable containsis assumed to be the name or partial name of another variable (if there is no such variable,%Var% resolves to a blank string).Thisis most commonly used to reference pseudo-array elements such as the following example:

For backward compatibility, command parameters that are documented as "can be an expression" treat an isolated name in percent signs (e.g.%Var%, but not Array%i%) as though the percent signs are absent.This can be avoided by enclosing the reference in parentheses; e.g.Sleep(%Var%).

environment variable:In addition to normal variables,%Var% may resolve to an environment variable, the clipboard,or any reserved/read-only variable. Prior to revision 52,%Var% yielded an empty string in these cases.

++--Pre-and post-increment/decrement. Adds or subtracts 1 from a variable (but in versions prior to 1.0.46, these can be used only by themselves on a line; no other operators may be present). The operator may appear either before or after the variable's name. If it appears before the name, the operation is performed immediately and its result is used by the next operation. For example, Var :=++X increments X immediately and then assigns its value to Var. Conversely, if the operator appears after the variable's name, the operation is performed after the variable is used by the next operation. For example, Var := X++ increments X only after assigning the current value of X to Var. Due to backward compatibility, the operators ++and-- treat blank variables as zero, but only when they are alone on a line; for example, y:=1,++x and MsgBox % ++x both produce a blank result when x is blank.

**Power. Both the baseand the exponent may contain a decimal point. If the exponent is negative, the result will be formatted as a floating point number even if the baseand exponent are both integers. Since **is of higher precedence than unary minus,-2**2is evaluated like -(2**2)and so yields -4. Thus, to raise a literal negative number to a power, enclose it in parentheses such as (-2)**2. Note: A negative base combined with a fractional exponent such as (-2)**0.5isnot supported; it will yield an empty string. But both (-2)**2and(-2)**2.0 are supported.

Unary minus (-):Although it uses the same symbol as the subtract operator, unary minus applies to only a single item or sub-expression as shown twice inthis example:-(3/-x). On a related note, any unary plus signs (+) within an expression are ignored.

Logical-not(!):If the operand is blank or0, the result of applying logical-notis1, which means "true". Otherwise, the result is0(false). For example: !x or !(y and z). Note: The word NOTis synonymous with ! except that ! has a higher precedence.In v1.0.46+, consecutive unary operators such as !!Var are allowed because they are evaluated inright-to-left order.

Bitwise-not(~):This inverts each bit of its operand. If the operand is a floating point value, it is truncated to an integer prior to the calculation. If the operand isbetween0and4294967295(0xffffffff), it will be treated as an unsigned 32-bit value. Otherwise, it is treated as a signed 64-bit value. For example, ~0xf0f evaluates to 0xfffff0f0 (4294963440).

Address (&):&MyVar retrieves the address of MyVar's contents in memory, which is typically used with DllCall structures.&MyVar also disables the caching of binary numbers in that variable, which can slow down its performance if it is ever used for math or numeric comparisons. Caching is re-enabled for a variable whenever its address changes (e.g. via VarSetCapacity()).

Dereference (*):*Expression assumes that Expression resolves to a numeric memory address; it retrieves the byte at that address as a number between0and255(0is always retrieved if the address is0; but any other invalid address must be avoided because it might crash the script). However,NumGet() generally performs much better when retrieving binary numbers.

*///Multiply (*):The result is an integer if both inputs are integers; otherwise, it is a floating point number.

True divide (/):Unlike EnvDiv,true division yields a floating point result even when both inputs are integers. For example,3/2 yields 1.5 rather than 1,and4/2 yields 2.0 rather than 2.

Floor divide (//):The double-slash operator uses high-performance integer division if the two inputs are integers. For example,5//3is1and5//-3is-1. If either of the inputs isin floating point format, floating point division is performed and the result is truncated to the nearest integer to the left. For example,5//3.0is1.0and5.0//-3is-2.0. Although the result of this floating point division is an integer, it is stored in floating point format so that anything else that uses it will see it as such. For modulo, see mod().

Shorthand Multiply (*=)and Divide (/=):operators are a shorthand way to multiply or divide the value in a variable by another value. For example, Var*=2 produces the same result as Var:=Var*2(though the former performs better).

+-Add (+)and subtract (-). On a related note, the +=and-= operators are a shorthand way to increment or decrement a variable. For example, Var+=2 produces the same result as Var:=Var+2(though the former performs better). Similarly, a variable can be increased or decreased by 1 by using Var++, Var--,++Var,or--Var.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

<<>>Bit shiftleft(<<)andright(>>). Example usage: Value1 << Value2. Any floating point input is truncated to an integer prior to the calculation.Shiftleft(<<)is equivalent to multiplying Value1 by "2 to the Value2th power".Shiftright(>>)is equivalent to dividing Value1 by "2 to the Value2th power"and rounding the result to the nearest integer leftward on the number line; for example,-3>>1is-2.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

&^| Bitwise-and(&), bitwise-exclusive-or(^),and bitwise-or(|). Of the three,& has the highest precedence and | has the lowest. Any floating point input is truncated to an integer prior to the calculation.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

.Concatenate. The period (dot) operator is used to combine two items into a single string (there must be at least one space on each side of the period). You may also omit the period to achieve the same result (except where ambiguous such as x -y,or when the item on the right side has a leading ++or--). When the dot is omitted, there should be at least one spacebetween the items to be merged.Example (expression method): Var :="The color is ". FoundColorExample (traditional method): Var = The color is%FoundColor%

Sub-expressions can also be concatenated. For example: Var :="The net price is ". Price *(1- Discount/100).

A line that begins with a period (or any other operator)is automatically appended to the line above it.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

~=Shorthand for RegExMatch. For example,"abc123" ~="\d" sets ErrorLevel to 0and yields 4(the position of the first numeric character). Prior to v1.1.03,this operator had the same precedence as the equal (=) operator and was not fully documented.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

><>=<=Greater (>), less (<), greater-or-equal (>=),and less-or-equal (<=). If either of the inputs isnot a number, both are compared alphabetically (a quoted literal string such as "55"is always considered non-numeric inthis context). The comparison is case sensitive only if StringCaseSense has been turned on. See also: Sort; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

NOTLogical-NOT. Except for its lower precedence,thisis the same as the ! operator. For example,not(x =3or y =3)is the same as !(x =3or y =3).; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

AND&&Both of these are logical-AND. For example: x >3and x <10. To enhance performance, short-circuit evaluation is applied. Also, a line that begins with AND/OR/&&/|| (or any other operator)is automatically appended to the line above it.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

OR|| Both of these are logical-OR. For example: x <=3or x >=10. To enhance performance, short-circuit evaluation is applied.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

?:Ternary operator [v1.0.46+].This operator is a shorthand replacement for the if-else statement. It evaluates the condition on its left side to determine which of its two branches should become its final result. For example, var := x>y ?2:3 stores 2in Var if x is greater than y; otherwise it stores 3. To enhance performance, only the winning branch is evaluated (see short-circuit evaluation).; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

:=+=-=*=/=//=.=|=&=^=>>=<<=

Assign. Performs an operation on the contents of a variable and stores the result back in the same variable (but in versions prior to 1.0.46, these could only be used as the leftmost operator on a line,and only the first five operators were supported). The simplest assignment operator is colon-equals (:=), which stores the result of an expression in a variable. For a description of what the other operators do, see their related entries inthis table. For example, Var //=2 performs floor division to divide Var by 2, then stores the result back in Var. Similarly, Var .="abc"is a shorthand way of writing Var := Var ."abc".

Unlike most other operators, assignments are evaluated from right to left. Consequently, a line such as Var1 := Var2 :=0 first assigns 0 to Var2 then assigns Var2 to Var1.

If an assignment is used as the input for some other operator, its value is the variable itself. For example, the expression (Var+=2)>50istrue if the newly-increased value in Var is greater than 50.This also allows an assignment to be passed ByRef,or its address taken; for example:&(x:="abc").

The precedence of the assignment operators is automatically raised when it would avoid a syntax error or provide more intuitive behavior. For example:not x:=y is evaluated as not(x:=y). Similarly,++Var := X is evaluated as ++(Var := X); and Z>0? X:=2: Y:=2is evaluated as Z>0?(X:=2):(Y:=2).

Known limitations caused by backward compatibility (these may be resolved in a future release):1) When /=is the leftmost operator in an expression and it isnot part of a multi-statement expression, it performs floor division unless one of the inputs is floating point (in all other cases,/= performs true division); 2) Date/time math is supported by +=and-= only when that operator is the leftmost one on a line; 3) The operators +=,-=,and*= treat blank variables as zero, but only when they are alone on a line; for example, y:=1, x+=1and MsgBox % x-=3 both produce a blank result when x is blank.

,Comma (multi-statement)[v1.0.46+]. Commas may be used to write multiple sub-expressions on a single line.Thisis most commonly used to group together multiple assignments or function calls. For example: x:=1, y+=2,++index,func(). Such statements are executed in order from left to right. Note: A line that begins with a comma (or any other operator)is automatically appended to the line above it. See also: comma performance.

In v1.0.46.01+, when a comma is followed immediately by a variable and an equal sign, that equal sign is automatically treated as an assignment (:=). For example, all of the following are assignments: x:=1, y=2, a=b=c.New scripts should not rely on this behavior as it may change. The rule applies only to plain variables andnot double-derefs, so the following contains only one assignment: x:=1,%y%=2; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

These and other built-in math functions are described here.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

func.()[v1.0.90+]: Attempts to call an empty-named method of the object func. By convention,thisis the object's "default" method. If func does not contain an object, the default base object is invoked instead.

[v1.0.95+]: If func contains a function name, the named function is called.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

newCreates a new object derived from another object. For example, x :=new y is often equivalent to x :={base: y}.new should be followed by a variable or simple class name of the form GlobalClass.NestedClass,and optionally parameters as in x :=new y(z)(where y is a variable,not a function name). For details, see Custom Objects.

The following variables are built into the program and can be referenced by any script. With the exception of Clipboard, ErrorLevel, and command line parameters, these variables are read-only; that is, their contents cannot be directly altered by the script.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

A_SpaceThis variable contains a single space character. See AutoTrim for details.;------------------------------------------A_TabThis variable contains a single tab character. See AutoTrim for details.

; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################Script Properties;------------------------------------------1,2,3, etc. These variables are automatically created whenever a script is launched with command line parameters. They can be changed and referenced just like normal variable names (for example:%1%). The variable %0%contains the number of parameters passed (0 if none). For details, see the command line parameters.;------------------------------------------A_WorkingDirThe script's current working directory, which is where files will be accessed by default. The final backslash isnot included unless it is the root directory. Two examples: C:\ and C:\My Documents. Use SetWorkingDir to change the working directory.;------------------------------------------A_ScriptDirThe full path of the directory where the current script is located. The final backslash is omitted (even for root directories).;------------------------------------------A_ScriptNameThe file name of the current script, without its path, e.g. MyScript.ahk.;------------------------------------------A_ScriptFullPathThe combination of the above two variables to give the complete file specification of the script, e.g. C:\My Documents\My Script.ahk;------------------------------------------A_ScriptHwnd[v1.1.01+] The unique ID (HWND/handle) of the script's hidden main window.;------------------------------------------A_LineNumberThe number of the currently executing line within the script (or one of its #Include files).This line number will match the one shown by ListLines; it can be useful for error reporting such as this example: MsgBox Could not write to log file (line number %A_LineNumber%).

Since a compiled script has merged all its #Include files into one big script, its line numbering may be different than when it is run in non-compiled mode.;------------------------------------------

A_LineFileThe full path and name of the file to which A_LineNumber belongs, which will be the same as A_ScriptFullPath unless the line belongs to one of a non-compiled script's #Include files.;------------------------------------------A_ThisFunc[v1.0.46.16+] The name of the user-defined function that is currently executing (blank if none); for example: MyFunction. See also:IsFunc();------------------------------------------A_ThisLabel[v1.0.46.16+] The name of the label (subroutine) that is currently executing (blank if none); for example: MyLabel. It is updated whenever the script executes Gosub/Return or Goto. It is also updated for automatically-called labels such as timers, GUI threads, menu items, hotkeys, hotstrings, OnClipboardChange (label),and OnExit. However,A_ThisLabelisnot updated when execution "falls into" a label from above; when that happens,A_ThisLabel retains its previous value. See also:A_ThisHotkeyandIsLabel();------------------------------------------A_AhkVersionIn versions prior to 1.0.22,this variable is blank. Otherwise, it contains the version of AutoHotkey that is running the script, such as 1.0.22.In the case of a compiled script, the version that was originally used to compile it is reported. The formatting of the version number allows a script to check whether A_AhkVersionis greater than some minimum version number with >or>= as inthis example: if A_AhkVersion>= 1.0.25.07.;------------------------------------------A_AhkPathFor non-compiled scripts: The full path and name of the EXE file that is actually running the current script. For example: C:\Program Files\AutoHotkey\AutoHotkey.exe

For compiled scripts: The same as the above except the AutoHotkey directory is discovered via the registry entry HKEY_LOCAL_MACHINE\SOFTWARE\AutoHotkey\InstallDir. If there is no such entry,A_AhkPathis blank.;------------------------------------------

A_IsUnicodeContains1 if strings are Unicode (16-bit)and an empty string (which is considered false) if strings are ANSI (8-bit). The format of strings depends on the version of AutoHotkey.exe which is used to run the script,or if it is compiled, which bin file was used to compile it.;------------------------------------------A_IsCompiledContains1 if the script is running as a compiled EXE and an empty string (which is considered false) if it isnot.;------------------------------------------A_ExitReasonThe most recent reason the script was asked to terminate.This variable is blank unless the script has an OnExit subroutine and that subroutine is currently running or has been called at least once by an exit attempt. See OnExit for details.

Date and Time;------------------------------------------A_YYYYCurrent 4-digit year (e.g.2004). Synonymous with A_Year. Note: To retrieve a formatted time or date appropriate for your locale and language, use FormatTime, OutputVar (time and long date)or FormatTime, OutputVar,, LongDate (retrieves long-format date).;------------------------------------------A_MMCurrent 2-digit month (01-12). Synonymous with A_Mon.;------------------------------------------A_DDCurrent 2-digit day of the month (01-31). Synonymous with A_MDay.;------------------------------------------A_MMMMCurrent month's full name in the current user's language, e.g. July;------------------------------------------A_MMMCurrent month's abbreviation in the current user's language, e.g. Jul;------------------------------------------A_DDDDCurrent day of the week's full name in the current user's language, e.g. Sunday;------------------------------------------A_DDDCurrent day of the week's 3-letter abbreviation in the current user's language, e.g. Sun;------------------------------------------A_WDayCurrent 1-digit day of the week (1-7).1is Sunday in all locales.;------------------------------------------A_YDayCurrent day of the year (1-366). The value isnot zero-padded, e.g.9is retrieved,not 009. To retrieve a zero-padded value, use the following: FormatTime, OutputVar,, YDay0.;------------------------------------------A_YWeekCurrent year and week number (e.g.200453) according to ISO 8601. To separate the year from the week, use StringLeft, Year,A_YWeek,4and StringRight, Week,A_YWeek,2. Precise definition of A_YWeek: If the week containing January 1st has four or more days in the new year, it is considered week 1. Otherwise, it is the last week of the previous year,and the next week is week 1.;------------------------------------------A_HourCurrent 2-digit hour (00-23)in24-hour time (for example,17is 5pm). To retrieve 12-hour time as well as an AM/PM indicator, follow this example: FormatTime, OutputVar,, h:mm:ss tt;------------------------------------------A_MinCurrent 2-digit minute (00-59).;------------------------------------------A_SecCurrent 2-digit second (00-59).;------------------------------------------A_MSecCurrent 3-digit millisecond (000-999). To remove the leading zeros, follow this example: Milliseconds :=A_MSec+0.;------------------------------------------A_NowThe current local time in YYYYMMDDHH24MISS format. Note: Date and time math can be performed with EnvAdd and EnvSub. Also, FormatTime can format the date and/or time according to your locale or preferences.;------------------------------------------A_NowUTCThe current Coordinated Universal Time (UTC)in YYYYMMDDHH24MISS format. UTC is essentially the same as Greenwich Mean Time (GMT).;------------------------------------------A_TickCountThe number of milliseconds since the computer was rebooted. By storing A_TickCountin a variable, elapsed time can later be measured by subtracting that variable from the latest A_TickCount value. For example:

A_IsSuspendedContains1 if the script is suspended and0 otherwise.;------------------------------------------A_IsPaused[v1.0.48+]Contains1 if the thread immediately underneath the current thread is paused. Otherwise it contains0.;------------------------------------------A_IsCritical[v1.0.48+]Contains0 if Critical is off for the current thread. Otherwise it contains an integer greater than zero, namely the message-check frequency being used by Critical. Since Critical 0 turns off critical, the current state of Critical can be saved and restored via Old_IsCritical :=A_IsCritical followed later by Critical %Old_IsCritical%.;------------------------------------------A_BatchLines(synonymous with A_NumBatchLines) The current value as set by SetBatchLines. Examples:200or 10ms (depending on format).;------------------------------------------A_TitleMatchModeThe current mode set by SetTitleMatchMode:1,2,3,or RegEx.;------------------------------------------A_TitleMatchModeSpeedThe current match speed (fast or slow) set by SetTitleMatchMode.;------------------------------------------A_DetectHiddenWindowsThe current mode (On or Off) set by DetectHiddenWindows.;------------------------------------------A_DetectHiddenTextThe current mode (On or Off) set by DetectHiddenText.;------------------------------------------A_AutoTrimThe current mode (On or Off) set by AutoTrim.;------------------------------------------A_StringCaseSenseThe current mode (On, Off,or Locale) set by StringCaseSense.;------------------------------------------A_FileEncoding[v1.0.90+]Contains the default encoding for various commands; see FileEncoding.;------------------------------------------A_FormatIntegerThe current integer format (H or D) set by SetFormat.[v1.0.90+]:This may also contain lower-case h.;------------------------------------------A_FormatFloatThe current floating point number format set by SetFormat.;------------------------------------------A_SendMode [v1.1.23+]: The current mode (Event, Input, Play or InputThenPlay) set by SendMode.;------------------------------------------A_SendLevel [v1.1.23+]: The current SendLevel setting (an integer between0and100, inclusive).;------------------------------------------A_StoreCapslockMode [v1.1.23+]: The current mode (On or Off) set by SetStoreCapslockMode.;------------------------------------------A_KeyDelay;------------------------------------------A_KeyDuration The current delay or duration set by SetKeyDelay (always decimal,not hex). A_KeyDuration requires [v1.1.23+].;------------------------------------------A_KeyDelayPlay;------------------------------------------A_KeyDurationPlay The current delay or duration set by SetKeyDelay for the SendPlay mode (always decimal,not hex). Requires [v1.1.23+].;------------------------------------------A_WinDelayThe current delay set by SetWinDelay (always decimal,not hex).;------------------------------------------A_ControlDelayThe current delay set by SetControlDelay (always decimal,not hex).;------------------------------------------A_MouseDelay;------------------------------------------A_MouseDelayPlay The current delay set by SetMouseDelay (always decimal,not hex).A_MouseDelayis for the traditional SendEvent mode, whereas A_MouseDelayPlay is for SendPlay.;------------------------------------------A_MouseDelayPlay requires [v1.1.23+].;------------------------------------------A_DefaultMouseSpeedThe current speed set by SetDefaultMouseSpeed (always decimal,not hex).;------------------------------------------A_CoordModeToolTipA_CoordModePixelA_CoordModeMouseA_CoordModeCaretA_CoordModeMenu [v1.1.23+]: The current mode (Window, Client or Screen) set by CoordMode.;------------------------------------------A_RegView[v1.1.08+]: The current registry view as set by SetRegView.;------------------------------------------A_IconHiddenContains1 if the tray icon is currently hidden or0 otherwise. The icon can be hidden via #NoTrayIcon or the Menu command.;------------------------------------------A_IconTipBlank unless a custom tooltip for the tray icon has been specified via Menu, Tray, Tip --in which case it's the text of the tip.;------------------------------------------A_IconFileBlank unless a custom tray icon has been specified via Menu, tray, icon --in which case it's the full path and name of the icon's file. Known limitation:This path may be incorrect if the script originally passed a relative path to a system DLL; for example, Menu, Tray, Icon, user32.dll,2.;------------------------------------------A_IconNumberBlank if A_IconFileis blank. Otherwise, it's the number of the icon inA_IconFile(typically 1).

;------------------------------------------A_TimeIdleThe number of milliseconds that have elapsed since the system last received keyboard, mouse,or other input.Thisis useful for determining whether the user is away. Physical input from the user as well as artificial input generated by any program or script (such as the Send or MouseMove commands) will reset this value back to zero. Since this value tends to increase by increments of 10, do not check whether it is equal to another value. Instead, check whether it is greater or less than another value. For example: IfGreater,A_TimeIdle,600000, MsgBox, The last keyboard or mouse activity was at least 10 minutes ago.;------------------------------------------A_TimeIdlePhysicalSimilar to above but ignores artificial keystrokes and/or mouse clicks whenever the corresponding hook (keyboard or mouse)is installed; that is, it responds only to physical events.(This prevents simulated keystrokes and mouse clicks from falsely indicating that a user is present.) If neither hook is installed,this variable is equivalent to A_TimeIdle. If only one hook is installed, only its type of physical input affects A_TimeIdlePhysical(the other/non-installed hook's input, both physical and artificial, has no effect).

;------------------------------------------A_DefaultGui [v1.1.23+] The name or number of the current thread's default GUI.;------------------------------------------A_DefaultListView [v1.1.23+] The variable name or HWND of the ListView control upon which the ListView functions operate. If the default GUI lacks a ListView,this variable is blank.;------------------------------------------A_DefaultTreeView[v1.1.23+] The variable name or HWND of the TreeView control upon which the TreeView functions operate. If the default GUI lacks a TreeView,this variable is blank.;------------------------------------------A_GuiThe name or number of the GUI that launched the current thread.This variable is blank unless a Gui control, menu bar item,or event such as GuiClose/GuiEscape launched the current thread.;------------------------------------------A_GuiControlThe name of the variable associated with the GUI control that launched the current thread. If that control lacks an associated variable,;------------------------------------------A_GuiControlinstead contains the first 63 characters of the control's text/caption (thisis most often used to avoid giving each button a variable name).A_GuiControlis blank whenever:1)A_Guiis blank; 2) a GUI menu bar item or event such as GuiClose/GuiEscape launched the current thread; 3) the control lacks an associated variable and has no caption; or4) The control that originally launched the current thread no longer exists (perhaps due to Gui Destroy).;------------------------------------------A_GuiWidth;------------------------------------------A_GuiHeightThese contain the GUI window's width and height when referenced in a GuiSize subroutine. They apply to the window's client area, which is the area excluding title bar, menu bar,and borders.[v1.1.11+]: These values are affected by DPI scaling.;------------------------------------------A_GuiXA_GuiYThese contain the X and Y coordinates for GuiContextMenu and GuiDropFiles events. Coordinates are relative to the upper-left corner of the window.[v1.1.11+]: These values are affected by DPI scaling.;------------------------------------------A_GuiEventorA_GuiControlEventThe type of event that launched the current thread. If the thread was not launched via GUI action,this variable is blank. Otherwise, it contains one of the following strings:

Normal: The event was triggered by a single left-clickor via keystrokes (arrow keys,TAB key,space bar, underlined shortcut key, etc.).This value is also used for menu bar items and the special events such as GuiClose and GuiEscape.

DoubleClick: The event was triggered by a double-click. Note: The first click of the click-pair will still cause a Normal event to be received first.In other words, the subroutine will be launched twice: once for the first clickand again for the second.

;------------------------------------------A_EventInfoContains additional information about the following events:

The OnClipboardChange labelMouse wheel hotkeys (WheelDown/Up/Left/Right)RegisterCallback()GUI events, namely GuiContextMenu, GuiDropFiles, ListBox, ListView, TreeView,and StatusBar. If there is no additional information for an event,A_EventInfocontains0.

;------------------------------------------Note: Unlike variables such as A_ThisHotkey, each thread retains its own value for A_Gui,A_GuiControl,A_GuiX/Y,A_GuiEvent,andA_EventInfo. Therefore, if a thread is interrupted by another, upon being resumed it will still see its original/correct values in these variables.

;------------------------------------------A_ThisMenuItemThe name of the most recently selected custom menu item (blank if none).;------------------------------------------A_ThisMenuThe name of the menu from which A_ThisMenuItem was selected.;------------------------------------------A_ThisMenuItemPosA number indicating the current position of A_ThisMenuItem within A_ThisMenu. The first item in the menu is1, the second is2,and so on. Menu separator lines are counted.This variable is blank if A_ThisMenuItemis blank or no longer exists within A_ThisMenu. It is also blank if A_ThisMenu itself no longer exists.;------------------------------------------A_ThisHotkeyThe most recently executed hotkey or non-auto-replace hotstring (blank if none), e.g. #z.This value will change if the current thread is interrupted by another hotkey, so be sure to copy it into another variable immediately if you need the original value for later use in a subroutine.

When a hotkey is first created -- either by the Hotkey command or a double-colon label in the script -- its key name and the ordering of its modifier symbols becomes the permanent name of that hotkey, shared by all variants of the hotkey.

;------------------------------------------A_PriorHotkeySame as above except for the previous hotkey. It will be blank if none.;------------------------------------------A_PriorKey[v1.1.01+]: The name of the last key which was pressed prior to the most recent key-press or key-release,or blank if no applicable key-press can be found in the key history. All input generated by AutoHotkey scripts is excluded. For this variable to be of use, the keyboard or mouse hook must be installed and key history must be enabled.;------------------------------------------A_TimeSinceThisHotkeyThe number of milliseconds that have elapsed since ;------------------------------------------A_ThisHotkeywas pressed. It will be -1 whenever A_ThisHotkeyis blank.;------------------------------------------A_TimeSincePriorHotkeyThe number of milliseconds that have elapsed since ;------------------------------------------A_PriorHotkey was pressed. It will be -1 whenever A_PriorHotkeyis blank.;------------------------------------------A_EndCharThe ending character that was pressed by the user to trigger the most recent non-auto-replace hotstring. If no ending character was required (due to the * option),this variable will be blank.

;------------------------------------------ComSpec[v1.0.43.08+]Contains the same string as the environment's ComSpec variable (e.g. C:\Windows\system32\cmd.exe). Often used with Run/RunWait. Note: there is no A_ prefix on this variable.;------------------------------------------A_Temp[v1.0.43.09+] The full path and name of the folder designated to hold temporary files (e.g. C:\DOCUME~1\UserName\LOCALS~1\Temp). It is retrieved from one of the following locations (in order):1) the environment variables TMP, TEMP,or USERPROFILE; 2) the Windows directory.;------------------------------------------A_OSTypeThe type of operating system being run. Since AutoHotkey 1.1 only supports NT-based operating systems,thisis always WIN32_NT. Older versions of AutoHotkey return WIN32_WINDOWS when run on Windows 95/98/ME.;------------------------------------------A_OSVersionOne of the following strings, if appropriate: WIN_7 [requires v1.0.90+], WIN_8 [requires v1.1.08+], WIN_8.1 [requires v1.1.15+], WIN_VISTA, WIN_2003, WIN_XP, WIN_2000.

Applying compatibility settings in the AutoHotkey executable or compiled script's properties causes the OS to report a different version number, which is reflected by A_OSVersion.

[v1.1.20+]: If the OS version isnot recognized as one of those listed above, a string in the format "major.minor.build"is returned. For example, the Windows 10 TP is 6.4.9841.

; This example is obsolete as these operating systems are no longer supported.ifA_OSVersionin WIN_NT4,WIN_95,WIN_98,WIN_ME ; Note: No spaces around commas.{MsgBoxThis script requires Windows 2000/XP or later.ExitApp}Select | Download;------------------------------------------A_Is64bitOS[v1.1.08+]:Contains1(true) if the OS is64-bit or0(false) if it is32-bit.;------------------------------------------A_PtrSize[v1.0.90+]:Contains the size of a pointer,in bytes.Thisis either 4(32-bit)or8(64-bit), depending on what type of executable (EXE)is running the script.;------------------------------------------A_LanguageThe system's default language, which is one of these 4-digit codes.;------------------------------------------A_ComputerNameThe name of the computer as seen on the network.;------------------------------------------A_UserNameThe logon name of the user who launched this script.;------------------------------------------A_WinDirThe Windows directory. For example: C:\Windows;------------------------------------------A_ProgramFilesorProgramFilesThe Program Files directory (e.g. C:\Program Files or C:\Program Files (x86)).Thisis usually the same as the ProgramFiles environment variable.

On 64-bit systems (andnot32-bit systems), the following applies:

If the executable (EXE) that is running the script is32-bit,A_ProgramFiles returns the path of the "Program Files (x86)" directory.For32-bit processes, the ProgramW6432 environment variable contains the path of the 64-bit Program Files directory. On Windows 7and later, it is also set for 64-bit processes.The ProgramFiles(x86) environment variable contains the path of the 32-bit Program Files directory.In v1.0.43.08+, the A_ prefix may be omitted, which helps ease the transition to #NoEnv.

;------------------------------------------A_AppData[v1.0.43.09+] The full path and name of the folder containing the current user's application-specific data. For example: C:\Documents and Settings\Username\Application Data;------------------------------------------A_AppDataCommon[v1.0.43.09+] The full path and name of the folder containing the all-users application-specific data.;------------------------------------------A_Desktop The full path and name of the folder containing the current user's desktop files.;------------------------------------------A_DesktopCommon The full path and name of the folder containing the all-users desktop files.;------------------------------------------A_StartMenu The full path and name of the current user's Start Menu folder.;------------------------------------------A_StartMenuCommon The full path and name of the all-users Start Menu folder.;------------------------------------------A_Programs The full path and name of the Programs folder in the current user's Start Menu.;------------------------------------------A_ProgramsCommon The full path and name of the Programs folder in the all-users Start Menu.;------------------------------------------A_Startup The full path and name of the Startup folder in the current user's Start Menu.A_StartupCommon The full path and name of the Startup folder in the all-users Start Menu.;------------------------------------------A_MyDocuments The full path and name of the current user's "My Documents" folder. Unlike most of the similar variables, if the folder is the root of a drive, the final backslash isnot included. For example, it would contain M: rather than M:\;------------------------------------------A_IsAdminIf the current user has admin rights,this variable contains1. Otherwise, it contains0.

To have the script automatically restart itself as admin (or show a prompt to the user requesting admin), add the following at the top of the script:

ifnotA_IsAdmin{Run*RunAs "%A_ScriptFullPath%"; Requires v1.0.92.01+ExitApp}Select | DownloadAlthough this also allows the script to automate windows of programs which are running as admin, it isnot the only way. See the FAQ for details.

The width and height of the primary monitor,in pixels (e.g.1024and768).

To discover the dimensions of other monitors in a multi-monitor system, use SysGet.

To instead discover the width and height of the entire desktop (even if it spans multiple monitors), use the following example:

SysGet, VirtualWidth,78SysGet, VirtualHeight,79Select | DownloadIn addition, use SysGet to discover the work area of a monitor, which can be smaller than the monitor's total area because the taskbar and other registered desktop toolbars are excluded.

;------------------------------------------A_ScreenDPI[v1.1.11+] Number of pixels per logical inch along the screen width.In a system with multiple display monitors,this value is the same for all monitors. On most systems thisis96; it depends on the system's text size (DPI) setting. See also Gui -DPIScale.;------------------------------------------A_IPAddress1through 4 The IP addresses of the first 4 network adapters in the computer.

;------------------------------------------A_CursorThe type of mouse cursor currently being displayed. It will be one of the following words: AppStarting, Arrow, Cross,Help, IBeam, Icon, No, Size, SizeAll, SizeNESW, SizeNS, SizeNWSE, SizeWE, UpArrow, Wait, Unknown. The acronyms used with the size-type cursors are compass directions, e.g. NESW = NorthEast+SouthWest. The hand-shaped cursors (pointing and grabbing) are classified as Unknown.

;------------------------------------------A_CaretXA_CaretYThe current X and Y coordinates of the caret (text insertion point). The coordinates are relative to the active window unless CoordMode is used to make them relative to the entire screen. If there is no active window or the caret position cannot be determined, these variables are blank.

The following script allows you to move the caret around to see its current position displayed in an auto-update tooltip. Note that some windows (e.g. certain versions of MS Word) report the same caret position regardless of its actual position.

;------------------------------------------A_IndexThisis the number of the current loop iteration (a 64-bit integer). For example, the first time the script executes the body of a loop,this variable will contain the number 1. For details see Loop or While-loop.;------------------------------------------A_LoopFileName,etc.Thisand other related variables are valid only inside a file-loop.;------------------------------------------A_LoopRegName,etc.Thisand other related variables are valid only inside a registry-loop.;------------------------------------------A_LoopReadLineSee file-reading loop.;------------------------------------------A_LoopFieldSee parsing loop.

%Var%If a variable is enclosed in percent signs within an expression (e.g.%Var%), whatever that variable containsis assumed to be the name or partial name of another variable (if there is no such variable,%Var% resolves to a blank string).Thisis most commonly used to reference pseudo-array elements such as the following example:

For backward compatibility, command parameters that are documented as "can be an expression" treat an isolated name in percent signs (e.g.%Var%, but not Array%i%) as though the percent signs are absent.This can be avoided by enclosing the reference in parentheses; e.g.Sleep(%Var%).

environment variable:In addition to normal variables,%Var% may resolve to an environment variable, the clipboard,or any reserved/read-only variable. Prior to revision 52,%Var% yielded an empty string in these cases.

++--Pre-and post-increment/decrement. Adds or subtracts 1 from a variable (but in versions prior to 1.0.46, these can be used only by themselves on a line; no other operators may be present). The operator may appear either before or after the variable's name. If it appears before the name, the operation is performed immediately and its result is used by the next operation. For example, Var :=++X increments X immediately and then assigns its value to Var. Conversely, if the operator appears after the variable's name, the operation is performed after the variable is used by the next operation. For example, Var := X++ increments X only after assigning the current value of X to Var. Due to backward compatibility, the operators ++and-- treat blank variables as zero, but only when they are alone on a line; for example, y:=1,++x and MsgBox % ++x both produce a blank result when x is blank.

**Power. Both the baseand the exponent may contain a decimal point. If the exponent is negative, the result will be formatted as a floating point number even if the baseand exponent are both integers. Since **is of higher precedence than unary minus,-2**2is evaluated like -(2**2)and so yields -4. Thus, to raise a literal negative number to a power, enclose it in parentheses such as (-2)**2. Note: A negative base combined with a fractional exponent such as (-2)**0.5isnot supported; it will yield an empty string. But both (-2)**2and(-2)**2.0 are supported.

Unary minus (-):Although it uses the same symbol as the subtract operator, unary minus applies to only a single item or sub-expression as shown twice inthis example:-(3/-x). On a related note, any unary plus signs (+) within an expression are ignored.

Logical-not(!):If the operand is blank or0, the result of applying logical-notis1, which means "true". Otherwise, the result is0(false). For example: !x or !(y and z). Note: The word NOTis synonymous with ! except that ! has a higher precedence.In v1.0.46+, consecutive unary operators such as !!Var are allowed because they are evaluated inright-to-left order.

Bitwise-not(~):This inverts each bit of its operand. If the operand is a floating point value, it is truncated to an integer prior to the calculation. If the operand isbetween0and4294967295(0xffffffff), it will be treated as an unsigned 32-bit value. Otherwise, it is treated as a signed 64-bit value. For example, ~0xf0f evaluates to 0xfffff0f0 (4294963440).

Address (&):&MyVar retrieves the address of MyVar's contents in memory, which is typically used with DllCall structures.&MyVar also disables the caching of binary numbers in that variable, which can slow down its performance if it is ever used for math or numeric comparisons. Caching is re-enabled for a variable whenever its address changes (e.g. via VarSetCapacity()).

Dereference (*):*Expression assumes that Expression resolves to a numeric memory address; it retrieves the byte at that address as a number between0and255(0is always retrieved if the address is0; but any other invalid address must be avoided because it might crash the script). However,NumGet() generally performs much better when retrieving binary numbers.

*///Multiply (*):The result is an integer if both inputs are integers; otherwise, it is a floating point number.

True divide (/):Unlike EnvDiv,true division yields a floating point result even when both inputs are integers. For example,3/2 yields 1.5 rather than 1,and4/2 yields 2.0 rather than 2.

Floor divide (//):The double-slash operator uses high-performance integer division if the two inputs are integers. For example,5//3is1and5//-3is-1. If either of the inputs isin floating point format, floating point division is performed and the result is truncated to the nearest integer to the left. For example,5//3.0is1.0and5.0//-3is-2.0. Although the result of this floating point division is an integer, it is stored in floating point format so that anything else that uses it will see it as such. For modulo, see mod().

Shorthand Multiply (*=)and Divide (/=):operators are a shorthand way to multiply or divide the value in a variable by another value. For example, Var*=2 produces the same result as Var:=Var*2(though the former performs better).

+-Add (+)and subtract (-). On a related note, the +=and-= operators are a shorthand way to increment or decrement a variable. For example, Var+=2 produces the same result as Var:=Var+2(though the former performs better). Similarly, a variable can be increased or decreased by 1 by using Var++, Var--,++Var,or--Var.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

<<>>Bit shiftleft(<<)andright(>>). Example usage: Value1 << Value2. Any floating point input is truncated to an integer prior to the calculation.Shiftleft(<<)is equivalent to multiplying Value1 by "2 to the Value2th power".Shiftright(>>)is equivalent to dividing Value1 by "2 to the Value2th power"and rounding the result to the nearest integer leftward on the number line; for example,-3>>1is-2.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

&^| Bitwise-and(&), bitwise-exclusive-or(^),and bitwise-or(|). Of the three,& has the highest precedence and | has the lowest. Any floating point input is truncated to an integer prior to the calculation.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

.Concatenate. The period (dot) operator is used to combine two items into a single string (there must be at least one space on each side of the period). You may also omit the period to achieve the same result (except where ambiguous such as x -y,or when the item on the right side has a leading ++or--). When the dot is omitted, there should be at least one spacebetween the items to be merged.Example (expression method): Var :="The color is ". FoundColorExample (traditional method): Var = The color is%FoundColor%

Sub-expressions can also be concatenated. For example: Var :="The net price is ". Price *(1- Discount/100).

A line that begins with a period (or any other operator)is automatically appended to the line above it.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

~=Shorthand for RegExMatch. For example,"abc123" ~="\d" sets ErrorLevel to 0and yields 4(the position of the first numeric character). Prior to v1.1.03,this operator had the same precedence as the equal (=) operator and was not fully documented.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

><>=<=Greater (>), less (<), greater-or-equal (>=),and less-or-equal (<=). If either of the inputs isnot a number, both are compared alphabetically (a quoted literal string such as "55"is always considered non-numeric inthis context). The comparison is case sensitive only if StringCaseSense has been turned on. See also: Sort; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

NOTLogical-NOT. Except for its lower precedence,thisis the same as the ! operator. For example,not(x =3or y =3)is the same as !(x =3or y =3).; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

AND&&Both of these are logical-AND. For example: x >3and x <10. To enhance performance, short-circuit evaluation is applied. Also, a line that begins with AND/OR/&&/|| (or any other operator)is automatically appended to the line above it.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

OR|| Both of these are logical-OR. For example: x <=3or x >=10. To enhance performance, short-circuit evaluation is applied.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

?:Ternary operator [v1.0.46+].This operator is a shorthand replacement for the if-else statement. It evaluates the condition on its left side to determine which of its two branches should become its final result. For example, var := x>y ?2:3 stores 2in Var if x is greater than y; otherwise it stores 3. To enhance performance, only the winning branch is evaluated (see short-circuit evaluation).; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

:=+=-=*=/=//=.=|=&=^=>>=<<=

Assign. Performs an operation on the contents of a variable and stores the result back in the same variable (but in versions prior to 1.0.46, these could only be used as the leftmost operator on a line,and only the first five operators were supported). The simplest assignment operator is colon-equals (:=), which stores the result of an expression in a variable. For a description of what the other operators do, see their related entries inthis table. For example, Var //=2 performs floor division to divide Var by 2, then stores the result back in Var. Similarly, Var .="abc"is a shorthand way of writing Var := Var ."abc".

Unlike most other operators, assignments are evaluated from right to left. Consequently, a line such as Var1 := Var2 :=0 first assigns 0 to Var2 then assigns Var2 to Var1.

If an assignment is used as the input for some other operator, its value is the variable itself. For example, the expression (Var+=2)>50istrue if the newly-increased value in Var is greater than 50.This also allows an assignment to be passed ByRef,or its address taken; for example:&(x:="abc").

The precedence of the assignment operators is automatically raised when it would avoid a syntax error or provide more intuitive behavior. For example:not x:=y is evaluated as not(x:=y). Similarly,++Var := X is evaluated as ++(Var := X); and Z>0? X:=2: Y:=2is evaluated as Z>0?(X:=2):(Y:=2).

Known limitations caused by backward compatibility (these may be resolved in a future release):1) When /=is the leftmost operator in an expression and it isnot part of a multi-statement expression, it performs floor division unless one of the inputs is floating point (in all other cases,/= performs true division); 2) Date/time math is supported by +=and-= only when that operator is the leftmost one on a line; 3) The operators +=,-=,and*= treat blank variables as zero, but only when they are alone on a line; for example, y:=1, x+=1and MsgBox % x-=3 both produce a blank result when x is blank.

,Comma (multi-statement)[v1.0.46+]. Commas may be used to write multiple sub-expressions on a single line.Thisis most commonly used to group together multiple assignments or function calls. For example: x:=1, y+=2,++index,func(). Such statements are executed in order from left to right. Note: A line that begins with a comma (or any other operator)is automatically appended to the line above it. See also: comma performance.

In v1.0.46.01+, when a comma is followed immediately by a variable and an equal sign, that equal sign is automatically treated as an assignment (:=). For example, all of the following are assignments: x:=1, y=2, a=b=c.New scripts should not rely on this behavior as it may change. The rule applies only to plain variables andnot double-derefs, so the following contains only one assignment: x:=1,%y%=2; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

These and other built-in math functions are described here.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

func.()[v1.0.90+]: Attempts to call an empty-named method of the object func. By convention,thisis the object's "default" method. If func does not contain an object, the default base object is invoked instead.

[v1.0.95+]: If func contains a function name, the named function is called.; ######################## ####################;---------------------------------------------------------------------------; ######################## ####################

newCreates a new object derived from another object. For example, x :=new y is often equivalent to x :={base: y}.new should be followed by a variable or simple class name of the form GlobalClass.NestedClass,and optionally parameters as in x :=new y(z)(where y is a variable,not a function name). For details, see Custom Objects.

;SetBatchLines is set to 10 ms (the default), a task that uses 20 ms of CPU time will run for ~10 ms, sleep to allow other processes to run, and then run for the final 10 ms. If SetBatchLines is set to 2 ms, a task that uses 20 ms of CPU will sleep ~10 times before completing.

My advice... Leave SetBatchLines at the default of 10 ms. 10 ms is a good default. Most scripts run fine with this setting. If needed, increase SetBatchLines to a higher value (20ms, 50ms, -1, etc.) if one or more of your tasks needs more priority.

As Lower the Value as Slower the Script runs !!!SetBatchLines, 20msSetBatchLines, LineCount

Process, Priority, , A

;L (or Low);B (or BelowNormal), N (or Normal), A (or AboveNormal), H (or High), R (or Realtime). ;Note: Any process not designed to run at Realtime priority might reduce system stability if set to that level.

SetKeyDelay, -1, -1 ; Delay, PressDuration; default = 10;Sets the delay that will occur after each keystroke sent by Send and ControlSend. -1 ;Use -1 for no delay at all and 0 for the smallest possible delay

;Mousesettings ***********************

SetMouseDelay, -1 ;Sets the delay that will occur after each mouse movement or click.;default = 10 - Sets the delay that will occur after each mouse movement or click.

#MaxThreadsBuffer On ;default Off - This is the default behavior. A hotkey press will be ignored whenever that hotkey is already running its maximum number of threads (usually 1, but this can be changed with #MaxThreadsPerHotkey).

ListLines, Off ;ListLines Off/On can be used to selectively omit some lines from the history, which can help prevent the history from filling up too quickly (such as in a loop with many fast iterations). ListLines Off may also improve performance by a few percent.

SetTitleMatchMode fast;Fast: This is the default behavior. Performance may be substantially better than Slow, but certain WinText elements for some types of windows may not be "seen" by the various window commands.;The built-in variables A_TitleMatchMode and A_TitleMatchModeSpeed contain the current settings.

SetWinDelay, 0 ;default = 100, no delay = -1 ;Sets the delay that will occur after each windowing command, such as WinActivate.

SendMode Input ; Recommended for new scripts due to its superior speed and reliability.;Input: Switches to the SendInput method for Send, SendRaw, Click, and MouseMove/Click/Drag. Known limitations:Windows Explorer ignores SendInput's simulation of certain navigational hotkeys such as Alt+LeftArrow. To work around this, use either SendEvent !{Left} or SendInput {Backspace}.

Little Practical Code Example. How to get Variables via Inputbox integrated in a loop. Maybe a bit hard for starters. But good Example for the practical usage.But tell me if its really to hard to understand the Example.

Its a really complex Topic. But i try to Split it up in the Part where it get tricky. I dont want to make you here Crazy how to Create a Gui. [url=viewtopic.php]Create a GUI is quite easy with the help from AutoGui.[/url] If you want to add advanced Options or really need some special things,take a look on the Official Help.Yes, this is really a mess. And i got myself really problems to understand the Interface. I allways took simple Message Boxes. But there come a point where you need more .

I only describe now part from the GUI which has a affect on the Coding. I dont explain how change colors and how to make it look pretty shiny.All Examples are collected in the Script at the End of the Tutorial. So we take a look on a simple Gui.

The Minimum to create Gui1.)Gui, New --> Creates the Gui - one Line2.)One - Gui add, ..... and sooooo much more 3.)Gui, Show --> Displays the Gui - one Line

Sure we have here a bit more, that i can show you a practical usage and some tricks how to handle things.

We take a closer look on the Gui Add controls. The important part is the addressing the Controls to Variables (vTheNameOfTheVariableYouWant) and the gLabels. The Official Help :Storing and Responding to User Input ¶V: Variable. Associates a variable with a control. Immediately after the letter V, specify the name of a global variable (or a ByRef local that points to a global, or a static variable in v1.0.46.01+). For example, specifying vMyEdit would store the control's contents in the variable MyEdit whenever the Gui Submit command is used. If a control is not input-capable -- such as a Text control or GroupBox -- associating a variable with it can still be helpful since that variable's name serves as the control's unique identifier for use with GuiControl, GuiControlGet, and A_GuiControl. Note: Gui Submit does not change the contents of variables of non-input-capable controls (such as Text and GroupBox), nor certain others as documented in their sections (such as ListView and TreeView).

G: Gosub (g-label). Launches a subroutine or function automatically when the user clicks or changes a control. Immediately after the letter G, specify the name of the label to execute. gCancel may be specified to perform an implicit Gui Cancel (but if a label named "Cancel" exists in the script, it will be executed instead). The subroutine may consult the following built-in variables: A_Gui, A_GuiControl, A_GuiEvent, and A_EventInfo.

In the short Versionthe vNameVariable decline the Variable from a Control Field - Cause we need them to return the result iniside Guithe gNameLabel decline the Label from a Control Field - Cause we need them to store the Inputs or run a Subroutine.

In Relation for our Example we are able to trigger 4 different Subroutines. For a good reason. We need them. Normally all InputControls got a gLabel. To transfer the Value and run a Subroutine we need for our TAsk. You can create maybe 10 Edit Fields without one gLabel and only use one Button. But it makes it more flexible. For the start these 2 things are important to know.

Loop{Sleep,250; Slows down the Cycle to 1/4 Second - WE want to see the Mousemovement; First in the Cycle because the Continue will skip it if it stands at the end of the Code !!!

; Call if MouseButton Right or Left Pressed AND the "UserInput" Variable is not Equal nothing ( or is not Empty )If(GetKeyState("RButton","P")ORGetKeyState("LButton","P"))AND( UserInput !=){MsgBox, STOPBreak;STops the Loop }