Click here to Skip to main content
15,889,834 members
Articles / Desktop Programming / MFC

Open or Close a CD/DVD Drive Drawer

Rate me:
Please Sign up or sign in to vote.
4.84/5 (15 votes)
27 Mar 20071 min read 84K   1.3K   31  
Provides a sample project with code to open and/or close a CD or DVD drive drawer.
// OpenCloseCDDlg.cpp : implementation file
//

#include "stdafx.h"
#include "OpenCloseCD.h"
#include "OpenCloseCDDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// COpenCloseCDDlg dialog




COpenCloseCDDlg::COpenCloseCDDlg(CWnd* pParent /*=NULL*/)
	: CDialog(COpenCloseCDDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void COpenCloseCDDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_DRIVELIST, m_cDriveList);
}

BEGIN_MESSAGE_MAP(COpenCloseCDDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_OPEN, &COpenCloseCDDlg::OnBnClickedOpen)
	ON_BN_CLICKED(IDC_CLOSE, &COpenCloseCDDlg::OnBnClickedClose)
	ON_CBN_SELCHANGE(IDC_DRIVELIST, &COpenCloseCDDlg::OnCbnSelchangeDrivelist)
END_MESSAGE_MAP()


// COpenCloseCDDlg message handlers

BOOL COpenCloseCDDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty()) {
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// Fill the combo box with CDROM type drives.
	PopulateDriveList();
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void COpenCloseCDDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX) {
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void COpenCloseCDDlg::OnPaint()
{
	if (IsIconic()) {
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
		CDialog::OnPaint();
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR COpenCloseCDDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

// 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;
}

bool COpenCloseCDDlg::PopulateDriveList()
{
	m_cDriveList.ResetContent();

	TCHAR szDriveRoot[] = _T("x:\\");
	TCHAR cDrive;
	UINT nDriveType;
	UINT nFlags = SHGFI_DISPLAYNAME;

	DWORD nSystemDrives = GetLogicalDrives();

    // Let the use know if they don't have any drives.
	ASSERT(nSystemDrives != 0);

	// Loop through all the drives and look for CD-ROM
	for(cDrive = 'A'; cDrive <= 'Z'; cDrive++, nSystemDrives >>= 1) {
        if(!(nSystemDrives & 1))
            continue;

		// See if this is one of the drives we're looking for and add it to the combo.
		szDriveRoot[0] = cDrive;
		nDriveType = GetDriveType(szDriveRoot);

		if(nDriveType == DRIVE_CDROM) {
			// Looks like "CD Drive (D:)"
			CString cs;
			cs.Format(_T("CD/DVD ROM Drive (%c:)"),szDriveRoot[0]);
			m_cDriveList.AddString(cs);
			// Store away the drive letter so we can retrieve it later if the user
			// selects this drive.
			m_cDriveList.SetItemData(m_cDriveList.GetCount()-1,szDriveRoot[0]);
        }
	}

	// Did we add any entries?  If not, flag that we have
	// no usable drives.
	if(m_cDriveList.GetCount() >= 1) {
		m_cDriveList.SetCurSel(0);
		m_cCurrentDrive = (TCHAR)m_cDriveList.GetItemData(0);
	}
	else
		return false;
	return true;
}

void COpenCloseCDDlg::OnBnClickedOpen()
{
	CWaitCursor wc;
	OpenCloseTray(true,m_cCurrentDrive);
}

void COpenCloseCDDlg::OnBnClickedClose()
{
	CWaitCursor wc;
	OpenCloseTray(false,m_cCurrentDrive);
}

void COpenCloseCDDlg::OnCbnSelchangeDrivelist()
{
	m_cCurrentDrive = (TCHAR)m_cDriveList.GetItemData(m_cDriveList.GetCurSel());
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
United States United States
I have been using VC++ with MFC since it first came out circa 1993 and I saw it demonstrated at a local Software Development show. I've been working for Rimage Corporation for around 23 years developing software to make our CD and DVD publishing hardware work.

When I'm not working I enjoy hanging out with my family, playing guitar, traveling, and taking my dogs for walks. My family enjoys watching Survivor on Thursday nights and we're not even embarassed by it.

Comments and Discussions