How To Open and Close CD/DVD Drives Via Software

Environment: VS6, Win9x, NT, 2000, XP, ME

This project was created for use as a testbed of what methods to use while inserting and ejecting a CD via software. Through trial and error, along with quite a bit of help from CodeGuru, we managed to develop this little app and decided to share it with others.

NOTE: This program has been tested on Win9x, NT4, 2000, XP, ME, but there is no guarantee it will work for you. I am not a professional, and as an amateur, chances are that the application has errors. I've done the best I could to weed them out, but I am definitely open to any and all suggestions. Please e-mail me if you have problems with the program, as I would love to get it running correctly.

The program is designed to be used as follows:

Enter a CD/DVD drive letter in the textbox. Select a command to perform (either insert or eject). Click the Go button and voila! The drive magically does just what it is commanded to do. If there is a CD in the tray when the drive is inserted, a check box will appear in the "CD Present" checkbox. If there is no CD available, the box remains unchecked. Currently, the app does not check for a CD when the program is started.

On systems where there is only one CD/DVD drive, no letter needs to be entered. One can just select an action and then click go. For multi-drive systems, a particular letter can be specified, and the appropriate drive will respond.

Note that there is very little error checking involved. Eg: if an invalid drive letter is specified, there is no response from the program; it will just wait for your next entry.

Also included in the program are some samples of how to create functional colored hyperlinks quickly and easily. For more details on that subject, take a look at this post on CodeGuru by us.

Here are a few snippets of code:

BOOL CCdejectDlg::OnDeviceChange( UINT nEventType, DWORD dwData )
{
  if (nEventType == DBT_DEVICEARRIVAL)
  {
    m_Present = TRUE;
    UpdateData (FALSE);
    MCIDEVICEID mciID;
    mciID = mciGetDeviceID (CD_AUDIO);
  }

  return TRUE;
}

if (!mciSendCommand(0,MCI_OPEN,flags,(unsigned long)&op)) 
{
  st.dwItem = MCI_STATUS_READY;
  if(bOpenDrive)  // decides whether to open or close
  {
    // open drive
    mciSendCommand(op.wDeviceID,MCI_SET,MCI_SET_DOOR_OPEN,0);
  }
  else
  {
    // close drive
    mciSendCommand(op.wDeviceID,MCI_SET,MCI_SET_DOOR_CLOSED,0);
  }
  // release access to the device
  mciSendCommand(op.wDeviceID,MCI_CLOSE,MCI_WAIT,0);
}

Downloads

Download demo project - 21 Kb
Download source - 9 Kb