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 CDDrive 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 Class CDDrive

    ' 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

    Private Enum CDDoorStatus
        Open
        Closed
    End Enum

    Public Shared Sub OpenDoor(ByVal Drive As String)
        SetDoorStatus(Drive, DoorStatus.Open)
    End Sub

    Public Shared Sub CloseDoor(ByVal Drive As String)
        SetDoorStatus(Drive, DoorStatus.Closed)
    End Sub

    Private 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:

CDDrive.OpenDoor("D:") 
⋮
CDDrive.CloseDoor("D:")