Autor Téma: Autohotkey  (Přečteno 19076 krát)


  • Administrator
  • Newbie
  • *****
  • Příspěvků: 99
    • Zobrazit profil
« kdy: 4. Leden 2010, 15:55:37 »
Stručný popis:
AutoHotkey is a free, open-source utility for Windows. With it, you can:

  • Automate almost anything by sending keystrokes and mouse clicks. You can write a mouse or keyboard macro by hand or use the macro recorder.
  • Create hotkeys for keyboard, joystick, and mouse. Virtually any key, button, or combination can become a hotkey.
  • Expand abbreviations as you type them. For example, typing "btw" can automatically produce "by the way".
  • Create custom data-entry forms, user interfaces, and menu bars. See GUI for details.
  • Remap keys and buttons on your keyboard, joystick, and mouse.
  • Respond to signals from hand-held remote controls via the WinLIRC client script.
  • Run existing AutoIt v2 scripts and enhance them with new capabilities.
  • Convert any script into an EXE file that can be run on computers that don't have AutoHotkey installed.

Odkaz na stránku programu:

AutoHotkey - Free Mouse and Keyboard Macro Program with Hotkeys and AutoText
(workshop handout)

Autor textu (text author):  Peter Lecky <peter(dot)lecky(add)> - Slovakia 2009

  • basic computer skills (working with files and directories),
  • simple text editing
  • programming experience can be useful but not necessary

Aim of the workshop:
After the completion of this workshop participants will:
  • know AutoHotKey utility
  • be able to define new useful shortcuts to open frequently used programs / documents (usable to increase the speed and efficiency of working on the computer)
  • be able to create simple (or perhaps even complicated) scripts to automatize frequent computer tasks

Workshop plan:
  • Who is who (getting to know each other),
  • What is what (description of working enwironment we will use during the workshop)
  • Our first script
  • Defining hotkeys
  • HotStrings
  • Simulating input
  • Basics about Windows
  • Miscellaneous interesting functions
  • Compiling the script
  • Interesting links

1 What is script

A script is a plain text file which can be edited in Notepad or any other text editor. We will edit all scripts in Notepad (simple text editor which is a part of Windows operating system). Script contains text written in a special language which is understandable for autohotkey script runner, compiler and of course for us "humans".

If you want to create a new script, do the following:
  • open My computer / Windows explorer and go to the folder where you want to create a script (E.G. c:my_scripts).
  • go to menu file or context menu and activate item "autohotkey script" item in "new" submenu.
  • name the script (don't change .ahk extension) and press enter.

to edit the script:
  • select it by arrow keys or a mouse and choose the item "edit script" in context menu.

There are other items in context menu which you can use to run and compile script. We will describe and use these items later.

2 Our first script

Create a new script (follow the steps described above) and open this new script in notepad (press the edit script menu item on newly created file). Explore this simple text file and remember the following:
  • lines starting with ";" character are comments and can be used to write notes in scripts. These notes improve readability of your scripts so you should write them. Longer comments (multiline) can be written between /* and */ pairs
  • other lines are processed by ahk programs and can contain script commands
  • each script command must be on a separate line (or can cover more lines in some situations - see ahk documentation)

This simple script contains only some comments (info about the author, AutoHotKey version, language, ...) and three initialization commands which are not important to understand now. In general, scripts are interpreted (runned) from top to bottom. Try to add the following 2 lines and save the script (all examples in this text are between <code> and <endcode> tags. These tags are here to clearly separate "code" from descriptive text. Don't copy these tags into your scripts):

Kód: [Vybrat]
msgbox Hello! I'm your first script! Press ok and I'll tel you something more.
msgbox something more!

Run this script (press enter on it or use "run script" item from context menu) and you will receive 2 message boxes. These standard boxes will appear one after the other in the order you placed them in the code of the script.

3 Defining hotkeys

Our next script will be a little bit more complicated. Copy this code into your script (you can use a script created as the prior example and modify it slightly):

Kód: [Vybrat]
^m::msgbox You pressed ctrl+m hotkey

Try this script. Run it and press ctrl+m shortcut. The code we used has the following meaning:
  • ^m means ctrl+m (symbol "^" is ctrl key)
  • : is a separator which separates hotkey from command we want to invoke
  • msgbox... you know this.

You may find that this script works somehow different. We have defined there something called "trigger" which means that the script waits for something (for pressing some hotkey in our case), and when something happens (when you press a proper shortcut) the script wakes up.

The most cryptic part of the previous example is probably the shortcut definition (^m). A shortcut definition is a string consisting of special characters (modifiers) and letters or key names. Here is a list of mostly used modifiers:
  • #: windows key
  • !: alt key
  • ^: ctrl key
  • +: shift key
  • <: use the left key of the pair keys E.G: <^ is a left control
  • >: use the right key of the pair keys
  • *: wildcard symbol hotkey works if keys in a string are pressed but also other modifiers can be pressed E.G. *#c:: hotkey fires if win+c is pressed but also if win+shift+c, ctrl+win+c,... is pressed

Still not very clear? Don't panic! Let's have a closer look at it in further examples. All the previous examples were not very useful? Don't panic. The following examples may be useful for you:

Kód: [Vybrat]
^!#o::msgbox you pressed ctrl+alt+win+o (well, this is the last stupid example :))
#n::run notepad.exe %a_desktop%quicknotes.txt

msgbox quitting the script. Press ok to continue
soundbeep 800,100
soundbeep 600,100

The first example is trivial and demonstrates how to describe more complicated key combinations.

The second example uses a new keyword "run" which has one parameter. This parameter can be a name of the program, an internet address as in our case (this address will be opened in default browser) or a file which will be opened by some program which is associated with this file.

The third example opens notepad (we used the run keyword again) with one parameter. This parameter is a path to file "quicknotes.txt" on your desktop. More detailed description follows:
  • #n:: nothing tricky
  • run is a keyword to run a program or open a file
  • notepad.exe is the name of the program notepad. This program is stored in one of "path" directories (c:windowsnotepad.exe) so we don't need to write full path to this program
  • %a_desktop% is a variable which contains a path to your desktop directory (we will play with variables in next examples)
  • quicknotes.txt is the filename on the desktop which we appended to the end of the desktop path (you probably know that "" character is a separator of directory and file names in a path)

Last example (invoked by windows+q) pops up a message box with some text, then (after the user presses ok) generates 2 beeps (short tones described by 2 parameters: first is a frequency in Hz and second is a duration in miliseconds) and exits the script. Notice that there is a linebreak after the "::" characters. Then, there is a list of commands which will be all processed after win+q shortcut. The list of commands ends with "exitapp" command which terminates the script. After this command there is a "return" keyword which terminates a logical block.

4 HotStrings

  • Can be used to expand some abbreviations
  • Or to invoke scripts
    See the following example:
    Kód: [Vybrat]
    ::btw::By the way

Copy this example into your script, run it, open some text editor (e.g. press win+r, type wordpad and press enter or use hotkey defined in previous examples to open quicknotes.txt) and type btw followed by ., space or enter. The word "btw" automatically disappears and will be replaced with "by the way" phrase.

See more examples:

Kód: [Vybrat]
msgbox don't use abbreviations in serious texts!

My name
email: my email
web: my web page
note: dont use this address when i'm at home

The first example displays a message box immediately after typing letters "btw". The "*" character between first 2 colons means "don't expect abbreviation termination character". Letters btw will be deleted and script will be invoked immediately after you type "w".

The multiline replacing text in the second example is enclosed in parentheses "()". You can use long replacing texts in this way.

5 Simulating input

One of smart functions of AutoHotKey is a possibility to simulate user input. Let's get started with keyboard remapping. See the following examples:

Kód: [Vybrat]
a::b ; press a and b appears in texts (character "b" is mapped to a)
f12::lwin ; press f12 and left windows will be simulated

The first example maps letter a to letter b which means that if you press a, then b will be typed. Remapping works also in combinations with other keys. So press ctrl+a and ctrl+b will be simulated, press shift+a and capital b will be typed.

The second example can be useful for those who has notebooks without the windows key. The key f12 is mapped to the windows key.

Last 2 examples map the f10 and f11 function keys to the left and right mouse buttons so you can simulate mouse clicks from the keyboard.

Here are some of key names you can use in your remappings (see AHK help for full list of keys and mouse buttons):
  • letters and numbers: use standard letters and numbers
  • f1 - f24: function keys
  • space, tab, enter, esc, backspace, delete, insert, home, end: names are self-explanatory
  • pgup, pgdn: page up and page down keys
  • up, down, left, right: arrow keys
  • scrollock, capslock, numlock: are self-explanatory

The remapping keys functionality described in the above lines gives you the possibility to remap only one single key to another key. There is a special command - "sendinput" - which gives us a possibility to simulate a list of keypresses. The parameter of this command is sent to the active window as a keyboard input.

Kód: [Vybrat]
appskey & g::sendinput With best regards{enter}John {+} +andrea
appskey & s::sendinput {lwin}{up}{enter}
appskey & c::sendinput ^a^c
appskey & v::sendinput %clipboard%

For all examples: notice that we have slightly modified the behavior of applications key (the key between right alt and right ctrl key) normally used to open context menu. We used this key as a new "modifier" key so we can use it in combination with other keys. "&" symbol is used to eliminate misunderstandings in multi-key combinations (it is ok to write ^c to simulate ctrl+c but lwine is a little bit confusing and not permitted in scripts. You must write it as lwin &e.)

The first example defines the special hotkey applications key +g which "types" (try it in notepad for example) a short 2 lines long text. "enter" key is inserted by word enter enclosed in braces {}. Character "+" is also in braces because (as you can see later in this example where capital e is inserted as +e) characters +^!# can be used as modifier keys.

The second example (appskey & s::sendinput {lwin}{up}{enter}) defines the shortcut applications key +s which simulates pressing of three keystrokes:
  • {lwin}: left windows key (start menu opens)
  • {up}: up arrow key (cursor is moved to shutdown item in start menu)
  • {enter}: enter key is pressed (shut down windows dialog opens)

The next example (appskey & c::sendinput ^a^c) defines a hotkey which simulates ctrl+a combination (select all, in many programs) and then ctrl+c combination (copy to clipboard).

The example (appskey & v::sendinput %clipboard%) defines a hotkey appskey+v which "types" the contents of the variable clipboard. This variable is provided automatically by autohotkey and contains contents of windows clipboard. This hotkey does not seem very useful (it is similar to standard ctrl+v hotkey) but has one special property. Try to open my computer, go to disk c, select one or more files and/or directories and copy them to the clipboard. Then, open notepad and use our hotkey. You will receive the full paths to files and folders in the clipboard.

The last line in the examples is to fix a problem which has emerged because we have used the applications key as a new modifier and so destroyed the standard functionality of that key. This line defines a mapping which sends the apps key in a situation when the user presses only the apps key without any other key.

6 Basics about windows

This text contains only pure basic information about windows and functions to work with windows. Please read the ahk help file if you want to understand all principles and advanced window operations. Experimenting without reading a documentation can be very frustrating for you and can lead to blundering in the darks of misunderstandings. :)

Let's get started with some basic information about windows:
  • Each standard application (notepad, wordpad, ms word, excel, internet explorer,...) provides one or more windows to its user which are used to control the application.
  • These windows can be somehow manipulated (closed, maximized, minimized, moved,...)
  • If we want to communicate with a particular window in our script, we must identify this window somehow
  • So each window has some identification information
    • window handle: is a special unique identificator which identifies one particular window. We can use this handle for example to communicate directly with one particular notepad, and also in case if more than one notepads were open,
    • window class: identifies windows which are somehow similar (e.g. the class "notepad" represents all currently opened notepads) (This drastically simplified description of classes is large enough for our workshop.),
    • Process identificator: is a number which identifies all windows created by one particular program.
  • Each window can contain one or more different controls (tabs, buttons, edits, multiline edits, checkboxes,...) which we can manage to control, too, but we will not include these possibilities in this very short workshop.

Let's start with one simple example which displays a message box with some information about active window:

Kód: [Vybrat]
winget wid,id,A
winget wpid,pid,A
winget wprocess,processname,A
msgbox id: %wid%, process id: %wpid%, process name: %wprocess%

This example uses variables again. The variable can be compared with a special "named" box which can contain some information. You can access and read or modify this information. Each "box" is automatically created for you the first time you use it in your script. If you want to store something into a box, you must give its name to a function which can provide back some information. (You can use variables in many other situations. See the ahk help file for more information.)

  • The first line of previous example says that hotkey windows+w will be used to start the script.
  • The second line contains a call of function winget with three parameters separated by comma "," character:
    • Variable name "windowid" which will contain the information returned by the function,
    • command" named "id" which tells the function what we want to know about the window,
    • capital a which means that we want to know an information about the active window.
  • The second and third lines are similar. We just use other variables to store asked information and, of course, other commands (we want to receive the information about the process id and the process name of the active window.)
  • Last line generates a message box with collected information. Notice that variable names are between 2 "%" characters. So, if we want to read a contents of a wariable, we must use %var_name% to access the contents.

The second window manipulation example is more practical:

Kód: [Vybrat]
soundbeep 2000,100
WinGet, active_id, ID, A
winwaitclose ahk_id %active_id%

  • The script is activated by pressing windows+-
  • One single beep is emitted to ensure user that script is runing,
  • Window handle of the active window is saved into the "active_id" variable,
  • Function winwaitclose pauses the script and waits until the window described by the parameter exists,
  • If you close the window, then script continues and 4 short beeps are emitted.

Try it with e.g. notepad.
  • Open notepad,
  • Press shortcut win+- and the active window (notepad window) will be "tracked"
  • Close notepad and your script notifies you about it by 4 tones.
  • You can use this simple script to monitor windows which are closed automatically, e.g. there is a "copying" window which appears when you copy big files. This file contains progress bar and "cancel" button and automatically disappears when copying finishes. So, enable tracking of this copying window and continue in other window. You will be notified when the tracked window disappears, and so you will know that all files are copied.

The next example is more complex but very useful:

Kód: [Vybrat]
; initialize one variable with zero

; next hotkey stores a id of active window into our variable
#+a:: ;windows +shift+a
winget win_a,id,A ;win_a now contains window id
soundbeep 1000,300 ;notify user that id was saved

; And now the hotkey to activate window which we saved
#!a:: ;win+alt+a
ifwinexist ahk_id %win_a% ;test if saved window still exists
{ ; start a block which will be invoked if window exists
winactivate ;activates last found window
soundbeep 2000,200 ;notify user that window was activated
return ; do not invoke next commands for this hotkey
} ; end of ifwinexist block
soundbeep 100,300 ;window does not exists so play another tone

The previous example defines 2 shortcuts. One is used to save the id of the active window. The second can be used to switch back to the window which we "bookmarked" by the first hotkey. You can define more hotkeys to store more of your favorite windows and use this mechanism to quickly switch between a few particular windows during your work. If you close the bookmarked window, then, of course, it will not possible to switch back to it.

7 Miscellaneous interesting functions

The following list contains some other interesting functions which you can use in your scripts. Each function is shortly described and a simple example is provided. For full description of all parameters and their meanings, refer to ahk help:
  • inputbox: displays a box with one edit field to type a string and ok and cancel buttons.
    Frequently used arguments: first parameter is a variable which will be used to store typed text, second argument represents window title and trird argument is a label for the edit.
    inputbox yourname,type your name,enter your full name
    msgbox you typed %yourname%
  • shutdown: use to restart / logoff/ shutdown/... the computer. has only one parameter which is a sum of the following codes:
    Logoff 0  
    Shutdown 1  
    Reboot 2  
    Force 4  
    Power down 8  
    appskey & r:: ;shortcut to restart the computer
    shutdown 2 ;2 = reboot
    appskey &s:: ;shortcut to shutdown and power off the computer
    shutdown 1+8 ;1=shutdown and 8 = power down
  • soundplay: play the specified sound or video file
    parameters: first parameter is a full path to filename you want to play, second parameter can be a word "wait". Use this word to pause the script until playing the specified file finishes.
    soundplay c:windowsmediading.wav,wait
  • soundsetwavevolume: set wave volume
    frequently used parameter: first parameter can be number between -100 and +100. use signs to change the volume by a specified number.
    ^#up::soundsetwavevolume +5 ;increase the volume by 5%
    ^#down::soundsetwavevolume -5 ;decrease the volume by 5%
    ^#left::soundsetwavevolume 20 ;set volume to 20%

8 Compiling the script

You can easily compile your script to an exe file and have it always with you on your memory stick. The compiled scripts can be runned on any computer without special requirements (it is not necessary to install autohotkey,...). To compile your script:
  • make sure that script works perfectly (run it and test all hotkeys and functions),
  • select the ahk file in my computer and press "compile script" in context menu.
The generated exe file can be distributed without .ahk script.

9 Interesting links

If you like AutoHotKey and you want to have it in your computer then go to

You can download it there. The ahk help file is a part of the installer, so if you install AutoHotKey, you will have the help file also in your computer (you can find it in the AutoHotKey program group in start menu). Online documentation is also available:

I would like to recommend especially the "script showcase" section on:
This section contains scripts created by users of AutoHotKey. There are some brilliant pieces of code. Check for example:
  • Context Sensitive Help in Any Editor
  • Minimize Window to Tray Menu
  • Using Keyboard Numpad as a Mouse
  • Seek (I loved this script until I wrote something better :))

AutoHotKey is also available as a portable program, so you can have it always with your on a stick and write scripts everywhere.
Peter Teplický
admin fóra ÚNSS
mail: peter(bodka)teplicky(zavinac)unss(bodka)sk