Dim pID As LongPrivate Sub Command1_Click()
    pID = Shell("c:\test\jj.exe", vbNormalFocus)
End SubPrivate Sub Command2_Click()
    Dim hWnd As Long
    Dim i As Integer
    hWnd = FindProcessWindow(pID)
    Text1.Text = CStr(hWnd) & vbCrLf & Text1.Text
    SetForegroundWindow hWnd
    PostMessage hWnd, WM_CLOSE, 0, 0&
End Sub问题:按Command1打开jj.exe后,要按多次Command2才能关闭,大侠们说说是为什么?

解决方案 »

  1.   

    PostMessage是把消息放到目标程序的消息队列
    如果目标程序还没处理这个消息就不会立即退出。可以试一下 SendMessage 代替 PostMessage。
      

  2.   

    还是不行,每次点击Comamd2得到的hWnd = FindProcessWindow(pID)都不同,照理应是一样的?代码在这里,你也可以试一下,是另一个大虾给的,这里暂时盗版一下了。:'窗体中的代码
    Option ExplicitDim pID As LongPrivate Sub Command1_Click()
        pID = Shell("c:\test\jj.exe", vbNormalFocus)  'jj.exe是用VB编的另一个程序
    End SubPrivate Sub Command2_Click()
       Dim hWnd As Long
        Dim i As Integer
        
        hWnd = FindProcessWindow(pID)
        SetForegroundWindow hWnd
        'PostMessage hWnd, WM_CLOSE, 0, 0&  '用post
        SendMessage hWnd, WM_CLOSE, 0, 0&End Sub'模板中的代码
    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 SendMessage Lib "user32" Alias "SendMessageA" (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