What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleFind a window from a partial title and move it to the upper left corner of the screen
Keywordsfind window, retrieve window, lost window, move window
CategoriesTips and Tricks, Utilities
Somehow my API Viewer application got moved way off my desktop. By right clicking on the taskbar icon, I could maximize it and see it but I could not get it normal sized where I could find it. I wrote this program to get it back.

This program looks for a window based on a partial title. It then moves the window to the upper left corner of the screen where you can find it.

When the user clicks Go, the cmd_Go event handler calls the FindWindowByPartialTitle function to find the window. If it succeeds, it uses the SetWindowPos API function to set the form's top and left coordinates to 0.

' Move the target window to (0, 0).
Private Sub cmdGo_Click()
Dim target_hwnd As Long

    ' Find the window.
    target_hwnd = FindWindowByPartialTitle(txtTitle.Text)
    If target_hwnd <> 0 Then
        ' Move the window.
        SetWindowPos target_hwnd, 0, 0, 0, 0, 0, _
    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
        ' Continue searching.
        EnumCallback = 1
    End If
End Function
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.