How to use FindWindow to bring to front an exe already running

J Trahair

Well-known member
Joined
May 14, 2008
Messages
175
Location
Spain
Programming Experience
10+
Hi. I have a series of exes, opened by a 'central' exe. After normal use, the child exes have become separated from the central exe, eg. by the user running a browser or any other program between using Central and Child, so when the child exe closes the topmost window is the browser.

I want to bring to front the 'Central'.exe when I close the child exe.

What WM_constant should I use? I'm looking for a WM_BRINGTOFRONT. But there isn't such a constant. What should I use?

VB.NET:
      Dim target_hwnd As Integer = FindWindow(vbNullString, "Central")
                If (target_hwnd = 0) Then
                    'MessageBox.Show("Error finding target window handle")
                    'Exit Sub
                End If

                PostMessage(target_hwnd, WM_?????, 0, 0)

Thank you.
 
Thanks Herman. Here's the final result:

VB.NET:
                'You'll need:
                'Imports System.Runtime.InteropServices

                '<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
                'Private Shared Function FindWindow(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
                'End Function

                '<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
                'Private Shared Function SetForegroundWindow(ByVal hWnd As IntPtr) As Long
                'End Function

                'Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hwnd As IntPtr, ByVal lpClassName As String, ByVal nMaxCount As Integer) As Integer

                Dim numID As Integer

                For Each p1 As Process In Process.GetProcesses(My.Computer.Name)
                    If p1.MainWindowTitle = "Not just for Notepad, this works for other apps too!" Then
                        numID = p1.Id
                        Exit For
                    End If
                Next

                Dim p As Process = Process.GetProcessById(numID)
                Dim lpszParentWindow As String = p.MainWindowTitle
                'Get class name from window handle
                Dim lpszParentClass As String = New String(" "c, 128)
                Dim lRet As Integer = GetClassName(p.MainWindowHandle, lpszParentClass, 128)
                lpszParentClass = lpszParentClass.Substring(0, lRet)

                Dim ParenthWnd As New IntPtr(0)
                ParenthWnd = FindWindow(lpszParentClass, lpszParentWindow)

                If ParenthWnd <> IntPtr.Zero Then
                    SetForegroundWindow(ParenthWnd)
                End If
 
Back
Top