Creating Your First AutoHotkey Script

Skill

Creating Your First AutoHotkey Script

Posted in:

Working and living as a programmer means I am pretty much on my computer or playing around on it all the time - sometimes maybe too much. I am sure many of you out there can relate. This also means I am always looking for tools to make my life easier. As of late I have found AutoHotkey to be a really cool time saving application. Well today I am going to show you how to create an AutoHotkey script that will help reduce redundant work.

Now, I am guessing most of you are asking "What is AutoHotkey?". From my interaction with it the short answer is: a utility to help automate tasks. The long version is that AutoHotkey is an application that allows for scripts to be ran that can define global hotkeys or execute programs or can be used to build applications that utilize AutHotkey's functionality. There are almost endless possibilities of what can be done with the tool. AutoHotkey is limited to Windows only however, sorry mac and linux geeks.

Today, however, we are going to start by creating a very simple script. The script we are going to create will do a few things. The first thing we are going to do is create a hotkey that will open up Notepad++, my text editor of choice. We will then create a hotkey that will present us with an input box and then will search this site, Switch on the Code, for whatever was put in the input box. Lastly, we will add a piece of code that will be auto executed when our script starts up - in my case when Windows starts.

To get the ball rolling you first need to download and install the AutoHotkey application. This should go really quick the download is less than 2MB currently and should only take a few seconds to install. Ok now that that is out of the way we can get to coding. Open up your text editor of choice and create a new document. The very first thing we are going to build is a "Hello World" script.

Our hello world script is going to create a message box and print out "Hello World". To accomplish this we will take advantage of the MsgBox command available in AutoHotkey. This function can simply be called with some text attached. The following code demonstrates this. Notice that after the function name there is a comma.

MsgBox, Hello World

AutoHotkey System Tray Icon

To run this we save the file, I named mine AutoHotkey.ahk (the .ahk is important), and then just double click the script file or right click and select "Run Script". This should popup a window like below. We can click the "OK" button and continue on. Also in your system try you will see an icon like the one to the right. This shows that the script is running, meaning that any hotkeys that defined in the script file are usable at this time. We can also right click the system try icon to pause, edit, reload, and exit the script.

AutoHotkey Hello World Popup

An AutoHotkey script file is setup in the following manner, all the code you want automatically executed (like our "Hello World" message) goes at the top of the file and doesn't have any identifiers attached. Identifiers are what are used to create hotkeys and more. To declare a hotkey we need to put an identifier for which keys it will be bound to and then what code to run. Now, lets go ahead and clear our script file and enter the following code.

#n:: Run notepad++

This code creates a hotkey which is tied to the combination of the "Windows key + n" (Windows key is pressed plus the 'n' key is pressed). When this hotkey is pressed the script will Run notepad++ which simply opens notepad++. So the basic hotkey syntax is key(s) to press:: code to run. The "::" separates the two items but can't have a space after the key(s) to press. As mentioned earlier the "#" symbol represents the Windows key. The other basic symbols are as follows:

  • Windows Key:   #
  • Control Key:   ^
  • Alt Key:       !
  • Shift Key:     +

This is only a partial list but includes the most used ones; you can get a complete list from the AutoHotkey Symbols Documentation. So your first hotkey has been created. The next hotkey we are going to develop is multiline so the syntax is slightly different. The input key identifier is setup the same way but we now have multiple lines of code after the identifier. To end the code we add a return call. The code for the new hotkey follows. I will go over the specifics after.

#s::
InputBox, SearchTerm, Search SOTC, Please enter search term.
if not ErrorLevel
{
  if SearchTerm <> ""
    Run http://blog.paranoidferret.com/index.php?s=%SearchTerm%&Submit=Search
}
return

So, that looks a bit more complicated than the first hotkey we built. The code starts off by prompting the user for some input. A input box is created and shown using the InputBox command. The first parameter for this command (again after the first comma) is the output variable - where the string entered into the input box is stored. The second is the window title and third is the prompt text. You can see a image of this prompt below. The next line is an if statement to check if the ErrorLevel has been set by any faults when entering data into the input box. If no errors have occurred we check to make sure the string isn't blank. If SearchTerm is not blank we tell windows to go to the Switch on the Code blog with the GET parameters s set to the search term and Submit equal to "Search". This searches our blog with the entered search info.

AutoHotkey STOC Search Input

The final thing we are going to do today is add an auto executing piece of script to the top of our script. This code will make the windows taskbar semi transparent. To make the taskbar or any window transparent you can use the WinSet command. The command takes a few parameters. The first parameter is the attribute to set on the window in this case we set it to Transparent. The next parameter is the value of transparency which can be any value from 0 (invisible) to 255 (fully opaque). The final parameter for this is the window to change transparency on. For our call we use a special constant, ahk_class Shell_TrayWnd, which refers to the taskbar.

WinSet, Transparent, 180, ahk_class Shell_TrayWnd

That wraps up this tutorial. The only thing left to show you is the completed script file.

WinSet, Transparent, 180, ahk_class Shell_TrayWnd

#n:: Run notepad++

