Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleStart a process using Shell and get its hWnd
KeywordsShell, PID, hWnd, start program
CategoriesAPI, Software Engineering
 
This is an important procedure because many API functions require an hWnd instead of the process id (PID) returned by Shell.

Iterate through the system's windows using the FindWindow and GetWindow API functions. Use the GetWindowThreadProcessId API function to compare each top level window's process id (PID) to the value returned by Shell.

 
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
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated