1
votes

I am writing a Little VBA Programm that Needs to wait until a specific windows is open. I want to do this using FindFindow form the user32.dll but i cant get it run. Weird Thing is that even if i set the 2 Parameters of the function to Null, i still get a negative return, although in that case all windows should match. Basically i dont get a result different from 0 for hwnd Independent of how i call FindWindow. I searched Stack OPverflow and i also Googled the Problem but i cant find what i am doing wrong. Any help is appreciated.

Declare Function FindWindow Lib "user32" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Sub Main
    Dim hwnd As Long

    hwnd = FindWindow(vbNullString, vbNullString)

    If (hwnd = 0) Then MsgBox ("failure")

End Sub

The Solutions to similar Problems like How to use FindWindow to find a visible or invisible window with a partial name in VBA dont seem to work either.

1

1 Answers

2
votes

The problem is that vbNullString is a length 0 string, the same as "". When that is marshalled to the unmanaged code a non-null pointer to a null-terminated array of characters is passed. Because the length is 0 then a pointer to a null-terminator is passed. That's different from NULL which is the null pointer.

I'm far from a VBA expert, but I think the solution is like so:

Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
    (ByRef lpClassName As Any, ByRef lpWindowName As Any) As Long

If you want to call this passing NULL for both arguments do so like this:

window = FindWindow(ByVal 0&, ByVal 0&)

Alternatively, if you want to pass a string value do it like this:

window = FindWindow(ByVal 0&, ByVal "Untitled - Notepad")