Click here to Skip to main content
15,885,546 members
Articles / Programming Languages / C#

Open and Close CD drive in C#

Rate me:
Please Sign up or sign in to vote.
2.63/5 (10 votes)
24 Jan 2005CPOL 77.5K   2.4K   21   4
An article on how to open and close the CD drive from your C# program.

Sample Image - Not really nessesary

Introduction

I was looking for code in C# to open/close the CD drive so I could make a funny program that when run would open the CD drive every five minutes and play with it "Another cup holder for your tea governor?". Yea, anyways, to my surprise, I couldn't find it.

Background

To continue my story, I was searching the net and I found a simple code in VB. Well, I don't know VB, but I do know some other languages, and to my surprise, I was actually able to translate it.

Using the Code

Well, first you have to import a DLL and a variable for the return status.

C#
[DllImport("winmm.dll", EntryPoint="mciSendStringA")]
public static extern void mciSendStringA(string lpstrCommand, 
       string lpstrReturnString, long uReturnLength, long hwndCallback);

string rt = "";

Now, all you have to do is call it like this to open/ close the CD drive:

C#
mciSendStringA("set CDAudio door open",rt,127,0);

mciSendStringA("set CDAudio door closed",rt,127,0);

Points of Interest

It's pretty short. I'm pretty happy with the results of that British joke!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalmore then one CD drive ... Pin
Anonymous24-Jan-05 4:24
Anonymous24-Jan-05 4:24 
GeneralRe: more then one CD drive ... Pin
mav.northwind24-Jan-05 6:27
mav.northwind24-Jan-05 6:27 
GeneralIncorrect mciSendStringA declaration Pin
mav.northwind24-Jan-05 1:23
mav.northwind24-Jan-05 1:23 
Hi!
Your P/invoke declaration is wrong. Although it might not be an immediate problem for just opening or shutting the CD door, someone trying to use your declaration to send more advanced MCI commands will fail.

Try this instead:
[DllImport("winmm.dll")]<br />
public static extern UInt32 mciSendString(string lpstrCommand, <br />
       StringBuilder lpstrReturnString, UInt32 uReturnLength, IntPtr hwndCallback);


long in .NET is 64 bit, not 32 like UINT.

mav
GeneralRe: Incorrect mciSendStringA declaration Pin
Uwe Keim24-Jan-05 5:56
sitebuilderUwe Keim24-Jan-05 5:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.