22/10: Ejecting the CD Using Code
Category: Programming
Posted by: admin
There is a simple and easy way to open/close the CD/DVD in Windows. The code I will be writing is a C++ code. It uses a simple API function implemented in winmm.dll (The windows MCI API DLL). In order to achieve our goal, we are going to use the mciSendCommand function.
First you need to include mmsystem.h in your code and you also need to link with Winmm.lib
Next we need to open the CD/DVD device. We do this using the following:
MCI_OPEN_PARMS MCIopen;
ZeroMemory(&MCIopen, sizeof(MCI_OPEN_PARMS));
MCIopen.lpstrDeviceType = (LPCSTR) MCI_DEVTYPE_CD_AUDIO;
MCIopen.lpstrElementName = drive;
DWORD flags = MCI_OPEN_TYPE | MCI_OPEN_TYPE_ID;
mciSendCommand(0, MCI_OPEN, flags, (DWORD) &MCIopen);
the drive is a char * of the drive letter to open for example d:
Issuing this command open the CD/DVD device and returns the device ID in the MCIopen variable. Yhis ID is to be used in later commands.
Now to issue open request, we write the following:
mciSendCommand(MCIopen.wDeviceID, MCI_SET, MCI_SET_DOOR_OPEN, 0); // To open the devic
mciSendCommand(MCIopen.wDeviceID, MCI_SET, MCI_SET_DOOR_CLOSED, 0); // To close the devic
Finally, we should close the device using this following:
mciSendCommand(MCIopen.wDeviceID, MCI_CLOSE, MCI_WAIT, 0);
One thing to note that we should check if the command issued to open the device succeeded by checking the return of the first mciSendCommand call. If the command returned an error, we can't continue with opening/closing the drive.
First you need to include mmsystem.h in your code and you also need to link with Winmm.lib
Next we need to open the CD/DVD device. We do this using the following:
MCI_OPEN_PARMS MCIopen;
ZeroMemory(&MCIopen, sizeof(MCI_OPEN_PARMS));
MCIopen.lpstrDeviceType = (LPCSTR) MCI_DEVTYPE_CD_AUDIO;
MCIopen.lpstrElementName = drive;
DWORD flags = MCI_OPEN_TYPE | MCI_OPEN_TYPE_ID;
mciSendCommand(0, MCI_OPEN, flags, (DWORD) &MCIopen);
the drive is a char * of the drive letter to open for example d:
Issuing this command open the CD/DVD device and returns the device ID in the MCIopen variable. Yhis ID is to be used in later commands.
Now to issue open request, we write the following:
mciSendCommand(MCIopen.wDeviceID, MCI_SET, MCI_SET_DOOR_OPEN, 0); // To open the devic
mciSendCommand(MCIopen.wDeviceID, MCI_SET, MCI_SET_DOOR_CLOSED, 0); // To close the devic
Finally, we should close the device using this following:
mciSendCommand(MCIopen.wDeviceID, MCI_CLOSE, MCI_WAIT, 0);
One thing to note that we should check if the command issued to open the device succeeded by checking the return of the first mciSendCommand call. If the command returned an error, we can't continue with opening/closing the drive.