【问题标题】:Freeze mouse and keyboard input temporarily from VBA从 VBA 暂时冻结鼠标和键盘输入
【发布时间】: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


【解决方案1】:

我一直在寻找(现在仍在寻找)是一种我可以自己控制的Windows 方法 或脚本语言。 但是,我发现小型免费软件 KeyFreeze (909 KB) 可以完美地完成所需的工作:

Sub Finish()        ' (in a Word form module)
Dim KF_PID As LongPtr
' …
Me.MousePointer = fmMousePointerHourGlass
Me.WaitMessage.Visible = True
DoEvents
KF_PID = Shell("C:\Programs(portable)\KeyFreeze\KeyFreeze_x64.exe", vbNormal)    ' ×32 version available, too
' starts minimized, if desired without any message 
' …
' critical part of the sub with many slow commands:
' Selection.GoTo What:=wdGoToBookmark, PasteIntoBookmark(),
' SetCursorPos, Sleep, Mouse_Event and SendKeys commands
' …
Call Shell("C:\Windows\SysWOW64\taskkill.exe /f /pid " & KF_PID)
End Sub

请注意,此免费软件可以很容易地配置为在启动时阻止键盘和鼠标,因此甚至不需要发送阻止键序列(默认情况下 F,可配置)。也不必再次发送相同的键序列来解锁,因为终止进程足以重新激活键盘和鼠标:不必担心哪个窗口具有焦点。

我当然更喜欢调用 Windows 函数,但我相信这个免费软件是可以信任的,因为 VirusTotal 报告“没有安全供应商将此文件标记为恶意 (0/65)”。

BlueLife KeyFreeze v1.4 (Block keyboard and mouse)

【讨论】:

    猜你喜欢
    • 2014-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 2019-02-13
    相关资源
    最近更新 更多