在Windows资源浏览器中,可在DVD/CD光驱图标上单击鼠标右键,选择"弹出"来打开光驱仓门,你可能也发现了,菜单中并没有"关闭"命令来关闭光驱。下面,就让我们用程序来控制打开、关闭光驱。
程序的主要工作部分为CD_OpenClose(BOOL bOpen, TCHAR cDrive)函数:
1 //cDrive是光驱盘符,或者0x01为默认驱动器。
2 //例如:
3 //CD_OpenCloseDrive(TRUE, 'G'); //打开光驱G:
4 //CD_OpenCloseDrive(FALSE, 'G'); //关闭光驱G:
5 //CD_OpenCloseDrive(TRUE, 1); //打开第一个逻辑光驱
6
7 void CD_OpenCloseDrive(BOOL bOpenDrive, TCHAR cDrive)
8 {
9 MCI_OPEN_PARMS op;
10 MCI_STATUS_PARMS st;
11 DWORD flags;
12
13 TCHAR szDriveName[4];
14 strcpy(szDriveName, "X:");
15
16 ::ZeroMemory(&op, sizeof(MCI_OPEN_PARMS));
17 op.lpstrDeviceType = (LPCSTR) MCI_DEVTYPE_CD_AUDIO;
18
19 if(cDrive > 1)
20 {
21 szDriveName[0] = cDrive;
22 op.lpstrElementName = szDriveName;
23 flags = MCI_OPEN_TYPE | MCI_OPEN_TYPE_ID | MCI_OPEN_ELEMENT| MCI_OPEN_SHAREABLE;
24 }
25 else flags = MCI_OPEN_TYPE | MCI_OPEN_TYPE_ID | MCI_OPEN_SHAREABLE;
26
27 if (!mciSendCommand(0,MCI_OPEN,flags,(unsigned long)&op))
28 {
29 st.dwItem = MCI_STATUS_READY;
30
31 if(bOpenDrive)
32 mciSendCommand(op.wDeviceID,MCI_SET,MCI_SET_DOOR_OPEN,0);
33 else
34 mciSendCommand(op.wDeviceID,MCI_SET,MCI_SET_DOOR_CLOSED,0);
35
36 mciSendCommand(op.wDeviceID,MCI_CLOSE,MCI_WAIT,0);
37 }
38 }
为了方便对多个光驱进行操作,添加了下面这个函数,其会调用上面的CD_OpenCloseDrive()函数:
1 void CD_OpenCloseAllDrives(BOOL bOpenDrives)
2 {
3 //判定所有光驱,并逐个打开或关闭。
4 int nPos = 0;
5 UINT nCount = 0;
6 TCHAR szDrive[4];
7 strcpy(szDrive, "?:");
8
9 DWORD dwDriveList = ::GetLogicalDrives ();
10
11 while (dwDriveList) {
12 if (dwDriveList & 1)
13 {
14 szDrive[0] = 0x41 + nPos;
15 if(::GetDriveType(szDrive) == DRIVE_CDROM)
16 CD_OpenCloseDrive(bOpenDrives, szDrive[0]);
17 }
18 dwDriveList >>= 1;
19 nPos++;
20 }
21 }
最后一点,别忘了在程序开头包括Mmsystem.h头文件,及在链接选项里写上Winmm.lib。