Introduction
This is a very simple article to know how to access and get information about the CD-ROM (open, close, occupied?, drive name), and this is achieved using some Windows APIs.
Using the code
The code is very small and includes comments that explain each line. And the namespaces used are:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using System.Text;
The only class in this program is the api
class which defines the methods that will be invoked from some Windows DLLs.
public class api
{
[DllImport("winmm.dll", EntryPoint="mciSendStringA")]
public static extern int mciSendString (string lpstrCommand,
string lpstrReturnString, int uReturnLength, int hwndCallback);
[DllImport("kernel32.dll", EntryPoint="GetVolumeInformationA")]
public static extern int GetVolumeInformation (string lpRootPathName,
StringBuilder lpVolumeNameBuffer, int nVolumeNameSize,
int lpVolumeSerialNumber, int lpMaximumComponentLength,
int lpFileSystemFlags, string lpFileSystemNameBuffer,
int nFileSystemNameSize);
[DllImport("kernel32.dll", EntryPoint="GetDriveTypeA")]
public static extern int GetDriveType (string nDrive);
}
Then in the button click or whatever, you can use these functions, but first we will get all the drives in the computer using this line of code:
string [] logDrives = System.IO.Directory.GetLogicalDrives();
Then for each drive in this array we will call the GetDriveType
method to know which one is the CD-ROM, then use the GetVolumeInformation
method to know whether there is a CD inside or not, but first we must declare and initialize the parameters used by these functions:
string s ="";
StringBuilder volumeName = new StringBuilder(256);
int srNum = new int();
int comLen = new int();
string sysName = "";
int sysFlags = new int();
int result;
Now let's call our methods:
for(int i=0;i< logDrives.Length;i++)
{
if(api.GetDriveType(logDrives[i])==5)
{
s+="Your CD ROM is on drive : " +
logDrives[i].ToString()+"\n";
result = api.GetVolumeInformation(logDrives[i].ToString(),
volumeName,256,srNum,comLen,sysFlags,sysName,256);
if(result==0)
s+="there is NO CD in ur CD ROM";
else
{
s+="There is a CD inside ur CD ROM and its name is " + volumeName;
}
}
}
Now the last lines of code will explain how to open and close the CDROM by calling the mciSendString
method.
private void button1_Click(object sender, System.EventArgs e)
{
api.mciSendString("set CDAudio door open",null, 127, 0);
}
private void button2_Click(object sender, System.EventArgs e)
{
api.mciSendString("set CDAudio door closed",null, 127, 0);
}
That's it it. It is simple and I hope it could help.
Reference
Apiviewer 2004 is cool program that contain all the APIs with their declarations.