在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。