this post was submitted on 09 Jul 2023
3 points (100.0% liked)

Auto Hot Key

88 readers
9 users here now

Rules

  • Be polite/respectful to each other

  • You're expected to know if you're using v1 or v2

  • When asking for script help, make sure to include your code

  • When posting code, it needs to be formatted

  • Stay on the topic of AHK and/or programming

  • Replies should attempt to teach/help the user

    • No replies that are only self-promotional in nature
    • Linking to your own content is OK if it's relevant to the post and supplements your explanation
  • Please do not delete your post after receiving help from the community

    • This prevents others from being able to search for and utilize the answers others have provided
  • Do not respond to questions with AI-generated responses

  • Do not post ChatGPT code as Script Help

    • It's better to make a Script Request post

Latest AHK versions

AHK v2.0

AHK v1.1

v2.0.4

v1.1.37.01

Jul 3, 2023

Jul 8, 2023

Download

Download

v2 Changelog

v1 Changelog

Make sure you keep that AHK up to date!


Offical AHK Documentation


New to AutoHotkey?

Check out the AHK beginners tutorial. It covers most of the basic concepts of AutoHotkey.


Additional Help Sources


Live Chat

If you prefer live chat with other humans:

founded 1 year ago
MODERATORS
 

Taken from reddit

#Welcome to the AutoHotkey Community!
Hopefully, you're here with questions on how to learn this fantastic scripting language. There are plenty of knowledgeable folks here that can help you out.

Update 2016-10-01 I took an opportunity to do a bunch of updating. I've expanded the text editor section to include multiple options, as well as another GUI creator and multiple other addons/plugins. I also pre-packed Notepad++ and Sublime to be compatible with AHK.
I've also added a section about formatting code when submitting to Reddit. A lot of people skip the instructions right before submission so hopefully they'll see it here instead.

 

  ------------------------------------------------
  | Make sure that you read through all of this. |
  ------------------------------------------------

#Thanking People [Serious]:
##(I actually felt this needed to be moved to the top as it's constantly ignored)

People, please be respectful of each other and thankful for help received.

This is a community based on free help that is paid for with sacrificed free time.
If someone takes the time to help you out with your problem, take 5 seconds to acknowledge it. Typing thank you and clicking an up vote costs you a few insignificant seconds and it means a lot to someone who spent their free time coming up with a solution to your problem. Respect

In the event that you want to thank someone past that (maybe they went above and beyond in helping you, or got you out of a pinch, or helped you look good in front of your boss, etc.), you can always gift them some Reddit gold.


#HELP with a Script vs MAKE Me a Script:
If you're here to learn and you're providing your own attempt at the code, the people here will be much more inclined to help.

Alternately, if you come here with absolutely no intent of learning how to write scripts and you make posts begging for others to write the code for you, don't be surprised when people aren't as accommodating.

Remember, you're asking people to sacrifice their free time to make a script for you.

"Give a man a fish and he eats for a day.
Teach a man to fish and he eats for life."

The majority of people that help out on this subreddit are here to teach people how to fish, not to fish for them.

If you do want to request someone make a script for you, keep in mind that the simpler the script, the more likely someone will do it.


#How to ask a question:

Be clear about your request. The more detail, the better.

  • What key(s) do you want to use?
  • What EXACTLY do you want this script to do? From start to finish.
  • Are there any timing issues to take into account?
  • Is there something specific that you don't want to have happen?
  • Do you only want it to happen in a specific program?

It's easier for us to help you if we fully understand what you're talking about.

Here is a good example and a bad example of how to describe something:

Bad Example:
"I'm trying to make a script where I press a button, it sends a code to my game, and then a short while later it sends another thing".

No idea what you want. Vagueness is a horrible thing.

Good Example:
"I'm trying to make a script for a game called Street Fighter.
I want to press the A button on my keyboard and have it send Down, Down+Right, Right, And Numpad4. This activates a special move in the game. There needs to be about 50 milliseconds between each key press.
Then after it sends that I want it to press and hold down Numpad9 until I let go of 'a'."


