You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

释放LMB时如何立即终止循环执行的键鼠动作序列

问题原因

原有脚本的Sleep()为阻塞函数,执行等待期间不会检测鼠标左键状态,必须等待时长走完才会判断循环终止条件,因此无法实现松开即停的效果。

解决方案

将所有长时长的Sleep拆分为小粒度的轮询等待,每次短等待后都检查鼠标是否仍被按住,一旦检测到松开立刻终止所有流程,同时额外增加按键释放逻辑,避免中途终止时F13处于按下状态导致卡键。

完整代码如下:

EnablePrimaryMouseButtonEvents(true);

-- 封装可中断的等待函数,参数为需要等待的总毫秒数,返回false表示中途鼠标松开
function SleepInterruptible(wait_ms)
    local start_time = GetRunningTime()
    while GetRunningTime() - start_time < wait_ms do
        if not IsMouseButtonPressed(1) then
            return false
        end
        Sleep(10) -- 单次等待粒度越小,中断响应越灵敏,可根据需要调整
    end
    return true
end

function OnEvent(event, arg)
    if event == "MOUSE_BUTTON_PRESSED" and arg == 1 then
        while IsMouseButtonPressed(1) do
            -- 执行动作1
            PressAndReleaseKey("f13")
            if not SleepInterruptible(200) then break end
            
            -- 执行动作2
            PressAndReleaseKey("f13")
            if not SleepInterruptible(200) then break end
            
            -- 执行动作3
            PressKey("f13")
            if not SleepInterruptible(400) then break end
            
            -- 执行动作4
            ReleaseKey("f13")
            if not SleepInterruptible(200) then break end
        end
        -- 终止时强制释放F13,避免卡键
        ReleaseKey("f13")
    end
end

效果验证

  • 按下左键300ms松开:动作1执行完成后等待200ms,动作2执行完成,后续等待过程中检测到左键松开,直接终止,符合预期。
  • 按下左键1800ms松开:动作序列单轮总时长为200+200+400+200=1000ms,1800ms时刚好完成两轮的动作1、动作2(耗时2*(200+200)=800ms),执行完第三轮的动作3后等待400ms过程中到达1800ms检测到松开,终止执行,符合预期。

内容的提问来源于stack exchange,提问作者Kel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 17:15:03