问题
I'm working on a Script that constrains the movement of the cursor to the horizontal direction only. I would like to activate and deactivate it using the same hotkey.
I'm using this code:
#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.
SendMode Input ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.
!s:: ; Hotkey will toggle status
Confine := !Confine
MouseGetPos, , SetY
ClipCursor( Confine, 0, SetY, A_ScreenWidth, SetY+1 )
return
!a::
Pause
Suspend
return
ClipCursor( Confine=True, x1=0 , y1=0, x2=1, y2=1 ) {
VarSetCapacity(R,16,0), NumPut(x1,&R+0),NumPut(y1,&R+4),NumPut(x2,&R+8),NumPut(y2,&R+12)
Return Confine ? DllCall( "ClipCursor", UInt,&R ) : DllCall( "ClipCursor" )
}
The code works, but when pressing ctrl + a the script doesn't stop.
Am I using incorrectly the pause and suspend commands? How could this task be done?
回答1:
That's a neat function! I can definitely see some use for that. Anyway, you are correctly using Pause
and Suspend
, but it appears that !s
was meant to toggle it on and off (so, no need for !a
).
For some reason, though, it won't toggle off. In my testing, the function was correctly seeing the value of "Confine", but wasn't returning the false-portion of the ternary operation. It appears to be coded properly, but I suspect there may be an issue (possible bug?) with Return
evaluating "Confine" properly.
Here are a few solutions:
- By testing explicitly whether "Confine" is equal to
True
works.
Return ( Confine = True ) ? DllCall( "ClipCursor" , UInt , &R ) : DllCall( "ClipCursor" )
- What I would do, however, is take the ternary operation out of the function and move it to your hotkey to avoid needless operations and assignments if it evaluates to false. To me, this is a bit cleaner.
!s:: ; Hotkey will toggle status
Confine := !Confine
MouseGetPos ,, SetY
Confine ? ClipCursor( 0 , SetY , A_ScreenWidth , SetY+1 ) : DllCall( "ClipCursor" )
Return
ClipCursor( x1=0 , y1=0 , x2=1 , y2=1 ) {
VarSetCapacity( R , 16 , 0 )
NumPut( x1 , &R + 0 )
NumPut( y1 , &R +4 )
NumPut( x2 , &R +8 )
NumPut( y2 , &R +12 )
Return DllCall( "ClipCursor" , UInt , &R )
}
- If you just want to use
!a
to turn it off, you could just do this,!a::DllCall( "ClipCursor" )
. If you decide to go this route, I would recommend removing all of the toggle portions of code from the hotkey and function.
来源:https://stackoverflow.com/questions/56426124/how-to-toggle-an-ahk-script-on-off-with-a-key