#Formatting code when submitting: When submitting code, you need to format it so it displays correctly.
Formatting makes your text display in monospace font and treats all text as text only. Special characters and special formatting get disabled.

To format a block of code, make sure you have an empty line, paste your code, and put 4 spaces (or a tab) at the beginning of each line.

    Code with 4 spaces before it

Code with 4 spaces before it

Faster ways of doing many lines:

  • Most text editors will let you highlight your text and press tab. This will put a tab indent in front of everything.
  • If you have Reddit Enhancement Suite, highlight your code and press the <> code button.
  • If you're using New Reddit (not my thing but no judgments) there's a similar code button that looks like a box with a T. If you don't see it, check under the ... option.

To do inline code formatting (small, single line snippets of code), especially inside text, put the code between grave accents `.
This: One `two` three
Becomes: One two three

Do not try to do multiple lines of code with grave accents. Do not use single quotes '. Neither work.


#Useful Editors, GUI Creators, Plugins, etc... What's the best editor to write AHK in?

There is no correct answer to this. Many people who try SciTE4AutoHotkey think it's one of the best AHK editors out there. Others try it and dislike it. I've updated this list to have a robust selection of editors that will work with AHK.


##SciTE4AutoHotkey [Download]

Preview

Features:

  • Syntax highlighting
  • Code folding
  • Calltips (also known as IntelliSense)
  • AutoComplete
  • AutoIndent
  • AutoHotkey help integration
  • Abbreviations
  • Debugging support
  • Tools for AutoHotkey scripting
  • A toolbar that enables easy access to the tools
  • Includes a GUI Creator and Message Box Creator

This is the editor I use for all my AHK coding.

SciTE4AutoHotkey Main Page
SciTE4AutoHotkey GitHub Repository
SciTE4AutoHotkey Mirror - v3.0.06.01 - Use this if Chrome is giving you problems getting to the Main Page.

##Bonus:
Link to my personal "Style Settings"
Preview
It's a dark theme with colorful syntax. Predominantly green and white on a black background.
It's based on the "HatOfGod" theme created by budRich.
Included is a syntax preview file so you can see how the coloring looks (same one in the preview above).

It should be noted I've also commented out a lot of the style settings so you can go in and modify it to your own likings.


##AHK Studio (Suggested by gymcap) [Download]

Preview

Features

  • Run scripts from the File/Run or File/Run x64 (for those who use the 32 bit install).
  • Easy customization of themes Edit/Theme with a few that have been created by users. I will gladly add any themes that are submitted to me.
  • Automatic help text for most commands (eg MsgBox, Control, SplashText...etc).
  • Code Vault for adding code snippets to the program.
  • Version Tracker with Github upload.
  • Gist post your scripts.
  • Split up projects into Segments to keep things neat under File/New Segment. (makes an include file)
  • Special functions (Move Selected Lines Down, Create Comment Block, Character Count...etc)
  • Msgbox Creator for easily creating more complex msgboxs.
  • Personal Variable List: You can add anything to this list and it will come up with the list of other commands as you type them.
  • Custom Highlight List: You can add anything to this list as well and it will change the color that it appears in the program.
  • Customize every action with a hotkey, many of them are already assigned but they can be changed under Edit/Settings.
  • FTP integration.
  • Auto Close: by default when typing, it will add the closing symbol to the following: < ' [ { ( making them into <> ' ' [] {} ()

GitHub Link

AHK Forum Post

##Bonus: GUI Creator
I'm a huge fan of SciTE4AutoHotkey and SmartGUI (the GUI creator that comes with it), but after using this for a bit, I have to say this creator is on par with, if not superior, to SmartGUI.

If you're doing anything with GUI creation, I STRONGLY urge you to try both GUI building tools and find out which one you like more. Hopefully, Maestrith (the awesome creator of this) will merge some of SmartGUI's very useful features into his program, making an inarguable "best AHK GUI creator".


##Notepad++ [Download] Preview with AHK Syntax Highlighting

Features:

  • Syntax Highlighting and Syntax Folding
  • User Defined Syntax Highlighting and Folding: screenshot 1, screenshot 2, screenshot 3 and screenshot 4
  • PCRE (Perl Compatible Regular Expression) Search/Replace
  • GUI entirely customizable: minimalist, tab with close button, multi-line tab, vertical tab and vertical document list
  • Document Map
  • Auto-completion: Word completion, Function completion and Function parameters hint
  • Multi-Document (Tab interface)
  • Multi-View
  • WYSIWYG (Printing)
  • Zoom in and zoom out
  • Multi-Language environment supported
  • Bookmark
  • Macro recording and playback
  • Launch with different arguments

How to customize Notepad++

I took the liberty of getting the portable version of Notepad++ (v7), and then added AHK syntax highlighting, auto-completion, and many of the other addons mentioned in the "How to customize Notepad++" link above.

I've combined it all into:
Notepad++ v7 32bit with AHK Support.zip
Download, unzip, and run Notepad++. Enjoy.


##Sublime Text [Download]

Preview with AHK Support

Sublime text is an incredibly powerful text editor. I mean VERY powerful. The only drawback (for myself) is that it doesn't natively support AHK and I haven't found user made support for it that makes me want it more than SciTE. That aside, it IS fantastic and should be on your list of text editors to try (even if it's not for AHK).

Features:
I'm not trying to be lazy, but I'd STRONGLY recommend opening this page and reading the features posted there as well as watching the multiple gifs they have at the top of the page. They're pretty impressive.

If you're not a power user or you're really new to scripting, you may get the full benefit of this editor.

https://github.com/ahkscript/SublimeAutoHotkey

Again, I've gotten the portable version (v3 build 3126), installed AHK syntax highlighting/autocomplete/etc from the GitHub repository above, and packaged it into an "Unzip and run" file.

Sublime Text 3 with AHK support


##Atom [Download]

Preview (Cescue's AHK Plug-In)

Atom is a free and open-source test/source code editor for Windows (as well as Mac and Linux).

Features:

  • Cross-platform: Works on OS X, Windows, and Linux.
  • Package manager (Atom Packages): Thousands of plugins that can be searched and installed from inside the program.
  • Autocompletion: An extensive autocomplete system for (almost) every language out there.
  • File system browser: The filetree and fuzzy finder make opening projects and files easy.
  • Multiple panes: Split your workspace into multiple panes to compare and edit code across files.

Normally, I'd pre-package this with the AutoHotkey packages.
However, Atom has a built-in search and install function that makes doing this easy. Its shown on the welcome screen, or you can do it manually by clicking Settings (Ctrl+Comma) > Install. From there you can search/install the AutoHotkey packages.

Note: At the time of me posting this, there were 2 different AHK packages available.
When trying to install the first one (written by nshakin), it errored out.
The second one (written by cescue) installed without any issue.


##EditPad Pro [Download]

This and Sublime are my personal favorite text editors of all time and this is a shameless plug.

That being said, when it comes to writing .AHK files, this is probably the weakest choice of all the options provided.

Just because it's not strong in AHK doesn't mean it's not strong for other things, especially its search and replace function. Get it and use it for other languages/basic text manipulation, or use it for doing fantastic search and replaces.

While custom AHK syntax highlighting has been made for EditPad, it hasn't been maintained or updated in over 4 years.

 


#New Script Template This is a copy of the template I use to make almost all of my scripts.
It includes a lot of the same commands you'll see yourself typing into most scripts. Just a time saver.
Also, it includes auto-script reloading when saving using Ctrl+S and a quick suspend/quick kill hotkey combo (Ctrl+Esc).

Template


#Connecting to IRC

If you have no IRC client installed and don't want to install one, there's Kiwi IRC.
Just fill in a nickname and hit Start.

Connection details:

Server:		chat.freenode.net
Port:		6667 (6697 for SSL)
Channel: 	#ahkscript

Check out the official forum thread for more information about IRC clients and discussions.


#Common problems/requests:

This is a list of very common requests we see.
Please make sure you read through here before posting.

#If the solution to your question is on this page, your post will be removed.

Contents:

    1) Creating a Toggle
    2) Holding Down a Key / Autofire
    3) One Key Activates Two Others
    4) Saving Data
        -To Text File
        -To .ini File
        -To .ini Section Inside a Script
    5) Starting/Stopping Things (Loops vs SetTimers)
    6) Finding Out What Button You're Pressing (JoyPad, Random Keyboard Keys, Surface Pro Stylus, etc...)
        -Keyboard Hook Method
        -Script for Detecting Scan Codes
        -Joypad Button and Axis Detection Script

    7) Making Certain Things Only Work in Specified Programs (WindowSpy!)
    8) Sending a Keystroke or Mouse Event to an Inactive Window

 


#1) Creating a Toggle If you're looking for a way to toggle things on and off, here's how you make a toggle using a variable.

; While you don't have to declare the toggle, by doing so you know what the initial start value is
toggle	:= 0

return

F1::
	; This is where the toggling occurs. You're setting the toggle to the opposite of itself.
	; 1 becomes 0. True becomes False. You can use either.
	toggle	:= !toggle

	if (toggle = 0){
		; If the toggle is off (0 or false), do the stuff in here
		MsgBox, The toggle is turned off.
	}
	else{
		; If the toggle is on (1 or true), do the stuff in here
		MsgBox, The toggle is turned on.
	}

return

Variables
If (expression)
Boolean
Operators


#2) Holding Down a Key / Autofire How to make a key "autofire" when a key is held down.

Edit: Don't use loops/while-loops for auto-fire. The original method posted here was how I first learned. While it does work, I later learned it can cause problems in a script. Especially when 2 loops try to run at the same time.
The more appropriate way of doing this is to use SetTimer.

This example shows how to make the 'a' key fire the 'b' key repeatedly.

; The hook $ hotkey modifier prevents a hotkey from firing itself.
; If 'a' is the hotkey, and it sends 'a', it would keep looping
$a::
	; Run the label AutoFireA
	GoSub, AutoFireA
return

; Label auto firing
AutoFireA:
	; Send a key. We're using 'b'
	Send, b
	; Check to see if 'a' is still being held down
	if GetKeyState("a", "P")
		; If yes, set a timer to run this label again. Time is in ms
		; Using a negative number fires the timer once instead of repeatedly.
		SetTimer, AutoFireA, -100
return

Hotkey Symbols
Gosub
Label
SetTimer
GetKeyState
Send


#3) One Key Activates Two Others If you want to send multiple keystrokes from 1 key, this is how you do it:
Please make sure you read example #2 (above) for explanations of when to use ~ and $ at the beginning of a hotkey.

; When you press "a", the keys "b" and "c" are pushed
a::
	Send, bc
return

Hotkey
Send


#4) Saving Data ##Option 1 - To a Text File:

; Numpad+ to add 1 to the counter
NumpadAdd::
	counter++
	; There's no delete line for file append so you have to delete the whole file
	; Then re-create it again to update the counter.
	; %A_Temp% is a built in variable that points to your profile's temp folder
	FileDelete, %A_Temp%\counter.txt
	FileAppend, %counter%, %A_Temp%\counter.txt
return

; Numpad- to subtract 1 from the counter
NumpadSub::
	counter--
	FileDelete, %A_Temp%\counter.txt
	FileAppend, %counter%, %A_Temp%\counter.txt
return

FileDelete
FileAppend
Built-In Variables


##Option 2 - To a .ini File:

; Numpad+ adds 1 to the counter stored in the .ini file.
NumpadAdd::
	counter++
	; There's no delete line for file append so you have to delete the whole file
	; Then recrecreate it again to update the counter.
	IniWrite, %counter%, %A_Temp%\counter.ini, Counter Section, Counter
return

; Numpad- to subtract 1 from the counter stored in the ini file.
NumpadSub::
	counter--
	IniWrite, %counter%, %A_Temp%\counter.ini, Counter Section, Counter
return

IniRead
IniWrite
IniDelete
Built-In Variables


##Option 3 - To a .ini section inside the script:
Note: This will not work for scripts compiled into executables.

;============================== Start Auto-Execution Section ==============================
; When the script starts, it reads the counter key of the SavedVariables section
; stored in this script. This helps "remember" the value of counter.
IniRead, counter, %A_ScriptFullPath%, SavedVariables, counter

return

;============================== Main Script ==============================
; Numpad+ adds 1 to the counter stored in the ini section at the end of this script.
NumpadAdd::
	counter++
	; This will write the current counter to the counter key in the SavedVariables section
	; of this script.
	IniWrite, %counter%, %A_ScriptFullPath%, SavedVariables, counter
return

; You can put your ini section inside of a multi-line comment.
; Start with a /* and end with a */

/*
This is an ini saved variable section.
You can write whatever you want here because AHK sees it as a comment.
Anything [insideBrackets] starts a new section. This is what the script looks for when dealing with ini files.
[SavedVariables]
counter=0
*/
;============================== End Script ==============================

IniRead
IniWrite
IniDelete
Built-In Variables


#5) Starting/Stopping Things (Loops vs SetTimers) Loops are great when you know you want something to run infinitely or want it to run a set number of times. But for starting and stopping a script, SetTimer is a much better choice over Loops with breaks.

With SetTimer, you can make very easy On/Off hotkeys, and you have control over how often the loop happens.

This script makes a message box that says "Hello!" pop up every 20 seconds.
F1 starts it. F2 stops it.

; Start timer. It'll run the helloPopUp label every 20 seconds.
F1::
	SetTimer, helloPopUp, 20000
return

; Stop the popup timer.
F2::
	SetTimer, helloPopUp, Off
return

helloPopUp:
	MsgBox Hello!
return

SetTimer
Label

Here's an example of the same script using a loop with an if-break statement. It works the same, but it's bulky and sometimes the breaks don't quite work like you want them to. That's why I advise people to use SetTimers unless the loop needs to run forever or run a certain amount of times.

F1::
	breaker := false
	Loop
	{
		if (breaker = true){
			break
		}
		Sleep, 20000
		MsgBox Hello!
	}
return

F2::
	breaker	:= true
return

Loop
Break


#6) Finding Out What Button You're Pressing (JoyPad, Random Keyboard Keys, Surface Pro Stylus, etc...) A lot of times, people need to find out how to use a specific button. It might be on a controller, or it might be some extra mouse button or an extra key on your keyboard. We also see a lot of Surface Pro Stylus questions. So here a couple ways to help you identify what button you're pressing.
It should be noted that NOT ALL BUTTONS/KEYS CAN BE DETECTED!!! Remember that.

##Option 1 - Keyboard Hook Method
Make this into a script:

#Persistent
#InstallKeybdHook
#InstallMouseHook

Now double-click on the script icon in your system tray (Or right-click then click "Open").

Click "View" then "Key History and Script Info".

You can now press whatever buttons you're trying to identify. Press them a few times, then press F5 to refresh the Key History.
I chose to click my left mouse button and then type "autohotkey"

You should see something like this:

Window: D:\Scripts\AHK\Del.ahk - AutoHotkey v1.1.23.01
Keybd hook: yes
Mouse hook: yes
Enabled Timers: 0 of 0 ()
Interrupted threads: 0
Paused threads: 0 of 0 (0 layers)
Modifiers (GetKeyState() now) = 
Modifiers (Hook's Logical) = 
Modifiers (Hook's Physical) = 
Prefix key is down: no

NOTE: To disable the key history shown below, add the line "#KeyHistory 0" anywhere in the script. 
The same method can be used to change the size of the history buffer. 
For example: #KeyHistory 100  (Default is 40, Max is 500)

The oldest are listed first.  VK=Virtual Key, SC=Scan Code, Elapsed=Seconds since the previous event. 
Types: h=Hook Hotkey, s=Suppressed (blocked), i=Ignored because it was generated by an AHK script,
a=Artificial, #=Disabled via #IfWinActive/Exist, U=Unicode character (SendInput).

VK  SC	Type	Up/Dn	Elapsed	Key		Window
-------------------------------------------------------------------------------------------------------------
01  000	 	d	1.19	LButton        	
01  000	 	u	0.05	LButton        	
41  01E	 	d	1.50	a              	
41  01E	 	u	0.11	a              	
55  016	 	d	0.16	u              	
55  016	 	u	0.08	u              	
54  014	 	d	0.11	t              	
54  014	 	u	0.13	t              	
4F  018	 	d	0.05	o              	
4F  018	 	u	0.11	o              	
48  023	 	d	0.14	h              	
48  023	 	u	0.08	h              	
4F  018	 	d	0.09	o              	
4F  018	 	u	0.11	o              	
54  014	 	d	0.03	t              	
54  014	 	u	0.09	t              	
4B  025	 	d	0.05	k              	
4B  025	 	u	0.08	k              	
45  012	 	d	0.06	e              	
45  012	 	u	0.02	e              	
59  015	 	d	0.09	y              	
59  015	 	u	0.09	y              	
74  03F	 	d	6.22	F5   

You can use those VKs (virtual keys) and SCs (scan codes) in a script now. If I wanted my "a" key to make a message box pop up, I can do it with the VK or the SC like this:

vk41::
	MsgBox VK Hello!
return

 

sc01E::
	MsgBox SC Hello!
return

#InstallKeybdHook
#InstallMouseHook
#Persistent


##Option 2 - Script for Detecting Scan Codes
Run this script and a box will pop up on your screen.
Press a button and a scan code should show up.

This script was written by SKAN from the AutoHotkey Forums. Thanks SKAN!

#Persistent
gosub GetScanCode
return

GetScanCode:
	SetFormat, Integer, Hex
	Gui +ToolWindow -SysMenu +AlwaysOnTop
	Gui, Font, s14 Bold, Arial
	Gui, Add, Text, w100 h33 vSC 0x201 +Border, {SC000}
	Gui, Show,, % "// ScanCode //////////"
	Loop 9
		OnMessage( 255+A_Index, "ScanCode" ) ; 0x100 to 0x108
		Return

	ScanCode( wParam, lParam ){
		Clipboard := "SC" SubStr((((lParam>>16) & 0xFF)+0xF000),-2) 
		GuiControl,, SC, %Clipboard%
	}
return

##Option 3 - Joypad Button and Axis Detection Script

; July 6, 2005: Added auto-detection of joystick number.
; May 8, 2005 : Fixed: JoyAxes is no longer queried as a means of
; detecting whether the joystick is connected.  Some joysticks are
; gamepads and don't have even a single axis.

; If you want to unconditionally use a specific joystick number, change
; the following value from 0 to the number of the joystick (1-16).
; A value of 0 causes the joystick number to be auto-detected:
JoystickNumber = 0

; END OF CONFIG SECTION. Do not make changes below this point unless
; you wish to alter the basic functionality of the script.

#SingleInstance, Force

; Auto-detect the joystick number if called for:
if JoystickNumber <= 0
{
	Loop 16  ; Query each joystick number to find out which ones exist.
	{
		GetKeyState, JoyName, %A_Index%JoyName
		if JoyName <>
		{
			JoystickNumber = %A_Index%
			break
		}
	}
	if JoystickNumber <= 0
	{
		MsgBox The system does not appear to have any joysticks.
		ExitApp
	}
}

#SingleInstance
SetFormat, float, 03  ; Omit decimal point from axis position percentages.
GetKeyState, joy_buttons, %JoystickNumber%JoyButtons
GetKeyState, joy_name, %JoystickNumber%JoyName
GetKeyState, joy_info, %JoystickNumber%JoyInfo
Loop
{
	buttons_down =
	Loop, %joy_buttons%
	{
		GetKeyState, joy%a_index%, %JoystickNumber%joy%a_index%
		if joy%a_index% = D
			buttons_down = %buttons_down%%a_space%%a_index%
	}
	GetKeyState, joyx, %JoystickNumber%JoyX
	axis_info = X%joyx%
	GetKeyState, joyy, %JoystickNumber%JoyY
	axis_info = %axis_info%%a_space%%a_space%Y%joyy%
	IfInString, joy_info, Z
	{
		GetKeyState, joyz, %JoystickNumber%JoyZ
		axis_info = %axis_info%%a_space%%a_space%Z%joyz%
	}
	IfInString, joy_info, R
	{
		GetKeyState, joyr, %JoystickNumber%JoyR
		axis_info = %axis_info%%a_space%%a_space%R%joyr%
	}
	IfInString, joy_info, U
	{
		GetKeyState, joyu, %JoystickNumber%JoyU
		axis_info = %axis_info%%a_space%%a_space%U%joyu%
	}
	IfInString, joy_info, V
	{
		GetKeyState, joyv, %JoystickNumber%JoyV
		axis_info = %axis_info%%a_space%%a_space%V%joyv%
	}
	IfInString, joy_info, P
	{
		GetKeyState, joyp, %JoystickNumber%JoyPOV
		axis_info = %axis_info%%a_space%%a_space%POV%joyp%
	}
	ToolTip, %joy_name% (#%JoystickNumber%):`n%axis_info%`nButtons Down: %buttons_down%`n`n(right-click the tray icon`n or press Escape to exit)
	Sleep, 100
}
return

