-- AHK BASICS --

Helpful script writing tricks and HowTo's
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

-- AHK BASICS --

28 Mar 2016, 19:14

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


[list]
Finished Components


[*] Commando-List sorted by Categories
[*] SwissArmy Knife of (AHK) Coding
[*] Structure Template v1.0
[/color][/list]



[list]
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.
[*] Structure Template V.1.1 - Insert Basic GUI - Will be basis for upcoming HowTo´s
[*] Workaround Windoze 10 - Scripts not working - Transparency - ... gimme links plz

[/color][/list]





1.) Basic Structure inside the AHK Script
  • General advices how to code and learn AHK
  • STRUCTURE TEMPLATE to get things in the right order
  • Some words about some important Script Environment Settings
  • The Official Tutorial / FAQ
  • Trial and Error


SwissArmy Knife of (AHK) Coding
  • How to use "=" and ":=" right
  • Variables and the % Usage
  • Functions - the Magic Expendable
Upcoming Tutorials
LoopTimer with If calls - Tutorial - Loops / Timer, continue,break, usage from Operators, Buildin-Variables
Gui - Tutorial - MsgBox-Inputbox, , Create Gui, Input/Output Handling (controlget,control,etc...), gLabel, Gui 2 data.ini transfer
Windows Environment - Open Windows/Programms - Read/ Get Information out of a window/control - Write / Edit a window
Input-Output - Hotkey Mouse and more Inputs,
Last edited by HinkerLoden on 03 Apr 2016, 15:44, edited 4 times in total.
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: -- AHK BASICS --

28 Mar 2016, 19:15

General advices how to code and learn AHK


1.) Get a Editor with Texthiglightning
Notepad++ 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.

    STRUCTURE TEMPLATE v1.0
    StructureTemplate.ahk
    STRUCTURE TEMPLATE v1.0
    (5.09 KiB) Downloaded 608 times

    Code: Select all

    ;************************************************
    ; AHK _ SCRIPT STRUCTURE TEMPLATE v1.0
    ; by HinkerLoden
    ; 25/03/2016 
    ;************************************************
    
    ;************************************************
    ;Script Global Settings
    ;************************************************
    
    #NoEnv						; Clear All Systemvariables 
    #Persistent 				;Keeps a script permanently running until ExitApp execute
    
    #SingleInstance force		;The word FORCE skips the dialog box and replaces the old instance automatically, which is similar in effect to the Reload command.
    
    ;************************************************
    ;Performance PARAMETERS - if you need speed 
    ;************************************************
    ;SetBatchLines, -1   		
    ;Process, Priority, , L  ;A  - Max Speed
    ;************************************************
    ; Input PARAMETERS
    ;************************************************
    SendMode Input
    SetKeyDelay, 10, 10   ; for speed -1, -1, 
    
    SetMouseDelay, 25		;0 recommend -1 for max speed 
    SetDefaultMouseSpeed, 0		;0-100 
    ;************************************************
    ;History Protocols 
    ;Switch setting for more Speed 
    ;************************************************
    #KeyHistory 1		;  0 - No Keyhistory 
    ListLines  On  		; Off  - for more speed 
    ;************************************************
    ;Window detection
    ;************************************************
    SetTitleMatchMode, 2
    SetTitleMatchMode Fast	;slow detect hidden windows
    
    SetWinDelay, 200  		;0 - for more speed   
    ;i double the standard settings to be on the save side 
    
    ;#######################				#######################
    ; Script Parameter
    ;#######################				#######################
    
    SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.
    
    ;#Include %A_ScriptDir%\YourLibrarys2integrate.ahk
    
    CoordMode, Pixel, Screen
    CoordMode, Mouse, Screen
    WinMinimizeAll
    
    ;#######################				#######################
    ; Try to avoid pure numbers inside the code - adress all Vars here
    ;=============================================================
    ; 						Variable Section
    ;=============================================================
    ;#######################				#######################
    ;global
    ;-------------------------------
    ;static
    ;-------------------------------
    
    ;===============================  TimerVars
    CycleTimer1=500
    CycleTimer2=500
    
    Timer1Status=0
    Timer2Status=0
    
    
    
    ;#######################				#######################
    ;=============================================================
    ; 						CODE 
    ;=============================================================
    ;#######################				#######################
    
     
     
    ;=============================================================
    ; 						GUI 
    ;=============================================================
    ; Template
    ;=============================================================
    
    ;#######################				#######################
    ; GUI Template
    ;=============================================================
    
    gui, font, s14, Verdana
    Gui Add, Text, vText x40 y24 w350 h40 +0x200, Text
    Gui Add, Edit, vedit gedit x40 y72 w350 h40, Edit
    ;----------
    Gui Add, Button, vButton1 gButton1 x40 y152 w132 h44,  Button1
    Gui Add, Button, vButton2 gButton2 x272 y152 w132 h44, Button2
    ;----------
    Gui Add, Button, gExit x72 y272 w352 h76 cRed , -- E X I T --
    
    Gui Show, w480 h380, Window
    Return
    
    
    ;=============================================================
    ; 						gLabel 
    ;=============================================================
    ; Button1 - Start-Stop-Timer
    ;=============================================================
    Button1:
    If Timer1Status=1
    	{
    	SetTimer, Timer1, Off
    	Timer1Status=0
    	}
    SetTimer, Timer1, %CycleTimer1%
    Timer1Status=1
    Return
    
    
    ; Button2 - Start-Stop-Timer
    ;=============================================================
    Button2:
    
    If Timer2Status=1
    	{
    	SetTimer, Timer2, Off
    	Timer2Status=0
    	}
    SetTimer, Timer2, %CycleTimer2%
    Timer2Status=1
    Return
    
    ; gEdit
    ;=============================================================
    Edit:
    
    
    return
    ;=============================================================
    ; 						TIMER 
    ;=============================================================
    
    ; Timer1
    ;=============================================================
    Timer1:
    
    
    
    return
    
    ; Timer2
    ;=============================================================
    Timer2:
     
    return
     
    ;=============================================================
    ; 						HOTKEYS 
    ;=============================================================
    
    ; Hotkey1
    ;=============================================================
    
    ; Hotkey2
    ;=============================================================
    
    
    
    
    ; Exit 
    ;=============================================================
    Exit:
    ^!x::  ; Hotkey ALT+x.
    GuiEscape:
    GuiClose:
     ExitApp
    
    
     
    ;#######################				#######################
    ;=============================================================
    ; 						FUNCTIONS 
    ;=============================================================
    ;#######################				#######################
    


    Some words about some important Script Environment Settings

    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.


    The Official Tutorial / FAQ


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

    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.
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: -- AHK BASICS --

28 Mar 2016, 19:40

PLACEHOLDER
Last edited by HinkerLoden on 04 Apr 2016, 03:39, edited 1 time in total.
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: -- AHK BASICS --

29 Mar 2016, 05:11

SwissArmy Knife of (AHK) Coding


4 Steps of Coding


INPUT ---> COMPARE ---> TRANSFER (STORE) --> OUTPUT

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.

INPUTs CAN BE DONE
Mouse, Key, running Programs / Tasks, Window settings (Size, Position, Title, etc.,), GUI, OS Environment (Time, Version)
Every INPUTS ends into a Value what assigned to a Variable. Quite Simple. But Keep them separate in your Script.

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.

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

How to use "=" and ":=" right


Official Tutorial - Variables

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

Usage: Store a Value/String into the variable .

Code: Select all

Example:
Variable_Integer = 123  
Variable_String  = Some Text to store in Variable

USE OF := ( Expressions )

Content Minimum one Operator and Minimum 2 Variable
OutPutVariable := 1_Variable + 2_Variable

Important Notes:
Text(strings) allways use in "quotation marks"
Never Use %Variable% here (Can do - but dont do this at the start !)
Never Use pure Numbers here


Special case - Transfer Variable

Usage:
Operations (Mathematic or Logical)
Tranfer Value into another Value
Combine Values with each other (Text and Numbers )


Code: Select all

VarOutput := Input_Var1 + Input_Var2 				;Operation Mathematic
	
VarOutput := VarInput							;Tranfer Value into another Value

VarOutput12:= 	Input_Var1 . Input_Var2 				;the dot combine/merge  them together

Now a mixed Example

;------------------------------

Code: Select all


Input_Var1 	= 	2
Input_VarText 	= 	Input Variables 

VarOutput	:= "In brackets you can get the Text between the "  "`n`n" . Input_Var1  . Input_VarText . "`n`n" . "The dot merge it together" 

MsgBox % VarOutput
return

Last edited by HinkerLoden on 29 Mar 2016, 12:37, edited 1 time in total.
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: -- AHK BASICS --

29 Mar 2016, 12:24

