Invoking a Function that Takes a Callback

To invoke a function that takes a callback, you need to define a class that extends Callback. The derived class must expose one non-static method whose name is callback (all lowercase). The C language definition of WNDENUMPROC is:

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lparam);

To author an EnumWindowsProc in Java, you declare a class that extends Callback as follows:

class EnumWindowsProc extends Callback
  {
    public boolean callback(int hwnd, int lparam)
    {
      StringBuffer text = new StringBuffer(50);
      GetWindowText(hwnd, text, text.capacity()+1);
         
      if (text.length() != 0) {
        System.out.println("hwnd = " + Integer.toHexString(hwnd) +
                           "h: Text = " + text);
      } 
      return true;  // return TRUE to continue enumeration.
    }
  
  /** @dll.import("USER32") */
  private static native int GetWindowText(int hwnd, StringBuffer text, 
                                          int cch);
  }

You can invoke EnumWindows with this Callback in the following way:

boolean result = EnumWindows(new EnumWindowsProc(), 0);