Opening and Closing a CD Tray (Views: 100)
How can I open and close the tray on a CD-ROM drive?
Most of you are probably familiar with the TMediaPlayer component. It's a nice multi-purpose component for multimedia. But it has one failing and that is its inability to close a CD-ROM drive tray if it's open. And unfortunately for us, there's no way to manipulate methods or properties of TMediaPlayer to enable this functionality. So what we have to do is use the Windows API; in particular, we'll be using the MMSystem.pas file.
One thing to note: We can use Windows API function calls solely, but TMediaPlayer does some internal handling that we don't need to worry about if we employ the component. So this example makes use of the TMediaPlayer.
Just follow these steps:
Start a new project and drop a TMediaPlayer and a TButton on it.
Add a "MMSystem" declaration to the uses statement of your form.
Set AutoOpen to True on the TMediaPlayer. Set the DeviceType property to dtCDAudio. You might want to consider disabling the btEject option from EnabledButtons property since we'll be handling that functionality in code.
One thing I use this for is for data CD's in some applications, so I also set the Visible property to False and just let my button do the opening and closing of the tray.
Finally, add the following code to the button's OnClick event:
procedure TForm1.Button2Click(Sender: TObject);
with MediaPlayer1 do
if (MediaPlayer1.Mode = mpOpen) then
mciSendCommand(MediaPlayer1.DeviceID, MCI_SET, MCI_SET_DOOR_CLOSED, 0)
mciSendCommand(MediaPlayer1.DeviceID, MCI_SET, MCI_SET_DOOR_OPEN, 0);
Notice we use the function mciSendCommand. This is the "Swiss Army Knife" of the MMSystem unit. In Windows, everything's controlled by messages. With respect to device control, mciSendCommand is very similar to a window's WndProc in that it acts as a message dipatcher. Just supply the device, the message type, message flags, and message parameters, and you're on your way. For more detailed information, I suggest you look in the help file.
<< Back to main page