The window caption required by the FindWindow API is made up from the application and and the file name, thus:-
Microsoft Excel - My Workbook
The above API function will return the window's handle if the window's caption is supplied correctly.
In the above situation, where the window's application name was known, the window's caption can be returned by the API GetWindowText as is demonstrated with the following code (written for 64-bit VBA7):-
- Code: Select all
Private Sub GetWindowCaption()
#If VBA7 Then
Dim WinHandle As LongPtr
#Else
Dim WinHandle As Long
#End If
Dim WinTitle As String
WinHandle = FindWindow("XLMAIN", vbNullString) ' Get the handle needed by GetWindowText
WinTitle = Space(260)
Call GetWindowText(WinHandle, WinTitle, 260)
Debug.Print WinTitle ' Print the Window caption
End Sub
While this code is backward compatible to Excel 2003 the API FindWindow published above needs to be made pointer safe to run on 64-bit Excel 2010. The API GetWindowText isn't supplied in this thread but would have to be adapted to the available VBA version as well.
With both, application name and window caption, known code like this can be written:-
- Code: Select all
If FindWindow("XLMAIN", "Microsoft Excel - My Workbook") Then
' do something
Else
' do something else
End If
This capability is of little, if any, use while programming for any one Office application because each one supplies its own code to check if a specific file is open. The advantage of the API becomes apparent when checking for windows that other applications have opened. I intend to use it to check if a particular web site is open and then, if it is, extract data from it into Excel.
Have a great day!
Sisyphus
I do this for "honour and country" - much less of the latter, actually.
If I helped you, award points, plenty of them.
If I bored you, deduct points for being too long-winded. (I know, :lol)