在Windows資源總管中,可在DVD/CD光碟機表徵圖上單擊滑鼠右鍵,選擇"彈出"來開啟光碟機倉門,你可能也發現了,菜單中並沒有"關閉"命令來關閉光碟機。下面,就讓我們用程式來控制開啟、關閉光碟機。
程式的主要工作部分為CD_OpenClose(BOOL bOpen, TCHAR cDrive)函數:
//cDrive是光碟機盤符,或者0x01為預設磁碟機。
//例如:
//CD_OpenCloseDrive(TRUE, 'G'); //開啟光碟機G:
//CD_OpenCloseDrive(FALSE, 'G'); //關閉光碟機G:
//CD_OpenCloseDrive(TRUE, 1); //開啟第一個邏輯光碟機
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 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);
}
}
為了方便對多個光碟機進行操作,添加了下面這個函數,其會調用上面的CD_OpenCloseDrive()函數:
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++;
}
}
最後一點,別忘了在程式開頭包括Mmsystem.h標頭檔,及在連結選項裡寫上Winmm.lib。