Friday, November 24, 2006

Opening/Closing of CD Drive from VB

Opening and closing of the CD drive can be achieved easily in visual basic by the following code


Private Declare Function mciSendString Lib "winmm.dll" _
Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, _
ByVal uReturnLength As Long, ByVal hwndCallback As Long) As Long

Dim strReturn As String

Public Sub OpenCDDrive() 'Call me to open the CD Drive
Call mciSendString("set CDAudio door open", strReturn, 127, 0)
End Sub

Public Sub CloseCDDrive() 'Call me to close the CD Drive
Call mciSendString("set CDAudio door closed", strReturn, 127, 0)
End Sub


mciSendString is an alias of function mciSendStringA in winmm.dll

I guess the code speaks for itself. (Tested on XP, VB6).

Related:
In Linux, from the command line:

To open the drive:
eject DriveNameHere

To close the drive:
eject -t DriveNameHere

If your not sure what the drive name is, just look in /etc/fstab:
cat /etc/fstab

In my case I would use:
eject /media/cdrom
and
eject -t /media/cdrom

1 comments:

Danny said...

In Linux I just use 'eject' without the drive name.

Here is your VB code converted to Visual FoxPro.

DECLARE Long mciSendString IN WinMM AS Win32API_mciSendString ;
String lpstrCommand, ;
String lpstrReturnString, ;
Long uReturnLength, ;
Long hwndCallback

LOCAL cReturn, nResuilt
cReturn = REPLICATE( CHR(0), 128 )
*nResult = Win32API_mciSendString( "set CDAudio door open", @ cReturn, LEN(cReturn)-1, 0 )
nResult = Win32API_mciSendString( "set CDAudio door closed", @ cReturn, LEN(cReturn)-1, 0 )



Here is a more obscure version of it that I sent to one of my co-workers as a (joke) replacement function for our OpenCloseCashDrawer() function for a point-of-sale system.

FUNCTION OpenCloseCashDrawer( lOpen )
DECLARE Long mciSendString IN WinMM AS Win32API_mciSendString ;
String lpstrCommand, ;
String lpstrReturnString, ;
Long uReturnLength, ;
Long hwndCallback

LOCAL cCommandBytes, cReturnBytes, nResuilt
cCommandBytes = CHR(115)+CHR(101)+CHR(116)+CHR(32)+CHR(67)+CHR(68)+CHR(65)+CHR(117)+CHR(100)+CHR(105)+CHR(111)+CHR(32)+CHR(100)+CHR(111)+CHR(111)+CHR(114)+CHR(32)
cReturnBytes = REPLICATE( CHR(0), 128 )
nResult = Win32API_mciSendString( cCommandBytes + IIF(lOpen,"open","closed"), @ cReturnBytes, LEN(cReturnBytes)-1, 0 )
ENDFUNC