我是一个新的VB脚本程序员,试图使用VB脚本通过默认程序(在本例中为Adobe Reader X)打开pdf文件,并将其保存为文本文件.
我打开PDF的当前脚本等待1秒钟,然后将其保存为文本.但是,对于速度较慢的计算机,加载PDF可能需要1秒以上的时间.有没有人知道如何在文件打开或状态准备好之前进行睡眠循环?
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run """C:\Temp\Gasprices.pdf"""
Set objShell = CreateObject("WScript.Shell")
wscript.sleep 1000
objShell.SendKeys "%FAX%S"
Run Code Online (Sandbox Code Playgroud)
首先,因为你是初学者,所以总是使用Option Explicit.许多错误都是由变量名中的拼写错误引起的,如果您强制自己声明所有使用的变量,就会捕获它们.
其次,您不需要创建两个WScript.Shell对象,只需重新使用现有对象即可.
第三,您需要激活要发送命令的应用程序.这就是Shell对象的AppActivate方法.它返回True或False指示将有问题的应用程序带到前台是否有效.您可以在循环(While Not Shell.AppActivate("Adobe Reader") ...)中使用它,以便在应用程序需要时完全等待.
但是,缺点是您需要知道应用程序窗口(或其进程ID)的确切标题才能使其正常工作.应用程序标题可能会在没有警告的情况下更改,因此这有点不稳定.PID很稳健,但不可猜测.
最后,您需要WMI的帮助列出所有进程,获取正确的PID然后将其传递给AppActivate.这Win32_Process堂课是为此而设.
Dim Shell, WMI, pid
Set Shell = WScript.CreateObject("WScript.Shell")
Set WMI = GetObject("winmgmts:!\\.\root\cimv2")
Shell.Run "start ""C:\Temp\Gasprices.pdf"""
pid = WaitForProcess("AcroRd32.exe", 5)
If pid > 0 Then
Shell.AppActivate pid
Shell.SendKeys "%FAX%S"
Else
WScript.Echo "Could not talk to PDF reader"
WScript.Quit 1
End If
Function WaitForProcess(imageName, tries)
Dim wql, process
wql = "SELECT ProcessId FROM Win32_Process WHERE Name = '" & imageName & "'"
WaitForProcess = 0
While tries > 0 And WaitForProcess = 0
For Each process In WMI.ExecQuery(wql)
WaitForProcess = process.ProcessId
Next
If WaitForProcess = 0 Then
WScript.Sleep 1000
tries = tries - 1
End If
Wend
End Function
Run Code Online (Sandbox Code Playgroud)
请注意,分配函数名称(如WaitForProcess = 0)将设置返回值.
您可以通过查找脚本自己的PID和查询来优化它
"SELECT ProcessId FROM Win32_Process WHERE ParentProcessId = '" & scriptPID & "'"
Run Code Online (Sandbox Code Playgroud)
在WaitForProcess().
| 归档时间: |
|
| 查看次数: |
5952 次 |
| 最近记录: |