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

如何用VBA实现非侵入式防止电脑屏幕锁屏?

更温和的VBA防电脑锁屏实现方案

原代码通过模拟鼠标点击防止锁屏,会干扰用户正常操作,侵入性较强。以下提供两种更温和的VBA实现方案,均不干扰用户交互,适配自动化场景:

方案一:使用SetThreadExecutionState API(推荐)

此方案直接通过Windows系统API声明程序需要保持系统活跃,不会触发锁屏或休眠,完全无用户交互干扰,是最可靠且温和的方式。

' 声明Windows API函数,用于设置线程执行状态
Public Declare Function SetThreadExecutionState Lib "kernel32.dll" (ByVal esFlags As Long) As Long

' 常量定义,指定保持系统活跃的参数
Public Const ES_CONTINUOUS = &H80000000
Public Const ES_SYSTEM_REQUIRED = &H1
Public Const ES_DISPLAY_REQUIRED = &H2

Dim keepAliveTimer As Date

Sub StartKeepAlive()
    ' 通知系统保持活跃,阻止锁屏和休眠
    SetThreadExecutionState ES_CONTINUOUS Or ES_SYSTEM_REQUIRED Or ES_DISPLAY_REQUIRED
    
    ' 设置3分钟后再次调用,维持活跃状态(可根据需求调整时间)
    keepAliveTimer = Now + TimeValue("00:03:00")
    Application.OnTime keepAliveTimer, "StartKeepAlive"
End Sub

Sub StopKeepAlive()
    ' 取消定时任务
    On Error Resume Next
    Application.OnTime keepAliveTimer, "StartKeepAlive", , False
    On Error GoTo 0
    
    ' 恢复系统默认的休眠/锁屏设置
    SetThreadExecutionState ES_CONTINUOUS
End Sub

使用说明

  • 运行StartKeepAlive即可启动防锁屏功能
  • 运行StopKeepAlive可停止功能,恢复系统默认设置

方案二:模拟微小鼠标移动(替代方案)

若因环境限制无法使用系统级API,可采用此方案:仅将鼠标移动1像素后立即移回原位置,用户几乎无法察觉,比原代码的点击操作温和得多。

' 声明获取和设置鼠标位置的API
Public Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Public Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long

' 定义存储鼠标位置的结构体
Type POINTAPI
    x As Long
    y As Long
End Type

Dim moveTimer As Date

Sub StartMouseMoveKeepAlive()
    Dim currentPos As POINTAPI
    
    ' 获取当前鼠标位置
    GetCursorPos currentPos
    
    ' 微小位移:移动1像素后立即返回原位置
    SetCursorPos currentPos.x + 1, currentPos.y
    SetCursorPos currentPos.x, currentPos.y
    
    ' 设置3分钟后重复执行(可调整时间间隔)
    moveTimer = Now + TimeValue("00:03:00")
    Application.OnTime moveTimer, "StartMouseMoveKeepAlive"
End Sub

Sub StopMouseMoveKeepAlive()
    ' 取消定时任务
    On Error Resume Next
    Application.OnTime moveTimer, "StartMouseMoveKeepAlive", , False
    On Error GoTo 0
End Sub

使用说明

  • 运行StartMouseMoveKeepAlive启动功能
  • 运行StopMouseMoveKeepAlive停止功能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 11:33:50