Results 1 to 2 of 2

Thread: How to know window handle by process ID?

  1. #1

    Thread Starter
    New Member
    Join Date
    Apr 2000
    Posts
    5
    Hi,

    I initate another application with ShellEx, which return a process ID.

    How can I figure out its window handle by the process ID? ( I don't want to find window handle by looking up its applicaton name b'coz there may be two Win Word application running simultaneously.

    Your kind & prompt advise is much appreciated.


    Thx,/Albert :-)

  2. #2
    Addicted Member
    Join Date
    Aug 1999
    Location
    Ottawa,ON,Canada
    Posts
    217
    Here's how I do it:
    Code:
    '<<< CONSTANTS >>>
    Private Const MAXSHORT As Integer = &H7FFF
    
    Private Const GW_HWNDFIRST As Integer = 0
    Private Const GW_HWNDLAST As Integer = 1
    Private Const GW_HWNDNEXT As Integer = 2
    Private Const GW_HWNDPREV As Integer = 3
    Private Const GW_OWNER As Integer = 4
    Private Const GW_CHILD As Integer = 5
    
    '<<< API DECLARES >>>
    Private Declare Function GetDesktopWindow _
                    Lib "user32" _
                    () As Long
    
    Private Declare Function GetWindow _
                    Lib "user32" _
                    (ByVal hwnd As Long, ByVal wCmd As Long) As Long
    
    Private Declare Function GetWindowThreadProcessId _
                    Lib "user32" _
                    (ByVal hwnd As Long, lpdwProcessId As Long) As Long
    
    'Function to retrieve the Handle based on a Process ID.
    Private Function hGetAppHandle(hProcID As Long) As Long
       Dim hCurWindow As Long
       Dim hCurProcID As Long
       Dim hAppHandle As Long
       Dim iSafeStep As Integer
       
       hCurWindow = GetDesktopWindow
       hCurWindow = GetWindow(hCurWindow, GW_CHILD)
       
       Do While hCurWindow <> 0 And iSafeStep < MAXSHORT
          Call GetWindowThreadProcessId(hCurWindow, hCurProcID)
          
          If hCurProcID = hProcID Then
             hAppHandle = hCurWindow
             Exit Do
          End If
          
          hCurWindow = GetWindow(hCurWindow, GW_HWNDNEXT)
          iSafeStep = iSafeStep + 1
       Loop
       
       mhGetAppHandle = hAppHandle
    End Function
    The iSafeStep counter is used to ensure that the loop doesn't get caught in an infinite loop because of the nature of crashing programs and such.

    If anyone has a better way of doing this I would like to know as well. It's the only way I know of and I would like to know if there is a better way.

    Later.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width