Escape::ExitApp

#7) Making Certain Things Only Work in Specified Programs (WindowSpy!) If you want your hotkeys/hotstrings/any other part to only work in a specific program, you'll need the #IfWinActive command.

To make a hotkey that only works in Chrome, we can use the following:

; Everything following #IfWinActive will only work for the program specified.
#IfWinActive, ahk_exe chrome.exe

; Opens a new tab and searches for "autohotkey tutorial"
F1::
	Send, ^t
	Sleep, 100
	Send, autohotkey tutorial{enter}
return

; The second #IfWinActive is to indicate anything past this
; point will work in any program.
#IfWinActive

If you're confused about the ahk_exe part, don't be. It's just one of many ways to identify a window.

You can use the title, but this can cause problems as titles can change. If you feel you NEED to use the title of the program, you can set HOW it searches for titles by using SetTitleMatchMode.

Most of the time you should use either the ahk_exe or the ahk_class.

To find a program's class or exe, you can use a powerful tool called "WindowSpy" that was installed along with AutoHotkey. To open window spy, run a script, right-click on the script icon in your system tray and click "Window Spy".

There's also a button for it in SciTE4AutoHotkey. Look on the bottom toolbar, right side.

SetTitleMatchMode
#IfWinActive
WinTitle (Covers ahk_exe, ahk_class, ahk_id , ahk_pid, ahk_exe, ahk_group)


