r/AutoHotkey • • 7h ago

v2 Script Help Some logic question

1 Upvotes

edit: excuse the codeblocks. currently fighting with the reddit UI to fix them edit: fixed them

I have some simple Cheatsheets for most of my programs. (Runs through a formatter called ShowHelp() which adds some color, but not important for this question)

Requires AutoHotkey v2.0
#HotIf WinActive("ahk_exe mintty.exe")
    
F1::ShowHelp_Mintty()
    
#HotIf
    
ShowHelp_Mintty() {
    ShowHelp([
        { title: "SSH AGENT  (F2 types these in order)", rows: [
            ["set +H",
             "Disables bash history expansion - needed because the ! in the repo name would otherwise trigger it"],
            ["eval $(ssh-agent -s)",
             "Starts the ssh-agent for this shell session"],
            ["ssh-add ~/.ssh/id_2026",
             "Adds the private key to the agent, so the passphrase is asked once instead of every time"] ] },

        "SSH / Git Cheatsheet  -  F1",

I wanted to change it so instead of writing my cheatsheet in .ahk, it reads in local .md files. Creating a #HotIf instance for each file found.

Like this: Foldercontents: 'Cheatsheet.ahk' 'mintty.md' 'powerpoint.md' 'brave.md' ->

Requires AutoHotkey v2.0

pseudo_code to give you an idea:
FindFiles() ->
FoundFile1 = "mintty.md"
FoundFile1_exe = Regex(FoundFile1) -> "mintty.exe"

#HotIf WinActive("ahk_exe " FoundFile1_exe)

F1::ShowHelp_FoundFile("." FoundFile1)

#HotIf

#HotIf WinActive("ahk_exe " FoundFile2_exe)

F1::ShowHelp_FoundFile("." FoundFile2)

#HotIf

Am I thinking in the correct direction?


r/AutoHotkey • • 1d ago

v2 Script Help Press a key every few minutes. PLEASE HELP.

0 Upvotes

Hello, im trying to make a script that presses the "J" key on the keyboard every 2 minutes and also pairs that input with a jump (Space) on the keyboard. I dont know anything about auto hotkey but i want to learn and installed it mainly for this. Anyone know how i can write a script for this purpose? Its for a game and i want to overnight a task in the game and this simple script should do the job.


r/AutoHotkey • • 2d ago

v2 Tool / Script Share Windows shortcut to toggle auto hide taskbar

4 Upvotes

I was looking for a shortcut to always show taskbar when I need it, but have it auto hide otherwise to avoid OLED monitor burn-in. I couldn't find anything so I asked AI to vibe code a script.

The shortcut is set to Ctrl+Shift+X in this script but you can change it in the line "^+x::".

#Requires AutoHotkey v2.0
#SingleInstance Force

^+x::
{
    ; Windows taskbar AppBar constants
    ABM_GETSTATE := 0x00000004
    ABM_SETSTATE := 0x0000000A
    ABS_AUTOHIDE := 0x00000001
    ABS_ALWAYSONTOP := 0x00000002

    ; Locate the taskbar
    hwnd := WinExist("ahk_class Shell_TrayWnd")

    if !hwnd {
        MsgBox("Cannot find the Windows taskbar.")
        return
    }

    ; Create APPBARDATA structure
    size := (A_PtrSize = 8) ? 48 : 36
    abd := Buffer(size, 0)

    NumPut("UInt", size, abd, 0)
    NumPut("Ptr", hwnd, abd, A_PtrSize)

    ; Read current state
    state := DllCall("Shell32\SHAppBarMessage",
        "UInt", ABM_GETSTATE,
        "Ptr", abd,
        "UPtr")

    ; Toggle auto-hide
    newState := (state & ABS_AUTOHIDE)
        ? ABS_ALWAYSONTOP
        : ABS_AUTOHIDE

    NumPut("Ptr", newState, abd, size - A_PtrSize)

    ; Apply new state
    DllCall("Shell32\SHAppBarMessage",
        "UInt", ABM_SETSTATE,
        "Ptr", abd,
        "UPtr")
}

r/AutoHotkey • • 2d ago

v2 Tool / Script Share Script to keep track of all your pressed keys

2 Upvotes

Yeah so in short, I wanted to get statistics on what keys I press the most on my computer for a thing, so I made this. This script, if combined with an ini file, can note for you and later show you exactly all the keys you've pressed when using the script (in order), and then you can do whatever you want with it, such as for myself putting all this on Excel to get an idea of what keys I use the most.

I'm sure some guy probably has already done this, but I wanted to make mine, and knowing the little extra things I added for my case, maybe I actually had to redo it from scratch, I dunno (but I did want to do it myself).

I'm sharing this both in case someone might be interested in using it and also to get some reviews of my code, as I've heard I'm not good at AutoHotKey, so I was curious to hear any possible mistakes or imperfections.

Be careful though, if you want to use it... yeah, you'll kind of have to redo lots of things lol. My keyboard is like ultra different from yours no doubt, so you'll probably have to change the scancodes (btw there is in the script a way to easily find scancodes (showSC)), as well I implemented ways to not count some hotstrings I use (such as "jj", ";;", "²²"...) that you probably don't have, though this might give you ideas if you want to do something similar. (also this script is just for single keys; obviously, for keyboard shortcuts it would be doable by adding all them in a similar way but I didn't do it here. Also, talking about keyboard shortcuts, the keyboard shortcuts are never counted here even if it uses one of the keys in the script, like "CtrlS" doesn't add s to the stack anywhere)

I won't explain in ultra detail for understandable reasons, but in short it's just adding to a stack all the keys in strings using simple one input hotkeys, saving the stack in an ini file once the script ends, and also adding the times when you started and ended the script for extra info, and also adding a counter to not overwrite things.

Sorry if the script is long btw, I hesitated to send it to pastebin or something or remove the repetitive parts, but just to be sure I left basically everything:

#Requires AutoHotkey v2.0


#SingleInstance


iniFile := A_ScriptDir "\StatistictsSettings.ini"
Counter := IniRead(iniFile, "ScriptReloads", "Count") + 1
starthour := FormatTime(, "HH") "h" FormatTime(, "mm") "m" FormatTime(, "ss") "s" ; Get current time at the start of the script


~SC010::{ ;a
RecordHotkey("reset")
    StatPush("a")
}
~SC011::{ ;z
RecordHotkey("reset")
    StatPush("z")
}
~SC012::{ ;e
RecordHotkey("reset")
    StatPush("e")
}
~SC013::{
RecordHotkey("reset")
    StatPush("r")
}
~SC014::{
RecordHotkey("reset")
    StatPush("t")
}
~SC015::{
RecordHotkey("reset")
    StatPush("y")
}
~SC016::{ ;"uu" is a hotstring for me and I don't want to count it, go look at the code of "~SC024" for details
History := RecordHotkey()
if(History.prior = "~SC016"){
    StatPush("Pop")
    RecordHotkey("reset")
}
else StatPush("u")
}
~SC017::{
RecordHotkey("reset")
    StatPush("i")
}
~SC018::{
RecordHotkey("reset")
    StatPush("o")
}
~SC019::{
RecordHotkey("reset")
    StatPush("p")
}
~SC01A::{
RecordHotkey("reset")
Cpsl := GetKeyState("CapsLock","T")
if(Cpsl = false)
    StatPush("^")
else StatPush("¨")
}
~+SC01A::{
RecordHotkey("reset")
StatPush("¨")
}
~SC01E::{
RecordHotkey("reset")
    StatPush("q")
}
~SC01F::{
RecordHotkey("reset")
    StatPush("s")
}
~SC020::{
RecordHotkey("reset")
    StatPush("d")
}
~SC021::{
RecordHotkey("reset")
    StatPush("f")
}
~SC022::{
RecordHotkey("reset") ;have to mention you could probably remove all these that aren't related to hotstring removals, it's just that without you can do something like type one of keys related like "ù", type somes keys that would record history and then type ù again and this one wouldn't be counted, but adding those might be costly and it isn't ultra necessary
    StatPush("g")
}
~SC023::{
History := RecordHotkey()
if(History.prior = "~SC023"){ ;"hh" inputs up
    StatPush("Pop")
    RecordHotkey("reset")
}
else StatPush("h")
}
~SC024::{ ;"jj" is one of my hotstrings (it inputs right) and I don't want this key to be counted every time I do this hotstring as it wouldn't be intresting for the info I want to gather, so we pop it.
History := RecordHotkey()
if(History.prior = "~SC024"){
    StatPush("Pop")
    RecordHotkey("reset") ;we reset the history for this hotstring and all the others simply because inputing j three times would false the data if not (it would execute the condition again and remove the input I did before my first j for no reason and not count this j that could be a real j, while reseting the history means it will wait once again for me to input j twice to recognize I did the hotstring, giving the data I want (that's also why I can't use A_PrioHotkey because you can't reset it)), same for all the similar cases
}
else StatPush("j")
}
~SC025::{ ;same for hotstring "kk" that inputs backspace
History := RecordHotkey()
if(History.prior = "~SC025"){
    StatPush("Pop")
    RecordHotkey("reset")
}
else StatPush("k")
}
~SC026::{
RecordHotkey("reset")
    StatPush("l")
}
~SC027::{
RecordHotkey("reset")
    StatPush("m")
}
~SC028::{
History := RecordHotkey()
Cpsl := GetKeyState("CapsLock","T")
if(History.prior = "~SC028"){ ; "ùù" is a hostring for the symbol "≥"
    StatPush("Pop")
    RecordHotkey("reset")
}
else if(Cpsl = false)
    StatPush("ù")
else StatPush("%")
}
~+SC028::{
RecordHotkey("reset")
StatPush("%")
}
~SC02C::{
RecordHotkey("reset")
    StatPush("w")
}
~SC02D::{
RecordHotkey("reset")
    StatPush("x")
}
~SC02E::{
RecordHotkey("reset")
    StatPush("c")
}
~SC02F::{
RecordHotkey("reset")
    StatPush("v")
}
~SC030::{
History := RecordHotkey()
if(History.prior = "~SC030"){ ;"bb" inputs left
    StatPush("Pop")
    RecordHotkey("reset")
}
else StatPush("b")
}
~SC031::{
History := RecordHotkey()
if(History.prior = "~SC031"){ ;"nn" inputs down
    StatPush("Pop")
    RecordHotkey("reset")
}
else StatPush("n")
}
~SC032::{
History := RecordHotkey()
if(History.prior = "~SC032"){ ;hotstrings ",," and "??" input enter
    StatPush("Pop")
    RecordHotkey("reset")
}
else{
    Cpsl := GetKeyState("CapsLock","T")
if(Cpsl = false)
    StatPush(",")
else StatPush("?")
}
}
~+SC032::{
History := RecordHotkey()
if(History.prior = "~+SC032"){
    StatPush("Pop")
    RecordHotkey("reset")
}
else StatPush("?")
}
~SC033::{
Cpsl := GetKeyState("CapsLock","T")
History := RecordHotkey()
if(Cpsl = false){
if(History.prior = "~SC033" || History.prior = "~SC034"){ ; same as ùù but for "≤" and ":;" does μ
    StatPush("Pop")
    RecordHotkey("reset")
}
else StatPush(";")
}
else if(History.prior = "~SC034"){ ;"/." does §
    StatPush("Pop")
    RecordHotkey("reset")
}
else StatPush(".")
}
~+SC033::{
RecordHotkey("reset")
StatPush(".")
}
~SC034::{
RecordHotkey()
Cpsl := GetKeyState("CapsLock","T")
if(Cpsl = false)
    StatPush(":")
else StatPush("/")
}
~+SC034::{
RecordHotkey()
StatPush("/")
}
~SC035::{
RecordHotkey("reset")
Cpsl := GetKeyState("CapsLock","T")
if(Cpsl = false)
    StatPush("*")
else StatPush("!")
}
~+SC035::{
RecordHotkey("reset")
StatPush("!")
}
~SC002::{
RecordHotkey("reset")
Cpsl := GetKeyState("CapsLock","T")
if(Cpsl = false)
    StatPush("&")
else StatPush("1")
}
~+SC002::{
RecordHotkey("reset")
StatPush("1")
}
~SC003::{
RecordHotkey("reset")
Cpsl := GetKeyState("CapsLock","T")
if(Cpsl = false)
    StatPush("é")
else StatPush("2")
}
~+SC003::{
RecordHotkey("reset")
StatPush("2")
}
~SC004::{
Cpsl := GetKeyState("CapsLock","T")
if(Cpsl = false){
History := RecordHotkey()
if(History.prior = "~SC004" || History.prior = "~SC005"){ ; """"" does « or » and "'"" does... things, it's long to explain but it does somethings
    StatPush("Pop")
    RecordHotkey("reset")
}
else StatPush("''") ;this is just ", but it kind of doesn't work if litterally had entered it and this is a ultra fine way around
}
else StatPush("3")
}
~+SC004::{
RecordHotkey("reset")
StatPush("3")
}
~SC005::{
Cpsl := GetKeyState("CapsLock","T")
if(Cpsl = false){
History := RecordHotkey()
if(History.prior = "~SC004"){ ; ""'" does... things, similarly to '"
    StatPush("Pop")
    RecordHotkey("reset")
}
    else StatPush("'")
}
else StatPush("4")
}
~+SC005::{
RecordHotkey("reset")
StatPush("4")
}
~SC006::{
RecordHotkey("reset")
Cpsl := GetKeyState("CapsLock","T")
if(Cpsl = false)
    StatPush("(")
else StatPush("5")
}
~+SC006::{
RecordHotkey("reset")
StatPush("5")
}
~SC007::{
RecordHotkey("reset")
Cpsl := GetKeyState("CapsLock","T")
if(Cpsl = false)
    StatPush("-")
else StatPush("6")
}
~+SC007::{
RecordHotkey("reset")
StatPush("6")
}
~SC008::{
Cpsl := GetKeyState("CapsLock","T")
if(Cpsl = false)
    StatPush("è")
else StatPush("7")
}
~+SC008::{
RecordHotkey("reset")
StatPush("7")
}
~SC009::{
Cpsl := GetKeyState("CapsLock","T")
if(Cpsl = false){
History := RecordHotkey()
if(History.prior = "~SC009"){ ; "__" does →
    StatPush("Pop")
    RecordHotkey("reset")
}
else StatPush("_")
}
else StatPush("8")
}
~+SC009::{
RecordHotkey("reset")
StatPush("8")
}
~SC00A::{
Cpsl := GetKeyState("CapsLock","T")
if(Cpsl = false){
History := RecordHotkey()
if(History.prior = "~SC00A"){ ; "çç" does "« "
    StatPush("Pop")
    RecordHotkey("reset")
}
else StatPush("ç")
}
else StatPush("9")
}
~+SC00A::{
RecordHotkey("reset")
StatPush("9")
}
~SC00B::{
Cpsl := GetKeyState("CapsLock","T")
if(Cpsl = false){
History := RecordHotkey()
if(History.prior = "~SC00B"){ ; "àà" does " »"
    StatPush("Pop")
    RecordHotkey("reset")
}
else StatPush("à")
}
else StatPush("0")
}
~+SC00B::{
RecordHotkey("reset")
StatPush("0")
}
~SC00C::{
RecordHotkey("reset")
Cpsl := GetKeyState("CapsLock","T")
if(Cpsl = false)
    StatPush(")")
else StatPush("°")
}
~+SC00C::{
RecordHotkey("reset")
StatPush("°")
}
~SC00D::{
RecordHotkey("reset")
Cpsl := GetKeyState("CapsLock","T")
if(Cpsl = false)
    StatPush("=")
else StatPush("+")
}
~+SC00D::{
RecordHotkey("reset")
StatPush("+")
}
~SC029::{
History := RecordHotkey()
if(History.prior = "~SC029"){ ;"²²" does ´e
    StatPush("Pop")
    RecordHotkey("reset")
}
else StatPush("²")
}
~LButton::{
RecordHotkey("reset")
}
~RButton::{
RecordHotkey("reset")
}



RecordHotkey(hk := A_ThisHotkey) {
    static current := "", prior := ""
    if (hk = "reset") {
        prior := ""
        current := ""
    }
    else if (hk != "") {
        prior := current
        current := hk
    }
    return { current: current, prior: prior}
}


;to test history
/*SetTimer(TestHistory, 100)


TestHistory() {
    History := RecordHotkey("")
    h := "current:" History.current " prior:" History.prior
    ToolTip h
}*/




;to easily get scan codes
/*SetTimer(ShowSC, 100)


ShowSC() {
    ScanCode := Format("SC{:X}", GetKeySC(A_PriorKey))
    ToolTip ScanCode
}*/


StatPush(c){
    static stat := []
    if(c = "Pop")
        stat.Pop()
    else if(c != "0")
        stat.Push([c])
    return stat
}


/*SetTimer(ShowArray, 100) ;to test your live inputs, I know this representations has mistakes (for hotstrings I wanted to remove) for reasons I don't want to know and fix, but it's mostly accurate


ShowArray(){
stat := StatPush("0")
static i := 1
static test := ""
;count := Counter(1)
while(stat.Has(i) != 0)
;while(i <= count)
{
test := test . " " . stat.Get(i)[1]
i := i + 1
}
ToolTip test
}*/
ArrayString(){
stat := StatPush("0")
test := ""
i := 1
while(stat.Has(i) != 0)
{
test := test . " " . stat.Get(i)[1]
i := i + 1
}
return test
}


OnExit Save


Save(ExitReason, ExitCode){
CurrentDate := FormatTime(, "dd-MM-yyyy")
    hour := FormatTime(, "HH") ; Get current time at the end of the script
    min := FormatTime(, "mm")
    sec := FormatTime(, "ss")
IniWrite(ArrayString() " /date:" CurrentDate " start:" starthour " end:" hour "h" min "m" sec "s", iniFile, "Stats", "Inputs" Counter,)
IniWrite(Counter, iniFile, "ScriptReloads", "Count")
}

r/AutoHotkey • • 3d ago

v2 Script Help Need help Remapped "shift" keeps getting held after pressing

4 Upvotes

This probably has been asked numerous times already, but I cannot find a solution that works on my side, so that's why I'm asking here directly. What did I do wrong with this cause im relatively new to AutoHotkey, I'm just using it for keybinds to make my life easier; everything seems to work except the Shift key. Any help would be appreciated :DD

#HotIf WinActive
Numpad1:: Ctrl
Numpad2:: Alt
Numpad3:: Shift 
Numpad4:: i
Numpad5:: o
Numpad6:: d
Numpad7:: ^+x
Numpad8:: ^b
Numpad9:: ^+v
NumpadAdd:: ^+
NumpadDiv:: ^z
NumpadDot:: +Space
NumpadEnter::Space
NumpadMult::^+z
NumpadSub:: ^-
#HotIf

r/AutoHotkey • • 4d ago

v2 Script Help How do I make my script kill running v1 scripts as well?

2 Upvotes

I'm currently working on translating my v1 master script to v2. In V1 I had this:

^#!e::
DetectHiddenWindows, On
SetTitleMatchMode, RegEx
WinGet, ahkWindows, List, ahk_class ^AutoHotkey$,, i)Keyboard Fixes.ahk
Loop % ahkWindows
   WinKill, % "ahk_id " . ahkWindows%A_Index%
return

which killed v1 as well as v2 scripts. For the v2 version, I frankensteined this together:

^#!e::
{
    DetectHiddenWindows(true)
    SetTitleMatchMode("RegEx")

    ahkWindows := WinGetList("ahk_class ^AutoHotkey$",, "i)Keyboard Fixes.ahk")

    for hwnd in ahkWindows
        WinKill("ahk_id " hwnd)
}

But this only kills v2 scripts and leaves the v1 ones running, and I can't figure out why. Especially considering that if I swap WinKill for MsgBox, I get the ID for the v1 scripts as well, so it can't be a problem with the list. I'm super new to v2 and I've been trying to find smth useful online and on the "handbook" on their website, but I'm at my wit's end. Please help me TwT


r/AutoHotkey • • 5d ago

v2 Script Help Keyboard layout stuck after uninstalling AutoHotKey

4 Upvotes

Hi everyone

I've been using an AHK (V2) Script to remap my keyboard to Colemak for the last few months and today I tried reverting back to qwerty because I'm using a qwerty keyboard. I wanted to stop the script but it's not appearing in my taskbar where it usually did. I tried uninstalling AHK altogether and deleting all the files related to it, and I checked in Windows settings but it says it's set to qwerty. I don't really know where else to look, since I assumed that deleting AHK would stop the script. Any help would be appreciated.

Windows 10 Pro build 19045.6466

(this is my first time posting here, sorry if I didn't include any important info)

EDIT: I fixed it by running '/i386/Clear remapping.reg' in the colemak windows package


r/AutoHotkey • • 5d ago

v1 Script Help Help with turning double hyphens into em-dashes

9 Upvotes

I am new to AutoHotkey (just joined a hour ago) and ive been trying to replace two hyphens with a em-dash, Ive tried every code i could find and tried every video explaining the scripts but i cant seem to find one that will work. I dont know if i am running the script wrong or if all the scripts i tried were wrong—one of the scripts i used were :*?:--::— and ive gotten to the point where i know how to open the notes for the script. please help cause all i want is my em-dash ):


r/AutoHotkey • • 6d ago

v1 Script Help my script has a weird stray pixel

0 Upvotes

https://pastebin.com/hB8a6kS3

i made this little color picker in ahk v1 as a local replacement for the rapidtables RGB color picker, and i also added a pick-from-screen feature. everything seems to work fine, but there's one weird visual issue i can't figure out: there's what looks like a single stray pixel on the left edge of the saturation/value box, roughly 15 pixels below the top, and i'm not even sure if it's actually sticking out or replacing the pixel that's supposed to be there. the weird part is that when i move the selection circle over that exact spot, the preview picks up the color of that pixel, while the hex value says "#F0F0F0", which is what that pixel is supposed to be according to the gradient, so the displayed pixel seems to have a different color from the actual color calculated by the picker. i've already tried asking AI to figure it out, but haven't managed to get a proper explanation or fix. the whole thing is also mostly vibe-coded, so that makes it even harder for me to figure out what's actually causing the problem


r/AutoHotkey • • 6d ago

Meta / Discussion I supercharged GeekDude's CodeQuickTester for AHK V1!

2 Upvotes

I didn't know what flair to use because this isn't really an autohotkey script but rather a Windows application I made for Autohotkey.

Here is the screenshot of what it looks like.

https://imgur.com/a/ZUQr5l1

Onto the post...

I write a lot of AHK v1 in CodeQuickTester and got tired of alt-tabbing to the help file and digging through old scripts. So I built a small tray native Windows app in C# that sits beside it. It's only active while CodeQuickTester is the active window and does nothing anywhere else. No AI, no network. Everything it inserts is always valid v1.

Honestly, in the age of AI, one is often tempted to just have it do everything. But there is a still a need for handwritten AHK because often you have to do things like a macro script where you're switching windows and clicking on certain controls within windows or moving windows to where you want them, etc. This tool easily lets you do that with integrated window/click detection by hotkey. No more pulling up windowspy or a million different tools. You literally aim your mouse at the highlighted region and it sends the exact AHK you need into CodeQuickTester! But that's not all, it has all autocomplete and docs lookup and even code snippets/search across all your scripts. It's fucken' awesome for V1. I optimized it for CodeQuickTester because it became my default editor since I always just want to test scripts without saving them first.

The tech stack is: C# / .NET / WPF.

NOTE: I shared it because i'm not sure how many people use V1/GeekDude's CodeQuickTester. I may consider making it open source so everyone who needs it can use it on their own scripts/setup.


Here is an AI summary of its main features.

✍️ Writing

  • Fuzzy autocomplete for commands, functions, directives, keys, your own functions and the current script's variables. wwa finds WinWaitActive. Tab inserts a parameter skeleton you can Tab through.

  • Live syntax hints: after a comma, the current parameter is underlined.

  • Context-aware completions: running programs after ahk_exe, key names inside Send {…}, and Gui sub-commands and options.

  • Closing pairs and auto-ce-aware indenting thatfollows your script's style.

  • Line tools: select line or word, multi-match select, move lines with Alt+↑↓, duplicate, select blockboard.

🎯 Pickers that write the Press a hotkey and click something on screen to get ready-to-run v1 code:

  • Window: WinActivate plus WinWaitActive

  • Click: with the right CoordMode

  • Color: PixelGetColor or a wait-for-color loop

  • Control: ControlClick, ControlSend and friends

  • Geometry: WinMove

  • Key: captures a hotkey combo

  • Chain mode: pick several things in a row and get one script block.

📚 Docs without leaving the editor

  • A Docs card shows the help page for whatever the caret is on and updates as you move. e or by task ("wait for window", "read ini").

  • Browse by category when you don't know what a command is called.

  • One click inserts the syntax or the example.

🧠 Your own scripts as a knowledge base

  • Search every line of every script you've written and insert a line or a whole block.

  • Next-line suggestions: press Enter after a line you've written before and it suggests what usually cthe current window, too.

  • Your own functions show up in autocomplete, with a one-key #Include.

🧩 Recipes with Tab stops

  • Snippets for a script skeleton, a toggle timer, safe clipboard handling, a tray menu, a ListView GUI and more.

  • Stops can be filled straight from a picker.

  • Select some code and save it as a recipe; the Tab stops are guessed for you.

🩺 Nudges A background linter for common v1 mistakes:

  • v2-style syntax pasted

  • Sleep after WinActivate

  • missing return

  • unclosed #If

  • undeclared globals

  • …

Most nudges have a one-key fix (one undo step), and you can add your own regex rules.

🗂️ Docked card workspace

  • Docs, Nudges, Tools, Recipes and My scripts arrange themselves in an automatic grid across the rest of your monitor.

  • Drag cards to dock or f.

  • One hotkey hides everything.

  • When CodeQuickTester is maximized, the cards fold into a strip so no card covers code.


r/AutoHotkey • • 8d ago

v2 Tool / Script Share How I model human typing mistakes in AutoHotkey v2

4 Upvotes

Hey everyone,

I built an AHK v2 script that reads a text file and types it out into VS Code (or any focused editor) like a real human would. Standard paste macros look way too robotic for UI demos and testing, so I wanted something that actually looks like someone sitting at the keyboard.(its not perfect I'd appreciate feedback)

What it does:

  • Reads from a .txt file and types it out using hotkeys (F6 to start, F7 pause, Esc to emergency kill).

  • Uses randomized, per-character delays (letters are faster, punctuation/symbols are slower).

  • Intentionally makes occasional typos, backspaces to correct them, and retypes the segment.

  • Adds "thinking" pauses and hesitates around code blocks/braces.

  • Waits for VS Code to actually be in focus before it starts.

Everything is configured in a single SimConfig class at the top of the script..(You can watch the short gif on the github page b4 installing to see if youd be interested)

GitHub Repo: https://github.com/Mwakio-empire/ahk-typing-simulator

Would love some feedback on the timing engine or if anyone has ideas for making the typo-correction logic feel even more natural.


r/AutoHotkey • • 8d ago

v2 Script Help Help with creating one key to cycle through multiple shortcuts? AHK v2

2 Upvotes

Hey guys,

I would have posted this in the AHK forum but I haven't been able to get an activation email for my account yet. I have average skills in AHK to make basic QoL shortcuts. I use OBS Studio which allows me to have overlays over gameplay footage (known as scenes), and each can be swapped via in-app shortcuts. Unfortunately there is no cycle feature baked into the software to save on remembering and wasting shortcut space on my keyboard. An example of an OBS short would be ctrl+shift+alt+q = Scene #1.

So I thought why can't I make a super shortcut that can work with one key press and each input is a different shortcut from OBS ( then it would cycle back to the first shortcut). I interpret this as the following (not actual code but follows examples of what I've seen online):

^!m::

{

key++

(list of shortcuts from OBS i.e. ^+!{e}, ^+!{f})

if key press = 1

{

Send "^+!{e}"

}

else if key press = 2

{

Send "^+!{f}"

}

}

I can visualize this but this follows from what I've seen as AHK V1 syntax so it doesn't work I've seen v2 examples using static values but I don't understand. If anyone can point me in the right direction I'd greatly appreciate it!


r/AutoHotkey • • 9d ago

v2 Script Help How to detect whether task view (MultitaskingViewFrame) is active before triggering a custom shortcut?

3 Upvotes

I'm a relatively new user of AutoHotKeys, and I’m trying to solve the same problem described here (link for reference, as it gives a clearer starting point). However, the solution in the link didn't work, as I'm using AHK v2. Script for AHK v1:

F1::
IfWinActive, ahk_class MultitaskingViewFrame
    MsgBox, windows is in task view mod ; [sic]
return

Edit: Seems like ahk_class can also be: "Windows.UI.Core.CoreWindow". Can anyone confirm/unconfirm?

I have “show desktop” (a built-in function in Windows 11) assigned to an advanced gesture for when I swipe down on the touchpad. When I swipe up, task view opens. A downward swipe while task view is active closes task view and restores the last window I had open. I'd like to keep this behavior.

The challenge is that I have a widget on my desktop that also minimizes when “show desktop” or Win+D is triggered, so I want to set Win+M (or anything else that replicates the same action) as a custom shortcut under advanced gestures because it shows the desktop while leaving the widget on the desktop.

The problem is that when I set Win+M as a custom shortcut, it doesn’t take into account that task view is active. Because of this, I want to create a script that checks whether task view is active and only triggers Win+M (or other similar shortcuts) when it isn't.

TL;DR:
I'd like to create a script that implements the following two-step behavior while task view is active (when using advanced gesture on touchpad):

  • 1st downward swipe closes task view.

  • 2nd downward swipe shows the desktop without minimizing the widget on the desktop.

I have two questions:

  1. Would a script that detects when task view is active solve this issue?

  2. How can I set up a script that makes the advanced gesture preserve the built-in “show desktop” behavior while sending Win+M (or an equivalent), so the desktop widget isn’t minimized?


r/AutoHotkey • • 12d ago

v2 Script Help Global variable not working across scripts

3 Upvotes

I'm new to AHK, but not scripting. From everything I've found in my searches, global variables should work across multiple scripts. I have several variables that will change frequently that I need to reference from multiple scripts. Below is a snippet of my code. The error is popping from script2.ahk and it's claiming BaseSpeed has never been assigned a value. Please help, thanks!

;script1.ahk runs first with this
#Include functions.ahk
global AdjSpeed := .00 ; this is what changes
global BaseSpeed := Round(28, 2) ; this never changes
RunWait "script2.ahk"

;script2.ahk contains this
#Include functions.ahk
global AdjSpeed
global BaseSpeed
CheckAdjSpeed

;script with all my functions has this:
CheckAdjSpeed()
{
global BaseSpeed
global AdjSpeed
If (BaseSpeed > 28) {
AdjSpeed := Round(((1 + (BaseSpeed - 28)) / 28), 2)
}
If (BaseSpeed == 28) {
AdjSpeed := .00
}
If (BaseSpeed < 28) {
AdjSpeed := Round(((1 - (BaseSpeed - 28)) / 28), 2)
}
}


r/AutoHotkey • • 12d ago

v2 Script Help Can someone please clean up this script?

0 Upvotes

Someone from here made this script for me a few months ago. We got to what I wanted eventually after some editing, but that left some bloat behind, and that bloat has finally caught up to me bc I've been experiencing some bugs now due to this script. What I want to retain is the ability for SHIFT to work like a sticky key. That's it. I don't need WIN, ALT, or CTRL to act like sticky keys. And I don't need any GUI. Please can someone clean that stuff from this whilst preserving the SHIFT sticky key function?

Edit- or an easy way to toggle if I want to include CTRL or ALT would be even better

Requires AutoHotkey v2.0

StickyKeys('Shift') StickyKeys.ShowOverlay := false

StickyKeys(mods*) { static trackedKeys := Map(), ih, dh, overlay, otherKeyPressed := 0, _ := Init()

if ih.InProgress
    ih.Stop()
if dh.InProgress
    dh.Stop()
for k in trackedKeys {
    Hotkey '~*' k, 'Off'
    Hotkey '~*' k ' Up', 'Off'
}
trackedKeys.Clear()

ih.KeyOpt('{All}', 'NS'), dh.KeyOpt('{All}', 'N')
for k in mods {
    keyName := GetKeyName(k)
    trackedKeys[keyName] := {isSticky: false, isDown: false}
    if keyName ~= '^(Control|Shift|Alt)$' {
        keys := '{L' keyName '}{R' keyName '}'
        ih.KeyOpt(keys, '-NS')
        dh.KeyOpt(keys, '-N')
    } else  {
        ih.KeyOpt('{' keyName '}', '-NS')
        dh.KeyOpt('{' keyName '}', '-N')
    }
    Hotkey '~*' keyName, OnHotkeyDown.Bind(keyName), 'On'
    Hotkey '~*' keyName ' Up', OnHotkeyUp.Bind(keyName), 'On'
}

Init() {
    if !StickyKeys.HasProp('ShowOverlay')
        StickyKeys.ShowOverlay := true
    ih := InputHook('L0 I')
    ih.OnKeyDown := OnKeyDown
    dh := InputHook('L0 V I')
    dh.OnKeyDown := (dh, *) => (dh.Stop(), otherKeyPressed := 1)
    overlay := Gui('+ToolWindow -Caption +AlwaysOnTop +E0x20 -DPIScale')
    overlay.BackColor := '0D1117'
    overlay.SetFont('s12 Bold cC9D1D9', 'Consolas')
    overlay.AddText('vText')
    WinSetTransparent(255, overlay)
    return 1
}

OnHotkeyDown(keyName, *) {
    if keyName ~= 'LWin|RWin'
        Send '{Blind}{VKE8}'
    trackedKeys[keyName].isDown := true
    downCount := 0
    for k, v in trackedKeys 
        downCount += v.isDown
    if downCount = 1 {
        otherKeyPressed := 0
        dh.Start()
    }
}

OnHotkeyUp(keyName, *) {
    dh.Stop()
    trackedKeys[keyName].isDown := false
    if !otherKeyPressed
        toggleStickyKey(keyName)
}

ToggleStickyKey(keyName) {
    trackedKeys[keyname].isSticky ^= 1
    stickyCount := 0
    for k, v in trackedKeys 
        stickyCount += v.isSticky
    if stickyCount > 0 {
        ih.Start()
        if StickyKeys.ShowOverlay
            UpdateGui()
    } else {
        ih.Stop()
        overlay.Hide()
    }
}

OnKeyDown(ih, vk, sc) {
    ih.Stop()
    overlay.Hide()
    keyName := GetKeyName(Format('VK{:X}SC{:X}', vk, sc))
    pressKeys := '{' keyName '}'
    for k, v in trackedKeys {
        if v.isSticky {
            v.isSticky := false
            pressKeys := '{' k ' down}' pressKeys '{' k ' up}'
        }
    }
    Send '{Blind}' pressKeys
}

UpdateGui() {
    text := ''
    for k, v in trackedKeys {
        if v.isSticky 
            text .= k ' + '
    }
    text := StrReplace(SubStr(text, 1, -3), 'Control', 'Ctrl')
    overlay['Text'].Value := text
    size := TextWidth(overlay['Text'], text)
    overlay['Text'].Move(,, size.Width, size.Height)
    
    xPos := A_ScreenWidth - (size.Width + overlay.MarginX*2 + 50)
    yPos := A_ScreenHeight - (size.Height + overlay.MarginY*2 + 150)
    overlay.Show('NA AutoSize x' xPos ' y' yPos)
}

TextWidth(ctrl, text) {
    hdc := DllCall('GetDC', 'ptr', ctrl.Hwnd, 'ptr')
    hFont := SendMessage(0x31, 0, 0, ctrl.Hwnd) ; WM_GETFONT
    oldFont := DllCall('SelectObject', 'ptr', hdc, 'ptr', hFont, 'ptr')
    size := Buffer(8)
    DllCall('GetTextExtentPoint32', 'ptr', hdc, 'str', text, 'int', StrLen(text), 'ptr', size)
    width := NumGet(size, 0, 'int')
    height := NumGet(size, 4, 'int')
    DllCall('SelectObject', 'ptr', hdc, 'ptr', oldFont)
    DllCall('ReleaseDC', 'ptr', ctrl.Hwnd, 'ptr', hdc)
    return {Width:width, Height:height}
}

}


r/AutoHotkey • • 12d ago

v2 Script Help AHK V2 - looping sending keystrokes to specific application window without pulling focus - beginner (non-coder)

0 Upvotes

Hey lovelies 🩷

Sorry to trouble everybody here.

For context, whilst we're¹ AuDHD² and used to be moderately capable of learning human languages, we've never successfully been able to self-teach ourselves any coding or scripting languages over many decades: not even BASIC 😑🤦‍♀️ We often don't grasp core concepts that others take for granted, but then can learn and understand things deeply if we can get over the initial learning struggle.

We tend to learn best from examples that match what we're trying to do, as they give us context for how something works / is used, rather than generic examples or raw documentation by itself. Sadly, whilst we've managed to make some progress, we've not been able to successfully work out how to do 😔 It's why we've admitted defeat and are finally asking for help.

At a high-level, what we want to do is loop sending a keystroke (down, up) to a specific application window only, irrespective of whether the application window is active or inactive, without pulling focus from or otherwise interrupting other tasks, with a random time range before looping, and with an on/off toggle.

If we understand it correctly, ControlSend is the way to send the key presses to a specific window. We've learnt how to use the AutoHotkey Window Spy to get the ControlID, but we've only managed to get it working when using an application's ClassNN and its title: it doesn't work if we use any ahk_ criteria. Additionally, our attempts to-date have only worked if the application window is focussed, which defeats the purpose.

Just to restate and summarise, in case any of the above is unclear, we'd really appreciate some kind ELI5 assistance, explanation, and best practice recommendations for combining:

  • An on/off toggle (using an F key) for a loop.

  • A loop.

    • Pressing a key (not holding down) in a specified application window only, irrespective of focus.

    • Waiting/sleeping for a random amount of time between a range before looping.

Thank you in advance for empathy and patience 🫶


¹ Plural (median, blurian system), so we typically write with we/us/our instead of I/me/my etc. It's not relevant to the query, but experience has taught us that if we don't explain it, one or more peeps will ask.
² Autistic and ADHD, which is common among many proficient coders.


Edit: Several of the disrespective responses thus far, seemingly from young teens (or adults with the maturity of them), are honestly one of the main reasons why we don't ask for help with things. Also, if you don't know how to help, that's okay, but please don't respond suggesting the use of agentic LLMs etc. No vibe coders, please.

Edit 2: Kinda worked it out, but it causes some odd issues, like preventing the shift key (and other modifier keys) from working. We combined ControlFocus with ControlSend as below.

ControlFocus "ClassNN", "ahk_exe ProgramName.exe"
ControlSend "{Space}", "ClassNN", "ahk_exe ProgramName.exe"

It may work far better with additional changes, but right now it will at least send space bar to the designated window only. Not sure why it's preventing shift/ctrl/alt + keys right now outside of that window, but it's better than before.


r/AutoHotkey • • 13d ago

General Question Could you have the current #HotIf always on-screen when you code?

3 Upvotes

Had a question that I'm sure might be interesting for some other people. In short, I personally code my ahk scripts in VisualStudio using the AHK++ pack. I think it's a very decent way to code ahk scripts, and I like that when you are inside of a hotkey, hostring or even function, the name is still visually there even if it passes the top of the screen; it's very useful, but honestly... I think I would need that more for #HotIfs. Maybe others use this less, but I use it a lot, and there are countless times where I scrolled up to check what was the last #HotIf of my script, it's even more important than knowing the hotkey/hotstring/function, and it's also something you're way more likely to forget or not know! (surprised this is not by default) So can you make the last #HotIf always be on screen in a similar way, either by using something in AHK++ I missed, or maybe in another way? Thanks in advance.


r/AutoHotkey • • 13d ago

v2 Tool / Script Share Open link in Split View Edge Browser

1 Upvotes

r/AutoHotkey • • 13d ago

v2 Script Help Vrto3d failed to activate mouse button as right click.

1 Upvotes

I used uevr and vrto3d to play 3d sbs game on my glass free 3d.

I manage to bind all my keyboard button even alt button. toggle or hold or switch.

However i failed to bind right click.

I have search google for hour now.I tried VK_RBUTTON and 2(not numpad2) all doesnt work.

I also tried auto hotkey and bind right click to numpad4. It does work if im not focus on game app.But when i return to game it just a normal right click again.

This method also disable right click completely and press numpad4 instead

I then channg the autohotkey script to

~RButton::

{

Send("{Numpad4}")

}

this time both rightclick and numpad4 fired simultanously but dont trigger vrto3d hotkeys at all


r/AutoHotkey • • 14d ago

v1 Script Help How do I prevent key up events from interrupting a remapped key?

4 Upvotes

I'm trying to make a script that remaps WASD to the arrow keys while keeping the arrow keys functional for better reaction speeds in Deltarune.

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.

#Persistent

~[::
    Toggle := 0
return

~]::
    Toggle := 1
return

#If Toggle
~w::Send Up
~a::Send Left
~s::Send Down
~d::Send Right

but if I hold down both the directional key and the remapped key, then release only one of either, the input stops. I've tried intercepting the key up events with more conditionals but it didn't do anything.


r/AutoHotkey • • 14d ago

Solved! How to disable a hotkey combination?

2 Upvotes

I need to disable this hotkey, but it's saying it doesn't exist.

~a & WheelUp:: Hotkey, a & WheelUp, Off

Edit: fixed it somehow


r/AutoHotkey • • 15d ago

v1 Script Help Need help with timer and loops

5 Upvotes

I want a timer to always run when a variable is true while keeping the loop going.

Toggle := false
Toggle2 := false

Numpad0::
    Toggle := !Toggle
return

F10::
Toggle2 := !Toggle2
return

macro:
Send, {b down}
sleep, 30
Send, {b up}
return

macro2:
Send, {z down}
sleep, 30
Send, {z up}

return

Home::
loop
{
send, {LButton}
sleep, 30
If Toggle{
        SetTimer, macro, 3000
        }
}
return

XButton1::
send, {9}
sleep, 20
send, {RButton}
sleep, 20
send {1}
return

XButton2::
pause
return

r/AutoHotkey • • 15d ago

v2 Script Help Reverse Mouse Direction in the X-axis only

3 Upvotes

Hi, i want a script that just reverse the mouse direction in the x-direction only, leaving the y-axis as it is. i tried asking chatgpt but none of the solutions worked so far. can someone post a script here please?

i want to avoid my mouse from jittering when the reverse is activated. i also want a toggle button to switch between reversing and not reversing


r/AutoHotkey • • 17d ago

v2 Tool / Script Share [Open Source] AHK v2 on macOS; Running AutoHotkey v2 scripts natively on Apple Silicon & Intel

1 Upvotes

Hi everyone,

I wanted to share an open-source project I've been working on to run AutoHotkey v2 scripts natively on macOS: ahk-v2-macos.

How it works: It is a specialized fork of the Keysharp engine targeting .NET 10, cross-compiling AHK v2 source code directly into in-memory Roslyn assemblies and running on macOS (both ARM64 and x64) using native macOS integrations (Accessibility API, Quartz event taps, IOKit).

What's implemented:

Limitations:

Check out the repo, build instructions, and examples: https://github.com/X6M-Work/ahk-v2-macos
Feedback, issue reports, and testing on various macOS configurations are very welcome!


r/AutoHotkey • • 18d ago

v2 Tool / Script Share [v2] Middle-click the empty tab strip in Brave to open a new tab

0 Upvotes

Missed Firefox's "middle-click empty tab strip = new tab" in Brave, so I made a small AHK v2 script for it. Tabs still close and links still open normally on middle-click.

Uses plain COM UI Automation (no library), no timers, and does nothing unless the click is clearly on the empty tab strip. Windows + horizontal tabs only. Has a debug mode and a tray toggle for run-at-startup.

Repo: https://github.com/barantunca/brave-middle-click-newtab

Written with Claude's help. Feedback welcome!