Home > Software design >  VBA Win32 EnumChildWindows causes the program to crash
VBA Win32 EnumChildWindows causes the program to crash

Time:09-21

I am trying to read information from a textboxes in a window. I have successfully pulled this information using .NET. However, this version needs to be written in VBA. Specifically, I am using VBA 7.1.

I have included a section of code below that simplifies the problem. I've tried the code in our 3D modeling software as well as Excel's VBA editor. Both crash when trying to use hwndEnum in any way.

Any thoughts on what I am doing wrong here?

    Private Declare PtrSafe Function FindWindow Lib "User32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr
    Private Declare PtrSafe Function FindWindowEx Lib "User32" Alias "FindWindowExA" (ByVal hwndParent As LongPtr, ByVal hwndChildAfter As LongPtr, ByVal lpszClass As String, ByVal lpszWindow As String) As LongPtr
    Private Declare PtrSafe Function EnumChildWindows Lib "User32" (ByVal hwndParent As LongPtr, ByVal lmEnumFunc As LongPtr, ByVal lParam As Long) As Long
    
    Private Function myCallback(hwndEnum As LongPtr, lParam As Long) As Long
        Dim testHwnd As LongPtr
        testHwnd = hwndEnum 'Crashes Here
        myCallback = True
    End Function
    
    Sub Main()
        Dim hwndParent As LongPtr, hwndChild As LongPtr, emptyLongPtr As LongPtr
        hwndParent = FindWindow(vbNullString, "Stock Size")
        hwndChild = FindWindowEx(hwndParent, emptyLongPtr, vbNullString, "Billet Dims")
        'Code successfully finds these two windows
        Dim retVal As Long
        retVal = EnumChildWindows(hwndChild, AddressOf myCallback, 0)
    End Sub

CodePudding user response:

You have two mistakes

  • lParam should be LongPtr
  • The callback function's parameters should be ByVal
Private Declare PtrSafe Function EnumChildWindows Lib "User32" (ByVal hwndParent As LongPtr, ByVal lmEnumFunc As LongPtr, ByVal lParam As LongPtr) As Long
    
Private Function myCallback(ByVal hwndEnum As LongPtr, ByVal lParam As LongPtr) As Long
...
  • Related