Search code examples
loopsif-statementautohotkeywait

If Then Loop in AutoHotkey to switch between desktops


Let's say ^RButton switches to my right desktop and ^LButton to my left desktop. The probelm then is, that whenever I switch to the right desktop a dropdown menu will open, because I'm using the right mouse button as a hotkey. To counteract this problem, I can add sleep 500 and then send, {Escape} to exit the dropdown menu. So far so good. However, if I now want to switch from desktop 1 to desktop 5 I cannot just do 5 ^RButtons in a row but instead have to wait half a second between each click. That's annoying! I'd be grateful for any ideas on how to avoid having to wait 500 milisecond between each click? My idea was to work with an if statement. Though I have no idea how to program one... It would look like this:

If ^RButton = True, go to right desktop, 
if after 500 miliseconds there were no further ^RButton clicks, 
then send, {Escape}. 
If there were ^RButton clicks, 
go to the right desktop and wait 500 miliseconds for another ^RButton click,
then send, {Escape}.

Would be awesome if someone could transform my text code into AutoHotkey code :D


Solution

  • Try this

    ^RButton:: SendEvent {LWin down}{LCtrl down}{Right down}{LWin up}{LCtrl up}{Right up} ; switch to next virtual desktop
    ^LButton:: SendEvent {LWin down}{LCtrl down}{Left down}{LWin up}{LCtrl up}{Left up}   ; switch to previous virtual desktop
    

    EDIT:

    As a stand-alone script works for me.

    Try also

    ^RButton:: 
        Send {LWin down}{Ctrl down}{Right}{LWin up}{Ctrl up}    ; switch to next virtual desktop
        SetTimer, CloseContextMenu, -50
    return
    
    ^LButton:: Send {LWin down}{Ctrl down}{Left}{LWin up}{Ctrl up}  ; switch to previous virtual desktop
    
    CloseContextMenu:
        KeyWait, Ctrl, L
        ; Sleep, 300
        Send {Esc}
    return
    

    https://www.autohotkey.com/docs/commands/SetTimer.htm