Private Sub cmdRun_Click()
Dim pid As Long
Dim h_wnd As Long
Dim buf As String
Dim buf_len As Long
' Start the program.
pid = Shell(txtProgram.Text, vbMinimizedNoFocus)
If pid = 0 Then
MsgBox "Error starting program"
Exit Sub
End If
' Get the window handle.
h_wnd = InstanceToWnd(pid)
' Display the program's caption.
buf = Space$(256)
buf_len = GetWindowText(h_wnd, buf, Len(buf))
buf = Left$(buf, buf_len)
txtHInstance.Text = Format$(pid)
txtHWnd.Text = Format$(h_wnd)
txtCaption.Text = Format$(buf)
End Sub
' Return the window handle for an instance handle.
Private Function InstanceToWnd(ByVal target_pid As Long) As _
Long
Dim test_hwnd As Long
Dim test_pid As Long
Dim test_thread_id As Long
' Get the first window handle.
test_hwnd = FindWindow(ByVal 0&, ByVal 0&)
' Loop until we find the target or we run out
' of windows.
Do While test_hwnd <> 0
' See if this window has a parent. If not,
' it is a top-level window.
If GetParent(test_hwnd) = 0 Then
' This is a top-level window. See if
' it has the target instance handle.
test_thread_id = _
GetWindowThreadProcessId(test_hwnd, _
test_pid)
If test_pid = target_pid Then
' This is the target.
InstanceToWnd = test_hwnd
Exit Do
End If
End If
' Examine the next window.
test_hwnd = GetWindow(test_hwnd, GW_HWNDNEXT)
Loop
End Function
|