Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / multimedia

Open and Close CD/DVD Drive Tray

4.71/5 (5 votes)
13 Mar 2014CPOL 17K  
Illustrates a method of ejecting and closing the CD or DVD drive tray programmatically
Here's another method of doing it. This is something I had written some time ago and forgotten about. Just a code dump for now. Same disclaimer as original tip.

C++
#include <tchar.h>
#include <windows.h>
#include <Mmsystem.h>
#include <iostream>
#include <string>

using namespace std;
 
void usage();
 
int _tmain(int argc, _TCHAR* argv[])
{
    int result = 0;
    char returnString[MAX_PATH] = { 0 };
    MCIERROR mcierror = 0;
 
    if (argc == 2)
    {
        basic_string<TCHAR> command = argv[1];
        if (command == TEXT("open"))
        {
            mcierror = mciSendStringA(
                ("set cdaudio door open"), returnString,
                _countof(returnString), NULL);
        }
        else if (command == TEXT("close"))
        {
            mcierror = mciSendStringA(
                ("set cdaudio door closed"), returnString,
                _countof(returnString), NULL);
        }
        else
        {
            usage();
            result = 1;
        }
        if (mcierror != 0)
        {
            cerr << "Unable to execute command - ";
            char errorString[MAX_PATH] = { 0 };
            mciGetErrorStringA(mcierror, errorString, _countof(errorString));
            cerr << errorString;
            result = 2;
        }
    }
    else
    {
        usage();
        result = 1;
    }
    return result;
}
 
void usage()
{
    cout << "Usage: cdtray <command>\n\n";
    cout << "Commands:\n";
    cout << " open  - Opens CD drive tray\n";
    cout << " close - Closes CD drive tray\n";
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)