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

如何通过Word VBA临时冻结键鼠输入,避免用户操作干扰程序运行

核心解决方案

方案1:Word VBA 原生调用系统API实现输入屏蔽(最适配你的场景)

不需要复杂的钩子实现,直接调用Windows内置的BlockInputAPI即可实现全局输入屏蔽,符合你的需求:

' 放在模块顶部的API声明,兼容32/64位Office
#If VBA7 Then
    Private Declare PtrSafe Function BlockInput Lib "user32.dll" (ByVal fBlockIt As Long) As Long
    Private Declare PtrSafe Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)
#Else
    Private Declare Function BlockInput Lib "user32.dll" (ByVal fBlockIt As Long) As Long
    Private Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)
#End If

Sub 你的主程序()
    On Error GoTo ErrHandler ' 一定要加错误处理,避免异常导致输入永久锁定
    ' 1. 先屏蔽用户输入
    BlockInput True
    
    ' 这里放你原来的业务代码:书签跳转、操作CodeTwo QR的代码
    ' --- 你的原有代码开始 ---
    ' 示例:模拟你原来的操作耗时
    Sleep 6000
    ' --- 你的原有代码结束 ---
    
    ' 2. 操作完成后立刻解除输入屏蔽
    BlockInput False
    MsgBox "操作完成,输入已恢复"
    Exit Sub
ErrHandler:
    ' 发生错误时强制解除输入屏蔽
    BlockInput False
    MsgBox "程序出错:" & Err.Description & vbCrLf & "输入已恢复"
End Sub

注意:需要以管理员身份运行Word,否则BlockInput不会生效,这是Windows系统安全限制

方案2:修复后的PowerShell方案

你之前的PowerShell代码失效是因为VBA调用时默认不会等待脚本执行完成就会关闭进程,修复后使用方式如下:

修复后的PowerShell脚本(保存为BlockInput.ps1)

param([int]$Seconds = 10,[switch]$Elevated)
function Test-Admin {
    $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
    $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
if ((Test-Admin) -eq $false)  {
    if ($elevated) {
        exit
    } else {
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -windowstyle hidden -file "{0}" -elevated -seconds {1}' -f ($myinvocation.MyCommand.Definition),$Seconds)
    }
    exit
}

$code = @"
[DllImport("user32.dll")]
public static extern bool BlockInput(bool fBlockIt);
"@
$userInput = Add-Type -MemberDefinition $code -Name UserInput -Namespace UserInput -PassThru

$userInput::BlockInput($true)
Start-Sleep $Seconds
$userInput::BlockInput($false)

VBA中调用的代码

Sub 调用PS屏蔽输入()
    Dim psPath As String, shellCmd As String
    psPath = "C:\你的脚本路径\BlockInput.ps1" ' 替换为你实际的脚本路径
    ' 调用PS脚本,指定屏蔽10秒,隐藏窗口运行
    shellCmd = "powershell -ExecutionPolicy Bypass -File """ & psPath & """ -Seconds 10"
    Shell shellCmd, vbHide
End Sub

方案3:AutoIt 可用脚本

下面的.au3代码编译成exe后,右键勾选「以管理员身份运行此程序」即可生效:

#include <WinAPI.au3>

; 屏蔽输入
_WinAPI_BlockInput(True)
; 这里替换为你需要执行的操作代码,或者直接设置等待时间
Sleep(10000) ; 等待10秒
; 恢复输入
_WinAPI_BlockInput(False)

编译时可在AutoIt编译选项中勾选「请求管理员权限」,不需要每次手动右键选管理员运行


额外优化建议

如果条件允许,建议替换模拟鼠标/按键的操作逻辑:通过FindWindow、FindWindowExAPI找到CodeTwo QR的窗口和对应按钮的句柄,直接调用SendMessage发送点击消息,不需要依赖鼠标位置,也不会被用户操作干扰,不需要插入Sleep等待,运行效率会高很多。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:15:03