【发布时间】:2022-01-02 23:58:20
【问题描述】:
我有一个 Word VBA 程序,它需要异常长的时间来完成书签跳转(可能代码第二次打开包含文档的小但很多帧,第一次定位函数调用大约需要 6 秒)。
然后代码发送键并移动鼠标以在免费软件窗口(CodeTwo QR ...)中执行简单的操作。为了使序列正常工作,我必须插入睡眠代码行。因此,整个操作很慢。
但是,任何其他按键或鼠标移动都会干扰代码并导致错误(例如,当鼠标不在非常精确的位置以单击按钮时)。因此,我正在寻找一种方法来抑制用户的任何无意干扰。请注意,代码是通过单击控制按钮启动的,用户的手仍然在鼠标上……
SetWindowsHookEx() 似乎是一种可能性。无需回调被捕获的垃圾(这些函数似乎没有在 VBA 中实现)。但我是一个爱好程序员,不知道如何实现这一点。非常欢迎尝试一段代码,在此先感谢!
当然,PowerShell 命令最终也会有所帮助。我在 Reddit 上看到过以下代码,但它需要以管理员身份运行(这可能从 vba 中运行吗?),即使这样它什么也不做,并且在
param([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) {
# tried to elevate, did not work, aborting
} else {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
}
exit
}
'running with full privileges'
$code = @"
[DllImport("user32.dll")]
public static extern bool BlockInput(bool fBlockIt);
"@
$userInput = Add-Type -MemberDefinition $code -Name UserInput -Namespace UserInput -PassThru
function Disable-UserInput($seconds) {
$userInput::BlockInput($true)
Start-Sleep $seconds
$userInput::BlockInput($false)
}
Disable-UserInput -seconds 10 | Out-Null
否则我尝试使用 AutoIt 脚本语言,但生成的 .exe 文件缺少权限(即使以管理员身份运行)。当然,我没有写一个合适的脚本。有人可以建议我使用合适的 .au3 代码来禁用外部输入并在几秒钟后再次启用它吗?
【问题讨论】:
-
将
exit移动到Start-Process powershell.exe -Verb RunAs ...行下在else {..}内 -
不幸的是没有区别:powershell 立即终止,鼠标和键盘保持活动状态。也许这个命令只在 powershell 中有效?
标签: vba powershell ms-word user-input disable