2
votes

So I'm trying to create a script that'll scroll left and right while holding the middle mouse button. However, the scroll left and right scrolls regardless if the middle mouse button is held down. It always executes. I need help trying to figure this out.

(I do notice at line 21 there is a bit too much space, ignore that) Code:

; Hold the scroll wheel and scroll to scroll horizontally
; Scroll up = left, scroll down = right

#NoEnv
;#InstallMouseHook

#HotkeyInterval 1
#MaxHotkeysPerInterval 1000000 ; Prevents the popup when scrolling too fast

GetKeyState, ScrollState, MButton

if(ScrollState = U)
{
        ;return
}
else if(ScrollState = D)
{
        WheelUp::Send {WheelLeft}
        return

        WheelDown::     Send {WheelRight}
        return
}
return
2

2 Answers

3
votes

This method keeps all normal middle click functionality but simply toggles a variable state when pressed. This variable is then checked whenever Wheelup or Wheeldown is used.

~Mbutton::
    state := 1
Return

~Mbutton up::
    state := 0
Return

WheelUp:: Send % (state) ? "{WheelLeft}" : "{WheelUp}"
WheelDown:: Send % (state) ? "{WheelRight}" : "{WheelDown}"

/*
The ternary operators are short for:
If state = 1
    Send {WheelLeft}
else
    Send {WheelUp}
*/
1
votes

Hotkeys, as defined by the double-colon, are not controlled by regular if statements. To make hotkeys context-sensitive, you need to use #If (or #IfWinActive or #IfWinExist). An example from the documentation (Context-sensitive Hotkeys section):

#If MouseIsOver("ahk_class Shell_TrayWnd")
WheelUp::Send {Volume_Up}     ; Wheel over taskbar: increase/decrease volume.
WheelDown::Send {Volume_Down} ; 

You can also put regular if logic inside the hotkey (here's an example from the Hotkey Tips and Remarks section):

Joy2::
if not GetKeyState("Control")  ; Neither the left nor right Control key is down.
    return  ; i.e. Do nothing.
MsgBox You pressed the first joystick's second button while holding down the Control key.
return

Context-sensitivity via #If is intended for controlling which application your hotkey is active in. Regular if logic inside the hotkey definition is for arbitrary conditions. What you are trying to do fits the latter.

In many cases, it is useful to do both. If you want your left/right behavior only in the browser but not in Microsoft Word, for example, you would use #If to limit the hotkey activity to the browser, and then if GetKeyState(...) inside the hotkey definition to check whether the scroll button is pressed.