Some more Placeholder - Maybe Software List here

Texteditors

GUI Creator

Librarys

Usefull AHK Coding Tools
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: -- AHK BASICS --

29 Mar 2016, 16:40


https://autohotkey.com/docs/Variables.htm

Variables and the % Usage


I integrate here a the Sample from the Official Tutorial

a. When to use percents

One of the most common issues with AutoHotkey involving variables is when to use the percent signs (%). Hopefully this will clear some confusion.

When to use %'s:
  • When you are using Commands (see above) you use percent signs.
    -- Except when the parameter is OutputVar or InputVar.
  • When you are assigning a variable to a value using a traditional mode (an equal sign with no symbol in front of it). Example VarOutput = %VarInput%
When not to use %'s:
  • In parameters that are input or output variables, For example: StringLen, OutputVar, InputVar
  • On the left side of an assignment: Var = 123abc
  • On the left side of traditional (non-expression) if-statements: If Var1 < %Var2%
  • Everywhere in expressions. For example:
    If (Var1 != Var2)
    Var1 := Var2 + 100

Force an expression:

From the Official Help
An 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:

Code: Select all

FileAppend, % MyArray[i], My File.txt
FileAppend, % MyPseudoArray%i%, My File.txt
MsgBox % "The variable MyVar contains " . MyVar . "."
Loop % Iterations + 1
WinSet, Transparent, % X + 100
Control, Choose, % CurrentSelection - 1
I implement some Examples in the Upcoming Functions

Functions - the Magic Expendable

Here are the Notes for the Official Help. Official Notes to Functions

USE FUNCTIONS WHENEVER YOU CAN
START USING THEM AS SOON AS POSSIBLE

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 position
2.) Get the Color from the active Cursor position
3.) Compare with 3 Colors If Found the Color
4.) If Found - Wait between 1-2 seconds
5.) 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.

Code: Select all

;************************************************
; AHK _ SCRIPT - Introducion Functions
; by HinkerLoden
; 25/03/2016 
;************************************************


;************************************************
;Script Global Settings
;************************************************

#NoEnv						; Clear All Systemvariables 
#Persistent 				;Keeps a script permanently running until ExitApp execute

#SingleInstance force		;The word FORCE skips the dialog box and replaces the old instance automatically, which is similar in effect to the Reload command.

;************************************************
;Performance PARAMETERS - if you need speed 
;************************************************
;SetBatchLines, -1   		
;Process, Priority, , L  ;A  - Max Speed
;************************************************
; Input PARAMETERS
;************************************************
SendMode Input
SetKeyDelay, 10, 10   ; for speed -1, -1, 

SetMouseDelay, 25		;0 recommend -1 for max speed 
SetDefaultMouseSpeed, 0		;0-100 
;************************************************
;History Protocols 
;Switch setting for more Speed 
;************************************************
#KeyHistory 1		;  0 - No Keyhistory 
ListLines  On  		; Off  - for more speed 
;************************************************
;Window detection
;************************************************
SetTitleMatchMode, 2
SetTitleMatchMode Fast	;slow detect hidden windows

SetWinDelay, 200  		;0 - for more speed   
;i double the standard settings to be on the save side 

;#######################				#######################
; Script Parameter
;#######################				#######################

SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.

;#Include %A_ScriptDir%\YourLibrarys2integrate.ahk

CoordMode, Pixel, Screen
CoordMode, Mouse, Screen
WinMinimizeAll

;#######################				#######################

;=============================================================
; 						Variable Section
;=============================================================
;global
;-------------------------------
;static
;-------------------------------

; Try to avoid pure numbers inside the code - adress all Vars here


Color_Pink		=	0xFF00FF
Color_White		=	0xFFFFFF
Color_Black		=	0x000000

MoveX			=	50
MoveX			=	50

WaitMin 		= 	1000
WaitMax			=   2000

;#######################				#######################
;=============================================================
; 						CODE 
;=============================================================
;#######################				#######################



F11::

;MouseMove, Coord_X2 ,Coord_Y2	 ; uncommend for testing 
;Sleep, % Sleeper


MouseGetPos, X_pos,Y_pos 					;	Get Mouse Coordinates
PixelGetColor, Color_OutputVar,X_pos, Y_pos	;	Get the Color from Mouseposition



; Comparison 

If (Color_OutputVar = Color_Pink) 
	{
	Random, Wait , WaitMin, WaitMax
	Sleep , % Wait
	
	MouseMove, MovementFoundX, MovementFoundY, ,R		
	MsgBox, Pink was Found Color:_%Color_OutputVar%		
	}
If (Color_OutputVar = Color_White)
	{
	Random, Wait , WaitMin, WaitMax
	Sleep , % Wait
	MouseMove, MovementFoundX, MovementFoundY, ,R
	MsgBox, White was Found Color:_%Color_OutputVar%		
	}

If (Color_OutputVar = Color_Black)
	{
	Random, Wait , WaitMin, WaitMax
	Sleep , % Wait
	MouseMove, MovementFoundX, MovementFoundY,, R
	MsgBox, Black was Found Color:_%Color_OutputVar%	
	}

MsgBox % Color_OutputVar "`n`n" "x_" X_pos "`n"	"y_" Y_pos   ;Example Forced Expression
return


Structure from a Function

You have 2 parts :
1.) The Function Call inside the Code - Without Braces (only Bracktes)

2.) The Function at end of the Code - Braces include the Code


FunctionName ()

{
X = 5 ;Decline Vars - Cause all Variables are empty inside the Function
Y = 2

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 -1x
2.) Get the Color from the active Cursor position - 1x
3.) Compare with 3 Colors If Found the Color -3x
4.) If Found - Wait between 1-2 seconds -3x
5.) Move the Cursor relative from the Position if the Search was sucessfull 50pixel Down and 50pixel Right. 3x
6.) 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 Function
Read 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 -3x
5.) 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.


Code: Select all


;=============================================================
; 						F 12 
;=============================================================

F12::


FunctionsOutput:=F_Sleep_and_Move()

MsgBox, % FunctionsOutput "_" F_Sleep_and_Move() 	;Example Forced Expression

/*
%FunctionsOutput% not the same as %F_Sleep_and_Move()% because the Functions runs / Excectuted again. You notice it because the Mouse jumps/move twice !

*/

return


;#######################				#######################
;=============================================================
; 						F U N C T I O N S  
;=============================================================
;#######################				#######################


F_Sleep_and_Move()			;Output Sleep Time

{
;All inside the Braces Belong to the Function

 
; () is empty - no variable is send outside of the function into it - so i have to decline them into the function 
WaitMin 		= 	1000
WaitMax			=  	2000
 
MoveX	=	50			;Negative change the Direction 
MoveY 	= 	50

Random, WaitTime , WaitMin, WaitMax
Sleep, % WaitTime

MouseMove, MoveX, MoveY, ,R

return WaitTime   ; Output Value is the Variable behind return !
}





Function with Input Variables


Structure:

F_Name (Input1,Input2)
{
Output := Input1 + Input2
return Output
}


Try to Avoid MsgBox or other Visual Outputs inside Functions. It Stops the Script. For testing or debugging you a MsgBox is a good way to locate Issues inside the code.

Try to avoid Number inside Function. Use Imputs Variables to get the Script more Flexible

What i want to show in the next Function:
  • Function can used inside other Functions
  • String input the need quotation marks "Your String inside quotaion marks"


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, WaitMax
Sleep, % 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 -1x
2.) Get the Color from the active Cursor position - 1x
3.) Compare with 3 Colors If Found the Color -3x

4.) + 5. ) F_Sleep_and_Move(MoveX,MoveY,WaitMin,WaitMax)
6.) Output the WaitTime -3x Via Message Box

So we add 2 new Functions to the code and implement it
F_CompareCoord_Color(X,Y,Colorinput,Colorname)

{
MouseGetPos, X_Pos,Y_Pos ; Get Mouse Coordinates
PixelGetColor, Color_OutputVar,X, Y ; Get the Color from Mouseposition

If ((X=X_Pos) & (Y_pos=Y)) ;Positioncheck
Status=found

; Comparison

If (Color_OutputVar = Colorinput) & (PinkPostionStatus=found)
{
F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax)

return Colorname
;MsgBox, Colorname was Found Color:_%Color_OutputVar%
}

return NotFound
}



Code: Select all


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

{

Random, Wait , WaitMin, WaitMax
Sleep, % Wait

MouseMove, MoveX, MoveY, ,R

return Wait   ; Output Value is the Variable behind return !

}

F_Compare_Color(Colorinput,Colorname)

