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
   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.

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: