如何用一个键切换 AHK 脚本 on/off?

How to toggle an AHK script on/off with a key?

我正在编写一个将光标移动限制在水平方向上的脚本。我想使用相同的热键激活和停用它。

我正在使用此代码:

#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" )
}

代码有效,但当按下 ctrl + a 时,脚本不会停止。

我是否错误地使用了暂停和挂起命令?这个任务怎么完成?

这是一个很好的功能!我绝对可以看到它的一些用途。无论如何,您正确地使用了 PauseSuspend,但似乎 !s 是为了打开和关闭它(因此,不需要 !a)。

但出于某种原因,它不会关闭。在我的测试中,该函数正确地看到了 "Confine" 的值,但没有返回三元运算的 false-portion。它似乎编码正确,但我怀疑 Return 正确评估 "Confine" 可能存在问题(可能是错误?)。

这里有几个解决办法:

  • 通过显式测试 "Confine" 是否等于 True 有效。
Return ( Confine = True ) ? DllCall( "ClipCursor" , UInt , &R ) : DllCall( "ClipCursor" )
  • 然而,我会做的是将三元运算从函数中取出并将其移至您的热键,以避免在计算结果为 false 时进行不必要的操作和赋值。对我来说,这有点干净。
!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 )
}
  • 如果您只想使用 !a 将其关闭,您可以这样做,!a::DllCall( "ClipCursor" )。如果您决定走这条路,我建议您从热键和功能中删除代码的所有切换部分。