|
|
Title | See if a window is running in three ways |
Keywords | find window, AppActivate, FindWindow, EnumWindows |
Categories | API |
|
|
First, use AppActivate. If the window does not exist, this raises an error.
|
|
' Use AppActivate to see if the window exists.
Private Sub cmdAppActivate_Click()
On Error Resume Next
AppActivate txtWindowTitle.Text
If Err.Number <> 0 Then
MsgBox "The window does not exist."
Else
MsgBox "The window exists."
End If
End Sub
|
|
Second, use the FindWindow API function. FindWindow returns 0 if the window doesn't exist.
|
|
' Use FindWindow to see if the window exists.
Private Sub cmdFindWindow_Click()
If FindWindow(ByVal 0, txtWindowTitle.Text) = 0 Then
MsgBox "The window does not exist."
Else
MsgBox "The window exists."
End If
End Sub
|
|
Finally, use EnumWindows. The window enumerator function uses GetWindowText to get each window's title. If the title matches the target window name, then it has found the target. This is the most complex method but also the most flexible. For example, you could look for a window when you know only part of its title or you could take action on all windows with the same or similar titles.
|
|
' Use EnumWindows to see if the window exists.
Private Sub cmdEnumWindows_Click()
TargetName = txtWindowTitle.Text
TargetHwnd = 0
' Examine the window names.
EnumWindows AddressOf WindowEnumerator, 0
' See if we got an hwnd.
If TargetHwnd = 0 Then
MsgBox "The window does not exist."
Else
MsgBox "The window exists."
End If
End Sub
' Return False to stop the enumeration.
Public Function WindowEnumerator(ByVal app_hwnd As Long, _
ByVal lparam As Long) As Long
Dim buf As String * 256
Dim title As String
Dim length As Long
' Get the window's title.
length = GetWindowText(app_hwnd, buf, Len(buf))
title = Left$(buf, length)
' See if the title contains the target.
If InStr(title, TargetName) > 0 Then
' Save the hwnd and end the enumeration.
TargetHwnd = app_hwnd
WindowEnumerator = False
Else
' Continue the enumeration.
WindowEnumerator = True
End If
End Function
|
|
|
|
|
|