Handling single, double, triple, quadruple... infinite key presses_v2

Post your working scripts, libraries and tools.
User avatar
rommmcek
Posts: 1478
Joined: 15 Aug 2014, 15:18

Handling single, double, triple, quadruple... infinite key presses_v2

Post by rommmcek » 28 Feb 2024, 15:57

I love HandleMultiplePresses. This is my v2 version. Not one to one translation, but should have the same functionality.

Code: Select all

#Requires AutoHotkey v2+
#SingleInstance Force

F1 Up:: HandleMultiplePresses(["F3", "SayGo", "SayFight", "SayWin"])
^F1::   HandleMultiplePresses(["SayGo", "SayFight", "SayWin"])
F2::    HandleMultiplePresses(["SayWin", "SayGo"])
$F3::   HandleMultiplePresses(["F3", "SayFight", "SayWin", "",, "SayGo"])

SayGo() {
  MsgBox A_ThisHotkey " says Go!"
}

SayFight() {
  MsgBox A_ThisHotkey " says Fight!"
}

SayWin() {
  MsgBox A_ThisHotkey " says Win!"
}

F3() {
    Send "{F3}"
}

HandleMultiplePresses(mp) {
    While (A_Index>1? "": (RegExMatch(A_ThisHotkey, "i)(?:[~#!<>\*\+\^\$]*([^ ]+)( UP)?)$", &Key), count:= key.2? 1: 0), KeyWait(Key.1, "D T.3"))
         count++, KeyWait(Key.1)
    mp.Has(count) && mp[count]? %mp[count]%(): ""
}

^Esc:: ExitApp

User avatar
GollyJer
Posts: 70
Joined: 19 Sep 2015, 19:33
Contact:

Re: Handling single, double, triple, quadruple... infinite key presses_v2

Post by GollyJer » 06 Apr 2024, 22:23

Thanks for posting this update @rommmcek! I'm finally getting around to updating my scripts to v2.

I like how your version allows for hotkeys that include `Up`.
However, your code is super succinct, and therefore, too complex for my feeble brain. 😀
Here's a version, more readable for me, and incorporates some improvements from @temoridao in the v1 thread.

Code: Select all

HandleMultiplePresses(pressHandlers, secondsToWaitAfterLastPress := 0.3) {
  RegExMatch(A_ThisHotkey, "i)(?:[~#!<>\*\+\^\$]*([^ ]+)( UP)?)$", &matchGroups)
  strippedHotkey := matchGroups[1]
  isKeyUp := matchGroups[2]
  pressCount := isKeyUp ? 1 : 0

  While (KeyWait(strippedHotkey, "DT" secondsToWaitAfterLastPress)) {
    pressCount += 1
    KeyWait(strippedHotkey)
  }

  if (!pressHandlers.Has(pressCount)) {
    return ""
  }

  f := pressHandlers[pressCount]
  if (!IsObject(f)) { ; If not Func or BoundFunc object (i.e. just a string).
    f := %f%
  }

  return f ? f.Call() : ""
}


F1:: HandleMultiplePresses([() => MsgBox(A_ThisHotkey " says Go!"), () => Say("Fight!"), "SayWin"])

Say(thingToSay) {
  MsgBox(A_ThisHotkey " says " thingToSay)
}

SayWin() {
  MsgBox(A_ThisHotkey " says Win!")
}

Post Reply

Return to “Scripts and Functions (v2)”