我给你相关代码,看能否帮助你!以下为放在FORM中的代码: Option ExplicitDim pID As LongPrivate Sub Command1_Click() pID = Shell("notepad", vbNormalFocus) End SubPrivate Sub Command2_Click() Dim hWnd As Long
hWnd = FindProcessWindow(pID) SetForegroundWindow hWnd PostMessage hWnd, WM_CLOSE, 0, 0& End Sub以下为放在modules中的代码: Option ExplicitPublic Const WM_CLOSE = &H10 Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As Long, ByVal lParam As Long) As Long Declare Function GetParent Lib "user32" (ByVal hWnd As Long) As Long Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As Long, lpdwProcessId As Long) As Long Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long Declare Function SetForegroundWindow Lib "user32" (ByVal hWnd As Long) As LongDim hWndProcess As LongFunction EnumWindowsProc(ByVal hWnd As Long, ByVal lParam As Long) As Boolean Dim pID As Long
GetWindowThreadProcessId hWnd, pID If pID = lParam Then If GetParent(hWnd) = 0 Then hWndProcess = hWnd EnumWindowsProc = False End If End If EnumWindowsProc = True End FunctionFunction FindProcessWindow(ByVal pID As Long) As Long hWndProcess = 0 EnumWindows AddressOf EnumWindowsProc, pID FindProcessWindow = hWndProcess End Function
先根据FINDWINDOWS函数取得程序的句柄,然后通过CLOSEWINDOW关闭程序.
Option ExplicitDim pID As LongPrivate Sub Command1_Click()
pID = Shell("notepad", vbNormalFocus)
End SubPrivate Sub Command2_Click()
Dim hWnd As Long
hWnd = FindProcessWindow(pID)
SetForegroundWindow hWnd
PostMessage hWnd, WM_CLOSE, 0, 0&
End Sub以下为放在modules中的代码:
Option ExplicitPublic Const WM_CLOSE = &H10
Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As Long, ByVal lParam As Long) As Long
Declare Function GetParent Lib "user32" (ByVal hWnd As Long) As Long
Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As Long, lpdwProcessId As Long) As Long
Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Declare Function SetForegroundWindow Lib "user32" (ByVal hWnd As Long) As LongDim hWndProcess As LongFunction EnumWindowsProc(ByVal hWnd As Long, ByVal lParam As Long) As Boolean
Dim pID As Long
GetWindowThreadProcessId hWnd, pID
If pID = lParam Then
If GetParent(hWnd) = 0 Then
hWndProcess = hWnd
EnumWindowsProc = False
End If
End If
EnumWindowsProc = True
End FunctionFunction FindProcessWindow(ByVal pID As Long) As Long
hWndProcess = 0
EnumWindows AddressOf EnumWindowsProc, pID
FindProcessWindow = hWndProcess
End Function
基本可以了,但关闭我的程序的时候,不知道为什么要连续点击多下Command2才能关闭。