'ShellWait示例
'先点击command3运行Notepad.exe
'然后再点点Command1
'如果在10秒之内关闭Notepad,则弹出提示框0
'如果10秒内未关闭Notepad.则弹出提示框258
'in a Form
Option Explicit
Dim ProcessID As Long
Private Sub Command1_Click()
Dim WaitHandle As Long
Dim Ret As Long
WaitHandle = OpenProcess(SYNCHRONIZE, True, ProcessID)
Ret = WaitForSingleObject(WaitHandle, 3000)
CloseHandle WaitHandle
MsgBox Ret
End Sub
Private Sub Command3_Click()
ProcessID = Shell("notepad.exe")
End Sub
'in a module
Option Explicit
Public Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Public Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Public Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Public Const SYNCHRONIZE = &H100000
'///
'函数名称:ShellWait( Process , [Timeout] )
'函数功能:等待程序运行结束
'参数说明:
' [ProcessID]:程序进程ID(Shell函数返回值)
' [Timeout]:超时时间(单位:毫秒),缺省为20秒
'返回值(Long型):
' [258]超时(进程未结束)
' [0]进程已结束
' [-1]不存在的进程
'///
Public Function ShellWait(ProcessID As Long, Optional Timeout As Long = 20000) As Long
Dim WaitHandle As Long
WaitHandle = OpenProcess(SYNCHRONIZE, True, ProcessID)
ShellWait = WaitForSingleObject(WaitHandle, Timeout)
CloseHandle WaitHandle
End Function