有时,我们需要设置和获得某个进程结束时的返回值,然后VB并没有C语言中Exit之类的函数,因此我们需要借助API来实现,思路如下:
1、设置进程返回值。
创建一个新的无窗口的工程,在标准模块中复制以下代码,编译成ProgA.EXE文件保存到C:/目录下待用。
Option Explicit Private Declare Sub ExitProcess Lib "kernel32" (ByVal uExitCode As Long) Sub Main() MsgBox "按回车键结束" ExitProcess 123 '设置进程结束时的返回值 End Sub
2、获得进程返回值。
创建一个新的无窗口工程,在标准模块中复制以下代码,按F5运行即可。
Option Explicit Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long,ByVal bInheritHandle As Long,ByVal dwProcessId As Long) As Long Private Declare Function GetExitCodeProcess Lib "kernel32" (ByVal hProcess As Long,lpExitCode As Long) As Long Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long Private Const PROCESS_QUERY_INFORMATION = &H400 Private Const STILL_ALIVE = &H103 Sub Main() Dim pid As Long,hProcess As Long,nExitCode As Long '运行progA pid = Shell("c:/progA.exe",vbNormalFocus) '等progA结束 hProcess = OpenProcess(PROCESS_QUERY_INFORMATION,pid) Do GetExitCodeProcess hProcess,nExitCode DoEvents Loop While nExitCode = STILL_ALIVE CloseHandle hProcess '显示progA进程返回值 MsgBox nExitCode End Sub