ATTENTION: You are viewing a page formatted for mobile devices; to view the full web page, click HERE.

Main Area and Open Discussion > General Software Discussion

AHK / Autohotkey / Auto Hotkey tutorial for absolute beginners

(1/4) > >>

evamaria:
("EDITED" July, 5, 2013 just for giving it a more expressive title for google!)



With this little Intro and Lesson 1, you'll have set your first key remappings in less than an hour, promised!

Why a scripting language?

"Hotkeys" (as they are called in AHK)

Most people wanting to shift characters or functions from one key (or key combination like shift-somekey, control-somekey, etc.) of their keyboard to another key or key combination, look out for (free or paid) proprietary macro tools, which means they get some additional application for their computer with which then they will be stuck for a long time, because of the INVESTMENT they will have put into it, some money perhaps, but first of all, many, many hours of "putting things into it" - that's why the switch, later on, to a full-grown scripting language like AHK, becomes more and more "psychologically impossible", all the more so since most of these proprietary macro tools will NOT allow for any "export" of your macros but force you to view them on screen and then recoup them, by hand, into your script (or any other competing proprietary tool, perhaps more "powerful" than the first one).

"Hotstrings" (as they are called in AHK)

Thus, macro tool users "learn" to live with the numerous limitations of most of such tools, and by the way, this also applies to so-called "text expander" tools: Most of them have many limitations, and many of them don't even allow for exporting your hotstrings into another tool. So what are hotstrings? If you use Microsoft Word, for example, you can "expand" some short "strings" (some characters devoid of meaning, not forming a real word in your language), plus a trigger (for example a punctuation character), into real (but much longer or difficult to spell / type) words, or even into texts of some length, including line breaks, for example your letterhead, complimentary closes, and many more.

So this is possible in Word and some other "text processors", but not many applications come with such functionality, so some people buy a "text expander" on top of their macro tool, in order to have available the same set of hotstrings in more than one application, "system-wide" (just a hint here: AHK even allows for different sets of hotstrings, for example if you write in more than one language, or if you have general texts and then legal texts, or whatever your needs are, AHK's possibilities are endless!).

Another aspect of interest here: Both your macro tool and your text expander tool will persistently monitor your system and every key you'll ever press, in order to detect when they are expected to do "something real", and this does not only make for "double overhead", but also, many such macro tools do not function well with many such text expander tools, so you would have to check out carefully your possible combinations. AHK, on the other hand, will also monitor your system, but for hotkeys and hotstrings at the same time, so this is "minimally invasive", and no interference of two tools disturbing each other will occur.

So why people get the above tools, instead of a scripting language?

Because the very first steps with a scripting language are not (made) evident, all the less so with the fact that most people would like to start their "macroing experience" with reassigning not some normal character keys (since those are needed for typing), but some "special keys", and here, in a macro tool, you just press the key in question in order to reassign it, but in a scripting language, you will need the "name" of that key, and worse, you will probably even need the "scan code" of that key - DON'T STOP READING HERE, THOUGH, there's no need to worry!!!

So you see, with a scripting language, some (imaginary) "real problems" seem to get into your way, right on your very first steps: Let's call this "very unfortunate", all the more so since there was no quick help easily available. But now, there is, and knowing how to do it is knowing how extremely easy it is! (If you really need to sneak beforehand: it's point 6 below!)


Lesson 1

Step 1

What do you need for your very first script? You need a script, so you need an editor: If you don't have any particular one, just open the "Editor" that comes with Windows. Then, copy the script below: As you can read in the script, it comprises two parts: An autoexec section, which will be executed once, just after "loading" the script, and a "persistently running", with all your hotkey and hotstring assignments; after some months, this could be several hundred such assignments (or even thousands, especially if you work with "scope" later on, meaning you'll have different assignments for different applications (or different hotstrings for different languages), but then, it's perfectly possible to just limit yourself on doing it straight, never doing anything else than what you find in this lesson 1).

