How To Open/Close CD Tray

November 7, 2008

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
   HANDLE hDrive = INVALID_HANDLE_VALUE;      
   hDrive = CreateFile(Drive.c_str(), GENERIC_READ, 
                       FILE_SHARE_READ | FILE_SHARE_WRITE, 
                       NULL, OPEN_EXISTING, 
                       FILE_ATTRIBUTE_NORMAL, 
                       NULL);

   // 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);
      }
      else
      {
         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.