以下程序在.BAS
Declare Function GetParent Lib "user32" (ByVal hwnd As Long) As Long
Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As Long, ByVal lParam As Long) As Long
Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwProcessId As Long) As Long
Declare Function SetForegroundWindow Lib "user32" Alias "SetForegroundWindow" (ByVal hwnd As Long) As Long
Declare Function OpenProcess Lib "kernel32" _
(ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, _
ByVal dwProcessId As Long) As Long
Declare Function WaitForSingleObject Lib "kernel32" _
(ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Declare Function CloseHandle Lib "kernel32" _
(ByVal hObject As Long) As Long
Declare Function GetExitCodeProcess Lib "kernel32" _
(ByVal hProcess As Long, lpExitCode As Long) As Long
Declare Function TerminateProcess Lib "kernel32" _
(ByVal hProcess As Long, ByVal uExitCode As Long) As Long
Declare Function PostMessage Lib "user32" Alias "PostMessageA" _
(ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, _
ByVal lParam As Long) As Long
Public Const SYNCHRONIZE = &H100000
Public Const STILL_ALIVE = &H103
Public Const INFINITE = &HFFFF
Public Const WM_CLOSE = &H10
Public hWnd5 As Long
Function EnumWindowsProc(ByVal hwnd As Long, ByVal lParam As Long) As Boolean
Dim S As String
If GetParent(hwnd) = 0 Then
Dim tid As Long, pid As Long
tid = GetWindowThreadProcessId(hwnd, pid)
If pid = lParam Then
hWnd5 = hwnd
EnumWindowsProc = False
End If
End If
EnumWindowsProc = True ' 表示继续列举 hWnd
End Function
以下程序在Form
Option Explicit
Private ExitCode As Long
Private hProcess As Long
Private isDone As Long
Private Sub Command1_Click()
Dim pid As Long
pid = Shell("notepad.exe", vbNormalFocus)
Call EnumWindows(AddressOf EnumWindowsProc, pid) '设定hWnd5的值
hProcess = OpenProcess(SYNCHRONIZE , 0, pid)
isDone = False
Do
Call GetExitCodeProcess(hProcess, ExitCode)
DoEvents
Loop While ExitCode = STILL_ALIVE Or isDone
Call CloseHandle(hProcess)
isDone = True
Label1.Caption = "Over"
End Sub
Private Sub Command2_Click()
Dim i As Long
Call SetForegroundWindow(hWnd5)
Call PostMessage(hWnd5, WM_CLOSE, 0, 0)
End Sub
Private Sub Form_Unload(Cancel As Integer)
isDone = True
End Sub