Search code examples
imageautohotkeygetstate

AHK keystroke to show image only while it's pressed


Good day,

I'm trying to create a script for AutoHotKey (AHK) which will show an image when having pressed Caps lock+A simultaneously and will hide after releasing the keys.

My current solution shows the image, but it only will go away after pressing Esc:

#Persistent
SetCapsLockState, AlwaysOff
#If, GetKeyState("CapsLock", "P")

a::
Gui +LastFound +AlwaysOnTop +ToolWindow -Theme -Border -Caption
Gui, Color, FFFFFF
WinSet, Transcolor, FFFFFF
Gui, Add, Picture, x0 y0 w1827 h635, C:\Users\User\Image.png
Gui, Show, xCenter y360 w1827 h635
Gui, Margin, 0,0
return
GuiEscape: 
Gui, Cancel
Gui, Hide
return

I've experimented with setting a state or a UP:: but nothing worked. Looking forward to some help.


Solution

  • KeyWait seems to be what you are looking for.

    From the docs:

    KeyWait

    Waits for a key or mouse/joystick button to be released or pressed down.

    KeyWait, KeyName , Options
    

    So in order to delay the script until the a key to be released, you would implement it as so:

    KeyWait a
    

    Final Code:

    SetCapsLockState, AlwaysOff
    #If, GetKeyState("CapsLock", "P")
    
    a::
    Gui +LastFound +AlwaysOnTop +ToolWindow -Theme -Border -Caption
    Gui, Color, FFFFFF
    WinSet, Transcolor, FFFFFF
    Gui, Add, Picture, x0 y0 w1827 h635, C:\Users\User\Image.png
    Gui, Show, xCenter y360 w1827 h635
    Gui, Margin, 0,0
    KeyWait a
    gosub GuiEscape
    return
    
    GuiEscape: 
    Gui, Cancel
    Gui, Hide
    return