{
MouseGetPos, X_Pos,Y_Pos 					;	Get Mouse Coordinates
PixelGetColor, Color_OutputVar,X_Pos, Y_Pos	;	Get the Color from Mouseposition


; Comparison 

If (Color_OutputVar = Colorinput) 
	{
	; F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax) ;Possible - Use function in Function 
	
	return Colorname
	;MsgBox, Colorname was Found Color:_%Color_OutputVar%	
	}	
	
return 0
}



[hr][/hr]


So the code shrinked a bit . 

[code=autohotkey file=F12.ahk]
F12::
StatusPink := 	F_Compare_Color(Color_Pink,"Pink")
StatusWhite :=	F_Compare_Color(Color_White,"White")
StatusBlack :=	F_Compare_Color(Color_Black,"Black")

If (StatusPink OR StatusWhite OR StatusBlack != 0)  ;
	WaitTime := F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax)



MsgBox, % StatusPink "_" StatusWhite "_" StatusBlack "`n`n" Waittime	;Example Forced Expression


Function with Output Variables


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

New Function :
F_Compare_Color2(Colorinput,Colorname,ByRef CursorX,ByRef CursorY,ByRef CursorColor)

{
MouseGetPos, CursorX,CursorY ; Get Mouse Coordinates
PixelGetColor, CursorColor,CursorX, CursorY ; Get the Color from Mouseposition


; Comparison

If (CursorColor = Colorinput)
{
; F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax) ;Possible - Use function in Function

return Colorname
;MsgBox, Colorname was Found Color:_%CursorColor%
}

return 0
}

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 )

So here the Final Complete Code

Code: Select all

;************************************************
; AHK _ SCRIPT - Introducion Functions
; by HinkerLoden
; 25/03/2016 
;************************************************


;************************************************
;Script Global Settings
;************************************************

#NoEnv						; Clear All Systemvariables 
#Persistent 				;Keeps a script permanently running until ExitApp execute

#SingleInstance force		;The word FORCE skips the dialog box and replaces the old instance automatically, which is similar in effect to the Reload command.

;************************************************
;Performance PARAMETERS - if you need speed 
;************************************************
;SetBatchLines, -1   		
;Process, Priority, , L  ;A  - Max Speed
;************************************************
; Input PARAMETERS
;************************************************
SendMode Input
SetKeyDelay, 10, 10   ; for speed -1, -1, 

SetMouseDelay, 25		;0 recommend -1 for max speed 
SetDefaultMouseSpeed, 0		;0-100 
;************************************************
;History Protocols 
;Switch setting for more Speed 
;************************************************
#KeyHistory 1		;  0 - No Keyhistory 
ListLines  On  		; Off  - for more speed 
;************************************************
;Window detection
;************************************************
SetTitleMatchMode, 2
SetTitleMatchMode Fast	;slow detect hidden windows

SetWinDelay, 200  		;0 - for more speed   
;i double the standard settings to be on the save side 

;#######################				#######################
; Script Parameter
;#######################				#######################

SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.

;#Include %A_ScriptDir%\YourLibrarys2integrate.ahk

CoordMode, Pixel, Screen
CoordMode, Mouse, Screen
WinMinimizeAll

;#######################				#######################

;=============================================================
; 						Variable Section
;=============================================================
;global
;-------------------------------
;static
;-------------------------------

; Try to avoid pure numbers inside the code - adress all Vars here


Color_Pink		=	0xFF00FF
Color_White		=	0xFFFFFF
Color_Black		=	0x000000

MoveX	=	50
MoveY	=	50

WaitMin 		= 	1000
WaitMax			=   2000

;#######################				#######################
;=============================================================
; 						CODE 
;=============================================================
;#######################				#######################


F11::

;MouseMove, Coord_X2 ,Coord_Y2	 ; uncommend for testing 
;Sleep, % Sleeper


MouseGetPos, X_pos,Y_pos 					;	Get Mouse Coordinates
PixelGetColor, Color_OutputVar,X_pos, Y_pos	;	Get the Color from Mouseposition



; Comparison 

If (Color_OutputVar = Color_Pink) 
	{
	Random, Wait , WaitMin, WaitMax
	Sleep , % Wait
	
	MouseMove, MovementFoundX, MovementFoundY, ,R		
	MsgBox, Pink was Found Color:_%Color_OutputVar%		
	}
If (Color_OutputVar = Color_White)
	{
	Random, Wait , WaitMin, WaitMax
	Sleep , % Wait
	MouseMove, MovementFoundX, MovementFoundY, ,R
	MsgBox, White was Found Color:_%Color_OutputVar%		
	}

If (Color_OutputVar = Color_Black)
	{
	Random, Wait , WaitMin, WaitMax
	Sleep , % Wait
	MouseMove, MovementFoundX, MovementFoundY,, R
	MsgBox, Black was Found Color:_%Color_OutputVar%	
	}

MsgBox % Color_OutputVar "`n`n" "x_" X_pos "`n"	"y_" Y_pos   ;Example Forced Expression
return

;=============================================================
; 						F 12 
;=============================================================

F12::
StatusPink := F_Compare_Color2(Color_Pink,"Pink",		CursorX,CursorY,CursorColor)
StatusWhite := F_Compare_Color2(Color_White,"White",	CursorX,CursorY,CursorColor)
StatusBlack := F_Compare_Color2(Color_Black,"Black",	CursorX,CursorY,CursorColor)


If (StatusPink OR StatusWhite OR StatusBlack != 0)  ;
	{
	WaitTime := F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax)
	MsgBox, % StatusPink "_" StatusWhite "_" StatusBlack "`n`n" Waittime "`n`n" 	;Example Forced Expression
	}

If (StatusPink + StatusWhite + StatusBlack = 0 ) 
	MsgBox, % "Nothing Found " "`n`n" "X_" CursorX "`nX_"CursorY "`n`n" CursorColor   ;Different Quotations here 
	


/*
%FunctionsOutput% not the same as %F_Sleep_and_Move()% because the Functions runs / Excectuted again. You notice it because the Mouse jumps/move twice !

*/

return


;#######################				#######################
;=============================================================
; 						F U N C T I O N S  
;=============================================================
;#######################				#######################


F_Sleep_and_Move()			;Output Sleep Time

{
;All inside the Braces Belong to the Function

 
; () is empty - no variable is send outside of the function into it - so i have to decline them into the function 
WaitMin 		= 	1000
WaitMax			=  	2000
 
MoveX	=	50			;Negative change the Direction 
MoveY 	= 	50

Random, WaitTime , WaitMin, WaitMax
Sleep, % WaitTime

MouseMove, MoveX, MoveY, ,R

return WaitTime   ; Output Value is the Variable behind return !
}


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

{

Random, Wait , WaitMin, WaitMax
Sleep, % Wait

MouseMove, MoveX, MoveY, ,R

return Wait   ; Output Value is the Variable behind return !

}

F_Compare_Color(Colorinput,Colorname)

{
MouseGetPos, X_Pos,Y_Pos 					;	Get Mouse Coordinates
PixelGetColor, Color_OutputVar,X_Pos, Y_Pos	;	Get the Color from Mouseposition


; Comparison 

If (Color_OutputVar = Colorinput) 
	{
	; F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax) ;Possible - Use function in Function 
	
	return Colorname
	;MsgBox, Colorname was Found Color:_%Color_OutputVar%	
	}	
	
return 0
}


F_Compare_Color2(Colorinput,Colorname,ByRef CursorX,ByRef CursorY,ByRef CursorColor)

{
MouseGetPos, CursorX,CursorY 					;	Get Mouse Coordinates
PixelGetColor, CursorColor,CursorX, CursorY	;	Get the Color from Mouseposition


; Comparison 

If (CursorColor = Colorinput) 
	{
	; F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax) ;Possible - Use function in Function 
	
	return Colorname
	;MsgBox, Colorname was Found Color:_%CursorColor%	
	}	

return 0
}


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.

a.) Add more 5 Colors

Green beige = 0xCCC58F
Beige = 0xD1BC8A
Sand yellow =0xD2B773
Signal yellow =0xF7BA0B
Golden yellow = 0xE2B007

b.) add different Movements

White -> Move 6x 10 Pixel X+Y
Black -> Move 9x 5Pixel X+Y
Last edited by HinkerLoden on 31 Mar 2016, 06:03, edited 2 times in total.
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: -- AHK BASICS --

29 Mar 2016, 22:18

Commando-list.ahk
(26.68 KiB) Downloaded 441 times


Commando Index sorted by Categories

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.

Code: Select all



;	################# 		Flow of Control
;	#################		Syntax  
#Include/#IncludeAgain
SetWorkingDir 			Changes the script's current working directory.


Var = value Assigns the specified value to a variable. 
Var := expression Evaluates an expression and stores the result in a variable.

