FindWindow

The FindWindow function returns a handle to a window. A handle doesn’t do you much good on its own, but you need it for some other API functions, so it’s pretty important.

You declare API functions in the declarations section (read: top) of a standard module. The FindWindow declaration looks like this:

Public Declare Function FindWindow Lib “user32? Alias “FindWindowA” _
    (ByVal lpClassName As String, _
    ByVal lpWindowName As String) As Long

This is an example of how to use the function in code. All it does is print out the handle number.

Sub GetVBEWindowHandle()

    Dim lHwnd As Long
    
    lHwnd = FindWindow(“wndClass_desked_gsk”, vbNullString)
    
    Debug.Print lHwnd
    
End Sub

The class name “wndClass_desked_gsk” I got from a program called Spy++ that ships with (at least) Visual Studio 6.0. If I didn’t have Spy++, I don’t know how I would find class names to pass to this function, but maybe someone who does know can comment. The class for the Excel window is XLMAIN.

For the second argument, I passed a null string. Since I know there’s only one VBE open, I can get away with the null string which tells the function to return the first window for that class. I could also sepecify that argument by using Application.VBE.MainWindow.Caption. Similarly, if you’re using XLMAIN as your class, you can use Application.Caption as the second argument.

Posted in Uncategorized

5 thoughts on “FindWindow

  1. I recall that wndClass_desked_gsk showed up in your ¨Clear the Immediate Window¨ post a couple of months ago.
    There you were using it as the parent of the Immediate window.
    Looks all-around useful.

  2. With respect, I wonder if you missed this form of the call;

    lHwnd = FindWindow(0&, “Caption of Window searched for”)

    You don’t need know the class as long as you know the text of the caption of the Window you are looking for.

    regards

  3. Ref my last message you will need to update the declaration to;

    Declare Function FindWindow Lib “user32? Alias “FindWindowA” (ByVal lpClassName As Any, ByVal lpWindowName As String) As Long

  4. Dim hwnd As Long

    hWnd = FindWindow(“XLMAIN”, 0)

    I’m using FindWindow form Visual Basic 6 with Officw 2010 32 bits but it doesn’t work… do I have to change the lpClassName wich is no more “XLMAIN”?

    Thanks in advance for your help

    INTELED


Posting code? Use <pre> tags for VBA and <code> tags for inline.

Leave a Reply

Your email address will not be published. Required fields are marked *