Opening and closing CD-Rom drive!

😀 Press the eject button buddy…

Everybody knows that! Well what I meant was to do it programmatically, using windows api’s. 😉

Here is a simple function that does this…

[sourcecode language=’cpp’]#pragma comment( lib, “winmm.lib” ) // Link to winmm.lib
#include “mmsystem.h” // Include this file

// Displays any error that has taken place
void ShowMCIError( const DWORD dwError )
{
   if( dwError )
   {
      TCHAR szErr[128] = { 0 };
      mciGetErrorString( dwError, szErr, 128 );
      MessageBox( 0, szErr, _T( “Error” ), MB_OK );
   }
}

void OpenCDRomDrive( const bool bOpenDrive )
{
   MCI_OPEN_PARMS mopParms = { 0 };
   mopParms.lpstrDeviceType = reinterpret_cast( MCI_DEVTYPE_CD_AUDIO );

// Open device
   DWORD dwErr = mciSendCommand( 0, MCI_OPEN, MCI_OPEN_TYPE | MCI_OPEN_TYPE_ID, ( DWORD ) &mopParms );
   if( dwErr )
   {
      ShowMCIError( dwErr );
      return;
   }

   // Close or open CD-Rom drives
   const DWORD dwSetFlags = ( bOpenDrive ? MCI_SET_DOOR_OPEN : MCI_SET_DOOR_CLOSED ) | MCI_WAIT;

   // Close/Open CD ROM Drive
   dwErr = mciSendCommand( mopParms.wDeviceID, MCI_SET, dwSetFlags, 0 );
   if( dwErr )
   {
      ShowMCIError( dwErr );
      return;
   }

// Close open device
   dwErr = mciSendCommand( mopParms.wDeviceID, MCI_CLOSE, MCI_WAIT, 0 );
   if( dwErr )
   {
      ShowMCIError( dwErr );
      return;
   }
}// End OpenCDRomDrive

int _tmain()
{
   OpenCDRomDrive( true ); // Open
   OpenCDRomDrive( false ); // Close
return 0;
}[/sourcecode]

One thought on “Opening and closing CD-Rom drive!

Appreciate your comments...