9

I want to create a small program in C# in Windows that would open the CD drive tongue - eject the CD if there is one. I'd like to know where to start with this.

Subha Jeet Sikdar
  • 446
  • 1
  • 4
  • 15
Matti
  • 93
  • 1
  • 1
  • 3

1 Answers1

19

Opening and closing a disk drive programmatically in C# is not all that difficult thanks to a useful API function called mciSendStringA.

First you will need to define the function that will be opening the disk tray:

[DllImport("winmm.dll", EntryPoint = "mciSendString")]
public static extern int mciSendStringA(string lpstrCommand, string lpstrReturnString, 
                            int uReturnLength, int hwndCallback);

If the code above does not compile try adding the following C# line at the very top of your source code:

using System.Runtime.InteropServices;

Opening the Disk Drive

To open the disk drive you need to send two command strings using mciSendStringA. The first one will assign a name to the desired drive. The second command will actually open the disk tray:

mciSendStringA("open " + driveLetter + ": type CDaudio alias drive" + driveLetter, 
                 returnString, 0, 0);
mciSendStringA("set drive" + driveLetter + " door open", returnString, 0, 0);

Closing the Disk Drive

To close the disk drive you need to send two command strings once again. The first one will be the same. The second command will now close the disk tray:

mciSendStringA("open " + driveLetter + ": type CDaudio alias drive" + driveLetter, 
                 returnString, 0, 0);
mciSendStringA("set drive" + driveLetter + " door closed", returnString, 0, 0);
Vaibhav
  • 6,620
  • 11
  • 47
  • 72
  • 3
    Thanks a lot, I was interested in learning more of these API's. Do you know good tutorials? – Matti Sep 26 '10 at 10:41