How To Open/Close CD Tray

Using VC++, it is quite simple. We can treat cd drive as an IO file using the windows API CreateFile(). Then we cann eject or retract using the function DeviceIoControl(). The following program illustrates this.

#include "wtypes.h"
#include "winioctl.h"
#include <string>
using namespace std;

// DriveName specifies the cd drive name (as string, eg: "D")
// Open specifies whether to open or close drive
bool OpenCloseDoor(const string& DriveName, const bool Open)
   // Make drive name in the format "\\.\D:" where D is the cd drive
   const string Drive = string("\\\\.\\") + DriveName + string(":");
   // Treat cd drive as an IO device file
   hDrive = CreateFile(Drive.c_str(), GENERIC_READ, 
                       FILE_SHARE_READ | FILE_SHARE_WRITE, 
                       NULL, OPEN_EXISTING, 

   // Open or close as needed                 
   BOOL bRetVal = FALSE;
   if ((hDrive != INVALID_HANDLE_VALUE) && (NO_ERROR == GetLastError()))
      DWORD dwDummy = 0;
      if (Open)
         bRetVal = DeviceIoControl(hDrive, IOCTL_STORAGE_EJECT_MEDIA, 
                                   NULL, 0, NULL, 0, &dwDummy, NULL);
         bRetVal = DeviceIoControl(hDrive, IOCTL_STORAGE_LOAD_MEDIA, 
                                   NULL, 0, NULL, 0, &dwDummy, NULL);
   return (!!bRetVal);  // To avoid performance warning                      

int main()
   OpenCloseDoor("D", true);  //D is my cd drive   
   OpenCloseDoor("D", false);
   return 0;

Click to see how to get CD drives in a system.


One Response to How To Open/Close CD Tray

  1. […] To Get All CD Drives In the last post, I described how to open/close cd tray. Some of you might have raised your eye brows as there is no description how to find the drive […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: