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); }
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); }
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);