Message Box Example

Visual Studio 6.0

This topic provides a message box application that uses the @dll.import directive.

Using J/Direct to call Win32 DLLs from Java code is straightforward. The following is a short Java application that displays a message box:

class ShowMsgBox {
   public static void main(String args[])
      MessageBox(0, "It worked!",
                 "This messagebox brought to you using J/Direct", 0);
   /** @dll.import("USER32") */
   private static native int MessageBox(int hwndOwner, String text,
                                        String title, int fuStyle);

The @dll.import directive tells the compiler that the MessageBox method will link to the Win32 USER32.DLL using the J/Direct protocol rather than the Raw Native Interface (RNI) protocol supported in previous versions. In addition, the Microsoft Virtual Machine (VM) for Java provides automatic type marshaling from String objects to the null-terminated strings expected by C.

It is not necessary to indicate whether the ANSI MessageBox (MessageBoxA) function or the Unicode MessageBox function (MessageBoxW) should be called. In the above example, the ANSI version is always called. How the VM Chooses Between ANSI and Unicode explains how to use the auto modifier to call the optimal version of the function, depending on the version of Microsoft Windows that is hosting the application.