VB 进程死亡的自动复活(进程结束再自动运行)
前两天看了Delphi版面精华区中的《进程死亡的自动复活》一文,觉得作者的思路很不错,利用api来监视进程的活动,当被销毁时就自动再创建进程。仔细推敲之后,发觉其实用vb也是可以做到的。于是花了半天的时间写了以下的程序,实现了使用WaitForSingleObject API来监视被创建的进程的活动,一旦返回除 time out 之外的消息就自动创建新的进程。以下为其实现代码。在 win2000 server + vb 6.0下通过。
(ByVal hObject As Long) As Long
Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare Function CreateProcess Lib "kernel32" Alias "CreateProcessA" (ByVal lpApplicationName As String, ByVal lpCommandLine As String, ByVal lpProcessAttributes As Long, ByVal lpThreadAttributes As Long, ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, lpEnvironment As Any, ByVal lpCurrentDirectory As String, lpStartupInfo As STARTUPINFO, lpProcessInformation As PROCESS_INFORMATION) As Long
Private Declare Function WaitForInputIdle Lib "user32" (ByVal hProcess As Long, ByVal dwMilliseconds As Long) As Long
Private Sub command1_Click()
Dim res&
Dim sinfo As STARTUPINFO
Dim pinfo As PROCESS_INFORMATION
sinfo.cb = Len(sinfo)
sinfo.lpReserved = vbNullString
sinfo.lpDesktop = vbNullString
sinfo.lpTitle = vbNullString
sinfo.dwFlags = 0
Label1.Caption = "正在启动程序"
Label1.Refresh
' CreateProcess函数,用于创建一个新的进程
res = CreateProcess(DemoFile, vbNullString, 0, 0, True, _
NORMAL_PRIORITY_CLASS, ByVal 0&, vbNullString, sinfo, pinfo)
If res Then
Label1.Caption = "程序正在运行中"
WaitForTerm pinfo
Label1.Caption = "程序已经结束"
Else
Label1.Caption = "启动程序时出错,可能未正确输入" & Chr(13) & "程序名或程序所在路径。"
End If
End Sub
Private Sub WaitForTerm(pinfo As PROCESS_INFORMATION)
Dim res&
Dim res1&
' 等待指定的进程进入空闲状态,,空闲(Idle)指的是进程准备处理一条消息、但目前暂时没有消息需要处理的一种状态
Call WaitForInputIdle(pinfo.hProcess, INFINITE)
Command1.Enabled = False
Command2.Enabled = True
Label1.Refresh
Do
If Flag Then Exit Do
'等待发出信号
res = WaitForSingleObject(pinfo.hProcess, 0)
If res <> WAIT_TIMEOUT Then '如果对象发出了信号
command1_Click
Exit Do
End If
DoEvents
Debug.Print res
Loop While True
Command1.Enabled = True
Command2.Enabled = False
End Sub
Private Sub Command3_Click()
Flag = True
End Sub
Private Sub Form_Load()
RunFile = InputBox$("请输入需要运行的程序名与路经")
Flag = False
End Sub
?