As you can see, the script here contains some assignments to start, in order for you to see that it's running; afterwards, you will "edit" this script, in your editor, and then "reload" it.

But first, you must SAVE this script in a way that it becomes available for AHK. Save it to .txt if you want, then rename it to .ahk, or save it to .ahk in the first place, which is preferable - even so, it stays a plain text file, let's say you save it under the name of first.ahk.

This script contains some hotkeys and hotstrings; trigger them in order to see what they do, and you will quickly replace them by those hotkeys and hotstrings that will be helpful in your daily work, from now on.

Step 2

You need AHK. So you go to www.autohotkey.com, and there, you click the orange button "Download AutoHotkey". Of interest here, the download dialog will show you you're downloading AHK_L, from the site http://l.autohotkey.net ! No, that's not a trick to get you malware from somewhere, but AHK_L is the AHK version in active development, and in order to get resources for the additional goodies of this most recent version, but it's recommended to refer, for help, to the principal site, autohotkey.com - you will not need anything in autohotkey.net for your start.

You install this AHK_L; the installer will ask you for the version you want to install, don't install the ANSI version (which is only there for historical reasons), but the Unicode version, and the right one for your system (32bit or 64bit).

Step 3

Now, with AHK_L installed, you RUN that file "first.ahk" (or whatever name you will have given to it, but always with the ".ahk" suffix).

