Open or Close a CD/DVD Drive Drawer






4.84/5 (15 votes)
Mar 27, 2007
1 min read

85064

1346
Provides a sample project with code to open and/or close a CD or DVD drive drawer.
Introduction
This project demonstrates how to open and close a CD or DVD drive drawer. It also works on the new Blu-ray drive I got recently.
Background
I needed a way to open and/or close a drive drawer without regard to whether or not the drawer was already open or closed. This sounds easy, but most of the ways of doing this I tried (like using the MCI library) and I had problems determining whether or not the drawer was open or closed. Using this code, I just tell it what I want it to do. If it's already open, it stays open; if it's closed, it stays closed.
Using the code
There is nothing fancy in this code. Users can simply cut and paste the code needed from this sample into their own projects. This uses a fairly simple IOCTL call. Note: the function returns whether or not the call worked, but this is not necessarily the result the caller intended. For example, most notebook computers will report that a drive is closed, but the drive must be closed manually. Programmers can get around this by detecting that the disc is not ready in the drive.
// Opens or closes the CD or DVD drive specified in drive letter. bool COpenCloseCDDlg::OpenCloseTray(bool bOpen, TCHAR cDrive) { // Open the device (drive) that we want to affect CString cs; cs.Format(_T("\\\\.\\%c:"),cDrive); HANDLE hDrive = CreateFile(cs, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); // Make sure the device was found and opened successfully if(hDrive == INVALID_HANDLE_VALUE || GetLastError() != NO_ERROR) return false; BOOL bStatus; // Let the caller know if it worked or not DWORD dwDummy; // We don't really need this info if(bOpen) // Open the tray bStatus = DeviceIoControl(hDrive, IOCTL_STORAGE_EJECT_MEDIA, NULL, 0, NULL, 0, &dwDummy, NULL); else // Close the tray bStatus = DeviceIoControl(hDrive, IOCTL_STORAGE_LOAD_MEDIA, NULL, 0, NULL, 0, &dwDummy, NULL); CloseHandle(hDrive); return bStatus?true:false; }
History
- Version 1.0 - March 28, 2007