|
|
Title | Find a window given part of its title and move it to the foreground |
Keywords | find window, foreground, partial title |
Categories | API |
|
|
When the user clicks Go, the cmd_Go event handler calls the FindWindowByPartialTitle function to find the window. If it succeeds, the routine it uses the SetForegroundWindow API function (which I think may not work in Windows XP) to set the focus to the window.
|
|
' Give the target focus.
Private Sub cmdGo_Click()
Dim target_hwnd As Long
' Find the window.
target_hwnd = FindWindowByPartialTitle(txtTitle.Text)
If target_hwnd = 0 Then
MsgBox "Window not found"
Else
' Give the window the focus.
SetForegroundWindow target_hwnd
End If
End Sub
|
|
Function FindWindowByPartialTitle calls the EnumWindows API function to enumerate all of the system's windows, passing it the address of the EnumWindowCallback function. (Note that this function must be in a .BAS module).
For each window, the system calls EnumWindowCallback. That function uses the GetWindowText API function to get the window's title. It uses InStr to see if the contains the partial title it wants to find. If the title matches, the function saves the window's hWnd and returns 0 to stop the enumeration.
|
|
Private m_TargetString As String
Private m_TargetHwnd As Long
' Find a window with a title containing target_string
' and return its hWnd.
Public Function FindWindowByPartialTitle(ByVal _
target_string As String) As Long
m_TargetString = target_string
m_TargetHwnd = 0
' Enumerate windows.
EnumWindows AddressOf EnumCallback, 0
' Return the hWnd found (if any).
FindWindowByPartialTitle = m_TargetHwnd
End Function
' Check a returned task to see if it's the one we want.
Public Function EnumCallback(ByVal app_hWnd As Long, ByVal _
param As Long) As Long
Dim buf As String
Dim title As String
Dim length As Long
' Get the window's title.
length = GetWindowTextLength(app_hWnd)
buf = Space$(length)
length = GetWindowText(app_hWnd, buf, length)
title = Left$(buf, length)
' See if the title contains the target string.
If InStr(title, m_TargetString) <> 0 Then
' This is the one we want.
m_TargetHwnd = app_hWnd
' Stop searching.
EnumCallback = 0
Else
' Continue searching.
EnumCallback = 1
End If
End Function
|
|
|
|
|
|