You'll do this by double-clicking on it in your file manager (if you don't have any file manager, install xplorer2 lite, which is free, or if you insist on doing it all within that one here I promised you above, use that Windows thing that pretends to "replace" a file manager (and of which I don't even know the name: never used it in my life!) later on, you will put this into your autostart folder), so this script is running (there is NO intermediate step for "compiling" here!).

Then, you press shift-control-m, in order to see that your first AHK script is running indeed!

Step 4

Also, you will see that there is now a new symbol / icon for this file, appearing in the "notification area" / "system tray" of your screen (the thing to the right of your task bar, right in the bottom right hand screen corner). Right-click on this icon, in order to have a look at the little right-click menu there. Of immediate interest here: "Help", of course (and you will also have seen the "AHK forum" link on the autohotkey.com site in step 2), "Edit this script" (which will open the script in your editor) and then "Reload this script", but also "Open", for step 6.

So this is the "traymenu".

Step 5

Edit your script: Add some new hotkey and / or hotstring assignments to it! Let's say some shift-control-h for "Hello aunt Birdie" or tyl for "Thank you very much for your letter that I received well" - everything you want, just play around with it some minutes in order to see how easy it all is.

After each editing, do a control-s for saving (but it's not necessary to close your script or your editor!), THEN do traymenu-"reload this script", and try your new hotkeys and hotstrings right in that same editor, in that same first.ahk file!

Before the next script changes,

; "out-comment" any changes your hotkeys / hotstrings will have made to your script, by a leading semicolon, or see this:


--- Code: Autohotkey ---a:: send b ; before the semicolon, it's a command, and this here is a comment, or see this: /*this is a commentspanningseveralor multiplelines*/
or simply delete what your first macros do within your first script; if you miss this step, your "reload this script" will get you an error message, and the "new version" is not loaded. Then, delete those text passages, save (^s), and reload again; it goes without saying that afterwards, you'll do really useful hotkeys and hotstrings that you will trigger not in your script, but in your real applications, but why not just minimize your script file after each addition / change / save / reload (also, see the general observations in step 6 for this!), to have it immediately ready for any further addition or change, during those very first weeks where you'll make a lot of such edits!

HERE'S WHAT YOU NEED TO KNOW FOR STEP 5 (You might print this out for handy reference)

1

Over and over, you'll need the SEND command; you'll find the official help here, together with the names of many special keys, so you'll access this site many times:

http://www.autohotkey.com/docs/commands/Send.htm

The official list for triggers is here: http://www.autohotkey.com/docs/KeyList.htm but I only use the "send" command help before, since it's all there what I need, and anyway, you must understand the following:

As the key TO WHICH you assign a command (the SEND key), the name of the key is without braces (be it normal character key or a special key with a special name), but for the key TO BE SENT (the SENT key), the ordinary character keys are without braces, but all those special keys are with the same names but WITH braces:


--- Code: Autohotkey ---a:: send ba:: send {home}home:: send ahome:: send {end} ; send key: no braces, but sent key: braces!
This also applies to special keys identified by their respective scan code (step 6):


--- Code: Autohotkey ---SC023:: send {SC029}
Also with so-called "modifiers", +, ^, !, # (shift, control alt, winkey), and which you can also use in combination, even in any order, but I strictly observe the order +^!#, because when you have hundreds of such hotkeys, some standardization will help with quickly identifying all these keys and key combinations. Note, all modifiers before the braces, not within; examples:


--- Code: Autohotkey ---^a:: send !b ; here, control-a sends an alt-b+!a:: send ^!b ; here, shift-alt-a sends a control-alt-b!#F10:: send +#{F11} ; here, alt-win-F10 sends shift-win-F11 (send key: no braces, but sent key: braces!)+^SC023:: ^!{SC029}
For an example of bolded and italicized text, see the script, but note that formatting will not be shown in your editor (but should, for example in Word or another text processor). Finally, the send command is with, or without a comma; do it the way you like:


--- Code: Autohotkey ---+^a:: send b ; or this way:a:: send, b
2

Above, we've always sent single keys, but you also can send strings and special characters that need a so-called "exception character" before them; in this example the accent grave is the exception character for the n, which makes a carriage return, and also, you need the exception character for special characters like +^!# since, as we have seen, AHK uses them as "modifiers", normally. So, this:


--- Code: Autohotkey ---+^a:: send Dear Sir, `n`nThank you very much for your letter `+ fax`! ; will make:
Dear Sir,

Thank you very much for your letter + fax!

As you see, the send command does NOT use any "" for strings (and would enclose variables (but that would be a further lession!) in p.c. signs: send somestring with %somevariable% and some other string and %someothervariable% perhaps).

Finally, you also can combine such strings with special keys; the following example would type the string into your text, but then not leave the cursor at the end of that text, but shift the cursor to position one, before the "D":


--- Code: Autohotkey ---+^b:: send Dear Sir, thank you very much{home}
3

In the same way, you'll build real macros, spanning several lines of code (and thus be ended by a so-called "return" (which has nothing to do with the return key on your keyboard)), but that will be a further lesson; here just an example which also shows the very important sleep and msgbox commands (look them up within the commands list linked above):


--- Code: Autohotkey ---+^c::send First linesend ^{left} ; control-leftarrowkeysleep, 1500 ; for your visual checkingsend (and only){space} ; here, a space not within text (as above), but (before or) after textsleep, 1500send {end}`nOh, second line here`!{home} ;sleep, 1500send {up}{end}{left, 3} ; sends the leftarrowkey 3 times in a rowsleep, 1500msgbox, See where the cursor is now! ; exception characters in send strings, but not needed in msgbox strings!return
Remember, for just key reassignments, nothing of such is needed, just do it one-line style as the examples above.

Step 6

You will want to reassign special keys, too, which cannot be identified by their "names" as in step 5, hence your need the respective scan codes of such keys.

If you do NOT want to do this at this time (but don't be afraid of this step, it's so easy!), out-comment the special line in the script, and also, BEFORE doing step 6, please check that the special line is NOT out-commented! And do NOT use any other external tool for identfying these scan codes, since they might be totally different from those you get (and need) here! (Don't ask me why this is so, but don't complain if your wrong scan codes won't work!)

AND, GENERAL OBSERVATION HERE: Check that the special line is not only NOT out-commented (meaning, it must NOT have the leading semicolon), AND CHECK THAT THIS NEWEST VERSION IS THE RUNNING ONE! This means, save the script, and reload it - often, you miss one of these steps, inadvertantly, and then you don't get why your script doesn't work as expected, when simply the running version is not the one you see before your eyes!

Ok, now for the oh-so-difficult part of it all!

Do "traymenu" (rightclick on the "H") and select "Open" there. In that new window then you select the menu "View - Key history and script info".

By this, AND WITH THAT SPECIAL SETTING IN THE SCRIPT that you later will "out-comment", by a semicolon, any key pressed will be listed in that window, and in order to have all this in just some minutes, just press the key "a", then a special key, then key "b", then the next special key you want to get the scancode of, etc. (why not beginning top left on your keyboard (except for everything that's not strictly a...z keys), then going down to bottom right?), and note all these a, b, c (which only serve to clearly distinguish what you then will read in the list on screen: in this list you will see which special keys would also be accessible by their name, and which keys must be addressed by their respective scan code in order to become available in AHK), AND the special keys pressed in-between (not their official "names", just some indications for yourself to identify these keys later on), on a sheet of paper. Then look into the list you got on screen, and note the corresponding scan codes, it's as simple as that. (Of course, you could do it one by one, but why should it take hours, right?)

Well, that's all! You've seen above how to use these scancodes in your script, and whenever you'll have finished with all this scan code identifying, you'll outcomment the "special line" in the screen, to avoid the overhead that line, when active, causes on your system.


And now the basic script, the text to put into your very first AHK script file (note the hotkeys / hotstrings, and try them out):


--- Code: Autohotkey ---; This auto execute section of the script is executed ONCE, immediately after loading the script: #NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.; #Warn ; Recommended for catching common errors.#Hotstring EndChars -()[]{}:;"/\,.?!`n `t ; different from the default setting, I excluded the ' character here #SingleInstance force SetTitleMatchMode, 2 ; = to identify applications by just PARTS of their caption, file title or such not interfering with this!/*which means that's for SCOPE, for application scope to begin with, but you will quickly get to context scope (dependingon variables, or on "controls", meaning the same key will trigger different commands if you are in the tree, or in the listfield of your file manager for example: again "trymenu", then "Window Spy", in order to identify those elements):AHK is just too powerful in order to not profit from these fine features! And yes, feel free to delete all my comments!*/ SendMode Input ; Recommended for new scripts due to its superior speed and reliability.SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.CoordMode, Mouse, Screen ; here "Screen" or "Relative"DetectHiddenWindows, On ; here "On" or (default) "Off" ; #Persistent : not necessary here since this script is persistent anyway because it contains hotkey assignments#InstallKeybdHook ; THIS IS FOR DETECTING THESE SCAN CODES ; outcomment when not needed anymore!   ; Here starts the persistently-running part of the script (AHK knows this because now assignments follow) +^m:: msgbox, Message - Yes, this script is running indeed. ; no return needed since single-line +^n:: send This is ^b^ijust example text^b^i, and in a text processor, it'd even appear formatted`! ::mmm:: After hotstrings, don't forget the trigger space or trigger "enter" or such`! ::nnn::: Just another hotstring, with ^utext formatting^u (invisible in your editor, though)... +!m:: ; and the example from above:send First linesend ^{left} ; control-leftarrowkeysleep, 1500 ; for your visual checkingsend (and only){space} ; here, a space not within text (as above), but (before or) after textsleep, 1500send {end}`nOh, second line here`!{home} ;sleep, 1500send {up}{end}{left, 3} ; sends the leftarrowkey 3 times in a rowsleep, 1500msgbox, See where the cursor is now! ; exception characters in send strings, but not needed in msgbox strings!return ; and here, your code:; ...
That's all!  Ok, I lied to you, I know it's 90 min. later now, but then, 60 min. of them were spent not with AHK, but with all this awful reading you had to do! ;-)

And now, you can stop learning here, and will have a versatile (though free!) macro tool and text expander, or you'll spend some time with the complete commands list, and have a look at the application scope command, "if (WinActive)" / IfWinActive (also in the form #IfWinActive - those "#" commands are at the end of the alphabetical list of commands, don't overlook them), at the ClipWait command (which will enhance all the ^c and ^x that you will soon put into your macros), and many more, just browse them and read "into" those that might be of interest.

The next big step then will be the introduction of "logical constructs", which means, as soon as you'll discover "if / else" and such, you'll have a big problem to understand how you ever did pc work without having these at your disposal: a fantastic, new world will open up to you (and you'll have got a fantastic, new hobby for your week-ends, that's the bad news for your family here)!

So, here's the command list (just the parent page of the send command above):

http://www.autohotkey.com/docs/commands.htm

(and that's just those for AHK, not incl. the additional AHK_L ones!), and then look here, for example:

http://www.autohotkey.com/docs/Variables.htm

and well, there will be strictly no end, since AHK's possibilities are stricly unlimited! (Have a look what a real, top-notch AHK expert is able to do with it (and with a lot of expertise, that is), here: http://skwire.dcmembers.com/fp/?page=software .)

Bye for today!

skwire:
Thanks, evamaria.  Do you mind if I add some AHK syntax highlighting to your post to make it a bit more readable?

evamaria:
Lesson 2

Of course, there's much more to AHK, for your week-ends you'll probably spend with this incredible (and incredibly functional) toy later on, especially logical constructs, like the if / else if, which in AHK also must serve as a replacement for the missing conditions / when construct, in most cases:


--- Code: Autohotkey ---if this ; = for example context, for example the value of a (toggle or other) variable   ; do this (1 line only)else if{   ; do this   ; and that} ; braces needed since more than 1 line; here, other "else if" if you need themelse   ; do another thing; and then no "end if" here!

Also, there is GOSUB, thesubroutine (which in fact is not really a sub-routine, but simply any OTHER routine, called from here); and elsewhere, that subroutine, then:


--- Code: Autohotkey ---THESUBROUTINE: ; this is called a "label"; here, your codeReturn ;here, the ending "return"
and there is even a GOTO, for jumping to something within that SAME routine. Purists will say this is the Devil's, but as long as your routines are just 1 page long (making abundant use of GOSUB - even in cascades, and it's here that scripting becomes really fascinating!), and that even your GOTO labels will be within that just 1 page, all will be perfect!

Without closing "end if" / "end loop" and so on, but with all these braces instead, AHK scripts might look rather strange for people who are accustomed to traditional programming languages, with closing elements for logical structures, but as for me, in some months I got quite used to this "modern style", see how I did it:


--- Code: Autohotkey ---IF this{   some code   some code   LOOP   {      code      code      if that      {         code         another loop         {            code            code         } ; end loop      else         code      } ; end if   } ; END LOOPELSE{   many more lines of code}} ; END IF
As you see, I do similar things here as with the variables in AHK (see my post below): I use comments for putting in the missing elements that I need! If you never have seen traditional code, please quickly FORGET this part, but if AHK style is a problem for you, well, I just have shown you a way to overcome these "code design" problems you might have. (And to say it all, there's even an "abbreviated braces style", but which is possible in some instances, but not in others, as with the commas above: Don't use alternative styles that don't apply everywhere, anyway!)


Ok then, I mixed up some considerations for further working with AHK, with the real basic stuff above, but it'll be my fault if you don't get the basics from here, so ask for my further edit. The real question is, Who needs (free or paid) macro tools anymore, with AHK now being at your service? (And the same goes for proprietary so-called "text expanders": AHK replaces both groups of proprietary (and often quite expensive) tools perfectly!)


P.S. Oh, and I forgot functions! Perhaps I should explain them in some other post? No, enough for today!

evamaria:
Part 1 shifted down from above:

Go ahead! In this context, another warning, variables ain't "typed" in AHK (meaning a logical distinction between strings, numbers of various types, Boolean, etc.), and there is no needed "declaration" / initialization of them (I always initialize them, but for my own "not getting lost", but it doesn't help with detecting misspellings), so lots of your script errors later on will be caused by your misspelling your own variables, and unfortunately, no syntax highlighting will do anything about that - on the other hand, most misspellings of commands will be reprimanded by the (otherwise, very basic) debugger, so syntax highlighting in a program like AHK unfortunately has only very mild effects, since it doesn't make you detect your variable misspellings. This being said -

Go ahead, skwire!

(Or to put this in other words, AHK with a much better compiler / debugger would be a real treat! In the end, it's the editor / compiler / debugger that should advise you about (probable) misspelled variable names and such, so perhaps, even with an alternative editor that "knows" and "reads" and checks AHK code, these problems would be solved, in practice!)

One more thing about "compiling" here: There is NO such step as "compile this script", it's just double-clicking on that readable script file, it's "loading" the script. This means there is no such thing as "real compilation" here - in my above tutorial, you might miss this step, wheen in fact there is no such step, so it's worth mentioning this.

P.S. Much more evident now, skwire - that's what I said about the indentation: Not needed for logical reasons, but so much helpful in order to not gettting lost!





"Formatted for Autohotkey with the GeSHI Syntax Highlighter"

What's THIS ??? Didn't know THAT !!! Would it color "declared" variables, this way leaving misspelled variables in black, thus facilitating their discovery? Will have to have a look at this!

Oh, and another hint for debugging: Often, you copy some script parts into other parts, since the code is more or less the same (but individual enough as to not being suitable to be put into a sub routine) - and then you only adjust SOME of the variables in that inserted code there, leaving others as they were in the source routine. These are some real standard ways to bring unnecessary bugs into your code, and for which any coder should look out first.

Then, of course, there are also those so-much-feared logic errors, but surpringly (or then, not), I do them very rarely - perhaps because with logic, you take careful attention, when with copy / insert actions, you sometimes do them without applying all the care they must be handled with; this being my experience, yours may differ. But in my practice, when debuggin, I check my logic again and again, without finding the fault, and then, it's a residual variable from the source within a copied code bit in the end, again and again... So this means, look out for variables in AHK, if you declare them or not, AHK "accepts" every such variable even if in its current context it's totally devoid of any meaning! And a last word about variables here: They are all "global" in AHK, in theory, but in practice, if you introduce some variables in some routine, without having declared them within your autoexec section, they will NOT be recognized in other routines triggered later on, in many cases, when in most cases, such variables WILL be recognized. So, declare any such variable-to-be-shared in your autoexec section, and initialize ANY variable anywhere in any routine (since without this, it might get its value from another routine), and do plenty of comments in the style

GOSUB, XYZ ; gets variables abc, ppp, efg, whatever from here, will return variables nop, rst to here then

So there IS a real problem with variables in all those languages that handle variables so badly as AHK does, BUT my speaking about these problems is not for putting you off AHK, but just in order to make you have a close look, and to do some "manual variable management", in order to replace the missing AHK variable management  functionality, as far as possible - if you do so, AHK is a fine language doing everything you want, and if the needed command isn't in the AHK command list, there's commands to directly address the Windows commands:

http://msdn.microsoft.com/en-us/library/windows/desktop/ff818516(v=vs.85).aspx

Ok, this has become FAR off-topic, so I'll stop here! ;-)

But what I want to say in the end, is this: With AHK, EVERYTHING will be possible, if you're out to explore its possibilities, some day, and at the same time, for those very limited immediate needs of yours, running your very first AHK script is AS EASY as the very first steps within any such proprietary tool would be (that quickly will show its various limitations, and which you then can NOT overcome BUT by switching to AHK or similar, so why make the detour to begin with?).

skwire:
Would it color "declared" variables-evamaria (May 16, 2013, 10:01 AM)
--- End quote ---

No.

Navigation

[0] Message Index

[#] Next page

Go to full version