#allowsamelinecomments · endchars newchars specify the word endchars followed a single space and...

2019
#AllowSameLineComments [v1.1.09+]: This directive was removed. AutoIt scripts are no longer supported. Only for AutoIt v2 (.aut) scripts: Allows a comment to appear on the same line as a command. #AllowSameLineComments Specifying this directive at the top of any AutoIt v2 (.aut) script will enable the use of same-line comments, which are normally disabled for compatibility reasons. If not used at the top of the script, same-line comments are not supported above the point where the directive occurs. Example #AllowSameLineComments Sleep, 1 ; This comment is a same-line comment.

Upload: others

Post on 25-Aug-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

  • #AllowSameLineComments

    [v1.1.09+]:Thisdirectivewasremoved.AutoItscriptsarenolongersupported.

    OnlyforAutoItv2(.aut)scripts:Allowsacommenttoappearonthesamelineasacommand.

    #AllowSameLineComments

    SpecifyingthisdirectiveatthetopofanyAutoItv2(.aut)scriptwillenabletheuseofsame-linecomments,whicharenormallydisabledforcompatibilityreasons.Ifnotusedatthetopofthescript,same-linecommentsarenotsupportedabovethepointwherethedirectiveoccurs.

    Example

    #AllowSameLineCommentsSleep,1;Thiscommentisasame-linecomment.

  • #ClipboardTimeoutChangeshowlongthescriptkeepstryingtoaccesstheclipboardwhenthefirstattemptfails.

    #ClipboardTimeoutMilliseconds

    Parameters

    MillisecondsThelengthoftheintervalinmilliseconds.Specify-1tohaveitkeeptryingindefinitely.Specify0tohaveittryonlyonce.Scriptsthatdonotcontainthisdirectiveusea1000mstimeout.

    Remarks

    Someapplicationskeeptheclipboardopenforlongperiodsoftime,perhapstowriteorreadlargeamountsofdata.Insuchcases,increasingthissettingcausesthescripttowaitlongerbeforegivingupanddisplayinganerrormessage.

    Thissettingsappliestoallclipboardoperations,thesimplestofwhicharethefollowingexamples: Var=%Clipboard% and Clipboard=NewText .

    Wheneverthescriptiswaitingfortheclipboardtobecomeavailable,newthreadscannotbelaunchedandtimerswillnotrun.However,iftheuserpressesahotkey,selectsacustommenuitem,orperformsaGUIactionsuchaspressingabutton,thateventwillbebuffereduntillater;inotherwords,itssubroutinewillbeperformedaftertheclipboardfinallybecomesavailable.

    Thisdirectivedoesnotcausethereadingofclipboarddatatobereattemptedifthefirstattemptfails.Priorto[v1.1.16],itdidcausethescripttowaituntilthetimeoutexpired,butindoingsopreventedanyfurtherdatafrombeingretrieved.

    Related

  • Clipboard,Thread

    Example

    #ClipboardTimeout2000

  • #CommentFlagChangesthescript'scommentsymbolfromsemicolontosomeotherstring.

    #CommentFlagNewString

    Parameters

    NewStringOneormorecharactersthatshouldbeusedasthenewcommentflag.Upto15charactersmaybespecified.

    Remarks

    Thedefaultcommentflagissemicolon(;).

    Thecommentflagisusedtoindicatethattextthatfollowsitshouldnotbeacteduponbythescript(commentsarenotloadedintomemorywhenascriptislaunched,sotheydonotaffectperformance).

    Acommentflagthatappearsonthesamelineasacommandisnotconsideredtomarkacommentunlessithasatleastonespaceortabtoitsleft.Forexample:

    MsgBox,Test1;Thisisacomment.MsgBox,Test2;ThisisnotacommentandwillbedisplayedbyMsgBox.

    Related

    #EscapeChar

    Example

  • #CommentFlag//;ChangetoC++commentstyle.

  • #ErrorStdOutSendsanysyntaxerrorthatpreventsascriptfromlaunchingtostderrratherthandisplayingadialog.

    #ErrorStdOut

    [AHK_L42+]:Errorsarewrittentostderrinsteadofstdout.Thecommandpromptandfancyeditorsusuallydisplayboth.Thischangewasundocumenteduntilafter[v1.1.19.01].

    ThisallowsfancyeditorssuchasTextpad,SciTE,Crimson,andEditPlustojumptotheoffendinglinewhenasyntaxerroroccurs.Sincethe#ErrorStdOutdirectivewouldhavetobeaddedtoeveryscript,itisusuallybettertosetupyoureditortousethecommandlineswitch/ErrorStdOutwhenlaunchinganyAutoHotkeyscript(seefurtherbelowforsetupinstructions).

    BecauseAutoHotkeyisnotaconsoleprogram,errorswillnotappearatthecommandpromptdirectly.Instead,suchoutputcanbecapturedviapipingorredirection.Forexample:

    "C:\ProgramFiles\AutoHotkey\AutoHotkey.exe"/ErrorStdOut"MyScript.ahk"2>&1|more"C:\ProgramFiles\AutoHotkey\AutoHotkey.exe"/ErrorStdOut"MyScript.ahk"2>"Syntax-ErrorLog.txt"

    Youcanalsopipetheoutputdirectlytotheclipboardbydownloadingcb.zip(4KB)andthenfollowingthisexample:

    "C:\ProgramFiles\AutoHotkey\AutoHotkey.exe"/ErrorStdOut"MyScript.ahk"2>&1|cb.exe

    http://www.autohotkey.com/misc/cb.zip

  • Note: 2>&1 causesstderrtoberedirectedtostdout,while2>Filename redirectsonlystderrtoafile.

    Instructionsforspecificeditors

    EditPlus:Fromthemenubar,selectTools>ConfigureUserTools.Pressbutton:AddTool>ProgramMenuText:YourchoiceCommand:C:\ProgramFiles\AutoHotkey\AutoHotkey.exeArgument:/ErrorStdOut"$(FilePath)"Initialdirectory:$(FileDir)Captureoutput:Yes

    TextPad:Fromthemenubar,selectConfigure>Preferences.ExpandtheToolsentry.PresstheAddbuttonandselect"Program".Copyandpaste(adjusttoyourpath):C:\Windows\System32\cmd.exe--thenpressOK.Triple-clickthenewlyaddeditem(cmd.exe)intheListBoxandrenameittoyourchoice(e.g.LaunchScript).PressApply.Selectthenewiteminthetreeattheleftandenterthefollowinginformation:Command(shouldalreadybefilledin):cmd.exe(orthefullpathtoit)Parameters(adjusttoyourpath,ifnecessary):/c""C:\ProgramFiles\AutoHotkey\AutoHotkey.exe"/ErrorStdOut"$File""Initialfolder:$FileDirCheckthefollowingboxes:1)Runminimized;2)Captureoutput.PressOK.ThenewlyaddeditemshouldnowexistintheToolsmenu.

    Related

    FileAppend(becauseitcanalsosendtexttostdout)

    Example

  • #ErrorStdOut

  • #EscapeChar(andexplanationofescapesequences)Changesthescript'sescapecharacter(e.g.accentvs.backslash).

    #EscapeCharNewChar

    Parameters

    NewCharSpecifyasinglecharacter.

    Remarks

    Theescapecharacterisusedtoindicatethatthecharacterimmediatelyfollowingitshouldbeinterpreteddifferentlythanitnormallywould.

    Thedefaultescapecharacterisaccent/backtick(`),whichisattheupperleftcornerofmostEnglishkeyboards.Usingthischaracterratherthanbackslashavoidstheneedfordoubleblackslashesinfilepaths.

    EscapeSequences(whenaccentistheescapecharacter)

    TypeThis ToGetThis

    `,

    ,(literalcomma).

    Note:Commasthatappearwithinthelastparameterofacommanddonotneedtobeescapedbecausetheprogramknowstotreatthemliterally(butitisbesttoescapethemanyway,forclarity).ThesameistrueforallparametersofMsgBoxbecauseithassmartcommahandling.

  • `% %(literalpercent)

    `` `(literalaccent;i.e.twoconsecutiveescapecharactersresultinasingleliteralcharacter)

    `;

    ;(literalsemicolon).

    Note:Itisnotnecessarytoescapeasemicolonwhichhasanycharacterotherthanspaceortabtoitsimmediateleft,sinceitwouldnotbeinterpretedasacommentanyway.

    `::::(literalpairofcolons).[v1.0.40+]:Itisnolongernecessarytoescapethese,exceptwhenusedliterallyinahotstring'sreplacementtext.

    `n newline(linefeed/LF)

    `r carriagereturn(CR)

    `b backspace

    `t tab(themoretypicalhorizontalvariety)

    `v verticaltab--correspondstoAsciivalue11.ItcanalsobemanifestinsomeapplicationsbytypingControl+K.

    `a alert(bell)--correspondstoAsciivalue7.ItcanalsobemanifestinsomeapplicationsbytypingControl+G.

    `f formfeed--correspondstoAsciivalue12.ItcanalsobemanifestinsomeapplicationsbytypingControl+L.

    Send

    WhentheSendcommandorHotstringsareusedintheirdefault(non-raw)mode,characterssuchas{}^!+#havespecialmeaning.Therefore,tousethemliterallyinthesecases,enclosetheminbraces.Forexample: Send{^}{!}{{} .

    ""Withinanexpression,twoconsecutivequotesenclosedinsidealiteralstringresolvetoasingleliteralquote.Forexample: Var:="Thecolor""red""wasfound." .

  • Related

    Thefollowingrarelyuseddirectivesalsoexist;theirusageisshownintheseexamples:

    #DerefChar#;Changeitfromitsnormaldefault,whichis%.#Delimiter/;Changeitfromitsnormaldefault,whichiscomma.

    Example

    #EscapeChar\;Changeittobebackslashinsteadofthedefaultofaccent(`).

  • #HotkeyIntervalAlongwith#MaxHotkeysPerInterval,specifiestherateofhotkeyactivationsbeyondwhichawarningdialogwillbedisplayed.

    #HotkeyIntervalMilliseconds

    Parameters

    MillisecondsThelengthoftheintervalinmilliseconds.

    Remarks

    Ifthisdirectiveisunspecifiedinthescript,itwillbehaveasthoughsetto2000.

    Fordetailsandremarks,see#MaxHotkeysPerInterval.

    Related

    #MaxHotkeysPerInterval

    Example

    #HotkeyInterval2000;Thisisthedefaultvalue(milliseconds).#MaxHotkeysPerInterval200

  • #HotkeyModifierTimeoutAffectsthebehaviorofhotkeymodifiers:CTRL,ALT,WIN,andSHIFT.

    #HotkeyModifierTimeoutMilliseconds

    Parameters

    MillisecondsThelengthoftheintervalinmilliseconds.Thevaluecanbe-1sothatitnevertimesout(modifierkeysarealwayspushedbackdownaftertheSend),or0sothatitalwaystimesout(modifierkeysareneverpushedbackdown).

    Remarks

    Thisdirectiveneednotbeusedwhen:

    HotkeyssendtheirkeystrokesviatheSendInputorSendPlaymethods.Thisisbecausethosemethodspostponetheuser'sphysicalpressingandreleasingofkeysuntilaftertheSendcompletes.Thescripthasthekeyboardhookinstalled(youcanseeifyourscriptusesthehookviathe"View->Keyhistory"menuiteminthemainwindow,orviatheKeyHistorycommand).Thisisbecausethehookcankeeptrackofwhichmodifierkeys(ALT/CTRL/WIN/SHIFT)theuserisphysicallyholdingdownanddoesn'tneedtousethetimeout.

    Toillustratetheeffectofthisdirective,considerthisexample: ^!a::Send,abc .

    WhentheSendcommandexecutes,thefirstthingitdoesisreleasetheCTRLandALTkeyssothatthecharactersgetsentproperly.Aftersendingallthekeys,thecommanddoesn'tknowwhetheritcansafelypushbackdownCTRLandALT(tomatchwhethertheuserisstillholdingthemdown).Butiflessthanthespecifiednumberofmillisecondshaveelapsed,itwillassumethattheuserhasn'thadachancetoreleasethekeysyetanditwillthuspushthembackdownto

  • matchtheirphysicalstate.Otherwise,themodifierkeyswillnotbepushedbackdownandtheuserwillhavetoreleaseandpressthemagaintogetthemtomodifythesameoranotherkey.

    Thetimeoutshouldbesettoavaluelessthantheamountoftimethattheusertypicallyholdsdownahotkey'smodifiersbeforereleasingthem.Otherwise,themodifiersmayberestoredtothedownposition(getstuckdown)evenwhentheuserisn'tphysicallyholdingthemdown.

    Youcanreduceoreliminatetheneedforthisdirectivewithoneofthefollowing:

    Installthekeyboardhookbyaddingtheline#InstallKeybdHookanywhereinthescript.UsetheSendInputorSendPlaymethodsratherthanthetraditionalSendEventmethod.WhenusingthetraditionalSendEventmethod,reduceSetKeyDelayto0or-1,whichshouldhelpbecauseitsendsthekeystrokesmorequickly.

    Ifthisisdirectiveisunspecifiedinascript,itbehavesasthoughsetto50.

    Related

    GetKeyState

    Example

    #HotkeyModifierTimeout100

  • #HotstringChangeshotstringoptionsorendingcharacters.

    #HotstringNoMouse#HotstringEndCharsNewChars#HotstringNewOptions

    Parameters

    NoMousePreventsmouseclicksfromresettingthehotstringrecognizerasdescribedhere.Asaside-effect,thisalsopreventsthemousehookfrombeingrequiredbyhotstrings(thoughitwillstillbeinstalledifthescriptrequiresitforotherpurposes,suchasmousehotkeys).Thepresenceof#HotstringNoMouse anywhereinthescriptaffectsallhotstrings,notjustthosephysicallybeneathit.

    EndCharsNewCharsSpecifythewordEndCharsfollowedasinglespaceandthenthenewendingcharacters.Forexample:

    #HotstringEndChars-()[]{}':;"/\,.?!`n`t

    Sincethenewendingcharactersareineffectgloballyfortheentirescript--regardlessofwheretheEndCharsdirectiveappears--thereisnoneedtospecifyEndCharsmorethanonce.

    Themaximumnumberofendingcharactersis100.Charactersbeyondthislengthareignored.

    Tomaketabanendingcharacter,include`tinthelist.Tomakespaceanendingcharacter,includeitbetweentwoothercharactersinthelist(oratthebeginningifthelistcontainsonlyoneothercharacter,ornoother

  • characters).

    NewOptionsSpecifynewoptionsasdescribedinHotstringOptions.Forexample:#Hotstringrsk0c0 .

    UnlikeEndCharsabove,the#Hotstringdirectiveispositionalwhenusedthisway.Inotherwords,entiresectionsofhotstringscanhavedifferentdefaultoptionsasinthisexample:

    ::btw::bytheway

    #Hotstringrc;Allthebelowhotstringswilluse"sendraw"andwillbecasesensitivebydefault.::al::airline::CEO::ChiefExecutiveOfficer

    #Hotstringc0;Makeallhotstringsbelowthispointcaseinsensitive.

    Related

    Hotstrings

  • #If [AHK_L]Createscontext-sensitivehotkeysandhotstrings.Suchhotkeysperformadifferentaction(ornoneatall)dependingontheresultofanexpression.

    #If[,Expression]

    Parameters

    ExpressionAnyvalidexpression.

    BasicOperation

    Anyvalidexpressionmaybeusedtodefinethecontextinwhichahotkeyshouldbeactive.Forexample:

    #IfWinActive("ahk_classNotepad")orWinActive(MyWindowTitle)#Space::MsgBoxYoupressedWin+SpacebarinNotepador%MyWindowTitle%.

    Likethe#IfWindirectives,#Ifispositional:itaffectsallhotkeysandhotstringsphysicallybeneathitinthescript.#Ifand#IfWinarealsomutuallyexclusive;thatis,onlythemostrecent#Ifor#IfWinwillbeineffect.

    Toturnoffcontextsensitivity,specify#Iforany#IfWindirectivebutomitalltheparameters.Forexample:

    #If

    GeneralRemarks

  • Whenthekeycombinationwhichformsahotkeyispressed,the#Ifexpressionisevaluatedtodetermineifthehotkeyshouldactivate.Thesystemmaynotrespondtokeyboardormouseinputuntilexpressionevaluationcompletesortimesout.Sendingkeystrokesormouseclickswhiletheexpressionisbeingevaluated(suchasfromafunctionwhichitcalls)maycausecomplicationsandshouldbeavoided.

    Theexpressionmayalsobeevaluatedwhenevertheprogramneedstoknowwhetherthehotkeyisactive.Forexample,the#Ifexpressionforacustomcombinationlike a&b:: mightbeevaluatedwhentheprefixkey( a inthisexample)ispressed,todeterminewhetheritshouldactasacustommodifierkey.

    Forthereasonsdescribedabove,theexpressionshouldbewrittentocompletequicklyandwithoutside-effects.

    [AHK_L53+]:A_ThisHotkeyandA_TimeSinceThisHotkeyaresetbasedonthehotkeyforwhichthecurrent#Ifexpressionisbeingevaluated.

    [v1.0.95.00+]:A_PriorHotkeyandA_TimeSincePriorHotkeytemporarilycontainthepreviousvaluesofthecorresponding"This"variables.

    Related

    Mostbehaviouralpropertiesofthe#IfWindirectivesalsoapplyto#If.

    #IfTimeoutmaybeusedtooverridethedefaulttimeoutvalue.

    Examples

    ;Example1:Adjustvolumebyscrollingthemousewheeloverthetaskbar.#IfMouseIsOver("ahk_classShell_TrayWnd")WheelUp::Send{Volume_Up}WheelDown::Send{Volume_Down}

    MouseIsOver(WinTitle){MouseGetPos,,,WinreturnWinExist(WinTitle."ahk_id".Win)

  • }

    ;Example2:Simpleword-deleteshortcutsforallEditcontrols.#IfActiveControlIsOfClass("Edit")^BS::Send^+{Left}{Del}^Del::Send^+{Right}{Del}

    ActiveControlIsOfClass(Class){ControlGetFocus,FocusedControl,AControlGet,FocusedControlHwnd,Hwnd,,%FocusedControl%,AWinGetClass,FocusedControlClass,ahk_id%FocusedControlHwnd%return(FocusedControlClass=Class)}

    ;Example3:Context-insensitivehotkey.#IfEsc::ExitApp

    ;Example4:Dynamichotkeys.RequiresExample1.NumpadAdd::Hotkey,If,MouseIsOver("ahk_classShell_TrayWnd")if(doubleup:=!doubleup)Hotkey,WheelUp,DoubleUpelseHotkey,WheelUp,WheelUpreturn

    DoubleUp:Send{Volume_Up2}return

  • #IfTimeout [AHK_L8+]Setsthemaximumtimethatmaybespentevaluatingasingle#Ifexpression.

    #IfTimeoutTimeout

    Parameters

    TimeoutThetimeoutvaluetoapplyglobally,inmilliseconds.

    Remarks

    Atimeoutisimplementedtopreventlong-runningexpressionsfromstallingkeyboardinputprocessing.Ifthetimeoutvalueisexceeded,theexpressioncontinuestoevaluate,butthekeyboardhookcontinuesasiftheexpressionhadalreadyreturnedfalse.

    Ifthisdirectiveisunspecifiedinthescript,itwillbehaveasthoughsetto1000.

    Notethatthesystemimplementsitsowntimeout,definedbytheDWORDvalueLowLevelHooksTimeoutinthefollowingregistrykey:

    HKEY_CURRENT_USER\ControlPanel\Desktop

    Ifthesystemtimeoutvalueisexceeded,thesystemmaystopcallingthescript'skeyboardhook,therebypreventinghookhotkeysfromworkinguntilthehookisre-registeredorthescriptisreloaded.Thehookcanusuallybere-registeredbysuspendingandun-suspendingallhotkeys.

    Ifagivenhotkeyhasmultiple#Ifvariants,thetimeoutmightbeappliedtoeachvariantindependently,makingitmorelikelythatthesystemtimeoutwillbeexceeded.Thismaybechangedinafutureupdate.

    Related

  • #If

    Example

    #IfTimeout10;Setthetimeoutto10ms.

  • #IfWinActive/#IfWinExistCreatescontext-sensitivehotkeysandhotstrings.Suchhotkeysperformadifferentaction(ornoneatall)dependingonthetypeofwindowthatisactiveorexists.

    #IfWinActive[,WinTitle,WinText]#IfWinExist[,WinTitle,WinText]#IfWinNotActive[,WinTitle,WinText]#IfWinNotExist[,WinTitle,WinText]#If[,Expression]

    Parameters

    WinTitleAwindowtitleorothercriteriaidentifyingthetargetwindow.SeeWinTitle.

    TitlematchingbehaviourisdeterminedbySetTitleMatchModeassetintheauto-executesection.

    Aswithmostotherdirectives,variablesarenotsupported.Althoughahk_pidandahk_idcanbeusedwithahard-codedprocessorwindowID,itismorecommonfor#IfWintousethemindirectlyviaGroupAddorHotkeyIfWin.

    WinTextIfpresent,thisparametermustbeasubstringfromasingletextelementofthetargetwindow(asrevealedbytheincludedWindowSpyutility).HiddentextelementsaredetectedifDetectHiddenTexthasbeenturnedonintheauto-executesection(toppartofthescript).

    ExcludeTitleExcludeText

  • Althoughthesearenotsupported,theycanbeusedindirectlybyspecifying ahk_groupMyGroup forWinTitle(whereMyGroupisagroupcreatedviaGroupAdd,whichsupportsExcludeTitle/Text).

    BasicOperation

    The#IfWindirectivesmakeiteasytocreatecontext-sensitivehotkeysandhotstrings.Forexample:

    #IfWinActiveahk_classNotepad#space::MsgBoxYoupressedWin+SpacebarinNotepad.

    The#IfWindirectivesarepositional:theyaffectallhotkeysandhotstringsphysicallybeneaththeminthescript.Theyarealsomutuallyexclusive;thatis,onlythemostrecentonewillbeineffect.

    Toturnoffcontextsensitivity,specifyany#IfWindirectivebutomitallofitsparameters.Forexample:

    #IfWinActive

    When#IfWinisturnedoff(orneverusedinascript),allhotkeysandhotstringsareenabledforallwindows(unlessdisabledviaSuspendortheHotkeycommand).

    Whenamouseorkeyboardhotkeyisdisabledvia#IfWin,itperformsitsnativefunction;thatis,itpassesthroughtotheactivewindowasthoughthereisnosuchhotkey.Thereisoneexception:Joystickhotkeys:although#IfWinworks,itneverpreventsotherprogramsfromseeingthepressofabutton.

    #IfWincanalsobeusedtoalterthebehaviorofanordinarykeylikeEnterorSpace.Thisisusefulwhenaparticularwindowignoresthatkeyorperformssomeactionyoufindundesirable.Forexample:

    #IfWinActiveRemindersahk_class#32770;The

  • "reminders"windowinOutlook.Enter::Send!o;Havean"Enter"keystrokeopentheselectedreminderratherthansnoozingit.#IfWinActive

    Variant(Duplicate)Hotkeys

    Aparticularhotkeyorhotstringcanbedefinedmorethanonceinthescriptifeachdefinitionhasdifferent#IfWincriteria.Theseareknownashotkeyvariants.Forexample:

    #IfWinActiveahk_classNotepad^!c::MsgBoxYoupressedControl+Alt+CinNotepad.#IfWinActiveahk_classWordPadClass^!c::MsgBoxYoupressedControl+Alt+CinWordPad.#IfWinActive^!c::MsgBoxYoupressedControl+Alt+CinawindowotherthanNotepad/WordPad.

    Ifmorethanonevariantiseligibletofire,onlytheoneclosesttothetopofthescriptwillfire.Theexceptiontothisistheglobalvariant(theonewithno#IfWincriteria):Italwayshasthelowestprecedence;therefore,itwillfireonlyifnoothervariantiseligible(thisexceptiondoesnotapplytohotstrings).

    Whencreatingduplicatehotkeys,theorderofmodifiersymbolssuchas^!+#doesnotmatter.Forexample, ^!c isthesameas !^c .However,keysmustbespelledconsistently.Forexample,EscisnotthesameasEscapeforthispurpose(thoughthecasedoesnotmatter).Also,anyhotkeywithawildcardprefix(*)isentirelyseparatefromanon-wildcardone;forexample, *F1 andF1 wouldeachhavetheirownsetofvariants.

    Tohavethesamehotkeysubroutineexecutedbymorethanonevariant,theeasiestwayistocreateastackofidenticalhotkeys,eachwithadifferent#IfWindirectiveaboveit.Forexample:

  • #IfWinActiveahk_classNotepad#z::#IfWinActiveahk_classWordPadClass#z::MsgBoxYoupressedWin+ZineitherNotepadorWordPad.return

    Alternatively,awindowgroupcanbeusedvia #IfWinActiveahk_groupMyGroup .

    Tocreatehotkeyvariantsdynamically(whilethescriptisrunning),see"HotkeyIfWin".

    GeneralRemarks

    #IfWinalsorestoresprefixkeystotheirnativefunctionwhenappropriate(aprefixkeyisthe"a"keyinahotkeysuchas"a&b").Thisoccurswhenevertherearenoenabledhotkeysforagivenprefix.

    WhenGosuborGotoisusedtojumptoahotkeyorhotstringlabel,itjumpstothevariantclosesttothetopofthescript.

    Whenahotkeyiscurrentlydisabledvia#IfWin,itskeyormousebuttonwillappearwitha"#"characterinKeyHistory's"Type"column.Thiscanhelpdebugascript.

    Variablereferencessuchas%Var%arenotcurrentlysupported.Therefore,percentsignsmustbeescapedvia`%toallowfuturesupportforthem.Similarly,literalcommasmustbeescaped(via`,)toallowadditionalparameterstobeaddedinthefuture.Ifyouneedtoworkaroundthislimitation,useGroupAddandahk_group.

    AlabeltowhichtheHotkeycommandhasassignedahotkeyisnotdirectlyaffectedby#IfWin.Instead,theuseof#IfWinclosesttothebottomofthescript(ifany)willbeineffectforallhotkeyscreatedbytheHotkeycommand(unless"HotkeyIfWin"hasbeenusedtochangethat).

  • Alt-tabhotkeysarenotaffectedby#IfWin:theyareineffectforallwindows.

    TheLastFoundWindowissetby#IfWinActive/Exist(thoughnotby#IfWinNotActive/NotExist).Forexample:

    #IfWinExistahk_classNotepad#n::WinActivate;Activatesthewindowfoundby#IfWin.

    Theescapesequences`sand`tmaybeusedifleadingortrailingspaces/tabsareneededinoneof#IfWin'sparameters.

    Forperformancereasons,#IfWindoesnotcontinuouslymonitortheactivationorexistenceofthespecifiedwindows.Instead,itchecksforamatchingwindowonlywhenyoutypeahotkeyorhotstring.Ifamatchingwindowisnotpresent,yourkeystrokeormouseclickisallowedtopassthroughtotheactivewindowunaltered.

    Windowtitlesandtextarecasesensitive.HiddenwindowsarenotdetectedunlessDetectHiddenWindowshasbeenturnedonintheauto-executesection(toppartofthescript).

    Related

    #Ifexpression,Hotkeycommand,Hotkeys,Hotstrings,Suspend,IfWinActive,IfWinExist,SetTitleMatchMode,DetectHiddenWindows

    Examples

    #IfWinActiveahk_classNotepad^!a::MsgBoxYoupressedCtrl-Alt-AwhileNotepadisactive.;Thishotkeywillhavenoeffectifpressedinotherwindows(anditwill"passthrough").#c::MsgBoxYoupressedWin-CwhileNotepadisactive.::btw::Thisreplacementtextfor"btw"willoccur

  • onlyinNotepad.#IfWinActive#c::MsgBoxYoupressedWin-CinawindowotherthanNotepad.

  • #Include/#IncludeAgainCausesthescripttobehaveasthoughthespecifiedfile'scontentsarepresentatthisexactposition.

    #IncludeFileOrDirName#Include#IncludeAgainFileOrDirName

    Parameters

    FileOrDirNameThepathofafileordirectoryasexplainedbelow.Thismustnotcontaindoublequotes,wildcards,orvariablereferencesexcept%A_ScriptDir%,%A_AppData%,%A_AppDataCommon%and[inv1.1.11+]%A_LineFile%.Escapesequencesotherthansemicolon(`;)mustnotbeused,noraretheyneededbecausecharacterssuchaspercentsignsaretreatedliterally.

    File:Thenameofthefiletobeincluded,whichisassumedtobeinthestartup/workingdirectoryifanabsolutepathisnotspecified(exceptforahk2exe,whichassumesthefileisinthescript'sowndirectory).Note:SetWorkingDirhasnoeffecton#Includebecause#Includeisprocessedbeforethescriptbeginsexecuting.

    Directory:Specifyadirectoryinsteadofafiletochangetheworkingdirectoryusedbyallsubsequentoccurrencesof#IncludeandFileInstall.Note:Changingtheworkingdirectoryinthiswaydoesnotaffectthescript'sinitialworkingdirectorywhenitstartsrunning(A_WorkingDir).Tochangethat,useSetWorkingDiratthetopofthescript.

    LibName[AHK_L57+]:Alibraryfileorfunctionname.Forexample, #include and #include wouldbothincludelib.ahkfromoneofthefunctionlibraryfolders.LibNamecannotcontainvariable

  • references.

    Remarks

    Ascriptbehavesasthoughtheincludedfile'scontentsarephysicallypresentattheexactpositionofthe#Includedirective(asthoughacopy-and-pasteweredonefromtheincludedfile).Consequently,itgenerallycannotmergetwoisolatedscriptstogetherintoonefunctioningscript(toachievethat,seewww.autohotkey.com/forum/topic18545.html).

    #IncludeensuresthatFileNameisincludedonlyonce,evenifmultipleinclusionsareencounteredforit.Bycontrast,#IncludeAgainallowsmultipleinclusionsofthesamefile,whilebeingthesameas#Includeinallotherrespects.

    TheFileNameparametermayoptionallybeprecededby*iandasinglespace,whichcausestheprogramtoignoreanyfailuretoreadtheincludedfile.Forexample: #Include*iSpecialOptions.ahk .Thisoptionshouldbeusedonlywhentheincludedfile'scontentsarenotessentialtothemainscript'soperation.

    LinesdisplayedinthemainwindowviaListLinesorthemenuView->Linesarealwaysnumberedaccordingtotheirphysicalorderwithintheirownfiles.Inotherwords,includinganewfilewillchangethelinenumberingofthemainscriptfilebyonlyoneline,namelythatofthe#Includelineitself(exceptforcompiledscripts,whichmergetheirincludedfilesintoonebigscriptatthetimeofcompilation).

    #Includeisoftenusedtoloadfunctionsdefinedinanexternalfile.Unlikesubroutinelabels,functionscanbeincludedattheverytopofthescriptwithoutaffectingtheauto-executesection.

    Likeother#directives,#Includecannotbeexecutedconditionally.Inotherwords,thisexamplewouldnotwork:

    ifx=1#IncludeSomeFile.ahk;Thislinetakeseffectregardlessofthevalueofx.

    http://www.autohotkey.com/forum/topic18545.html

  • y=2;AndthislinewouldbelongtotheIFabove,since#directivescannotbelongtoIFs.

    Filescanbeautomaticallyincluded(i.e.withouthavingtouse#Include)bycallingalibraryfunctionbyname.

    [v1.1.11+]:Use %A_LineFile%\.. torefertothedirectorywhichcontainsthecurrentfile,evenifitisnotthemainscriptfile.Forexample, #Include%A_LineFile%\..\other.ahk .

    Related

    LibrariesofFunctions,Functions,FileInstall

    Example

    #IncludeC:\MyDocuments\Scripts\UtilitySubroutines.ahk#Include%A_ScriptDir%;Changestheworkingdirectoryforsubsequent#IncludesandFileInstalls.#IncludeC:\MyScripts;Sameasabovebutforanexplicitlynameddirectory.

  • #InputLevel [v1.1.06+]Controlswhichartificialkeyboardandmouseeventsareignoredbyhotkeysandhotstrings.

    #InputLevel[,Level]

    Parameters

    LevelAnintegerbetween0and100.Ifomitted,itdefaultsto0.

    GeneralRemarks

    ForanexplanationofhowSendLeveland#InputLevelareused,seeSendLevel.

    Thisdirectiveispositional:itaffectsallhotkeysandhotstringsbetweenitandthenext#InputLeveldirective.Ifnotspecifiedbyan#InputLeveldirective,hotkeysandhotstringsdefaulttolevel0.

    [v1.1.23+]:Ahotkey'sinputlevelcanalsobesetusingtheHotkeycommand.Forexample: Hotkey,#z,my_hotkey_sub,I1

    Theinputlevelofahotkeyornon-auto-replacehotstringisalsousedasthedefaultsendlevelforanykeystrokesorbuttonclicksgeneratedbythathotkeyorhotstring.Sinceakeyboardormouseremappingisactuallyapairofhotkeys,thisallows#InputLeveltobeusedtoallowremappingstotriggerotherhotkeys.

    AutoHotkeyversionsolderthan[v1.1.06]behaveasthough#InputLevel0andSendLevel0areineffect.

    Related

    SendLevel,Hotkeys,Hotstrings

  • Examples

    #InputLevel1Numpad0::LButton#InputLevel0;ThishotkeycanbetriggeredbybothNumpad0andLButton:~LButton::MsgboxClicked

  • #InstallKeybdHookForcestheunconditionalinstallationofthekeyboardhook.

    #InstallKeybdHook

    Remarks

    ThekeyboardhookmonitorskeystrokesforthepurposeofactivatinghotstringsandanykeyboardhotkeysnotsupportedbyRegisterHotkey(whichisafunctionbuiltintotheoperatingsystem).ItalsosupportsafewotherfeaturessuchastheInputcommand.

    AutoHotkeydoesnotinstallthekeyboardandmousehooksunconditionallybecausetogethertheyconsumeatleast500KBofmemory.Therefore,thekeyboardhookisnormallyinstalledonlywhenthescriptcontainsoneofthefollowing:1)hotstrings;2)oneormorehotkeysthatrequirethekeyboardhook(mostdonot);3)SetCaps/Scroll/NumlockAlwaysOn/AlwaysOff;4)theInputcommand,forwhichthehookisinstalleduponfirstactualuse.

    Bycontrast,the#InstallKeybdHookdirectivewillunconditionallyinstallthekeyboardhook,whichmightbeusefultoallowKeyHistorytodisplaythelast20keystrokes(fordebuggingpurposes),ortoavoidtheneedfor#HotkeyModifierTimeout.

    YoucandeterminewhetherascriptisusingthehookviatheKeyHistorycommandormenuitem.YoucandeterminewhichhotkeysareusingthehookviatheListHotkeyscommandormenuitem.

    Thisdirectivealsomakesascriptpersistent,meaningthatExitAppshouldbeusedtoterminateit.

    Related

    #InstallMouseHook,#UseHook,Hotkey,Input,#Persistent,KeyHistory,Hotstrings,GetKeyState,KeyWait

  • Example

    #InstallKeybdHook

  • #InstallMouseHookForcestheunconditionalinstallationofthemousehook.

    #InstallMouseHook

    Remarks

    Themousehookmonitorsmouseclicksforthepurposeofactivatingmousehotkeysandfacilitatinghotstrings.

    AutoHotkeydoesnotinstallthekeyboardandmousehooksunconditionallybecausetogethertheyconsumeatleast500KBofmemory(butifthekeyboardhookisinstalled,installingthemousehookonlyrequiresabout50KBofadditionalmemory;andviceversa).Therefore,themousehookisnormallyinstalledonlywhenthescriptcontainsoneormoremousehotkeys.Itisalsoinstalledforhotstrings,butthatcanbedisabledvia#HotstringNoMouse.

    Bycontrast,the#InstallMouseHookdirectivewillunconditionallyinstallthemousehook,whichmightbeusefultoallowKeyHistorytomonitormouseclicks.

    YoucandeterminewhetherascriptisusingthehookviatheKeyHistorycommandormenuitem.YoucandeterminewhichhotkeysareusingthehookviatheListHotkeyscommandormenuitem.

    Thisdirectivealsomakesascriptpersistent,meaningthatExitAppshouldbeusedtoterminateit.

    Related

    #InstallKeybdHook,#UseHook,Hotkey,#Persistent,KeyHistory,GetKeyState,KeyWait

    Example

  • #InstallMouseHook

  • #KeyHistorySetsthemaximumnumberofkeyboardandmouseeventsdisplayedbytheKeyHistorywindow.Youcansetitto0todisablekeyhistory.

    #KeyHistoryMaxEvents

    Parameters

    MaxEventsThemaximumnumberofkeyboardandmouseeventsdisplayedbytheKeyHistorywindow(default40,limit500).Specify0todisablekeyhistoryentirely.

    Remarks

    Becausethissettingisputintoeffectbeforethescriptbeginsrunning,itisonlynecessarytospecifyitonce(anywhereinthescript).

    Becauseeachkeystrokeormouseclickconsistsofadown-eventandanup-event,KeyHistorydisplaysonlyhalfasmany"completeevents"asspecifiedhere.Forexample,ifthescriptcontains #KeyHistory50 ,upto25keystrokesandmouseclickswillbedisplayed.

    Related

    KeyHistory,#NoTrayIcon

    Example

    #KeyHistory0;Disablekeyhistory.#KeyHistory100;Storeupto100events.

  • #MaxHotkeysPerIntervalAlongwith#HotkeyInterval,specifiestherateofhotkeyactivationsbeyondwhichawarningdialogwillbedisplayed.

    #MaxHotkeysPerIntervalValue

    Parameters

    ValueThemaximumnumberofhotkeysthatcanbepressedintheintervalspecifiedby#HotkeyIntervalwithouttriggeringawarningdialog.

    Remarks

    Careshouldbetakennottomaketheabovetoolenientbecauseifyoueverinadvertentlyintroduceaninfiniteloopofkeystrokes(viaaSendcommandthataccidentallytriggersotherhotkeys),yourcomputercouldbecomeunresponsiveduetotherapidfloodofkeyboardevents.

    Asanoversimplifiedexample,thehotkey ^c::Send^c wouldproduceaninfiniteloopofkeystrokes.Toavoidthis,addthe$prefixtothehotkeydefinition(e.g. $^c:: )sothatthehotkeycannotbetriggeredbytheSendcommand.

    Ifthisdirectiveisunspecifiedinthescript,itwillbehaveasthoughsetto70.

    Related

    #HotkeyInterval

    Example

    #MaxHotkeysPerInterval200

  • #MaxMemSetsthemaximumcapacityofeachvariabletothespecifiednumberofmegabytes.

    #MaxMemMegabytes

    Parameters

    MegabytesThenumberofmegabytestoallowforeachvariable.Avaluelargerthan4095isconsideredtobe4095.Avaluelessthan1isconsideredtobe1.

    Remarks

    Ifthisdirectiveisunspecifiedinthescript,itwillbehaveasthoughsetto64.

    Thepurposeoflimitingeachvariable'scapacityistopreventabuggyscriptfromconsumingallavailablesystemmemory.Raisingorloweringthelimitdoesnotaffecttheperformanceofascript,nordoesitchangehowmuchmemorythescriptactuallyuses(exceptinthecaseofWinGetTextandControlGetText,whichwillbecapableofretrievingmoretextif#MaxMemisincreased).

    Thissettingisglobal,meaningthatitneedstobespecifiedonlyonce(anywhereinthescript)toaffectthebehavioroftheentirescript.

    Thissettingrestrictsonlytheautomaticexpansionthatavariabledoesonitsown.ItdoesnotaffectVarSetCapacity.

    Related

    VarSetCapacity,Variables,Sort,WinGetText,ControlGetText,#MaxThreads

    Example

  • #MaxMem256;Allow256MBpervariable.

  • #MaxThreadsSetsthemaximumnumberofsimultaneousthreads.

    #MaxThreadsValue

    Parameters

    ValueThemaximumtotalnumberofthreadsthatcanexistsimultaneously.Specifyinganumberhigherthan255isthesameasspecifying255(inversionspriorto1.0.48,thelimitwas20).

    Remarks

    Thissettingisglobal,meaningthatitneedstobespecifiedonlyonce(anywhereinthescript)toaffectthebehavioroftheentirescript.

    Althoughavalueof1isallowed,itisnotrecommendedbecauseitwouldpreventnewhotkeysfromlaunchingwheneverthescriptisdisplayingaMsgBoxorotherdialog.Itwouldalsopreventtimersfromrunningwheneveranotherthreadissleepingorwaiting.

    Uptotwoofthefollowingtypesofthreadsmaybecreatedevenwhen#MaxThreadshasbeenreached:Ahotkey,hotstring,OnClipboardChange,orGUIeventifthefirstlineofitssubroutineisExitApp,Pause,Edit,Reload,KeyHistory,ListLines,ListVars,orListHotkeys.Also,theOnExitsubroutinewillalwayslaunchregardlessofhowmanythreadsexist.

    Ifthissettingislowerthan#MaxThreadsPerHotkey,iteffectivelyoverridesthatsetting.

    Ifthisdirectiveisunspecifiedinthescript,itwillbehaveasthoughsetto10.

    Related

  • #MaxThreadsPerHotkey,Threads,#MaxHotkeysPerInterval,#HotkeyInterval,ListHotkeys,#MaxMem

    Example

    #MaxThreads2

  • #MaxThreadsBufferCausessomeorallhotkeystobufferratherthanignorekeypresseswhentheir#MaxThreadsPerHotkeylimithasbeenreached.

    #MaxThreadsBufferOn|Off

    Parameters

    On|OffOn:Allhotkeysubroutinesbetweenhereandthenext#MaxThreadsBufferON directivewillbufferratherthanignorepressesoftheirhotkeyswhenevertheirsubroutinesareattheir#MaxThreadsPerHotkeylimit.

    Off:Thisisthedefaultbehavior.Ahotkeypresswillbeignoredwheneverthathotkeyisalreadyrunningitsmaximumnumberofthreads(usually1,butthiscanbechangedwith#MaxThreadsPerHotkey).

    Remarks

    Thisdirectiveisrarelyusedbecausethistypeofbuffering,whichisOFFbydefault,usuallydoesmoreharmthangood.Forexample,ifyouaccidentallypressahotkeytwice,havingthissettingONwouldcausethathotkey'ssubroutinetoautomaticallyrunasecondtimeifitsfirstthreadtakeslessthan1secondtofinish(thistypeofbufferexpiresafter1second,bydesign).NotethatAutoHotkeybuffershotkeysinseveralotherways(suchas ThreadInterrupt and Critical ).It'sjustthatthisparticularwaycanbedetrimental,thusitisOFFbydefault.

    Themainuseforthisdirectiveistoincreasetheresponsivenessofthekeyboard'sauto-repeatfeature.Forexample,whenyouholddownahotkeywhose#MaxThreadsPerHotkeysettingis1(thedefault),incomingkeypressesareignoredifthathotkeysubroutineisalreadyrunning.Thus,whenthesubroutinefinishes,itmustwaitforthenextauto-repeatkeypresstocomein,

  • whichmighttake50msormoreduetobeingcaughtinbetweenkeystrokesoftheauto-repeatcycle.This50msdelaycanbeavoidedbyenablingthisdirectiveforanyhotkeythatneedsthebestpossibleresponsetimewhileitisbeingauto-repeated.

    Aswithall#directives,thisoneshouldnotbepositionedinthescriptasthoughitwereacommand(i.e.itisnotnecessarytohaveitcontainedwithinasubroutine).Instead,positionitimmediatelybeforethefirsthotkeylabelyouwishtohaveaffectedbyit.

    Related

    #MaxThreads,#MaxThreadsPerHotkey,Critical,Thread(command),Threads,Hotkey,#MaxHotkeysPerInterval,#HotkeyInterval,ListHotkeys

    Example

    #MaxThreadsBufferon#x::MsgBox,Thishotkeywillusethistypeofbuffering.#y::MsgBox,Andthisonetoo.#MaxThreadsBufferoff#z::MsgBox,Butnotthisone.

  • #MaxThreadsPerHotkeySetsthemaximumnumberofsimultaneousthreadsperhotkeyorhotstring.

    #MaxThreadsPerHotkeyValue

    Parameters

    ValueThemaximumnumberofthreadsthatcanbelaunchedforagivenhotkey/hotstringsubroutine(limit255).

    Remarks

    Thissettingisusedtocontrolhowmany"instances"ofagivenhotkeyorhotstringsubroutineareallowedtoexistsimultaneously.Forexample,ifahotkeyhasamaxof1anditispressedagainwhileitssubroutineisalreadyrunning,thepresswillbeignored.Thisishelpfultopreventaccidentaldouble-presses.However,ifyouwishthesekeypressestobebufferedratherthanignored--perhapstoincreasetheresponsivenessofthekeyboard'sauto-repeatfeature--use#MaxThreadsBuffer.

    Unlike#MaxThreads,thissettingisnotglobal.Instead,positionitbeforethefirsthotkeylabelyouwishtohaveaffectedbyit,whichwillresultinallsubsequenthotkeysusingthatvalueuntilanotherinstanceofthisdirectiveisencountered.

    AnyhotkeysubroutinewhosefirstlineisExitApp,Pause,Edit,Reload,KeyHistory,ListLines,ListVars,orListHotkeyswillalwaysrunregardlessofthissetting.

    Thesettingof#MaxThreads--iflowerthanthissetting--takesprecedence.

    Ifthisdirectiveisunspecifiedinthescript,itwillbehaveasthoughsetto1.

    Related

  • #MaxThreads,#MaxThreadsBuffer,Critical,Threads,Hotkey,#MaxHotkeysPerInterval,#HotkeyInterval,ListHotkeys

    Example

    #MaxThreadsPerHotkey3

  • #MenuMaskKey [AHK_L38+]ChangeswhichkeyisusedtomaskWinorAltkeyupevents.

    #MenuMaskKeyKeyName

    Parameters

    KeyNameAkeynameorvkNNsequencewhichspecifiesanon-zerovirtualkeycode.Scancodesarenotused.

    Remarks

    ThedefaultmaskkeyisCtrl.Thisdirectivecanbeusedtochangethemaskkeytoakeywithfewersideeffects.

    Thissettingisglobal,meaningthatitneedstobespecifiedonlyonce(anywhereinthescript)toaffectthebehavioroftheentirescript.

    ThemaskkeyissentautomaticallytopreventtheStartmenuortheactivewindow'smenubarfromactivatingatunexpectedtimes.

    Hotkeys:Ifahotkeyisimplementedusingthekeyboardhookormousehook,thefinalkeypressmaybeinvisibletotheactivewindowandthesystem.IfthesystemwastodetectonlyaWinorAltkeydownandkeyupwithnointerveningkeypress,itwouldusuallyactivateamenu.Topreventthis,thekeyboardormousehookmayautomaticallysendthemaskkey.

    [v1.1.27+]:PressingahookhotkeycausesthenextAltorWinkeyuptobemaskedifallofthefollowingconditionsaremet:

    Thehotkeyissuppressed(itlacksthetildemodifier).AltorWinislogicallydownwhenthehotkeyispressed.Themodifierisphysicallydownorthehotkeyrequiresthemodifiertoactivate.Forexample, $#a:: incombinationwith AppsKey::RWin

  • causesmaskingwhenAppsKey+Aispressed,butAppsKeyonitsownisabletoopentheStartMenu.AltisnotmaskedifCtrlwasdownwhenthehotkeywaspressed,sinceCtrl+Altdoesnotactivatethemenubar.WinisnotmaskedifthemostrecentWinkeydownwasmodifiedwithCtrl,ShiftorAlt,sincetheStartMenudoesnotnormallyactivateinthosecases.However,key-repeatoccursevenfortheWinkeyifitwasthelastkeyphysicallypressed,soitcanbehardtopredictwhenthemostrecentWinkeydownwas.Eitherthekeyboardhookisnotinstalled(i.e.foramousehotkey),ortherehavebeennoother(unsuppressed)keydownorkeyupeventssincethelastAltorWinkeydown.Notethatkey-repeatoccursevenformodifierkeysandevenaftersendingotherkeys,butonlyforthelastphysicallypressedkey.

    Mousehotkeysmaysendthemaskkeyimmediatelyifthekeyboardhookisnotinstalled.

    Hotkeyswiththetildemodifierarenotintendedtoblockthenativefunctionofthekey,soin[v1.1.27+]theydonotcausemasking.Hotkeyslike ~#a:: stillsuppressthemenu,sincethesystemdetectsthattheWinkeyhasbeenusedincombinationwithanotherkey.However,mousehotkeysandtheWinkeysthemselves( ~LWin:: and ~RWin:: )donotsuppresstheStartMenu.

    TheStartMenu(ortheactivewindow'smenubar)canbesuppressedbysendinganykeystroke.ThefollowingexampledisablestheabilityforLWintoactivatetheStartMenu,whilestillallowingitsuseasamodifier:

    ~LWin::Send{Blind}{vk07}

    Send:Send,ControlSendandrelatedoftenreleasemodifierkeysaspartoftheirnormaloperation.Forexample,thehotkey

  • Seethisthreadforbackgroundinformation.

    Examples

    #MenuMaskKeyvk07;vk07isunassigned.#UseHook#Space::!Space::KeyWaitLWinKeyWaitRWinKeyWaitAltKeyHistoryreturn

    https://autohotkey.com/board/topic/20619-extraneous-control-key-presses-generated-by-or-hotkeys/

  • #NoEnv [v1.0.43.08+]Avoidscheckingemptyvariablestoseeiftheyareenvironmentvariables(recommendedforallnewscripts).

    #NoEnv

    Specifyingtheline #NoEnv anywhereinascriptpreventsemptyvariablesfrombeinglookedupaspotentialenvironmentvariables.Forexample:

    #NoEnvMsgBox%WinDir%

    Theabovewouldnotretrievethe"WinDir"environmentvariable(thoughthatcouldbesolvedbydoing WinDir:=A_WinDir nearthetopofthescript).

    Specifying #NoEnv isrecommendedforallnewscriptsbecause:

    1. Itsignificantlyimprovesperformancewheneveremptyvariablesareusedinanexpressionorcommand.ItalsoimprovesDllCall'sperformancewhenunquotedparametertypesareused(e.g.intvs."int").

    2. Itpreventsscriptbugscausedbyenvironmentvariableswhosenamesunexpectedlymatchvariablesusedbythescript.

    3. AutoHotkeyv2willmakethisbehaviorthedefault.

    Tohelpeasethetransitionto#NoEnv,thebuilt-invariablesComspecandProgramFileshavebeenadded.Theycontainthesamestringsasthecorrespondingenvironmentvariables.

    When#NoEnvisineffect,thescriptshoulduseEnvGettoretrieveenvironmentvariables,orusebuilt-invariableslikeA_WinDir.

    Related

    EnvGet,Comspec,ProgramFiles,A_WinDir

    https://autohotkey.com/v2/

  • #NoTrayIconDisablestheshowingofatrayicon.

    #NoTrayIcon

    Specifyingthisanywhereinascriptwillpreventtheshowingofatrayiconforthatscriptwhenitislaunched(evenifthescriptiscompiledintoanEXE).

    Ifyouusethisforascriptthathashotkeys,youmightwanttobindahotkeytotheExitAppcommand.Otherwise,therewillbenoeasywaytoexittheprogram(withoutrestartingthecomputerorkillingtheprocess).Forexample:#x::ExitApp .

    Thetrayiconcanbemadetodisappearorreappearatanytimeduringtheexecutionofthescriptbyusingthecommand Menu,Tray,Icon orMenu,Tray,NoIcon .Theonlydrawbackofusing Menu,Tray,NoIcon attheverytopofthescriptisthatthetrayiconmightbebrieflyvisiblewhenthescriptisfirstlaunched.Toavoidthat,use#NoTrayIconinstead.

    Thebuilt-invariableA_IconHiddencontains1ifthetrayiconiscurrentlyhiddenor0otherwise.

    Related

    Menu,ExitApp

    Example

    #NoTrayIcon

  • #PersistentKeepsascriptpermanentlyrunning(thatis,untiltheuserclosesitorExitAppisencountered).

    #Persistent

    Ifthisdirectiveispresentanywhereinthescript,thatscriptwillstayrunningaftertheauto-executesection(toppartofthescript)completes.Thisisusefulincaseswhereascriptcontainstimersand/orcustommenuitemsbutnothotkeys,hotstrings,oranyuseofOnMessage()orGui.

    Ifthisdirectiveisaddedtoanexistingscript,youmightwanttochangesomeoralloccurrencesofExittobeExitApp.ThisisbecauseExitwillnotterminateapersistentscript;itterminatesonlythecurrentthread.

    [v1.0.16+]:Thisdirectivealsomakesascriptsingle-instance.Tooverridethisorchangethewaysingle-instancebehaves,see#SingleInstance.

    Related

    #SingleInstance,SetTimer,Menu,Exit,ExitApp

    Example

    #Persistent

  • #SingleInstanceDetermineswhetherascriptisallowedtorunagainwhenitisalreadyrunning.

    #SingleInstance[force|ignore|off]

    Parameters

    force|ignore|offThisparameterdetermineswhathappenswhenascriptislaunchedwhileapreviousinstanceofitselfisalreadyrunning:

    ThewordFORCEskipsthedialogboxandreplacestheoldinstanceautomatically,whichissimilarineffecttotheReloadcommand.

    ThewordIGNOREskipsthedialogboxandleavestheoldinstancerunning.Inotherwords,attemptstolaunchanalready-runningscriptareignored.

    ThewordOFFallowsmultipleinstancesofthescripttorunconcurrently.

    Iftheparameterisomitted,adialogboxisdisplayedaskingwhethertokeeptheoldinstanceorreplaceitwiththenewone.

    Remarks

    Ascriptcontaininghotkeys,hotstrings,#Persistent,OnMessage(),orGuiissingle-instance(dialog&prompt)bydefault.Otherscriptsdefaulttoallowingmultipleinstances.Thisbehaviorcanbedisabledormodifiedasdescribedabove.

    Thisdirectiveisignoredwhenanyofthefollowingcommandlineswitchesareused:/force/f/restart/r

    Related

  • Reload,#Persistent

    Example

    #SingleInstanceforce#SingleInstanceignore#SingleInstanceoff

  • #UseHookForcestheuseofthehooktoimplementallorsomekeyboardhotkeys.

    #UseHook[On|Off]

    Parameters

    On|Off#UseHookwithoutoneofthefollowingwordsafteritisequivalentto#UseHookOn .

    On:Thekeyboardhookwillbeusedtoimplementallkeyboardhotkeysbetweenhereandthenext #UseHookOFF (ifany).

    Off:Hotkeyswillbeimplementedusingthedefaultmethod(RegisterHotkey()ifpossible;otherwise,thekeyboardhook).

    Remarks

    Normally,thewindowsAPIfunctionRegisterHotkey()isusedtoimplementakeyboardhotkeywheneverpossible.However,theresponsivenessofhotkeysmightbebetterundersomeconditionsifthekeyboardhookisusedinstead.

    TurningthisdirectiveONisequivalenttousingthe$prefixinthedefinitionofeachaffectedhotkey.

    Aswithall#directives--whichareprocessedonlyoncewhenthescriptislaunched-- #UseHook shouldnotbepositionedinthescriptasthoughitwereacommand(thatis,itisnotnecessarytohaveitcontainedwithinasubroutine).Instead,positionitimmediatelybeforethefirsthotkeylabelyouwishtohaveaffectedbyit.

    Bydefault,hotkeysthatusethekeyboardhookcannotbetriggeredbymeansoftheSendcommand.Similarly,mousehotkeyscannotbetriggeredbycommandssuchasClickbecauseallmousehotkeysusethemousehook.Oneworkaround

  • istouseGosubtojumpdirectlytothehotkey'ssubroutine.Forexample:Gosub#LButton .

    [v1.1.06+]:#InputLevelandSendLevelprovideadditionalcontroloverwhichhotkeysandhotstringsaretriggeredbytheSendcommand.

    Ifthisdirectivedoesnotappearinthescriptatall,itwillbehaveasthoughsettoOFF.

    Related

    #InstallKeybdHook,#InstallMouseHook,ListHotkeys,#InputLevel

    Example

    #UseHook;Forcetheuseofthehookforhotkeysafterthispoint.#x::MsgBox,Thishotkeywillbeimplementedwiththehook.#y::MsgBox,Andthisonetoo.#UseHookoff#z::MsgBox,Butnotthisone.

  • #Warn [v1.0.95.00+]Enablesordisableswarningsforspecificconditionswhichmayindicateanerror,suchasatypoormissing"global"declaration.

    #Warn[,WarningType,WarningMode]

    Parameters

    WarningTypeThetypeofwarningtoenableordisable.Ifomitted,itdefaultstoAll.

    UseUnsetLocalorUseUnsetGlobal:WarnwhenavariableisreadwithouthavingpreviouslybeenassignedavalueorinitializedwithVarSetCapacity.Ifthevariableisintendedtobeempty,assignanemptystringtosuppressthiswarning.

    Thisissplitintoseparatewarningtypesforlocalsandglobalsbecauseitismorecommontouseaglobalvariablewithoutpriorinitialization,duetotheirpersistentandscript-widenature.Forthisreason,somescriptauthorsmaywishtoenablethistypeofwarningforlocalsbutdisableitforglobals.

    #Warn;y:="";Thiswouldsuppressthewarning.x:=y;yhasn'tbeenassignedavalue.

    UseEnv:Warnwhenanenvironmentvariableisautomaticallyusedinplaceofanemptyscriptvariable.Thissometimesoccurswhenanenvironmentvariable'snameunexpectedlymatchesavariableusedbythescript.Thiswarningoccurswhenthevariableisaccessed,butneveroccursifthescriptenables#NoEnv(recommendedformultiplereasons).

  • #Warn;#NoEnv;Addthisif"temp"isnotintendedtobeanenvironmentvariable.;EnvGettemp,TEMP;Thiswouldcopytheenvironmentvariable'svalueintothescriptvariable.temp:="";Despitethisline,tempstillseemstohaveavalue.MsgBox%temp;Thisaccessestheenvironmentvariablenamed"TEMP".

    LocalSameAsGlobal:Beforethescriptstartstorun,displayawarningforeachundeclaredlocalvariablewhichhasthesamenameasaglobalvariable.Thisisintendedtopreventerrorscausedbyforgettingtodeclareaglobalvariableinsideafunctionbeforeattemptingtoaccessit.Ifthevariablereallywasintendedtobelocal,adeclarationsuchas localxor staticy canbeusedtosuppressthewarning.Thiswarningisnevershownforvariablesinsideaforce-localfunction.

    #Warng:=1ShowG(){;Thewarningisdisplayedevenifthefunctionisnevercalled.;globalg;

  • All:ApplythegivenWarningModetoallsupportedwarningtypes.

    WarningModeAvalueindicatinghowwarningsshouldbedelivered.Ifomitted,itdefaultstoMsgBox.

    MsgBox:Showamessageboxdescribingthewarning.Notethatoncethemessageboxisdismissed,thescriptwillcontinueasusual.

    StdOut[v1.1.04+]:Sendadescriptionofthewarningtostdout(theprogram'sstandardoutputstream),alongwiththefilenameandlinenumber.ThisallowsfancyeditorssuchasSciTEtocapturewarningswithoutdisruptingthescript-theusercanlaterjumptoeachoffendinglineviatheeditor'soutputpane.

    OutputDebug:Sendadescriptionofthewarningtothedebuggerfordisplay.Ifadebuggerisnotactive,thiswillhavenoeffect.Formoredetails,seeOutputDebug.

    Off:DisablewarningsofthegivenWarningType.

    Remarks

    Bydefault,allwarningsareoff.

    Warningscan'tbeenabledordisabledatrun-time;thesettingsaredeterminedwhenascriptloads.Therefore,thelocationinthescriptisnotsignificant(and,likeother#directives,#Warncannotbeexecutedconditionally).

    However,theorderingofmultiple#Warndirectivesissignificant:thelastoccurrencethatsetsagivenwarningdeterminesthemodeforthatwarning.So,forexample,thetwostatementsbelowhavethecombinedeffectofenablingallwarningsexceptUseEnv:

    #WarnAll#WarnUseEnv,Off

    EnvSetEnvVar,1

  • x:=EnvVar;Okaysince#NoEnvhasnotbeenused.x:=NotAnEnvVar;Warning.

    Related

    LocalandGlobalVariables

    Example

    #WarnAll,Off;Disableallwarnings.Thisisthedefaultstate.#Warn;Enableeverytypeofwarning;showeachwarninginamessagebox.#WarnUseUnsetLocal,OutputDebug;Warnwhenalocalvariableisusedbeforeit'sset;sendwarningtoOutputDebug.

  • #WinActivateForceSkipsthegentlemethodofactivatingawindowandgoesstraighttotheforcefulmethod.

    #WinActivateForce

    Specifyingthisanywhereinascriptwillcausecommandsthatactivateawindow--suchasWinActivate,WinActivateBottom,andGroupActivate--toskipthe"gentle"methodofactivatingawindowandgostraighttothemoreforcefulmethods.

    Althoughthisdirectivewillusuallynotchangehowquicklyorreliablyawindowisactivated,itmightpreventtaskbarbuttonsfromflashingwhendifferentwindowsareactivatedquicklyoneaftertheother.

    Related

    WinActivate,WinActivateBottom,GroupActivate

    Example

    #WinActivateForce

  • Var:=expressionEvaluatesanexpressionandstorestheresultinavariable.

    Var:=expression

    Parameters

    VarThenameofthevariableinwhichtostoretheresultofexpression.

    ExpressionSeeexpressionsandtheexamplesbelowfordetails.

    Remarks

    The:=operatorisoptimizedsothatitperformsjustasquicklyasthe=operatorforsimplecasessuchasthefollowing:

    x:=y;Sameperformanceasx=%y%x:=5;Sameperformanceasx=5.x:="literalstring";Sameperformanceasx=literalstring.

    Thewords true and false arebuilt-inconstantscontaining1and0.Theycanbeusedtomakeascriptmorereadableasintheseexamples:

    CaseSensitive:=falseContinueSearch:=true

    Itispossibletocreateapseudo-arraywiththiscommandandanyothersthatacceptanOutputVar.ThisisdonebymakingOutputVarcontainareferencetoanothervariable,e.g. Array%i%:=Var/100+5 .SeeArraysformore

  • information.

    Related

    Expressions,IF(expression),Functions,SetEnv,EnvSet,EnvAdd,EnvSub,EnvMult,EnvDiv,If,Arrays

    Examples

    Var:=3Var:="literalstring"Var:=Price*(1-Discount/100)

    Finished:=notDoneorA_Index>100ifnotFinished{FileAppend,%NewText%`n,%TargetFile%return}elseExitApp

  • Loop(normal)Performaseriesofcommandsrepeatedly:eitherthespecifiednumberoftimesoruntilbreakisencountered.

    Loop[,Count]

    Parameters

    CountHowmanytimes(iterations)toperformtheloop.Ifomitted,theLoopcontinuesindefinitelyuntilabreakorreturnisencountered.

    IfCountisavariablereferencesuchas%ItemCount%,theloopisskippedentirelywheneverthevariableisblankorcontainsanumberlessthan1.

    Duetotheneedtosupportfile-patternloops,Countcannotbeanexpression.However,aswithallnon-expressionparameters,anexpressioncanbeforciblyusedbyprecedingitwitha%andaspace.Forexample: Loop%Count+1 .Insuchcases,theexpressionisevaluatedonlyonce,rightbeforetheloopbegins.

    Remarks

    Theloopcommandisusuallyfollowedbyablock,whichisacollectionofstatementsthatformthebodyoftheloop.However,aloopwithonlyasinglestatementdoesnotrequireablock(an"if"andits"else"countasasinglestatementforthispurpose).

    Acommonuseofthiscommandisaninfiniteloopthatusesthebreakcommandsomewhereintheloop'sbodytodeterminewhentostoptheloop.

    Theuseofbreakandcontinueinsidealoopareencouragedasalternativestogoto,sincetheygenerallymakeascriptmoreunderstandableandmaintainable.Onecanalsocreatea"While"or"Do...While/Until"loopbymakingthefirstor

  • laststatementoftheloop'sbodyanIFstatementthatconditionallyissuesthebreakcommand,buttheuseofWhileorLoop...Untilisusuallypreferred.

    Thebuilt-invariableA_Indexcontainsthenumberofthecurrentloopiteration.Itcontains1thefirsttimetheloop'sbodyisexecuted.Forthesecondtime,itcontains2;andsoon.Ifaninnerloopisenclosedbyanouterloop,theinnerlooptakesprecedence.A_Indexworksinsidealltypesofloops,includingfile-loopsandregistry-loops;butA_Indexcontains0outsideofaloop.

    TheOneTrueBrace(OTB)stylemayoptionallybeusedwithnormalloops(butnotspecializedloopssuchasfile-patternandparsing).Forexample:

    Loop{...}Loop%RepeatCount%{...}

    Specializedloops:Loopscanbeusedtoautomaticallyretrievefiles,folders,orregistryitems(oneatatime).Seefile-loopandregistry-loopfordetails.Inaddition,file-readingloopscanoperateontheentirecontentsofafile,onelineatatime.Finally,parsingloopscanoperateontheindividualfieldscontainedinsideadelimitedstring.

    Related

    Until,While-loop,For-loop,Files-and-foldersloop,Registryloop,File-readingloop,Parsingloop,Break,Continue,Blocks

    Examples

    Loop,3{MsgBox,Iterationnumberis%A_Index%.;A_Indexwillbe1,2,then3Sleep,100

  • }

    Loop{ifa_index>25break;Terminatetheloopifa_index<20continue;SkipthebelowandstartanewiterationMsgBox,a_index=%a_index%;Thiswilldisplayonlythenumbers20through25}

  • LanguageCodesThefollowinglistcontainsthelanguagenamethatcorrespondstoeachlanguagecodethatcanbecontainedintheA_Languagevariable.Thelanguagecodeitselfisthelastfourdigitsontheleftsideoftheequalsignbelow.Forexample,ifA_Languagecontains0436,thesystem'sdefaultlanguageisAfrikaans.

    Note:Codesthatcontainlettersmightuseeitheruppercaseorlowercase.

    YoucancompareA_Languagedirectlytooneormoreofthe4-digitcodesbelow;forexample: if(A_Language="0436") .Alternatively,youcanpastetheentirelistintoascriptandthenaccessthenameofthecurrentlanguageasdemonstratedatthebottomofthelist.

    languageCode_0436=AfrikaanslanguageCode_041c=AlbanianlanguageCode_0401=Arabic_Saudi_ArabialanguageCode_0801=Arabic_IraqlanguageCode_0c01=Arabic_EgyptlanguageCode_0401=Arabic_Saudi_ArabialanguageCode_0801=Arabic_IraqlanguageCode_0c01=Arabic_EgyptlanguageCode_1001=Arabic_LibyalanguageCode_1401=Arabic_AlgerialanguageCode_1801=Arabic_MoroccolanguageCode_1c01=Arabic_TunisialanguageCode_2001=Arabic_OmanlanguageCode_2401=Arabic_YemenlanguageCode_2801=Arabic_SyrialanguageCode_2c01=Arabic_JordanlanguageCode_3001=Arabic_LebanonlanguageCode_3401=Arabic_KuwaitlanguageCode_3801=Arabic_UAElanguageCode_3c01=Arabic_BahrainlanguageCode_4001=Arabic_Qatar

  • languageCode_042b=ArmenianlanguageCode_042c=Azeri_LatinlanguageCode_082c=Azeri_CyrilliclanguageCode_042d=BasquelanguageCode_0423=BelarusianlanguageCode_0402=BulgarianlanguageCode_0403=CatalanlanguageCode_0404=Chinese_TaiwanlanguageCode_0804=Chinese_PRClanguageCode_0c04=Chinese_Hong_KonglanguageCode_1004=Chinese_SingaporelanguageCode_1404=Chinese_MacaulanguageCode_041a=CroatianlanguageCode_0405=CzechlanguageCode_0406=DanishlanguageCode_0413=Dutch_StandardlanguageCode_0813=Dutch_BelgianlanguageCode_0409=English_United_StateslanguageCode_0809=English_United_KingdomlanguageCode_0c09=English_AustralianlanguageCode_1009=English_CanadianlanguageCode_1409=English_New_ZealandlanguageCode_1809=English_IrishlanguageCode_1c09=English_South_AfricalanguageCode_2009=English_JamaicalanguageCode_2409=English_CaribbeanlanguageCode_2809=English_BelizelanguageCode_2c09=English_TrinidadlanguageCode_3009=English_ZimbabwelanguageCode_3409=English_PhilippineslanguageCode_0425=EstonianlanguageCode_0438=FaeroeselanguageCode_0429=FarsilanguageCode_040b=FinnishlanguageCode_040c=French_StandardlanguageCode_080c=French_BelgianlanguageCode_0c0c=French_Canadian

  • languageCode_100c=French_SwisslanguageCode_140c=French_LuxembourglanguageCode_180c=French_MonacolanguageCode_0437=GeorgianlanguageCode_0407=German_StandardlanguageCode_0807=German_SwisslanguageCode_0c07=German_AustrianlanguageCode_1007=German_LuxembourglanguageCode_1407=German_LiechtensteinlanguageCode_0408=GreeklanguageCode_040d=HebrewlanguageCode_0439=HindilanguageCode_040e=HungarianlanguageCode_040f=IcelandiclanguageCode_0421=IndonesianlanguageCode_0410=Italian_StandardlanguageCode_0810=Italian_SwisslanguageCode_0411=JapaneselanguageCode_043f=KazakhlanguageCode_0457=KonkanilanguageCode_0412=KoreanlanguageCode_0426=LatvianlanguageCode_0427=LithuanianlanguageCode_042f=MacedonianlanguageCode_043e=Malay_MalaysialanguageCode_083e=Malay_Brunei_DarussalamlanguageCode_044e=MarathilanguageCode_0414=Norwegian_BokmallanguageCode_0814=Norwegian_NynorsklanguageCode_0415=PolishlanguageCode_0416=Portuguese_BrazilianlanguageCode_0816=Portuguese_StandardlanguageCode_0418=RomanianlanguageCode_0419=RussianlanguageCode_044f=SanskritlanguageCode_081a=Serbian_LatinlanguageCode_0c1a=Serbian_Cyrillic

  • languageCode_041b=SlovaklanguageCode_0424=SlovenianlanguageCode_040a=Spanish_Traditional_SortlanguageCode_080a=Spanish_MexicanlanguageCode_0c0a=Spanish_Modern_SortlanguageCode_100a=Spanish_GuatemalalanguageCode_140a=Spanish_Costa_RicalanguageCode_180a=Spanish_PanamalanguageCode_1c0a=Spanish_Dominican_RepubliclanguageCode_200a=Spanish_VenezuelalanguageCode_240a=Spanish_ColombialanguageCode_280a=Spanish_PerulanguageCode_2c0a=Spanish_ArgentinalanguageCode_300a=Spanish_EcuadorlanguageCode_340a=Spanish_ChilelanguageCode_380a=Spanish_UruguaylanguageCode_3c0a=Spanish_ParaguaylanguageCode_400a=Spanish_BolivialanguageCode_440a=Spanish_El_SalvadorlanguageCode_480a=Spanish_HonduraslanguageCode_4c0a=Spanish_NicaragualanguageCode_500a=Spanish_Puerto_RicolanguageCode_0441=SwahililanguageCode_041d=SwedishlanguageCode_081d=Swedish_FinlandlanguageCode_0449=TamillanguageCode_0444=TatarlanguageCode_041e=ThailanguageCode_041f=TurkishlanguageCode_0422=UkrainianlanguageCode_0420=UrdulanguageCode_0443=Uzbek_LatinlanguageCode_0843=Uzbek_CyrilliclanguageCode_042a=Vietnamese

    the_language:=languageCode_%A_Language%;Getthenameofthesystem'sdefaultlanguage.

  • MsgBox%the_language%;Displaythelanguagename.

  • HotstringsandAuto-replace

    IntroductionandSimpleExamples

    Althoughhotstringsaremainlyusedtoexpandabbreviationsasyoutypethem(auto-replace),theycanalsobeusedtolaunchanyscriptedaction.Inthisrespect,theyaresimilartohotkeysexceptthattheyaretypicallycomposedofmorethanonecharacter(thatis,astring).

    Todefineahotstring,enclosethetriggeringabbreviationbetweenpairsofcolonsasinthisexample:

    ::btw::bytheway

    Intheaboveexample,theabbreviationbtwwillbeautomaticallyreplacedwith"bytheway"wheneveryoutypeit(however,bydefaultyoumusttypeanendingcharacteraftertypingbtw,suchasaspace,period,orenter).

    The"bytheway"exampleaboveisknownasanauto-replacehotstringbecausethetypedtextisautomaticallyerasedandreplacedbythestringspecifiedafterthesecondpairofcolons.Bycontrast,ahotstringmayalsobedefinedtoperformanycustomactionasinthefollowingexamples.Notethatthecommandsmustappearbeneaththehotstring:

    ::btw::MsgBoxYoutyped"btw".return

    :*:]d::;Thishotstringreplaces"]d"withthecurrentdateandtimeviathecommandsbelow.FormatTime,CurrentDateTime,,M/d/yyyyh:mmtt;Itwilllooklike9/1/20053:53PMSendInput%CurrentDateTime%return

  • Eventhoughthetwoexamplesabovearenotauto-replacehotstrings,theabbreviationyoutypeiserasedbydefault.Thisisdoneviaautomaticbackspacing,whichcanbedisabledviatheb0option.

  • EndingCharacters

    Unlesstheasteriskoptionisineffect,youmusttypeanendingcharacterafterahotstring'sabbreviationtotriggerit.Endingcharactersinitiallyconsistofthefollowing:-()[]{}':;"/\,.?!`n`t(notethat`nisEnter,`tisTab,andthereisaplainspacebetween`nand`t).Thissetofcharacterscanbechangedbyeditingthefollowingexample,whichsetsthenewendingcharactersforallhotstrings,notjusttheonesbeneathit:

    #HotstringEndChars-()[]{}:;'"/\,.?!`n`t

  • Options

    Ahotstring'sdefaultbehaviorcanbechangedintwopossibleways:

    1. The#Hotstringdirective,whichaffectsallhotstringsphysicallybeneaththatpointinthescript.ThefollowingexampleputstheCandRoptionsintoeffect: #Hotstringcr .

    2. Puttingoptionsinsideahotstring'sfirstpairofcolons.ThefollowingexampleputstheCand*optionsintoeffectforasinglehotstring::c*:j@::[email protected];Casesensitiveand"endingcharacternotrequired". .

    Thelistbelowdescribeseachoption.Whenspecifyingmorethanoneoptionusingthemethodsabove,spacesoptionallymaybeincludedbetweenthem.

    *(asterisk):Anendingcharacter(e.g.space,period,orenter)isnotrequiredtotriggerthehotstring.Forexample:

    :*:j@::[email protected]

    Theexampleabovewouldsenditsreplacementthemomentyoutypethe@character.Whenusingthe#Hotstringdirective,use*0toturnthisoptionbackoff.

    ?(questionmark):Thehotstringwillbetriggeredevenwhenitisinsideanotherword;thatis,whenthecharactertypedimmediatelybeforeitisalphanumeric.Forexample,if :?:al::airline isahotstring,typing"practical"wouldproduce"practicairline".Use?0toturnthisoptionbackoff.

    B0(Bfollowedbyazero):Automaticbackspacingisnotdonetoerasetheabbreviationyoutype.UseaplainBtoturnbackspacingbackonafteritwaspreviouslyturnedoff.Ascriptmayalsodoitsownbackspacingvia{bs5},whichsends5backspaces.Similarly,itmaysendleft-arrowkeystrokesvia{left5}.Forexample,thefollowinghotstringproduces""andmovesthecaret5placestotheleft(sothatit'sbetweenthetags):

  • :*b0:::{left5}

    C:Casesensitive:Whenyoutypeanabbreviation,itmustexactlymatchthecasedefinedinthescript.UseC0toturncasesensitivitybackoff.

    C1:Donotconformtotypedcase.Usethisoptiontomakeauto-replacehotstringscaseinsensitiveandpreventthemfromconformingtothecaseofthecharactersyouactuallytype.Case-conforminghotstrings(whicharethedefault)producetheirreplacementtextinallcapsifyoutypetheabbreviationinallcaps.Ifyoutypeonlythefirstletterincaps,thefirstletterofthereplacementwillalsobecapitalized(ifitisaletter).Ifyoutypethecaseinanyotherway,thereplacementissentexactlyasdefined.Whenusingthe#Hotstringdirective,C0canbeusedtoturnthisoptionbackoff,whichmakeshotstringsconformagain.

    Kn:Key-delay:Thisrarely-usedoptionsetsthedelaybetweenkeystrokesproducedbyauto-backspacingorauto-replacement.Specifythenewdelayforn;forexample,specifyk10tohavea10msdelayandk-1tohavenodelay.Theexactbehaviorofthisoptiondependsonwhichsendingmodeisineffect:

    SI(SendInput):Key-delayisignoredbecauseadelayisnotpossibleinthismode.TheexceptiontothisiswhenSendInputisunavailable,inwhichcasehotstringsreverttoSendPlaymodebelow(whichdoesobeykey-delay).SP(SendPlay):Adelayoflengthzeroisthedefault,whichforSendPlayisthesameas-1(nodelay).Inthismode,thedelayisactuallyaPressDurationratherthanadelaybetweenkeystrokes.SE(SendEvent):Adelayoflengthzeroisthedefault.Zeroisrecommendedformostpurposessinceitisfastbutstillcooperateswellwithotherprocesses(duetointernallydoingaSleep0).Specifyk-1tohavenodelayatall,whichisusefultomakeauto-replacementsfasterifyourCPUisfrequentlyunderheavyload.Whensetto-1,ascript'sprocess-prioritybecomesanimportantfactorinhowfastitcansendkeystrokes.Toraiseascript'spriority,use Process,Priority,,High .

    O:Omittheendingcharacterofauto-replacehotstringswhenthereplacementisproduced.Thisisusefulwhenyouwantahotstringtobekeptunambiguousbystillrequiringanendingcharacter,butdon'tactuallywanttheendingcharactertobeshownonthescreen.Forexample,if :o:ar::aristocrat isa

  • hotstring,typing"ar"followedbythespacebarwillproduce"aristocrat"withnotrailingspace,whichallowsyoutomakethewordpluralorpossessivewithouthavingtobackspace.UseO0(theletterOfollowedbyazero)toturnthisoptionbackoff.

    Pn:Thepriorityofthehotstring(e.g.P1).Thisrarely-usedoptionhasnoeffectonauto-replacehotstrings.

    R:Sendthereplacementtextraw;thatis,withouttranslating{Enter}toanENTERkeystroke,^ctoControl-C,etc.Thisoptionisputintoeffectautomaticallyforhotstringsthathaveacontinuationsection.UseR0toturnthisoptionbackoff.

    Note:Textmodemaybemorereliable.TheRandToptionsaremutuallyexclusive.

    SIorSPorSE[v1.0.43+]:Setsthemethodbywhichauto-replacehotstringssendtheirkeystrokes.Theseoptionsaremutuallyexclusive:onlyonecanbeineffectatatime.Thefollowingdescribeseachoption:

    SIstandsforSendInput,whichtypicallyhassuperiorspeedandreliabilitythantheothermodes.AnotherbenefitisthatlikeSendPlaybelow,SendInputpostponesanythingyoutypeduringahotstring'sauto-replacementtext.Thispreventsyourkeystrokesfrombeinginterspersedwiththoseofthereplacement.WhenSendInputisunavailable,hotstringsautomaticallyuseSendPlayinstead.SPstandsforSendPlay,whichmayallowhotstringstoworkinabroadervarietyofgames.SEstandsforSendEvent,whichisthedefaultinversionsolderthan1.0.43.

    Ifnoneoftheaboveoptionsareused,thedefaultmodein[v1.0.43]andlaterisSendInput.However,unliketheSIoption,SendEventisusedinsteadofSendPlaywhenSendInputisunavailable.

    T[v1.1.27+]:Sendthereplacementtextraw,withouttranslatingeachcharactertoakeystroke.Fordetails,seeTextmode.UseT0orR0toturnthisoptionbackoff,oroverrideitwithR.

    Z:Thisrarely-usedoptionresetsthehotstringrecognizeraftereachtriggeringof

  • thehotstring.Inotherwords,thescriptwillbeginwaitingforanentirelynewhotstring,eliminatingfromconsiderationanythingyoupreviouslytyped.Thiscanpreventunwantedtriggeringsofhotstrings.Toillustrate,considerthefollowinghotstring:

    :b0*?:11::SendInputxxreturn

    SincetheabovelackstheZoption,typing111(threeconsecutive1's)wouldtriggerthehotstringtwicebecausethemiddle1isthelastcharacterofthefirsttriggeringbutalsothefirstcharacterofthesecondtriggering.ByaddingtheletterZinfrontofb0,youwouldhavetotypefour1'sinsteadofthreetotriggerthehotstringtwice.UseZ0toturnthisoptionbackoff.

  • LongReplacements

    Hotstringsthatproducealargeamountofreplacementtextcanbemademorereadableandmaintainablebyusingacontinuationsection.Forexample:

    ::text1::(Anytextbetweenthetopandbottomparenthesesistreatedliterally,includingcommasandpercentsigns.Bydefault,thehardcarriagereturn(Enter)betweenthepreviouslineandthisoneisalsopreserved.Bydefault,theindentation(tab)totheleftofthislineispreserved.

    Seecontinuationsectionforhowtochangethesedefaultbehaviors.)

    Thepresenceofacontinuationsectionalsocausesthehotstringtodefaulttorawmode.Theonlywaytooverridethisspecialdefaultistospecifyther0optionineachhotstringthathasacontinuationsection(e.g. :r0:text1:: ).

  • Context-sensitiveHotstrings

    Thedirectives#IfWinActive/Existcanbeusedtomakeselectedhotstringscontextsensitive.Suchhotstringssendadifferentreplacement,performadifferentaction,ordonothingatalldependingonthetypeofwindowthatisactiveorexists.Forexample:

    #IfWinActiveahk_classNotepad::btw::ThisreplacementtextwillappearonlyinNotepad.#IfWinActive::btw::ThisreplacementtextappearsinwindowsotherthanNotepad.

  • AutoCorrect

    Thefollowingscriptuseshotstringstocorrectabout4700commonEnglishmisspellingson-the-fly.ItalsoincludesaWin+Hhotkeytomakeiteasytoaddmoremisspellings:

    Download:AutoCorrect.ahk(127KB)

    Author:JimBiancoloandWikipedia'sListsofCommonMisspellings

    http://www.autohotkey.com/download/AutoCorrect.ahkhttp://www.biancolo.com/blog/autocorrect/http://en.wikipedia.org/wiki/Wikipedia:Lists_of_common_misspellings

  • Remarks

    Variablereferencessuchas %MyVar% arenotcurrentlysupportedwithinthereplacementtext.Toworkaroundthis,don'tmakesuchhotstringsauto-replace.Instead,usetheSendInputcommandbeneaththeabbreviation,followedbyalinecontainingonlythewordReturn.

    Tosendanextraspaceortabafterareplacement,includethespaceortabattheendofthereplacementbutmakethelastcharacteranaccent/backtick(`).Forexample:

    :*:btw::Bytheway`

    Anyclickoftheleftorrightmousebuttonwillresetthehotstringrecognizer.Inotherwords,thescriptwillbeginwaitingforanentirelynewhotstring,eliminatingfromconsiderationanythingyoupreviouslytyped(ifthisisundesirable,specifytheline #HotstringNoMouse anywhereinthescript).This"resetuponmouseclick"behavioristhedefaultbecauseeachclicktypicallymovesthetextinsertionpoint(caret)orsetskeyboardfocustoanewcontrol/field.Insuchcases,itisusuallydesirableto:1)fireahotstringevenifitlacksthequestionmarkoption;2)preventafiringwhensomethingyoutypeafterclickingthemouseaccidentallyformsavalidabbreviationwithwhatyoutypedbefore.

    Thebuilt-invariableA_EndCharcontainstheendingcharacterthatyoutypedtotriggerthemostrecentnon-auto-replacehotstring.Ifnoendingcharacterwasrequired(duetothe*option),itwillbeblank.A_EndCharisusefulwhenmakinghotstringsthatusetheSendcommandorwhosebehaviorshouldvarydependingonwhichendingcharacteryoutyped.Tosendtheendingcharacteritself,use SendRaw%A_EndChar% (SendRawisusedbecausecharacterssuchas!{}wouldnotbesentcorrectlybythenormalSendcommand).

    Althoughcommas,percentsigns,andsingle-colonswithinhotstringdefinitionsdonotneedtobeescaped,backticksandthosesemicolonshavingaspaceortabtotheirleftrequireit.Seeescapesequencesforacompletelist.

  • AlthoughtheSendcommand'sspecialcharacterssuchas{Enter}aresupportedinauto-replacementtext(unlesstherawoptionisused),thehotstringabbreviationsthemselvesdonotusethis.Instead,specify`nfortheENTERkeyand`t(oraliteraltab)forTAB(seeescapesequencesforacompletelist).Forexample,thehotstring :*:ab`t:: wouldbetriggeredwhenyoutype"ab"followedbyatab.

    Spacesandtabsaretreatedliterallywithinhotstringdefinitions.Forexample,thefollowingwouldproducetwodifferentresults: ::btw::bythewayand ::btw::bytheway .

    Eachhotstringabbreviationcanbenomorethan40characterslong.Theprogramwillwarnyouifthislengthisexceeded.Bycontrast,thelengthofhotstring'sreplacementtextislimitedtoabout5000characterswhenthesendingmodeisatitsdefaultofSendInput.Thatlimitcanbeincreasedto16,383charactersbyswitchingtooneoftheothersendingmodes.Furthermore,anunlimitedamountoftextcanbesentbyusing SendPlay%MyVariable%inthebodyofthehotstring.

    Theorderinwhichhotstringsaredefineddeterminestheirprecedencewithrespecttoeachother.Inotherwords,ifmorethanonehotstringmatchessomethingyoutype,onlytheonelistedfirstinthescriptwilltakeeffect.Relatedtopic:context-sensitivehotstrings.

    Anybackspacingyoudoistakenintoaccountforthepurposeofdetectinghotstrings.However,theuseofarrowkeys,PageUp,PageDown,Home,andEndtonavigatewithinaneditorwillcausethehotstringrecognitionprocesstoreset.Inotherwords,itwillbeginwaitingforanentirelynewhotstring.

    Ahotstringmaybetypedevenwhentheactivewindowisignoringyourkeystrokes.Inotherwords,thehotstringwillstillfireeventhoughthetriggeringabbreviationisnevervisible.Inaddition,youmaystillpressthebackspacekeytoundothemostrecentlytypedkeystroke(eventhoughyoucan'tseetheeffect).

    ItispossibletoGosuborGotoahotstringlabelbyincludingitsfirstpairofcolons(includinganyoptionsymbols)infrontofitsname.Forexample:Gosub::xyz .However,jumpingtoasingle-line(auto-replace)hotstringwilldonothingotherthanexecuteareturn.

  • AlthoughhotstringsarenotmonitoredandwillnotbetriggeredduringthecourseofaninvisibleInputcommand,visibleInputsarecapableoftriggeringthem.

    Bydefault,hotstringsarenevertriggeredbykeystrokesproducedbyanyAutoHotkeyscript.Thisavoidsthepossibilityofaninfiniteloopwherehotstringstriggereachotheroverandover.In[v1.1.06]andlater,thisbehaviourcanbecontrolledwith#InputLevelandSendLevel.However,auto-replacehotstringsalwaysusesendlevel0andthereforenevertriggerhookhotkeysorhotstrings.

    TheInputcommandismoreflexiblethanhotstringsforcertainpurposes.Forexample,itallowsyourkeystrokestobeinvisibleintheactivewindow(suchasagame).Italsosupportsnon-characterendingkeyssuchasEscape.

    Thekeyboardhookisautomaticallyusedbyanyscriptthatcontainshotstrings.

    Hotstringsbehaveidenticallytohotkeysinthefollowingways:

    TheyareaffectedbytheSuspendcommand.Theyobey#MaxThreadsand#MaxThreadsPerHotkey(butnot#MaxThreadsBuffer).Scriptscontaininghotstringsareautomaticallypersistent.Non-auto-replacehotstringswillcreateanewthreadwhenlaunched.Inaddition,theywillupdatethebuilt-inhotkeyvariablessuchasA_ThisHotkey.

    Knownlimitation:OnsomesystemsinJavaapplications,hotstringsmightinterferewiththeuser'sabilitytotypediacriticalletters(viadeadkeys).Toworkaroundthis,Suspendcanbeturnedontemporarily(whichdisablesallhotstrings).

  • HotstringHelper

    AndreasBoruttasuggestedthefollowingscript,whichmightbeusefulifyouareaheavyuserofhotstrings.BypressingWin+H(oranotherhotkeyofyourchoice),thecurrentlyselectedtextcanbeturnedintoahotstring.Forexample,ifyouhave"bytheway"selectedinawordprocessor,pressingWin+Hwillpromptyouforitsabbreviation(e.g.btw)andthenaddthenewhotstringtothescript.Itwillthenreloadthescripttoactivatethehotstring.

    #h::;Win+Hhotkey;Getthetextcurrentlyselected.Theclipboardisusedinsteadof;"ControlGetSelected"becauseitworksinagreatervarietyofeditors;(namelywordprocessors).Savethecurrentclipboardcontentstobe;restoredlater.Althoughthishandlesonlyplaintext,itseemsbetter;thannothing:AutoTrimOff;Retainanyleadingandtrailingwhitespaceontheclipboard.ClipboardOld=%ClipboardAll%Clipboard=;Muststartoffblankfordetectiontowork.Send^cClipWait1ifErrorLevel;ClipWaittimedout.return;ReplaceCRLFand/orLFwith`nforuseina"send-raw"hotstring:;Thesameisdoneforanyothercharactersthatmightotherwise;beaprobleminrawmode:StringReplace,Hotstring,Clipboard,``,````,All;Dothisreplacementfirsttoavoidinterfering

  • withtheothersbelow.StringReplace,Hotstring,Hotstring,`r`n,``r,All;Using`rworksbetterthan`ninMSWord,etc.StringReplace,Hotstring,Hotstring,`n,``r,AllStringReplace,Hotstring,Hotstring,%A_Tab%,``t,AllStringReplace,Hotstring,Hotstring,`;,```;,AllClipboard=%ClipboardOld%;Restorepreviouscontentsofclipboard.;ThiswillmovetheInputBox'scarettoamorefriendlyposition:SetTimer,MoveCaret,10;ShowtheInputBox,providingthedefaulthotstring:InputBox,Hotstring,NewHotstring,Typeyourabreviationattheindicatedinsertionpoint.Youcanalsoeditthereplacementtextifyouwish.`n`nExampleentry::R:btw`::bytheway,,,,,,,,:R:`::%Hotstring%ifErrorLevel;TheuserpressedCancel.returnIfInString,Hotstring,:R`:::{MsgBoxYoudidn'tprovideanabbreviation.Thehotstringhasnotbeenadded.return};Otherwise,addthehotstringandreloadthescript:FileAppend,`n%Hotstring%,%A_ScriptFullPath%;Puta`natthebeginningincasefilelacksablanklineatitsend.ReloadSleep200;Ifsuccessful,thereloadwillclosethisinstanceduringtheSleep,sothelinebelowwillneverbereached.

  • MsgBox,4,,Thehotstringjustaddedappearstobeimproperlyformatted.Wouldyouliketoopenthescriptforediting?Notethatthebadhotstringisatthebottomofthescript.IfMsgBox,Yes,Editreturn

    MoveCaret:IfWinNotActive,NewHotstringreturn;Otherwise,movetheInputBox'sinsertionpointtowheretheuserwilltypetheabbreviation.Send{Home}{Right3}SetTimer,MoveCaret,Offreturn

  • AcknowledgementsInadditiontotheAutoItauthorsalreadymentioned:

    RobertYaklin:Alotoftirelesstestingtoisolatebugs,agreatfirstdraftoftheinstaller,aswellasgreatsuggestionsforhowcommandsoughttowork:)

    JasonPayamAhdoot:Forsuggestinganddescribingfloatingpointsupport.

    JayD.Novak:FordiscoveringmanyWin9xproblemswiththeSendcommand,Capslock,andhotkeymodifiers;andforgenerouslysharinghiswealthofcodeandwisdomforhotkeys,hot-strings,hookusage,andtypingacceleration.

    Rajat:ForcreatingstylishreplacementsfortheoriginalAHKicons;agreatproductlogo;makingthesyntaxcustomizationsforTextPad;discoveringsomebugswiththeregistrycommandsandAutoItv2compatibility;makingSmartGUICreator;andmanyotherthings.

    ThaddeusBeck(Beardboy):ForNT4testingtofixGetKeyStateandtheSendcommand;foralotofhelpontheforum;andformanysuggestionsandbugreports.

    GregoryF.HoggofHogg'sSoftware:Forwritingthesourcecodeformulti-monitorsupportintheSysGetcommand.

    AurelianMaga:ForwritingthesourcecodeforImageSearchandthefasterPixelSearch.

    JoostMulders:Whosesourcecodeprovidedthefoundationforexpressions.

    LaszloHars:Foradviceaboutdatastructuresandalgorithms,whichhelpedgreatlyspeeduparraysanddynamicvariables.

    MarcusSonntag(Ultra):Fortheresearch,design,coding,andtestingofDllCall.

    GenaShimanovich:Fordebuggingandcodingassistance;andforsomeadvancedprototypescriptsuponwhichfuturefeaturesmaybebased.

  • EricMorin(numEric):Foradviceonmathematics;forsteadfastdebuggingofareaslikeOnMessage,floatingpointcomputations,andmousemovement;andforimprovementstooverallquality.

    PhilipHazel:ForPerl-CompatibleRegularExpressions(PCRE).

    Titan/polyethene:Forprovidingcommunityhostingonautohotkey.net,creatingmanyusefulscriptsandlibraries,creatingtheJavaScripttocolorizecode-commentsintheforum,andmanyotherthings.

    PhilippeLhoste(PhiLho):Fortirelessmoderationandsupportintheforum,RegExadviceandtesting,syntaxanddesignideas,andmanyotherthings.

    JohnBiederman:Forgreatlyimprovingthepresentationandergonomicsofthedocumentation.

    JonathanRennison(JGR):FordevelopingRegisterCallback(),andforbeneficialsuggestions.

    SteveGray(Lexikos):Fordevelopingdynamicfunctioncallingandothernewfunctionity;analyzingandfixingbugs;andvaluablesupportandadviceforhundredsofindividualvisitorsattheforum.

    AutoHotkey_L:

    jackeiku:FordevelopingUnicodesupportandothernewfunctionality.

    fincs:Fordevelopingnative64-bitsupportandtry/catch/throw,writingareplacementfortheoldcompiler,analyzingandfixingbugs.

    Sean:Fordevelopingbuilt-inCOMfunctionalityandprovidingvaluableinsightintoCOM.

    TheGood:Formergingthedocumentationandadaptingtheinstallerscript.

    ac:Fordeveloping#Warn.

    RussellDavis:FordevelopingA_PriorKey,ahk_path(thebasisofahk_exeinWinTitleparameters),#InputLevelandSendLevel.

    http://www.pcre.org/

  • ChristianSander:FordevelopingsupportforSysLinkcontrols.

    Andtoeveryoneelsewho'scontributedorsentinbugreportsorsuggestions:Thanks!

  • WinActivateActivatesthespecifiedwindow(makesitforemost).

    WinActivate[,WinTitle,WinText,ExcludeTitle,ExcludeText]

    Parameters

    WinTitleAwindowtitleorothercriteriaidentifyingthetargetwindow.SeeWinTitle.

    WinTextIfpresent,thisparametermustbeasubstringfromasingletextelementofthetargetwindow(asrevealedbytheincludedWindowSpyutility).HiddentextelementsaredetectedifDetectHiddenTextisON.

    ExcludeTitleWindowswhosetitlesincludethisvaluewillnotbeconsidered.

    ExcludeTextWindowswhosetextincludethisvaluewillnotbeconsidered.

    Remarks

    Ifthewindowisminimized,itisautomaticallyrestoredpriortobeingactivated.In[v1.1.20]andlater,thewindowisrestoredevenifitisalreadyactive.

    Sixattemptswillbemadetoactivatethetargetwindowoverthecourseof60ms.Thus,itisusuallyunnecessarytofollowWinActivatewithWinWaitActiveorIfWinNotActive.

    Ifamatchingwindowisalreadyactive,thatwindowwillbekeptactiveratherthanactivatinganyothermatchingwindowbeneathit.Ingeneral,ifmorethan

  • onewindowmatches,thetopmost(mostrecentlyused)willbeactivated.Youcanactivatethebottommost(leastrecentlyused)viaWinActivateBottom.

    [v1.1.20+]:IftheactivewindowishiddenandDetectHiddenWindowsisturnedoff,itisneverconsideredamatch.Instead,avisiblematchingwindowisactivatedifoneexists.

    Whenawindowisactivatedimmediatelyaftertheactivationofsomeotherwindow,taskbarbuttonsmightstartflashingonsomesystems(dependingonOSandsettings).Topreventthis,use#WinActivateForce.

    Windowtitlesandtextarecasesensitive.HiddenwindowsarenotdetectedunlessDetectHiddenWindowshasbeenturnedon.

    Knownissue:Ifthescriptisrunningonacomputerorserverbeingaccessedviaremotedesktop,WinActivatemayhangiftheremotedesktopclientisminimized.Oneworkaroundistousecommandswhichdon'trequirewindowactivation,suchasControlSendandControlClick.Anotherpossibleworkaroundistoapplythefollowingregistrysettingonthelocal/clientcomputer:

    ;ChangeHKCUtoHKLMtoaffectallusersonthissystem.RegWriteREG_DWORD,HKCU,Software\Microsoft\TerminalServerClient,RemoteDesktop_SuppressWhenMinimized,2

    Related

    WinActivateBottom,#WinActivateForce,SetTitleMatchMode,DetectHiddenWindows,LastFoundWindow,IfWinExist,IfWinActive,WinWaitActive,WinWait,WinWaitClose,WinClose,GroupActivate,WinSet

    Example

    IfWinExist,Untitled-NotepadWinActivate;usethewindowfoundaboveelse

  • WinActivate,Calculator

  • EnvAddSetsavariabletothesumofitselfplusthegivenvalue(canalsoaddorsubtracttimefromadate-timevalue).Synonymouswith: var+=value .

    EnvAdd,Var,Value[,TimeUnits]Var+=Value[,TimeUnits]Var++

    Parameters

    VarThenameofthevariableuponwhichtooperate.

    ValueAnyinteger,floatingpointnumber,orexpression.

    TimeUnitsIfpresent,thisparameterdirectsthecommandtoaddValuetoVar,treatingVarasadate-timestampintheYYYYMMDDHH24MISSformatandtreatingValueastheintegerorfloatingpointnumberofunitstoadd(specifyanegativenumbertoperformsubtraction).TimeUnitscanbeeitherSeconds,Minutes,Hours,orDays(orjustthefirstletterofeachofthese).

    IfVarisanemptyvariable,thecurrenttimewillbeusedinitsplace.IfVarcontainsaninvalidtimestamporayearpriorto1601,orifValueisnon-numeric,Varwillbemadeblanktoindicatetheproblem.

    Thebuilt-invariableA_NowcontainsthecurrentlocaltimeinYYYYMMDDHH24MISSformat.

    Tocalculatetheamountoftimebetweentwotimestamps,useEnvSub.

    Remarks

  • Thiscommandisequivalenttotheshorthandstyle: Var+=Value .

    Variablescanbeincreasedordecreasedby1byusing Var++ , Var-- ,++Var ,or --Var .

    IfeitherVarorValueisblankordoesnotstartwithanumber,itisconsideredtobe0forthepurposeofthecalculation(exceptwhenusedinternallyinanexpressionandexceptwhenusingtheTimeUnitsparameter).

    IfeitherVarorValuecontainsadecimalpoint,theendresultwillbeafloatingpointnumberintheformatsetbySetFormat.

    Related

    EnvSub,EnvMult,EnvDiv,SetFormat,Expressions,Ifvaris[not]type,SetEnv,FileGetTime

    Example

    EnvAdd,MyCount,2MyCount+=2;Equivalenttoabove

    var1=;Makeitblanksothatthebelowwillusethecurrenttimeinstead.var1+=31,daysMsgBox,%var1%;Theanswerwillbethedate31daysfromnow.

  • Ifvaris[not]typeCheckswhetheravariable'scontentsarenumeric,uppercase,etc.

    ifVarisTypeifVarisnotType

    Parameters

    VarThevariablename.

    TypeSeetheremarksbelow.

    Remarks

    SupportedTypes:

    integer

    TrueifVarisnon-emptyandcontainsapurelynumericstring(decimalorhexadecimal)withoutadecimalpoint.Leadingandtrailingspacesandtabsareallowed.Thestringmaystartwithaplusorminussign.

    float

    TrueifVarisnon-emptyandcontainsafloatingpointnumber;thatis,apurelynumericstringcontainingadecimalpoint.Leadingandtrailingspacesandtabsareallowed.Thestringmaystartwithaplussign,minussign,ordecimalpoint.

    number TrueifVarcontainsanintegerorfloatingpointnumber(eachofwhichisdescribedabove).

    digit

    TrueifVarisemptyorcontainsonlydigits,whichconsistofthecharacters0through9.Othercharacterssuchasthefollowingarenotallowed:spaces,tabs,plussigns,minussigns,decimalpoints,hexadecimaldigits,andthe0xprefix.

  • xdigitHexadecimaldigit:SameasdigitexceptthecharactersAthroughF(uppercaseorlowercase)arealsoallowed.[v1.0.44.09+]:Aprefixof0xistoleratedifpresent.

    alpha

    TrueifVarisemptyorcontainsonlyalphabeticcharacters.Falseifthereareanydigits,spaces,tabs,punctuation,orothernon-alphabeticcharactersanywhereinthestring.Forexample,ifVarcontainsaspacefollowedbyaletter,itisnotconsideredtobealpha.

    upperTrueifVarisemptyorcontainsonlyuppercasecharacters.Falseifthereareanydigits,spaces,tabs,punctuation,orothernon-uppercasecharactersanywhereinthestring.

    lowerTrueifVarisemptyorcontainsonlylowercasecharacters.Falseifthereareanydigits,spaces,tabs,punctuation,orothernon-lowercasecharactersanywhereinthestring.

    alnum Sameasalphaexceptthatcharacters0through9arealsoallowed.

    spaceTrueifVarisemptyorcontainsonlywhitespace,whichconsistsofthefollowingcharacters:space(%A_Space%),tab(%A_Tab%or`t),linefeed(`n),return(`r),verticaltab(`v),andformfeed(`f).

    time

    TrueifVarcontainsavaliddate-timestamp,whichcanbeallorjusttheleadingpartoftheYYYYMMDDHH24MISSformat.Forexample,a4-digitstringsuchas2004isconsideredvalid.UseStringLentodeterminewhetheradditionaltimecomponentsarepresent.

    Yearslessthan1601arenotconsideredvalidbecausetheoperatingsystemgenerallydoesnotsupportthem.Themaximumyearconsideredvalidis9999.

    ThewordDATEmaybeusedasasubstituteforthewordTIME,withthesameresult.

    Note:Theoperators"between","is","in",and"contains"arenot

  • supportedinexpressions.

    [AHK_L42+]:ThesystemlocaleisignoredunlessStringCaseSenseLocalehasbeenused.

    Related

    %A_YYYY%,SetFormat,FileGetTime,IfEqual,ifvarin/containsMatchList,ifvarbetween,StringLen,IfInString,StringUpper,EnvAdd,Blocks,Else

    Example

    ifvarisfloatMsgBox,%var%isafloatingpointnumber.elseifvarisintegerMsgBox,%var%isaninteger.ifvaristimeMsgBox,%var%isalsoavaliddate-time.

  • WinSetMakesavarietyofchangestothespecifiedwindow,suchas"alwaysontop"andtransparency.

    WinSet,Attribute,Value[,WinTitle,WinText,ExcludeTitle,ExcludeText]

    Parameters

    Attribute,ValueSeelistbelow.

    WinTitleAwindowtitleorothercriteriaidentifyingthetargetwindow.SeeWinTitle.

    WinTextIfpresent,thisparametermustbeasubstringfromasingletextelementofthetargetwindow(asrevealedbytheincludedWindowSpyutility).HiddentextelementsaredetectedifDetectHiddenTextisON.

    ExcludeTitleWindowswhosetitlesincludethisvaluewillnotbeconsidered.

    ExcludeTextWindowswhosetextincludethisvaluewillnotbeconsidered.

    Attribute,Value

    AlwaysOnTop,[On|Off|Toggle]:Makesawindowstayontopofallotherwindows.UseONtoturnonthesetting,OFFtoturnitoff,orTOGGLEtosetittotheoppositeofitscurrentstate.Ifomitted,itdefaultstoTOGGLE.ThewordTopmostcanbeusedinplaceofAlwaysOnTop.

  • Bottom:Sendsawindowtothebottomofstack;thatis,beneathallotherwindows.TheeffectissimilartopressingAlt-Escape.Forexample: WinSet,Bottom,,WinTitle .

    Top:Bringsawindowtothetopofthestackwithoutexplicitlyactivatingit.However,thesystemdefaultsettingswillprobablycauseittoactivateinmostcases.Inaddition,thiscommandmayhavenoeffectduetotheoperatingsystem'sprotectionagainstapplicationsthattrytostealfocusfromtheuser(itmaydependonfactorssuchaswhattypeofwindowiscurrentlyactiveandwhattheuseriscurrentlydoing).Onepossiblework-aroundistomakethewindowbrieflyAlwaysOnTop,thenturnoffAlwaysOnTop.

    DisableorEnable:Disablesorenablesawindow(respectively).Whenawindowisdisabled,theusercannotmoveitorinteractwithitscontrols.Inaddition,disabledwindowsareomittedfromthealt-tablist.

    Redraw:Attemptstoupdatetheappearance/contentsofawindowbyinformingtheOSthatthewindow'srectangleneedstoberedrawn.Ifthismethoddoesnotworkforaparticularwindow,tryWinMove.Ifthatdoesnotwork,trythefollowing:

    WinHide,WinTitleWinShow,WinTitle

    Style,NorExStyle,N:Changesthestyleorextendedstyleofawindow,respectively.IfthefirstcharacterofNisaplusorminussign,thestyle(s)inNareaddedorremoved,respectively.Ifthefirstcharacterisacaret(^),thestyle(s)inNareeachtoggledtotheoppositestate.Ifthefirstcharacterisadigit,thewindow'sstyleisoverwrittencompletely;thatis,itbecomesN.

    ErrorLevelissetto1uponfailureand0uponsuccess.Failureoccursifthetargetwindowisnotfoundorthestyleisnotallowedtobeapplied.

    Afterapplyingcertainstylechangestoavisiblewindow,itmightbenecessarytoredrawthewindowusing WinSetRedraw (seebelow).Finally,thestylestablelistssomeofthecommonstylenumbers.Examples:

    WinSet,Style,-0xC00000,A;Removetheactive

  • window'stitlebar(WS_CAPTION).WinSet,ExStyle,^0x80,WinTitle;ToggletheWS_EX_TOOLWINDOWattribute,whichremoves/addsthewindowfromthealt-tablist.

    WinSet,Region[,Options,WinTitle,...]

    Changestheshapeofawindowtobethespecifiedrectangle,ellipse,orpolygon.IftheOptionsparameterisblank,thewindowisrestoredtoitsoriginal/defaultdisplayarea.Otherwise,oneormoreofthefollowingoptionscanbespecified,eachseparatedfromtheotherswithspace(s):

    Wn:Widthofrectangleorellipse.Forexample: w200 .Hn:Heightofrectangleorellipse.Forexample: h300 .X-Y:EachoftheseisapairofX/Ycoordinates.Forexample, 200-0 woulduse200fortheXcoordinateand0fortheY.E:Makestheregionanellipseratherthanarectangle.ThisoptionisvalidonlywhenWandHarepresent.R[w-h]:Makestheregionarectanglewithroundedcorners.Forexample, R30-30 wouldusea30x30ellipseforeachcorner.Ifw-hisomitted,30-30isused.RisvalidonlywhenWandHarepresent.

    Rectangleorellipse:IftheWandHoptionsarepresent,thenewdisplayareawillbearectanglewhoseupperleftcornerisspecifiedbythefirst(andonly)pairofX-Ycoordinates.However,iftheEoptionisalsopresent,thenewdisplayareawillbeanellipseratherthanarectangle.Forexample: WinSet,Region,50-0W200H250E,WinTitle .

    Polygon:WhentheWandHoptionsareabsent,thenewdisplayareawillbeapolygondeterminedbymultiplepairsofX-Ycoordinates(eachpairofcoordinatesisapointinsidethewindowrelativetoitsupperleftcorner).Forexample,ifthreepairsofcoordinatesarespecified,thenewdisplayareawillbeatriangleinmostcases.Theorderofthecoordinatepairswithrespecttoeachotherissometimesimportant.Inaddition,thewordWindmaybebepresentinOptionstousethewindingmethodinsteadofthealternatingmethodtodeterminethepolygon'sregion.

    ErrorLevelissetto1uponfailureand0uponsuccess.Failureoccurswhen:1)

  • thetargetwindowdoesnotexist;2)oneormoreOptionsareinvalid;3)morethan2000pairsofcoordinateswerespecified;or4)thespecifiedregionisinvalidorcouldnotbeappliedtothetargetwindow.

    Seethebottomofthispageforexamplesofhowtousethiscommand.

    WinSet,Transparent,N,WinTitle

    Makesawindowsemi-transparent.SpecifyforNanumberbetween0and255t