4

I'm trying to open and close the CD tray of my computer using a piece of code. I have been using MCI commands and have included winmm.lib in the additional dependencies of my project configuration. I've included windows.h and mmsystem.h as well.

The code I'm using is as follows:

mciSendCommand(0, MCI_SET, MCI_SET_DOOR_OPEN, NULL);
mciSendCommand(1, MCI_SET, MCI_SET_DOOR_CLOSED, NULL);

The code builds and runs fine, there's just no CD tray action going on! Can anyone suggest how I need to adapt this?

Dmitry Sazonov
  • 8,801
  • 1
  • 35
  • 61
user3332704
  • 41
  • 2
  • 3

3 Answers3

6

If you have multiple CD-Drives you should use the following code:

#include <windows.h>  
#include <tchar.h>  
#include <stdio.h>  

int _tmain() 
{ 
   DWORD dwBytes; 
   HANDLE hCdRom = CreateFile(_T("\\\\.\\M:"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); 
   if (hCdRom == INVALID_HANDLE_VALUE) 
   { 
     _tprintf(_T("Error: %x"), GetLastError()); 
     return 1; 
   } 

   // Open the door:  
   DeviceIoControl(hCdRom, IOCTL_STORAGE_EJECT_MEDIA, NULL, 0, NULL, 0, &dwBytes, NULL); 

   Sleep(1000); 

   // Close the door:  
   DeviceIoControl(hCdRom, IOCTL_STORAGE_LOAD_MEDIA, NULL, 0, NULL, 0, &dwBytes, NULL); 

   CloseHandle(hCdRom); 
} 
Jochen Kalmbach
  • 3,549
  • 17
  • 18
4

You are missing some steps, first you need to open the device.

Try this:

#pragma comment( lib, "winmm.lib" )

#include "stdafx.h"
#include <Windows.h>
#include <mmsystem.h>


int _tmain()
{

    MCI_OPEN_PARMS mPar = { 0 };
    mPar.lpstrDeviceType = reinterpret_cast<LPCWSTR>(MCI_DEVTYPE_CD_AUDIO);

    // Open device
    mciSendCommand(0, MCI_OPEN, MCI_OPEN_TYPE | MCI_OPEN_TYPE_ID, (DWORD)&mPar);

    // Open tray
    mciSendCommand(mPar.wDeviceID, MCI_SET, MCI_SET_DOOR_OPEN, 0);

    // Close tray
    mciSendCommand(mPar.wDeviceID, MCI_SET, MCI_SET_DOOR_CLOSED, 0);

    // Close device
    mciSendCommand(mPar.wDeviceID, MCI_CLOSE, MCI_WAIT, 0);

    return 0;
}
Edgar
  • 1,097
  • 1
  • 15
  • 25
2

Try using DevC++ IDE (WINDOWS ONLY)

Then follow steps:

Step 1: File > Project > Console Application << Enter

Step 2: Project Options > Parameters > Linker > write "-lWinmm" in Linker << Enter

Step 3: Open cdtray Copy and paste this small code in your IDE. I recommend DevC++ for this one..

#include<windows.h>
int main(){
mciSendString("set cdaudio door open",0,0,0);
}

Step 4: Close tray, Just change door 'open' to 'closed'

 mciSendString("set cdaudio door closed",0,0,0);
Subha Jeet Sikdar
  • 446
  • 1
  • 4
  • 15