0

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?

George Smith
  • 415
  • 8
  • 25
  • 2
    If it works the why you wrote (using a wrapper function, I see no reason why it shouldn't work when calling it directly - have you tried? Personally, I think using a wrapper Function is a good idea. – FunThomas Jan 19 '22 at 17:03
  • @FunThomas - Whenever I try with `Dim test As Boolean` and `test = IsIconic(hWndAccessApp) * -1` it gives me that `IsIconic Sub or Function is not defined` and I am not sure how to define it further than adding `Private Declare PtrSafe Function IsIconic...` inside a module. To be completely honest I agree with you, but there is not really a real case behind this. I am just playing around with functions and subs as an exercise more than anything else. – George Smith Jan 19 '22 at 17:37

1 Answers1

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.

FunThomas
  • 23,043
  • 3
  • 18
  • 34
  • Oh, I am not seeing where my mistake was. Thank you for pointing it out, I really appreciate it. In addition, I have moved away from `* - 1` and instead picked what you have suggested. Once again, thank you for the help! – George Smith Jan 19 '22 at 20:17