Real'sHowTo AddThis Feed Button
Custom Search

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.
import com.ms.dll.DllLib;

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 {
   System.out.println("Done.");
   }
  // keep the console open...
  try {System.in.read();}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:

import com.ms.security.*;
...
PolicyEngine.assertPermission(PermissionID.SYSTEM);
Thanks to H. Parvillers for the tip.
blog comments powered by Disqus


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2014
[ home ]