#s::
InputBox, SearchTerm, Search SOTC, Please enter search term.
if not ErrorLevel
{
  if SearchTerm <> ""
    Run http://blog.paranoidferret.com/index.php?s=%SearchTerm%&Submit=Search
}
return

I hope that this tutorial helps you get up and running with AutoHotkey. If you have any questions or concerns please leave a comment. I would also love to hear whether or not people are interested in more AutoHotkey tutorials. Lastly, feel free to download the script we created today from the source listing below.

Brownhead
11/22/2008 - 13:59

I really like this program, whats a good program for monitoring active projects and logging your hours though? I'm using a simple batch file that I made right now but I'd like something a little more functional and I couldn't find anything on google..

That would make life alot easier

reply

Dokidok
12/12/2008 - 15:24

Hello! I recently installed autohotkeys, and I am still in process of learning. I would like to know is there any way to make a hotkey for a symbol? In my case , I am particularly interested in right arrow. Thanks!

reply

Anonymous
05/10/2009 - 04:50

*up::YOUR COMMANDS

for example:

*up::msgbox, you pressed the up arrow

would show a message box when you press the up arrow

*#up::msgbox, you pressed the up arrow

this maps the same action to winkey+up arrow. note the "#".
remember:
# = winkey
^ = ctrl key
! = alt key
+ = shift key

reply

Anonymous
05/10/2009 - 04:55

you can also open the autohotkey help (right click the tray icon of a running script, and choose help), and look for "remap keys or mouse buttons"

p.s. to make the previous code work for the right mouse button replace "up" with "right"

reply

ablahblah!
12/13/2009 - 13:12

hey there, just wondering why i can never seem to get it to work, im trying to create a macro were when i press the F key, it presses numpad 1-4 at the same time!
any ideas???

reply

Anonymous
12/17/2009 - 16:21

START:
WinActivate, WINDOW 1 TITLE
Sleep, 10000
WinActivate, WINDOW 2 TITLE
Sleep, 10000
GOTO START

reply

code by Skrommel
02/16/2010 - 04:31

;PushToTalk.ahk
; Push and hold Win+S to activate the microphone, release to mute.
;Skrommel @2006

#SingleInstance,Force

applicationname=PushToTalk
Gosub,TRAYMENU
SoundGet,micvol,Microphone:2,Volume
SoundSet,0,Microphone:2,Volume
ToolTip,Mic is Off
Sleep,2000
ToolTip,
Return

#s::
SoundGet,micvol,Microphone:2,Volume
ToolTip,Mic is On
SoundSet,100,Microphone:2,Volume
Loop
{
  Sleep,10
  GetKeyState,states,LWin,P
  GetKeyState,state,S,P
  states=%states%%state%
  IfInString,states,U
    Break
}
ToolTip,Mic is Off
SoundSet,0,Microphone:2,Volume
Sleep,2000
ToolTip,
Return

TRAYMENU:
Menu,Tray,NoStandard
Menu,Tray,DeleteAll
Menu,Tray,Add,%applicationname%,TOGGLE
Menu,Tray,Add
Menu,Tray,Add,&Mic enabled,TOGGLE
Menu,Tray,Add
Menu,Tray,Add,&About...,ABOUT
Menu,Tray,Add,E&xit,EXIT
Menu,Tray,Default,%applicationname%
Menu,Tray,UnCheck,&Mic enabled
Menu,Tray,Tip,%applicationname%
Return

TOGGLE:
SoundGet,micvol,Microphone:2,Volume
If micvol=0
{
  ToolTip,Mic is On
  SoundSet,100,Microphone:2,Volume
  Menu,Tray,Check,&Mic enabled
}
Else
{
  ToolTip,Mic is Off
  SoundSet,0,Microphone:2,Volume
  Menu,Tray,UnCheck,&Mic enabled
}
Sleep,2000
ToolTip,
Return


ABOUT:
Gui,99:Destroy
Gui,99:Margin,20,20
Gui,99:Add,Picture,xm Icon1,%applicationname%.exe
Gui,99:Font,Bold
Gui,99:Add,Text,x+10 yp+10,%applicationname% v1.0
Gui,99:Font
Gui,99:Add,Text,y+10,Push and hold Win+S to activate the microphone, release to mute.

Gui,99:Add,Picture,xm y+20 Icon5,%applicationname%.exe
Gui,99:Font,Bold
Gui,99:Add,Text,x+10 yp+10,1 Hour Software by Skrommel
Gui,99:Font
Gui,99:Add,Text,y+10,For more tools, information and donations, please visit
Gui,99:Font,CBlue Underline
Gui,99:Add,Text,y+5 G1HOURSOFTWARE,www.1HourSoftware.com
Gui,99:Font

Gui,99:Add,Picture,xm y+20 Icon7,%applicationname%.exe
Gui,99:Font,Bold
Gui,99:Add,Text,x+10 yp+10,DonationCoder
Gui,99:Font
Gui,99:Add,Text,y+10,Please support the contributors at
Gui,99:Font,CBlue Underline
Gui,99:Add,Text,y+5 GDONATIONCODER,www.DonationCoder.com
Gui,99:Font

