Adam Caudill

Security Leader, Researcher, Developer, Writer, & Photographer

SetFocusByCaption

This post was imported from an old blog archive, and predates the creation of AdamCaudill.com.

This is a simple function really, it just sets the focus to a window based on its caption.

API: #

Private Declare Function SetForegroundWindow Lib "user32" ( _
    ByVal hwnd As Long) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" ( _
    ByVal lpClassName As Any, _
    ByVal lpWindowName As Any) As Long

Function: #

Public Function SetFocusByCaption(strCaption As String) As Boolean
Dim lngHandle As Long
Dim lngResult As Long

    lngHandle = FindWindow(vbNullString, strCaption)
    If lngHandle <> 0 Then
        lngResult = SetForegroundWindow(lngHandle)
        If lngResult = 0 Then
            SetFocusByCaption = False
        Else
            SetFocusByCaption = True
        End If
    Else
        SetFocusByCaption = False
    End If
End Function

Returns True/False based on success.

Adam Caudill