Gosub 			Jumps to the specified label and continues execution until Return is encountered.
Goto 			Jumps to the specified label and continues execution. 		


SetTimer 		Causes a subroutine to be launched automatically and repeatedly at a specified time interval.
Sleep 			Waits the specified amount of time before continuing. 


{ ... } (block)

Break
Continue
Else
Until

While-loop
For-loop

Return	Returns from a subroutine to which execution had previously jumped via function-call, 


Reload 				Replaces the currently running instance of the script with a new one
ExitApp 		Terminates the script unconditionally. 

;	#################			CALLS


{ ... } (Block) A pair of braces denotes a block. Blocks are typically used with functions,
 Else, Loop, While-loop, and IF-commands.
 
Break Exits (terminates) a loop. Valid inside any kind of loop.

{ ... } / Object() 	Creates a scriptable associative array
[ ... ] / Array() 	Creates a scriptable associative array with integer keys.

		









;	#################			Thread / process Handling  

Pause 				Pauses the script's current thread.

Exit Exits the current thread or (if the script is not persistent and contains 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

Loop (normal) 			Perform a series of commands repeatedly: either the specified number of times or until break is 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 >= Value
IfInString / 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. 

Edit 				Opens the current script for editing in the associated editor. 

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.



ClipWait 			Waits until the clipboard contains data.
OutputDebug 		Sends a string to the debugger (if any) for display.



RegisterCallback() 	Creates a machine-code address that when called, redirects the call to a function in the script
DllCall() 			Calls a function inside a DLL, such as a standard Windows API function. 


func() 				Retrieves a reference to a function. 

FormatTime 			Transforms a YYYYMMDDHH24MISS timestamp into the specified date/time format. 

SysGet 				Retrieves screen resolution, multi-monitor info, dimensions of system objects, and other system properties.
Shutdown 			Shuts down, restarts, or logs off the system. 


;	#################			 Global Script modifiers
; i dont know how to call it

SendMode 		Makes Send synonymous with SendInput or SendPlay rather than the default (SendEvent). Also makes Click and MouseMove/Click/Drag use the specified method. 

BlockInput 		Disables or enables the user's ability to interact with the computer via keyboard and mouse. 


;	#################			
;	#################			


;	#################			String Commandos
StringCaseSense 	Determines whether string comparisons are case sensitive (default is "not case sensitive"). 
AutoTrim 			Determines whether Var1 = %Var2% statements omit spaces and tabs from the beginning and end of Var2.
 
Trim 				Trims certain characters from the beginning and/or end of a string.
InStr() 			Searches for a given occurrence of a string, from the left or 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. 

StringLower 		Converts a string to lowercase.
StringUpper 		Converts a string to uppercase.

StringLen / StrLen()Retrieves the count of how many characters are in a string. 
StringGetPos / InStr()	Retrieves the position of the specified substring within a string. 

; editing
StringReplace 		Replaces the specified substring with a new string.
StringSplit 		Separates a string into an array of substrings using the specified delimiters. 

StrPut() / StrGet() Copies a string to or from a memory address, optional converting it between code pages.

 
;	#################			WINDOW

SetControlDelay 	Sets the delay that will occur after each control-modifying command.

SetTitleMatchMode 	Sets the matching behavior of the WinTitle parameter in commands such as WinWait. 
SetWinDelay 		Sets the delay that will occur after each windowing command, such as WinActivate. 


IfWinActive / IfWinNotActive Checks if the specified window exists and is currently active (foremost). 
IfWinExist / IfWinNotExist Checks if the specified window exists.

;Open / Close 
 
 
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. 

WinWait 			Waits until the specified window exists.
WinWaitActive 		Waits until the specified window is active
WinWaitClose 		Waits until the specified window does not exist. 
WinWaitNotActive 	Waits until the specified window is not active. 

WinClose 			Closes the specified window.
WinHide 			Hides the specified window. 
WinKill 			Forces the specified window to close. 

WinExist() 			Returns the Unique ID (HWND) of the first matching window. 


; WINDOW INFORMATION
WinGet 				Retrieves the specified window's unique ID, process ID, process name, or a list of its controls. It can also retrieve a list of all windows matching the specified criteria. 


WinGetActiveStats 	Combines the functions of WinGetActiveTitle and WinGetPos into one command.

WinGetActiveTitle 	Retrieves the title of the active window.
WinGetClass 		Retrieves the specified window's class name. 


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. 


; Resizing
WinMove 			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

WinMinimizeAll 
WinRestore 			Unminimizes or unmaximizes the specified window if it is minimized or maximized.

; Set new Window Setting 

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. 


 
 ;	#################			Gui
Gui 				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 or control.

;		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 control in a GUI window
ControlSend / ControlSendRaw Sends simulated keystrokes to a window or control. 

ControlGet 			Retrieves various types of information about a control.
ControlGetFocus 	Retrieves which control of the target window has input focus, if any. 
ControlGetPos 		Retrieves the position and size of a control. 
ControlGetText 		Retrieves text from a control. 

; 	Change / modifie Gui Controls
GuiControl 			Makes a variety of changes to a control in a GUI window.

Control 			Makes a variety of changes to a control. 

ControlClick 		Sends a mouse button or mouse wheel event to a control. 
ControlFocus 		Sets input focus to a given control on a window. 
ControlMove 		Moves or resizes a control. 

ControlSetText 		Changes the text of a control. 
 

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 by
GroupActivate or 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 not in 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. 

SplashImage 		Creates or updates a window containing a JPG, GIF, or BMP image. SplashTextOn Creates a customizable text popup window.
SplashTextOff 		Closes the above window.

;	#################			Reg / INI / File

RegExMatch() 		Determines whether a string contains a pattern (regular expression). 
RegExReplace() 		Replaces occurrences of a pattern (regular expression) inside a string. 

RegDelete 			Deletes a subkey or value from the registry
RegRead 			Reads a value from the registry.
RegWrite 			Writes a value to the registry.

IniDelete 			Deletes a value from a standard format .ini file. 
IniRead 			Reads a value from a standard format .ini file.
IniWrite 			Writes a value to a standard format .ini file.

FileCopy 			Copies one or more files.
FileCopyDir 		Copies a folder along with all its sub-folders and files (similar to xcopy). 
FileCreateDir 		Creates a folder. 

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. 

FileDelete 			Deletes one or more files. 
FileEncoding 		Sets the default encoding for FileRead, FileReadLine, Loop Read, FileAppend, and FileOpen.
See also: Text Encodings 

FileGetAttrib 		Reports whether a file or folder is read-only, hidden, etc. 

FileGetSize 		Retrieves the size of a file.
FileGetTime 		Retrieves the datetime stamp of a file or folder. 
FileGetVersion 		Retrieves the version of a file.

FileMove 			Moves or renames one or more files.
FileMoveDir 		Moves a folder along with all its sub-folders and files. It can also rename a folder. 
FileRemoveDir 		Deletes a folder. 

FileOpen 			Provides object-oriented file I/O.
FileRead 			Reads a file's contents into a variable. 
FileReadLine 		Reads the specified line from a file and stores the text in a variable.
 
FileRecycle 		Sends a file or directory to the recycle bin, if possible.
FileRecycleEmpty 	Empties the recycle bin.

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.

; other
UrlDownloadToFile 	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 += Value
EnvDiv 		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. 

SetEnv 		(Var = Value) Assigns the specified value to a variable. 

VarSetCapacity() Enlarges a variable's holding capacity or frees its memory. Normally, this is necessary only for unusual circumstances such as DllCall.

;	#################			Pixel 

CoordMode 		Sets coordinate mode for various commands to be relative to either the active window or the screen.
 
PixelGetColor 	Retrieves the color of the pixel at the specified x,y coordinates. 
PixelSearch 	Searches a region of the screen for a pixel of the specified color. 

ImageSearch 	Searches a region of the screen for an image.




;	#################			 Keys 

Send / SendRaw / SendInput / SendPlay Sends simulated keystrokes and mouse clicks to the active window.


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 or not 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 or control and waits for acknowledgement.

SetStoreCapslockMode Whether to restore the state of CapsLock after a Send. 


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 is down or up. 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 or click. 
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 in Click and 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 and control 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 of
Run and RunWait. 
RunWait Runs an external program and waits until it finishes.



;	#################			Sound
SoundBeep 			Emits a tone from the PC speaker.
SoundPlay 			Plays a sound, video, or other supported file type.

SoundGet 			Retrieves various settings from a sound device (master mute, master volume, etc.)
SoundSet 			Changes various settings of a sound device (master mute, master volume, etc.) 

SoundGetWaveVolume 	Retrieves the wave output volume from a sound device. 
SoundSetWaveVolume 	Changes the wave output volume for a sound device. 
 
 ;	#################			COM 
 
 ComObjActive() 	Retrieves a registered COM object.
 ComObjArray() 		Creates a SAFEARRAY for use with COM
 ComObjConnect() 	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. 
 

;	#################			MATHEMATIC 


Transform 			Performs miscellaneous math functions, bitwise operations, and tasks such as ASCII/Unicode conversion. 

SetFormat 			Sets the format of integers and floating point numbers generated by math operations. 

;special cases
Random 				Generates a pseudo-random number.
Mod() 				Modulo. Returns the remainder when Dividend is divided by Divisor.


; Calculating

Abs() 				Returns the absolute value of Number.

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 or 0, 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). 


