Windows API in a Sub Function [VBA]

I am new to VBA therefore please excuse me in advance if my question is silly. That said, I have the following Windows API:

Private Declare PtrSafe Function IsIconic Lib "user32" (ByVal hWnd As LongPtr) As Integer

and inside the module where we have declared the API I have the following function:

Function IsMinimized(hWndAccessApp As Long) As Boolean
    IsMinimized = IsIconic(hWndAccessApp) * -1
End Function

In addition to that I also have a form that has a button and a click event on that button that looks like:

Private Sub btn_one_Click()
    Dim test As Boolean
    test = IsMinimized(hWndAccessApp)
    MsgBox test
End Sub

And everything is working perfectly. However, I was wondering if there is a way to skip the function inside the module and call the "IsIconic" API directly from the Private Sub associated with the button inside the form?


Solution 1:

a) There is no way to avoid the Declare-Statement for an API function.

b) You have defined your IsIconic-declaration as Private, therefore it is known only in that module. If the code of btn_one_Click is not in that module, it cannot access the function - but that has nothing to do with being an API function. Just remove the Private-keyword, and you can access it from "everywhere".

c) As already mentioned in the comments, I think it is a good idea to use a wrapper function that hides the details of the API-call (and the conversion of the integer value that is returned into an boolean).

d) Using IsIconic(hWndAccessApp) * -1 to convert an Integer-Value 1 to a boolean looks dirty to me. To avoid a calculation to get a boolean, I would suggest to use

IsMinimized = (IsIconic(hWndAccessApp) <> 0)     ' Or = 1

In almost all cases, you should forget about the fact that a boolean is stored as 0 and -1 for False and True. Let VBA do the conversion from 1 to True for you.