Skip to Main Content

Java HotSpot Virtual Machine

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Open CD tray using JNA in Java

843829Jun 5 2008 — edited Aug 7 2008
I know this is about JNA and not JNI, but I couldn't find a better forum to place this. And since JNA builds upon JNI, I thought I would give it a try here.
I was looking for a while to figure out how to open the CD tray using Java on Windows. After a while I came up with this solution:

1. Download the jna library (jna.rar) from [https://jna.dev.java.net/|https://jna.dev.java.net/]
2. Add this to your project (in NetBeans right click the Libraries folder in the Project view and click Add JAR/Folder, then locate the jna.jar file and add this).
3. Then, make a new Java class and name it WinMM.java, and add the following code to that file
import com.sun.jna.Library;
import com.sun.jna.Native;

interface WinMM extends Library { /* We'll make a new library */

    WinMM INSTANCE = (WinMM) Native.loadLibrary(("winmm"), WinMM.class); //Create the library from the winmm.dll file
    long mciSendStringA(String lpstrCommand, String lpstrReturnString, long uReturnLength, long hwndCallback); //Create the function we need to use to open the CD tray
}
4. Now you can add the following code into a button event in another class in your app to open the CD tray:
WinMM.INSTANCE.mciSendStringA("set CDAudio door open", null, 0, 0);
5. Or to close the tray:
WinMM.INSTANCE.mciSendStringA("set CDAudio door closed", null, 0, 0);
6. A simple app, which opens and closes the CD tray, would look like this:
public class Main {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    WinMM.INSTANCE.mciSendStringA("set CDAudio door open", null, 0, 0); //Open tray
    WinMM.INSTANCE.mciSendStringA("set CDAudio door closed", null, 0, 0); //Close tray
    }
}
I hope this will save someone some hours of googling. And if you really don't want to use JNA, there is a solution in [this thread|http://forum.java.sun.com/thread.jspa?threadID=566946&messageID=4103195] which might work just as well. I haven't tested it though.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 4 2008
Added on Jun 5 2008
1 comment
685 views