I was recently asked to present how to open/close a CD tray programatically using C#. The Media Control Interface (MCI) is the way to go. According to MSDN, the Media Control Interface (MCI) provides standard commands for playing multimedia devices and recording multimedia resource files. These commands are a generic interface to nearly every kind of multimedia device.”

You can interact with the MCI devices using two different command types, say, Command Messages and Command Strings. The command message addresses the MCI device using constants and structures while the command string provides a textual version of the command messages.

Using the Command Strings under .NET Framework is straight forward, since it doesn’t interact with the structures that have to be usually DllImported and/or redefined under the CLR. Therefore, I’m going to use the Command Strings to get the job done. Here’s the steps we’ve to take:

  • Open the handle to the cd-rom drive. (To make things easier, we’ll assign an alias to the cd-rom drive letter).
  • Send the Open/Close door command to the aliased cd-rom drive.
  • Close the handle to the cd-rom drive.
string drive = "g";
string openHandleCmd = string.Format("open {0}:\ type cdaudio alias cd_drive", drive);
string closeHandleCmd = "close cd_drive";
string openCmd = "set cd_drive door open";
string closeCmd = "set cd_drive door closed";

//Open the CD-ROM's door.
mciSendString(openHandleCmd, null, 0, IntPtr.Zero);
mciSendString(openCmd, null, 0, IntPtr.Zero);
mciSendString(closeHandleCmd, null, 0, IntPtr.Zero);

//Close the CD-ROM's door.
mciSendString(openHandleCmd, null, 0, IntPtr.Zero);
mciSendString(closeCmd, null, 0, IntPtr.Zero);
mciSendString(closeHandleCmd, null, 0, IntPtr.Zero);

Where drive variable indicates the g drive (the cd-rom drive). Then add the following mciSendString declaration somewhere in your class:

[DllImport("winmm.dll", EntryPoint = "mciSendStringW", CharSet = CharSet.Unicode)]
protected static extern int mciSendString(string lpstrCommand, StringBuilder lpstrReturnString, int uReturnLength, IntPtr hwndCallback);

FYI: DllImport resides in the System.Runtime.InteropServices namespace.

That’s all for now, folks!

 

3 Responses to How to open/close a CD tray programatically using C#?

  1. Anonymous says:

    Hi,
    I red many of your articles and honestly I did not find anything except some easy (sometimes childish) articles (i.e. opening a CD tray!). But I noticed that you call yourself a software architect! Do you even know WHO IS A SOFTWARE ARCHITECT?!!

    • Mehdi Mosuavi says:

      Thank you for your comments. It’s been always easy to judge books by cover.
      I’ll consider your comments for my next posts, though.

  2. Anonymous says:

    hi
    tnx for blog.

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Tweets

Rubber horse attack? Seriously? It's Rubber hose dudes! #security #fail

Sponsors