Call a Win API (this howto is deprecated)Tag(s): DEPRECATED

Use the @dll.import directive. This is allowed only in Application. In the following example, we are calling the API to detect the currect user name.
public class TestWinAPI {
  public static void main (String[] args)   {
    // Give us some room,
    //   let's say 128 characters (MAX 127 + '\0').
    long[] buffer =  { 128 } ;
    StringBuffer username= new StringBuffer((int)buffer[0]);
    GetUserNameA(username, buffer);
    System.out.println("UserName: " + username);
    MessageBox(0, "UserName : " + username,  "Box issued from Java", 0);
    // IO.PressAnyKey();

  /** @dll.import("ADVAPI32") */
  static native void GetUserNameA
   (StringBuffer userName, long buffer[]);
  // string by ref are passed with a StringBuffer
  // basic scalar type by ref are passed via an array

  /** @dll.import("USER32") */
  private static native int  MessageBox
    (int hwndOwner, String text,String title, int fuStyle);
If an error is returned by the Win32 API called, you can't get the actual error code by calling the standard getLastError() Win32 API. You must use the special keyword setLastError in the @dll.import directive to instruct the JVM to keep the error code. Then you retrieve the error code by calling the getLastWin32Error() method from the DllLib class.

public class TestChangeDirectory {
 public static void main (String[] args) {
  boolean rc;
  // for demonstration
  // we specify a non-existent directory, to get an error code...
  StringBuffer newdir = new StringBuffer("Unknown directory");
  rc = SetCurrentDirectoryA(newdir);
  if (!rc) {
   int err = DllLib.getLastWin32Error();
   // should be rc : 2  "ERROR_FILE_NOT_FOUND"
   System.out.println("rc : " + err);
   // you may want to throw an exception here...
  else {
  // keep the console open...
  try {;}catch(Exception e){}

/** @dll.import("KERNEL32",setLastError) */
 static native boolean SetCurrentDirectoryA(StringBuffer newdir);
NOTE: The example above call the Win32 API to change the current direcotry but you should note that you don't really need to do that. Simply call the static method setCurrentDirectory() from the File class instead...

To be able to do the same in Applet, you need to sign the Applet then make the following call before making API calls:

Thanks to H. Parvillers for the tip.
blog comments powered by Disqus