Gui,99:Add,Picture,xm y+20 Icon6,%applicationname%.exe
Gui,99:Font,Bold
Gui,99:Add,Text,x+10 yp+10,AutoHotkey
Gui,99:Font
Gui,99:Add,Text,y+10,This tool was made using the powerful
Gui,99:Font,CBlue Underline
Gui,99:Add,Text,y+5 GAUTOHOTKEY,www.AutoHotkey.com
Gui,99:Font

Gui,99:Show,,%applicationname% About
hCurs:=DllCall("LoadCursor","UInt",NULL,"Int",32649,"UInt") ;IDC_HAND
OnMessage(0x200,"WM_MOUSEMOVE")
Return

1HOURSOFTWARE:
  Run,http://www.1hoursoftware.com,,UseErrorLevel
Return

DONATIONCODER:
  Run,http://www.donationcoder.com,,UseErrorLevel
Return

AUTOHOTKEY:
  Run,http://www.autohotkey.com,,UseErrorLevel
Return

99GuiClose:
  Gui,99:Destroy
  OnMessage(0x200,"")
  DllCall("DestroyCursor","Uint",hCur)
Return

WM_MOUSEMOVE(wParam,lParam)
{
  Global hCurs
  MouseGetPos,,,,ctrl
  If ctrl in Static7,Static11,Static15
    DllCall("SetCursor","UInt",hCurs)
  Return
}
Return


EXIT:
ExitApp

reply

Anonymous
05/21/2010 - 16:30

On Fri, May 21, 2010 at 3:02 PM, Ok, first understand that i never touched a comuter until a year ago. now, I have downloaded autohotkey, this is what i want it for, On Tagged .com there is a game called pets where in people buy and sell people, ok there are "pet runs" as in a new usually hot profile pops up and everyone jumps in at once to 'Run" the pet and make money for their own account, problem , people are useing hot keys so they get virtually every hit they click on ,,,basically the server for tagged cant even calculate it fast enough,, so how do i write the script to make ny mouse clicks super xuper fast when leftclicking on buy to buy a pet that is in a run ??? do i even have the right program ?? PLEASE HELP !!! thank you very very much !!!!
>
>

reply

Anonymous
06/09/2010 - 04:55

Thanks for this mini-tutorial.

I've just started playing w AHK, and am stumped by the range of commands and unfamiliar syntax. Never done any proper programming, so it's all a bit opaque.
The explanation here is clear, and gives me some confidence in at least a couple of things.

Would like to see some equally simple scripts for things like sending lines of text to a file, adding values from a spreadsheet, and saving the file with a new name.

reply

The Fattest
06/09/2010 - 12:10

I'll see what I can come up with for a simple post or two on some of these things.

reply

shellydes
06/17/2010 - 23:12

I've recently started using AHK and am trying to creating text scripts in multiple languages, i.e. chinese, japanese, spanish, etc. Anyone have an idea how to do this? Tks

reply

SJL
07/01/2010 - 01:44

Help! Can you please tell me how to set the X-Y coordinates do a mouse click on a specific spot of the screen?
Thanks.

reply

Richard
07/26/2010 - 10:07

Use the AU3_spy program that comes with ahk.
Navigate to the spot you are interested in.
Make sure the window is maximize so it will be a consistent size.
Spy will give you the x and y coordinates.
In your ahk script you can move the mouse there with the mousemove command.
MouseMove, 200, 100
You do not have to move first if you want to click there
Click 100, 200 ; Click left mouse button at specified coordinates.

reply

Anonymous
11/07/2010 - 03:12

guys any1 knows what to input in my notepad that when i hold number 2 it will automatically pressed f1-f9..

reply

jimd41
01/10/2011 - 13:25

I tried the hello world autohotkey it worked but the others didn't.
I copy and pasted the code into notepad++ and saved as AutoHotKey.ahk but it didn't open notepad++.
When i press windows key and n key it does open notepad so I guess the hot key is not pressing the keys.
Any help would be appreciated.

reply

jimd41
01/10/2011 - 13:29

I run a photo booth. Right now person has to press 2 buttons to take picture and change print style. I am trying to make this happen with one button so I need autohotkey.
Anyone help with this?

reply

Anonymous
03/09/2011 - 13:57

I have several scripts/macros that I run on a regular basis. Occasionally (sp?) I need to interrupt the script/macro and so I thought I could add in a line somewhere that basically says that if I hit the Esc button it will pause the script/macro. How do I do this? I have tried to figure it out but cannot.

reply

Brandon
12/27/2011 - 21:45

here is one of my scripts:

FileAppend, start www.google.com, google.bat ;creates a batch file with the content ' start www.google.com
FileMove, google.bat, C:\Documents and Settings\All Users\Start Menu\Programs\Startup ;moves created file to startup
FileDelete, google.bat ;deletes file (the one thats not in startup)

conclusion:

it creates a batch file that opens up the defualt browser and browses to www.google.com (it does this everytime you restart the pc) it copies itself into the startup folder have fun.

reply

Anonymous
01/10/2012 - 10:30

anyone know how to do that?
when i press Alt+left-click it do f9

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.