DriveEject

Ejects or retracts the tray of the specified CD/DVD drive.

DriveEject Drive, Retract := false

Parameters

Drive

Type: String

The drive letter followed by a colon and an optional backslash (might also work on UNC paths and mapped drives). If omitted, the default CD/DVD drive will be used.

Retract

Type: Integer (boolean)

Specify 1 (true) to retract/close the tray. Specify 0 (false) or omit this parameter to eject/open the tray.

Error Handling

An exception is thrown on failure, if detected.

Remarks

This function waits for the ejection or retraction to complete before allowing the script to continue.

This function will probably not work on a network drive or non-CD/DVD drive. If it fails in such cases or for any other reason, an exception is thrown. To eject other types of media or devices, see the DllCall example at the bottom of this page.

It may be possible to detect the previous tray state by measuring the time the function takes to complete. For example, the following hotkey toggles the tray to the opposite state (open or closed):

#c::
{
    DriveEject()
    ; If the function completed quickly, the tray was probably already ejected.
    ; In that case, retract it:
    if (A_TimeSinceThisHotkey < 1000)  ; Adjust this time if needed.
        DriveEject(, true)
}

Related

DriveGetStatusCD, Drive functions

Examples

#1: Retracts (closes) the tray of the default CD/DVD drive:

DriveEject(, true)

#2: This is an alternate ejection method that also works on types of media/devices other than CD/DVD. Update the first line below to match the desired drive letter (you can ignore all the other lines below):

DriveLetter := "I:"  ; Set this to the drive letter you wish to eject.

hVolume := DllCall("CreateFile"
    , "Str", "\\.\" . DriveLetter
    , "UInt", 0x80000000 | 0x40000000  ; GENERIC_READ | GENERIC_WRITE
    , "UInt", 0x1 | 0x2  ; FILE_SHARE_READ | FILE_SHARE_WRITE
    , "UInt", 0
    , "UInt", 0x3  ; OPEN_EXISTING
    , "UInt", 0, "UInt", 0)
if (hVolume != -1)
{
    DllCall("DeviceIoControl"
        , "UInt", hVolume
        , "UInt", 0x2D4808   ; IOCTL_STORAGE_EJECT_MEDIA
        , "UInt", 0, "UInt", 0, "UInt", 0, "UInt", 0
        , "UIntP", dwBytesReturned := 0  ; Unused.
        , "UInt", 0)
    DllCall("CloseHandle", "UInt", hVolume)
}