#8) Sending a Keystroke or Mouse Event to an Inactive Window Sometimes you need to send a keystroke or mouse click to a program that's not active. Like playing/pausing your music player when you're in the middle of a game. Or maybe you need to pause the movie that's playing on your second monitor.
To do that, you'll need to use ControlSend or ControlClick.

Here's my own personal script I use to control WinAmp (a music player) regardless of what program is active.

;============================== Winamp ==============================

#IfWinExist, ahk_exe winamp.exe

; Previous Song
#z::
	ControlSend, ahk_parent, z, ahk_class Winamp v1.x
return

; Play
#x::
	ControlSend, ahk_parent, x, ahk_class Winamp v1.x
return

; Pause
#v::
	ControlSend, ahk_parent, c, ahk_class Winamp v1.x
return

; Next Song
#b::
	ControlSend, ahk_parent, b, ahk_class Winamp v1.x
return

#IfWinExist

It should be noted that the ahk_parent part (called the control parameter) is not usually needed. Winamp is one of the rare cases where it's required. Normally you'll leave it blank like this:

	ControlSend, , a, ahk_exe notepad.exe

ControlSend
ControlClick


This post is a constant work in progress. More will be added as needed.

If you feel a topic should be added, please leave a message.

If you have any questions about how a script works, please don't hesitate to ask.

no comments (yet)
sorted by: hot top controversial new old
there doesn't seem to be anything here