Link to home
Start Free TrialLog in
Avatar of peterwest
peterwest

asked on

Determining hWnd from Process ID....

HI there,

My application uses the Shell command to instigate an instance of a sub-programme.  My question is this - the Shell command returns a double which is the process ID created - is there any way of finding the Window with which the process is associated.  Ideally i'd like to retrieve the hWnd value.

I want to do this so I can post a WM_CLOSE message to the window in order to terminate it gracefully.

Pete
ASKER CERTIFIED SOLUTION
Avatar of alamo
alamo

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of alamo
alamo

Private Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As Long, ByVal lParam As Long) As Integer

ProcessID& = Shell("notepad")
ret = EnumWindows(AddressOf EnumWindowsProc, ProcessID&)
If ret = 0 Then MsgBox "failed"

' This must be in a module
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwProcessId As Long) As Long

Public Function EnumWindowsProc(ByVal hWind As Long, ByVal lParam As Long) As Boolean
Dim WProcessID&,ThreadID&

 ThreadID& = GetWindowThreadProcessId(hWind, WProcessID&)
 If WProcessID& = lParam Then
  ' send WM_CLOSE here
 End If
 EnumWindowsProc = True  'set to false if you don't want any more enumerated
End Function

That will do it... you will probably get more windows than you expect, but you are at the mercy of EnumWindows as to what windows you get. You might be able to winnow them down with something like:
If IsWindowEnabled(hWind) <> False and If IsWindowVisible(hWind) <> False and If IsIconic(hWind) = False Then

Hope this helps, good luck!
Avatar of peterwest

ASKER

Hi again,

Sorry for the delay in grading your answer - i've tested the code and it worked fine.

Cheers

Pete