Log() 				Returns the logarithm (base 10) of Number.
Ln() 				Returns the natural logarithm (base e) of Number.

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. 


#ClipboardTimeout 		Changes how long the script keeps trying to access the clipboard when the first attempt fails.

; ## 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, and SHIFT.
#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.

#MaxHotkeysPerInterval 	Along with 
#HotkeyInterval, 		specifies the rate of hotkey activations beyond which a warning dialog will be displayed. 

#MaxMem 				Sets the maximum capacity of each variable to the specified number of megabytes.

#MaxThreads 			Sets the maximum number of simultaneous threads. 
#MaxThreadsBuffer 		Causes some or all hotkeys to buffer rather than ignore keypresses when their
#MaxThreadsPerHotkey 	limit has been reached.
#MaxThreadsPerHotkey 	Sets the maximum number of simultaneous threads per hotkey or hotstring.
#MenuMaskKey 			Changes which key is used to mask Win or Alt keyup events. 

#UseHook 				Forces the use of the hook to implement all or some keyboard hotkeys. #Warn Enables or disables warnings for selected conditions that may be indicative of developer errors.

#WinActivateForce 		Skips the gentle method of activating a Window

; ########################

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.
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: -- AHK BASICS --

30 Mar 2016, 03:35

Under Construction - Structuring the Order and clear out some Things. Maybe get a better visual overview

Code: Select all

; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

Expression Operators (in descending precedence order)
; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

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

Var := MyArray%A_Index% + 100

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 base and 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 base and exponent are both integers. Since ** is of higher precedence than unary minus, -2**2 is 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.5 is not supported; it will yield an empty string. But both (-2)**2 and (-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 in this example: -(3 / -x). On a related note, any unary plus signs (+) within an expression are ignored.

Logical-not (!): 
If the operand is blank or 0, the result of applying logical-not is 1, which means "true". Otherwise, the result is 0 (false). For example: !x or !(y and z). Note: The word NOT is synonymous with ! except that ! has a higher precedence. In v1.0.46+, consecutive unary operators such as !!Var are allowed because they are evaluated in right-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 is between 0 and 4294967295 (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 between 0 and 255 (0 is always retrieved if the address is 0; 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, and 4/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//3 is 1 and 5//-3 is -1. If either of the inputs is in floating point format, floating point division is performed and the result is truncated to the nearest integer to the left. For example, 5//3.0 is 1.0 and 5.0//-3 is -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).

Division by zero yields a blank result (empty string).
; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

+
-	
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 shift left (<<) and right (>>). Example usage: Value1 << Value2. Any floating point input is truncated to an integer prior to the calculation. Shift left (<<) is equivalent to multiplying Value1 by "2 to the Value2th power". Shift right (>>) 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>>1 is -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 space between the items to be merged.
Example (expression method): Var := "The color is " . FoundColor
Example (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 0 and 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 is not a number, both are compared alphabetically (a quoted literal string such as "55" is always considered non-numeric in this context). The comparison is case sensitive only if StringCaseSense has been turned on. See also: Sort
; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

=
==
<> !=	
Equal (=), case-sensitive-equal (==), and not-equal (<> or !=). 
The operators != and <> are identical in function. The == operator behaves identically to = except when either of the inputs is not a number, in which case == is always case sensitive and = is always case insensitive (the method of insensitivity depends on StringCaseSense). By contrast, <> and != obey StringCaseSense. Note: A quoted literal string such as "55" is always considered non-numeric in this context.
; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

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

AND 
&&	
Both of these are logical-AND. For example: x > 3 and 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 <= 3 or 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 2 in 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 in this 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) > 50 is true 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:=2 is 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 is not 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+=1 and 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. This is 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 and not double-derefs, so the following contains only one assignment: x:=1, %y%=2
; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

mod()
round()
abs()

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, this is 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.
; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

F(p*)	[v1.0.90+]: See Variadic Functions.
; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

x[y]	[v1.0.90+]: Object access. Get or set a value or call a method of object x, where y is a parameter list or calculated method name. See array syntax and object syntax.

; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################






; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

x.y	
Object access. Get or set a value or call a method of object x, where y is a literal value. See object syntax.

; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

new	
Creates 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.
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: -- AHK BASICS --

30 Mar 2016, 04:33

Built-in Variables

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


Code: Select all

; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################
Special Characters

A_Space	
This variable contains a single space character. See AutoTrim for details.
;------------------------------------------
A_Tab	
This 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_WorkingDir	
The script's current working directory, which is where files will be accessed by default. The final backslash is not included unless it is the root directory. Two examples: C:\ and C:\My Documents. Use SetWorkingDir to change the working directory.
;------------------------------------------
A_ScriptDir	
The full path of the directory where the current script is located. The final backslash is omitted (even for root directories).
;------------------------------------------
A_ScriptName	
The file name of the current script, without its path, e.g. MyScript.ahk.
;------------------------------------------
A_ScriptFullPath	
The 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_LineNumber	
The 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_LineFile	
The 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_ThisLabel is not updated when execution "falls into" a label from above; when that happens, A_ThisLabel retains its previous value. See also: A_ThisHotkey and IsLabel()
;------------------------------------------
A_AhkVersion	
In 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_AhkVersion is greater than some minimum version number with > or >= as in this example: if A_AhkVersion >= 1.0.25.07.
;------------------------------------------
A_AhkPath	
For 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_AhkPath is blank.
;------------------------------------------

A_IsUnicode	
Contains 1 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_IsCompiled	
Contains 1 if the script is running as a compiled EXE and an empty string (which is considered false) if it is not.
;------------------------------------------
A_ExitReason	
The 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_YYYY	
Current 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_MM	
Current 2-digit month (01-12). Synonymous with A_Mon.
;------------------------------------------
A_DD	
Current 2-digit day of the month (01-31). Synonymous with A_MDay.
;------------------------------------------
A_MMMM	
Current month's full name in the current user's language, e.g. July
;------------------------------------------
A_MMM	
Current month's abbreviation in the current user's language, e.g. Jul
;------------------------------------------
A_DDDD	
Current day of the week's full name in the current user's language, e.g. Sunday
;------------------------------------------
A_DDD	
Current day of the week's 3-letter abbreviation in the current user's language, e.g. Sun
;------------------------------------------
A_WDay	
Current 1-digit day of the week (1-7). 1 is Sunday in all locales.
;------------------------------------------
A_YDay	
Current day of the year (1-366). The value is not zero-padded, e.g. 9 is retrieved, not 009. To retrieve a zero-padded value, use the following: FormatTime, OutputVar,, YDay0.
;------------------------------------------
A_YWeek	
Current year and week number (e.g. 200453) according to ISO 8601. To separate the year from the week, use StringLeft, Year, A_YWeek, 4 and 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_Hour	
Current 2-digit hour (00-23) in 24-hour time (for example, 17 is 5pm). To retrieve 12-hour time as well as an AM/PM indicator, follow this example: FormatTime, OutputVar, , h:mm:ss tt
;------------------------------------------
A_Min	
Current 2-digit minute (00-59).
;------------------------------------------
A_Sec	
Current 2-digit second (00-59).
;------------------------------------------
A_MSec	
Current 3-digit millisecond (000-999). To remove the leading zeros, follow this example: Milliseconds := A_MSec + 0.
;------------------------------------------
A_Now	
The 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_NowUTC	
The current Coordinated Universal Time (UTC) in YYYYMMDDHH24MISS format. UTC is essentially the same as Greenwich Mean Time (GMT).
;------------------------------------------
A_TickCount	
The number of milliseconds since the computer was rebooted. By storing A_TickCount in a variable, elapsed time can later be measured by subtracting that variable from the latest A_TickCount value. For example:

StartTime := A_TickCount
Sleep, 1000
ElapsedTime := A_TickCount - StartTime
MsgBox,  %ElapsedTime% milliseconds have elapsed.
Select | Download
If you need more precision than A_TickCount's 10ms, use QueryPerformanceCounter().
; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################
Script Settings


A_IsSuspended	
Contains 1 if the script is suspended and 0 otherwise.
;------------------------------------------
A_IsPaused
[v1.0.48+]	
Contains 1 if the thread immediately underneath the current thread is paused. Otherwise it contains 0.
;------------------------------------------
A_IsCritical
[v1.0.48+]	Contains 0 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: 200 or 10ms (depending on format).
;------------------------------------------
A_TitleMatchMode	
The current mode set by SetTitleMatchMode: 1, 2, 3, or RegEx.
;------------------------------------------
A_TitleMatchModeSpeed	
The current match speed (fast or slow) set by SetTitleMatchMode.
;------------------------------------------
A_DetectHiddenWindows	
The current mode (On or Off) set by DetectHiddenWindows.
;------------------------------------------
A_DetectHiddenText	
The current mode (On or Off) set by DetectHiddenText.
;------------------------------------------
A_AutoTrim	
The current mode (On or Off) set by AutoTrim.
;------------------------------------------
A_StringCaseSense	
The current mode (On, Off, or Locale) set by StringCaseSense.
;------------------------------------------
A_FileEncoding	
[v1.0.90+] Contains the default encoding for various commands; see FileEncoding.
;------------------------------------------
A_FormatInteger	
The current integer format (H or D) set by SetFormat. [v1.0.90+]: This may also contain lower-case h.
;------------------------------------------
A_FormatFloat	
The 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 between 0 and 100, 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_WinDelay	
The current delay set by SetWinDelay (always decimal, not hex).
;------------------------------------------
A_ControlDelay	
The current delay set by SetControlDelay (always decimal, not hex).
;------------------------------------------
A_MouseDelay
;------------------------------------------
A_MouseDelayPlay	
The current delay set by SetMouseDelay (always decimal, not hex). A_MouseDelay is for the traditional SendEvent mode, whereas A_MouseDelayPlay is for SendPlay. ;------------------------------------------
A_MouseDelayPlay 
requires [v1.1.23+].
;------------------------------------------
A_DefaultMouseSpeed	
The current speed set by SetDefaultMouseSpeed (always decimal, not hex).
;------------------------------------------
A_CoordModeToolTip
A_CoordModePixel
A_CoordModeMouse
A_CoordModeCaret
A_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_IconHidden	
Contains 1 if the tray icon is currently hidden or 0 otherwise. The icon can be hidden via #NoTrayIcon or the Menu command.
;------------------------------------------
A_IconTip	
Blank 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_IconFile	
Blank 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_IconNumber	
Blank if A_IconFile is blank. Otherwise, it's the number of the icon in A_IconFile (typically 1).

; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################
User Idle Time

;------------------------------------------
A_TimeIdle	
The number of milliseconds that have elapsed since the system last received keyboard, mouse, or other input. This is 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_TimeIdlePhysical	
Similar 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).

; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################
GUI Windows and Menu Bars

;------------------------------------------
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_Gui	
The 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_GuiControl	
The name of the variable associated with the GUI control that launched the current thread. If that control lacks an associated variable, ;------------------------------------------
A_GuiControl 
instead contains the first 63 characters of the control's text/caption (this is most often used to avoid giving each button a variable name). A_GuiControl is blank whenever: 1) A_Gui is 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; or 4) The control that originally launched the current thread no longer exists (perhaps due to Gui Destroy).
;------------------------------------------
A_GuiWidth
;------------------------------------------
A_GuiHeight	
These 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_GuiX
A_GuiY	
These 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_GuiEvent
or A_GuiControlEvent	
The 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-click or 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 click and again for the second.

RightClick: Occurs only for GuiContextMenu, ListViews, and TreeViews.

Context-sensitive values: For details see GuiContextMenu, GuiDropFiles, Slider, MonthCal, ListView, and TreeView.

;------------------------------------------
A_EventInfo	
Contains additional information about the following events:

The OnClipboardChange label
Mouse 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_EventInfo contains 0.

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

; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################
Hotkeys, Hotstrings, and Custom Menu Items

;------------------------------------------
A_ThisMenuItem	
The name of the most recently selected custom menu item (blank if none).
;------------------------------------------
A_ThisMenu	
The name of the menu from which A_ThisMenuItem was selected.
;------------------------------------------
A_ThisMenuItemPos	
A number indicating the current position of A_ThisMenuItem within A_ThisMenu. The first item in the menu is 1, the second is 2, and so on. Menu separator lines are counted. This variable is blank if A_ThisMenuItem is blank or no longer exists within A_ThisMenu. It is also blank if A_ThisMenu itself no longer exists.
;------------------------------------------
A_ThisHotkey	
The 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.

See also: A_ThisLabel

;------------------------------------------
A_PriorHotkey	
Same 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_TimeSinceThisHotkey	
The number of milliseconds that have elapsed since ;------------------------------------------
A_ThisHotkey 
was pressed. It will be -1 whenever A_ThisHotkey is blank.
;------------------------------------------
A_TimeSincePriorHotkey	
The number of milliseconds that have elapsed since ;------------------------------------------
A_PriorHotkey was pressed. It will be -1 whenever A_PriorHotkey is blank.
;------------------------------------------
A_EndChar	
The 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.

; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################
Operating System and User Info

;------------------------------------------
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_OSType	
The type of operating system being run. Since AutoHotkey 1.1 only supports NT-based operating systems, this is always WIN32_NT. Older versions of AutoHotkey return WIN32_WINDOWS when run on Windows 95/98/ME.
;------------------------------------------
A_OSVersion	
One 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 is not 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.
if A_OSVersion in WIN_NT4,WIN_95,WIN_98,WIN_ME  ; Note: No spaces around commas.
{
    MsgBox This script requires Windows 2000/XP or later.
    ExitApp
}
Select | Download
;------------------------------------------
A_Is64bitOS	
[v1.1.08+]: Contains 1 (true) if the OS is 64-bit or 0 (false) if it is 32-bit.
;------------------------------------------
A_PtrSize	
[v1.0.90+]: Contains the size of a pointer, in bytes. This is either 4 (32-bit) or 8 (64-bit), depending on what type of executable (EXE) is running the script.
;------------------------------------------
A_Language	
The system's default language, which is one of these 4-digit codes.
;------------------------------------------
A_ComputerName	
The name of the computer as seen on the network.
;------------------------------------------
A_UserName	
The logon name of the user who launched this script.
;------------------------------------------
A_WinDir	
The Windows directory. For example: C:\Windows
;------------------------------------------
A_ProgramFiles
or ProgramFiles	
The Program Files directory (e.g. C:\Program Files or C:\Program Files (x86)). This is usually the same as the ProgramFiles environment variable.

On 64-bit systems (and not 32-bit systems), the following applies:

If the executable (EXE) that is running the script is 32-bit, A_ProgramFiles returns the path of the "Program Files (x86)" directory.
For 32-bit processes, the ProgramW6432 environment variable contains the path of the 64-bit Program Files directory. On Windows 7 and 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 is not included. For example, it would contain M: rather than M:\
;------------------------------------------
A_IsAdmin	
If the current user has admin rights, this variable contains 1. Otherwise, it contains 0.

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:

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

;------------------------------------------
A_ScreenWidth
A_ScreenHeight

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

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, 78
SysGet, VirtualHeight, 79
Select | Download
In 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 this is 96; it depends on the system's text size (DPI) setting. See also Gui -DPIScale.
;------------------------------------------
A_IPAddress1 
through 4	The IP addresses of the first 4 network adapters in the computer.


; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

Misc.

;------------------------------------------
A_Cursor	
The 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_CaretX
A_CaretY	
The 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.

#Persistent
SetTimer, WatchCaret, 100
return
WatchCaret:
  ToolTip, X%A_CaretX% Y%A_CaretY%, A_CaretX, A_CaretY - 20
return
Select | Download
;------------------------------------------
Clipboard	
The contents of the OS's clipboard, which can be read or written to. See the Clipboard section.
;------------------------------------------
ClipboardAll	
The entire contents of the clipboard (such as formatting and text). See ClipboardAll.
;------------------------------------------
ErrorLevel	
See ErrorLevel.
;------------------------------------------
A_LastError	
The result from the OS's GetLastError() function or the last COM object invocation. For details, see DllCall() and Run/RunWait.
Loop

;------------------------------------------
A_Index	This 
is 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.This and other related variables are valid only inside a file-loop.
;------------------------------------------
A_LoopRegName, 
etc.	This and other related variables are valid only inside a registry-loop.
;------------------------------------------
A_LoopReadLine	
See file-reading loop.
;------------------------------------------
A_LoopField	
See parsing loop.
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: -- AHK BASICS --

30 Mar 2016, 12:13

Code: Select all

; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

Expression Operators (in descending precedence order)
; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

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

Var := MyArray%A_Index% + 100

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 base and 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 base and exponent are both integers. Since ** is of higher precedence than unary minus, -2**2 is 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.5 is not supported; it will yield an empty string. But both (-2)**2 and (-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 in this example: -(3 / -x). On a related note, any unary plus signs (+) within an expression are ignored.

Logical-not (!): 
If the operand is blank or 0, the result of applying logical-not is 1, which means "true". Otherwise, the result is 0 (false). For example: !x or !(y and z). Note: The word NOT is synonymous with ! except that ! has a higher precedence. In v1.0.46+, consecutive unary operators such as !!Var are allowed because they are evaluated in right-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 is between 0 and 4294967295 (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 between 0 and 255 (0 is always retrieved if the address is 0; 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, and 4/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//3 is 1 and 5//-3 is -1. If either of the inputs is in floating point format, floating point division is performed and the result is truncated to the nearest integer to the left. For example, 5//3.0 is 1.0 and 5.0//-3 is -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).

Division by zero yields a blank result (empty string).
; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

+
-	
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 shift left (<<) and right (>>). Example usage: Value1 << Value2. Any floating point input is truncated to an integer prior to the calculation. Shift left (<<) is equivalent to multiplying Value1 by "2 to the Value2th power". Shift right (>>) 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>>1 is -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 space between the items to be merged.
Example (expression method): Var := "The color is " . FoundColor
Example (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 0 and 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 is not a number, both are compared alphabetically (a quoted literal string such as "55" is always considered non-numeric in this context). The comparison is case sensitive only if StringCaseSense has been turned on. See also: Sort
; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

=
==
<> !=	
Equal (=), case-sensitive-equal (==), and not-equal (<> or !=). 
The operators != and <> are identical in function. The == operator behaves identically to = except when either of the inputs is not a number, in which case == is always case sensitive and = is always case insensitive (the method of insensitivity depends on StringCaseSense). By contrast, <> and != obey StringCaseSense. Note: A quoted literal string such as "55" is always considered non-numeric in this context.
; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

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

AND 
&&	
Both of these are logical-AND. For example: x > 3 and 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 <= 3 or 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 2 in 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 in this 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) > 50 is true 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:=2 is 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 is not 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+=1 and 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. This is 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 and not double-derefs, so the following contains only one assignment: x:=1, %y%=2
; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

mod()
round()
abs()

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, this is 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.
; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

F(p*)	[v1.0.90+]: See Variadic Functions.
; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

x[y]	[v1.0.90+]: Object access. Get or set a value or call a method of object x, where y is a parameter list or calculated method name. See array syntax and object syntax.

; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################






; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

x.y	
Object access. Get or set a value or call a method of object x, where y is a literal value. See object syntax.

; ########################								####################
;---------------------------------------------------------------------------
; ########################								####################

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


User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: -- AHK BASICS --

31 Mar 2016, 06:50

Performance Template - With all descriptions for all possible cases / settings.

Code: Select all


;************************************************
; AHK _ PERFORMANCE TESTER
; by HinkerLoden
; 25/03/2016 
;************************************************

;************************************************
;Script Global Settings
;************************************************

#NoEnv						; Clear All Systemvariables 
#Persistent 				;Keeps a script permanently running until ExitApp execute

#SingleInstance force		;The word FORCE skips the dialog box and replaces the old instance automatically, which is similar in effect to the Reload command.

;************************************************
;Performance PARAMETERS
;************************************************
SetBatchLines, -1
Process, Priority, , A  
;************************************************
; Input PARAMETERS
;************************************************
SendMode Input
SetKeyDelay, -1, -1, Play

SetMouseDelay, -1
SetDefaultMouseSpeed, 0
;************************************************
;History Protocols
;************************************************
#KeyHistory 0
ListLines Off
;************************************************
;Window detection
;************************************************
SetTitleMatchMode 2
SetTitleMatchMode Fast

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

SetControlDelay, 0	 ; default = 20     , fastest = -1 
;Sets the delay that will occur after each control-modifying command.



;************************************************
;PERFORMANCE PARAMETERS DESCRIPTION
;************************************************
/*
;************************************************
;Performance PARAMETERS
;************************************************

SetBatchLines, -1

;default = 10ms
   
;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, 20ms
SetBatchLines, 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.

Process, Priority, , L ;if unstable, comment or remove this line

;************************************************
; Input PARAMETERS
;************************************************

SendMode Input

;Keysettings		***********************

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.
 
SetDefaultMouseSpeed, 0
;default = 2 , Min = 0 , Max = 100

;Hotkeysettings		***********************
#MaxHotkeysPerInterval 99000000	:default = 70  	- prevent creating endless loops

#HotkeyInterval 99000000		;default = 2000 - Hoy much hotkeys can activate per ms

#MaxThreads 255					;default 10 	- How many Hotkeys + Timers .. can run simultanously 

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


;************************************************
;History Protocols
;************************************************
#KeyHistory 0					;disable KeyHistory log

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.
 

;************************************************
;Window detection
;************************************************

 
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.


SetControlDelay, 0	 ; default = 20     , fastest = -1 
;Sets the delay that will occur after each control-modifying command.


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

;************************************************
;Other 
;************************************************

#MaxMem 4095					;default 64MB - Max 4095	 set the Memory use for each Variable 


*/


Last edited by HinkerLoden on 03 Apr 2016, 16:05, edited 1 time in total.
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: -- AHK BASICS --

31 Mar 2016, 06:51

Gui - Tutorial


MsgBox-Inputbox
Required the previous Tutorial

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.


Beginners should take a look on the following Lines:

1.) InputBox_Title := "InputBox_Title" . A_Index - OutputVar:= "Textonly" . A_Index ;Loop Up Buildin-Variable->A_Index ,

2.) InputBox, OutputVar, % %InputBox_Title%, % %Input... - Forced Expression with Percentage - Only the Name is Changed in the Loop.




Code: Select all

;************************************************
; AHK _ GUI _ TUTORIAL
/*
1.) MsgBox, InputBox
2.)	InputBox

3.) Min Gui Settings
4.) All Commandons 
*/
; by HinkerLoden
; 25/03/2016 
;************************************************


;************************************************
;Script Global Settings
;************************************************

#NoEnv						; Clear All Systemvariables 
#Persistent 				;Keeps a script permanently running until ExitApp execute

#SingleInstance force		;The word FORCE skips the dialog box and replaces the old instance automatically, which is similar in effect to the Reload command.

;************************************************
;Performance PARAMETERS - if you need speed 
;************************************************
;SetBatchLines, -1   		
;Process, Priority, , L  ;A  - Max Speed
;************************************************
; Input PARAMETERS
;************************************************
SendMode Input
SetKeyDelay, 10, 10   ; for speed -1, -1, 

SetMouseDelay, 25		;0 recommend -1 for max speed 
SetDefaultMouseSpeed, 0		;0-100 
;************************************************
;History Protocols 
;Switch setting for more Speed 
;************************************************
#KeyHistory 1		;  0 - No Keyhistory 
ListLines  On  		; Off  - for more speed 
;************************************************
;Window detection
;************************************************
SetTitleMatchMode, 2
SetTitleMatchMode Fast	;slow detect hidden windows

SetWinDelay, 200  		;0 - for more speed   
;i double the standard settings to be on the save side 

;#######################				#######################
; Script Parameter
;#######################				#######################

SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.

;#Include %A_ScriptDir%\YourLibrarys2integrate.ahk

CoordMode, Pixel, Screen
CoordMode, Mouse, Screen

;WinMinimizeAll					


; Try to avoid pure numbers inside the code - adress all Vars here
;=============================================================
; 						Variable Section
;=============================================================

;-------------------------------  INPUTBOX VARIABLES / SETTINGS

;InputBox, OutputVar [, Title, Prompt, HIDE, Width, Height, X, Y, Font, Timeout, Default]

InputBox_Title			=		HANGMAN			;Text at the Top
InputBox_Prompt		=		Enter a Letter		;Text inside the Box

InputBox_HIDE			=						;Parameter HIDE 

InputBox_Width			=		150				;default = 350 
InputBox_Height		=		150				;default = 189

InputBox_X			=		250				;default = Screen Center, Display Box at X
InputBox_Y			=		250				;default = Screen Center,  Display Box at Y
;InputBox_Font			=					Not implemented - leave empty

InputBox_Timeout		=		2				;Timeout in seconds ! ErrorLevel 2 
InputBox_Default		=		Enter a Letter


;InputBox, InputBoxVar , %InputBox_Title%, %InputBox_Prompt%, , %InputBox_X%,%InputBox_Y%, %InputBox_Width%, %InputBox_Height%, , %InputBox_Timeout%, %InputBox_Default%
;-------------------------------


NumberOfInputs=4


InputBox_Title1 = Your Car 
InputBox_Prompt1= YourCarsBrand

InputBox_Title2 = Color 
InputBox_Prompt2= What Color have your Car ?

InputBox_Title3 = Horse Power 
InputBox_Prompt3= How Many Horser Power ?

InputBox_Title4 = Max Speed 
InputBox_Prompt4= How Fast is your Car ?

;#######################				#######################
;						MsgBox
;#######################				#######################
;MsgBox [, Options, Title, Text, Timeout]

;Options - 
/*
0		= 	OK (that is, only an OK button is displayed)	
1		=	OK/Cancel		0x1
2		=	Abort/Retry/Ignore	2	0x2
3		=	Yes/No/Cancel	3	0x3
4		=	Yes/No	4	0x4
5		=	Retry/Cancel		0x5
6		=	Cancel/Try Again/Continue		0x6

16384	=	Adds a Help button (see remarks below)		0x4000
 	 	 
16		=	Icon Hand (stop/error)		0x10
32		=	Icon Question		0x20
48		=	Icon Exclamation		0x30
64		=	Icon Asterisk (info)		0x40
 	 	 
256		=	Makes the 2nd button the default		0x100
512		=	Makes the 3rd button the default		0x200
 	 	 
4096	=	System Modal (always on top)		0x1000
8192	=	Task Modal		0x2000
262144	=	Always-on-top (style WS_EX_TOPMOST)(like System Modal but omits title bar icon)		0x40000
 	 	 
524288	=	Make the text right-justified		0x80000
1048576	=	Right-to-left reading order for Hebrew/Arabic		0x100000
*/





;#######################				#######################
;=============================================================
; 						CODE 
;=============================================================
;#######################				#######################



;=============================================================
; 						INPUT BOX LOOP 
;=============================================================
 Loop,
 
 {

 InputBox_Title := "InputBox_Title" . A_Index
 InputBox_Prompt := "InputBox_Prompt" . A_Index
 
; InputBox_Default = InputBox_Prompt
 
InputBox, OutputVar, % %InputBox_Title%, % %InputBox_Prompt%, , ,, , , , %Timeout%, %InputBox_Default%	;,%InputBox_Timeout%, % %InputBox_Default%
If ErrorLevel = 0
	{
	OutputVar%A_Index% := OutputVar
	
	;MsgBox, You Pressed the OK Button `n`nInsert Text: %OutputVar% 
	 
	}
else if ErrorLevel = 2
	{
	MsgBox, TIMEOUT 
	}
else if ErrorLevel = 1 
	{
	MsgBox, You Pressed Cancel or Close `n Type a letter  !
	ExitApp
	} 
 
 If (NumberOfInputs = A_Index)
	Break
	

 }
;=============================================================
; 						SPLASH TEXT SAMPLE 
;=============================================================

SplashTextOn, 400, 300, Your Car , % "Brand: "OutputVar1 "`nColor: " OutputVar2 "`nHorses: " OutputVar3 "`nSpeed: "OutputVar4
Sleep, 2000
SplashTextOff
 















Create Gui, Input/Output Handling (controlget,control,etc...), gLabel, Gui 2 data.ini transfer
Last edited by HinkerLoden on 01 Apr 2016, 02:55, edited 1 time in total.
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: -- AHK BASICS --

31 Mar 2016, 06:52

Windows Environment - Open Windows/Programms - Read/ Get Information out of a window/control - Write / Edit a window
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: -- AHK BASICS --

31 Mar 2016, 06:54

Input-Output - Hotkey Mouse and more Inputs,
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: -- AHK BASICS --

01 Apr 2016, 03:46

Search algorithm - FastPixelSearch Options - Circle Search (Get direction from Postion) - Cone Search Based on Circle Search - LineFollower - ....
User avatar
nnnik
Posts: 4500
Joined: 30 Sep 2013, 01:01
Location: Germany

Re: -- AHK BASICS --

01 Apr 2016, 08:02

Wow this is getting big.
Recommends AHK Studio
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: -- AHK BASICS --

02 Apr 2016, 04:12

GUI - Tutorial


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.
Create a GUI is quite easy with the help from AutoGui.
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. :crazy:
All Examples are collected in the Script at the End of the Tutorial.
So we take a look on a simple Gui.

Code: Select all

Gui, New 				;Create or Override the Gui 
;Gui, SimpleGui:New , -ToolWindow +AlwaysOnTop	;Create Gui SimpleGui with Options
;----------
gui, font, s14, Verdana					;Not Need - but better readability 
;----------
Gui Add, Text, vText , -- A Text we can put here in 		;Variable Text assigned  
Gui Add, Edit, vEdit gEdit, In these field we can edit something
;Variable Edit and Label Edit assigned to the Edit field. 
;----------
Gui Add, Button, gButton1 ,  -- Button 1 --		;Button need no Variables 
Gui Add, Button, gButton2 ,  -- Button 2 --
 ;----------
Gui Add, Button, gExit  cRed , -- E X I T --		;Exit in Red - a bit of Color we need 

Gui Show, w480 h380, Window				;Size of the Window the Gui created

The Minimum to create Gui
1.)Gui, New --> Creates the Gui - one Line
2.)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 Version

the vNameVariable decline the Variable from a Control Field - Cause we need them to return the result iniside Gui
the 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.

GUI ----> VAR

Get the Information out of the Gui happens with the Syntax GuiControlGet --> Official Help


RESULT/VAR ---> GUI

Put the Information into the Gui happens with the Syntax GuiControl --> Official Help
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: -- AHK BASICS --

09 Apr 2016, 03:37

Really have problems , especially with the Basic Tut . Advices for more Examples or it contains allready to much. Its hard to get a combine a Practical Example without using to much enhanced code.

1. One StringInput Example 2. Loop Example with MouseMove

Code: Select all


F9::

StartInput:

InputBox, UserInput, BoxText, Enter a Number
if ErrorLevel
    {
	MsgBox, CANCEL was pressed.
	}
else
    {
	If UserInput = 				; If 
		{
		MsgBox, Input is empty - Try Again
		Goto, StartInput
		}
else if ( StrLen(UserInput) >= 3 )	
;OutputVar := StrLen(InputVar)		is equal to 		StringLen, OutputVar, InputVar
;But a function is usable inside a If-Call or Expressions !!! 
		{
		MsgBox, This is a bit to long. Try Again. 
		Goto, StartInput
		}
		
	MsgBox, You entered "%UserInput%"
	}
Return 



F10::

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") OR GetKeyState("LButton","P") ) AND ( UserInput != )
	{
	MsgBox, STOP
	Break 					;STops the Loop 
	}

X := Y := UserInput			; Adress one VAriable UserInput --> X and Y 

 If GetKeyState("UP","P") 
	{
	MouseMove, 0, Y * -1 ,50, R			; 
	Continue 
	}

 If GetKeyState("DOWN","P") 					
	{
	MouseMove, 0, Y , 50, R
	Continue 
	}

 If GetKeyState("Left","P") 
	{
	MouseMove, X * -1, 0 ,50, R
	Continue 
	}

 If GetKeyState("RIGHT","P") 					;
	{
	MouseMove, X, 	0,50, R
	Continue 									
	;End of the Cylce - not really need the Continue if no code follows. 
	}


}





BoBo
Posts: 6563
Joined: 13 May 2014, 17:15

Re: -- AHK BASICS --

15 May 2017, 04:01

Moin HinkerLoden (kerle, ich könnt mich stundenlang über deinen nickname beömmeln)

1st things first. R-E-S-P-E-K-T für deinen einsatz an der noob front !!! Much appreciated! 8-)

2tens. Mein englisch ist eher wackelig, und ich habe schon allein deshalb, und aus schierer neugier, vor kurzem [Grammarly] auf meinem rechner installiert. Dasamatotalcooldattool !!! Dazu gibts [hier] was auf die augen :idea:
Damit lässt sich manchertypisch "deutsche" flüchtigkeitsfehler (auch im browser!) recht gut abfangen: of/off, your/you're, on/at, ...
Schau mal drauf, ist bei der menge deiner ausführungen IMHO eine hilfreiche anwendung.

3tens. Freue mich mehr weiter von d'hier zu lesen :)

btw, Gruss auch an deinen eineiigen Zwilling HechterRoden ... MUAHAHAHAHAHA :lol:

PS. wenn du möchtest dann lösche ich den beitrag auch wieder (-> PM) damit er den fluss des tutorials nicht unterbricht !
PPS. ich bin auf der suche nach einem "template"-thread auf diesen beitrag gestoßen. Falls jemand ein template tool/script versteckt hält bitte melden. Thx :)

Return to “Tutorials (v1)”

Who is online

Users browsing this forum: No registered users and 28 guests