In Windows Explorer, you can right-click on the DVD/CD Optical drive icon, select Eject to open the drive compartment door, and you may also find that there is no "close" command on the menu to turn off the optical drive. Next, let us use the program to control the open and close the optical drive.
The main work part of the program is the Cd_openclose (BOOL bopen, TCHAR cdrive) function:
The
//cdrive is the optical drive letter, or 0x01 is the default drive.
//For example:
//cd_openclosedrive (TRUE, ' g ');//Open CD drive G:
//cd_openclosedrive (FALSE, ' g ');//Turn off optical drive G:
//cd_ Openclosedrive (TRUE, 1); Open the first logical optical drive
void cd_openclosedrive (BOOL bopendrive, TCHAR cdrive)
{
Mci_open_parms op;
Mci_status_parms St;
DWORD flags;
TCHAR szdrivename[4];
strcpy (Szdrivename, "X:");
:: ZeroMemory (&op, sizeof (mci_open_parms));
Op.lpstrdevicetype = (LPCSTR) Mci_devtype_cd_audio;
if (cdrive > 1)
{
Szdrivename[0] = cdrive;
Op.lpstrelementname = Szdrivename;
Flags = Mci_open_type | mci_open_type_id | Mci_open_element| mci_open_shareable;
}
Else is flags = Mci_open_type | mci_open_type_id | mci_open_shareable;
if (!mcisendcommand 0,mci_open,flags, (unsigned long) &op)
{
St.dwitem = Mci_status_ready;
if (bopendrive)
Mcisendcommand (op.wdeviceid,mci_set,mci_set_door_open,0);
else
Mcisendcommand (op.wdeviceid,mci_set,mci_set_door_closed,0);
Mcisendcommand (op.wdeviceid,mci_close,mci_wait,0);
}
}
To facilitate operation of multiple optical drives, add the following function, which invokes the cd_openclosedrive () function above:
void CD_OpenCloseAllDrives(BOOL bOpenDrives)
{
//判定所有光驱,并逐个打开或关闭。
int nPos = 0;
UINT nCount = 0;
TCHAR szDrive[4];
strcpy(szDrive, "?:\\");
DWORD dwDriveList = ::GetLogicalDrives ();
while (dwDriveList) {
if (dwDriveList & 1)
{
szDrive[0] = 0x41 + nPos;
if(::GetDriveType(szDrive) == DRIVE_CDROM)
CD_OpenCloseDrive(bOpenDrives, szDrive[0]);
}
dwDriveList >>= 1;
nPos++;
}
}
Finally, don't forget to include the Mmsystem.h header file at the beginning of the program, and write Winmm.lib in the link options.