Opening and Closing the CD-ROM Drive
Sometimes it is necessary to open or close a CD-ROM drive by its drive letter. This can be done using MCI, namely the mciExecute
API function. The class CDDoorController
provides a wrapper around this function that can be used to set the status of a CD-ROM drive’s door. The drive type of the drive to be opened or closed is checked and an exception is thrown if it is not a CD-ROM drive:
Public Enum CDDoorStatus
Open
Closed
End Enum
Public Class CDDoorController
' Undocumented, seems to be a relict from 16-bit Windows times.
' 'mciSendString' can be used instead, but requires more code.
Private Declare Function mciExecute Lib "winmm.dll" ( _
ByVal lpstrCommand As String _
) As Int32
Private Declare Auto Function GetDriveType Lib "kernel32.dll" ( _
ByVal nDrive As String _
) As DRIVE_TYPE
Private Enum DRIVE_TYPE As Int32
DRIVE_CDROM = 5
DRIVE_FIXED = 3
DRIVE_NO_ROOT_DIR = 1
DRIVE_RAMDISK = 6
DRIVE_REMOTE = 4
DRIVE_REMOVABLE = 2
DRIVE_UNKNOWN = 0
End Enum
Public Shared Sub SetDoorStatus( _
ByVal Drive As String, _
ByVal DoorStatus As CDDoorStatus _
)
If Len(Drive) <> 2 AndAlso Right(Drive, 1) <> ":" Then
Throw _
New ArgumentException( _
"The value of the parameter 'Drive' must be a " & _
"string of length two consisting of the drive " & _
"letter followed by a colon ("":"")." _
)
End If
If GetDriveType(Drive & "\") <> DRIVE_TYPE.DRIVE_CDROM Then
Throw _
New ArgumentException( _
"Drive """ & Drive & """ is not a CD-ROM drive." _
)
End If
Dim ID As String = "cd_drive_" & Drive
mciExecute("open " & Drive & ": alias " & ID & " type cdaudio")
mciExecute( _
"set " & ID & " door " & _
CStr(IIf(DoorStatus = CDDoorStatus.Open, "open", "closed")) _
)
mciExecute("close " & ID)
End Sub
End Class
Usage:
CDDoorController.SetDoorStatus("D:", CDDoorStatus.Open)
⋮
CDDoorController.SetDoorStatus("D:", CDDoorStatus.Closed)