Wilson WindowWare Tech Support

WinBatch WinBatch+Compiler WebBatch
Home | Tech Database | Tech BBS | White Papers | Purchase


Lock Unlock CDROM Drive

 Keywords:  lock unlock CDROM CD ROM CD-ROM drive tray

Question:

Is there a command to lock the cd tray? I can open and close it, I also want to lock it shut so my two year old is not playing with the cd rom drive.

Answer:

I was not able to find any MCI strings to lock the CDROM.

However I was able to write a UDF which makes a DLLCall to the DeviceIOControl API. This code can lock and unlock the CDROM drive.

The following code is designed to run on Windows NT platforms (4.0, 2000, and XP)


#DefineFunction LockMedia(DriveLetterAndColon, LockSetting) 
	IntControl(73, 1, 0, 0, 0)
	INVALID_HANDLE_VALUE = -1
	OPEN_EXISTING = 3
	FILE_ATTRIBUTE_NORMAL = 128
	FILE_SHARE_WRITE = 2
	GENERIC_READ = 2147483648
	IOCTL_STORAGE_MEDIA_REMOVAL = 2967556
	

	;Fuction for (un)locking Media inside a removable storage drive
	;DriveLetterAndColon should be two characters WITHOUT a trailing 
	;backslash, ex: "D:"
	;LockSetting specifies if we want to lock the media in the drive (True) 
	;or unlock it (False)
	;Returns True if it succeeds and False if it fails
	;CreateFile will probably fail on Win9x systems so this function is only 
	;intended for use on NT 4 and greater
	drivepath = StrCat("\\.\", DriveLetterAndColon)
	DaDll=strcat(DirWindows(1),"kernel32.dll")
	hDrive=DllCall(DaDll,long:"CreateFileA",lpstr:drivepath,long:GENERIC_READ,long:FILE_SHARE_WRITE,lpnull, long:OPEN_EXISTING, long:FILE_ATTRIBUTE_NORMAL, lpnull)
	If hDrive <> INVALID_HANDLE_VALUE 
	    lpLock = BinaryAlloc(4)
	    BinaryPoke(lpLock,0,locksetting)
	    LockSz = BinaryEodGet(lpLock)
            lpReturnedBytes = BinaryAlloc(4)
	    LockMediaRslt = DllCall(DaDll,long:"DeviceIoControl",long:hDrive, long:IOCTL_STORAGE_MEDIA_REMOVAL, lpbinary:lpLock, long:LockSz, long:0, long:0, lpbinary:lpReturnedBytes, lpnull)
	    LastErr = DllLastError()
	    BinaryFree(lpLock)
	    BinaryFree(lpReturnedBytes)
	    DllCall(DaDll,long:"CloseHandle",long:hDrive)  ;Clean up after outselves
	    if LockMediaRslt == 0
		   Message("DeviceIoControl Failed with Error",LastErr)
		 	Return 0
	    Endif 
	    Return 1
	Endif
	Return 0

	:WBERRORHANDLER
	if hDrive !=0 then DllCall(DaDll,long:"CloseHandle",long:hDrive)  
	if IsDefined(lpLock) then BinaryFree(lpLock)
	if IsDefined(lpReturnedBytes) then BinaryFree(lpReturnedBytes)
	Message("Error Occured on line",wberrorhandlerline)
	Return 0

#EndFunction

;Grab CDROM Drive letter
CDROMLIST = DiskScan (8)
CDROM = ItemExtract(1,CDROMLIST,@TAB)


;Lock CDROM Drive
ret = LockMedia(CDROM, @True)

Pause("Check CDROM Drive","The CDROM drive %CDROM% should now be locked")

;UnLock CDROM Drive 
ret = LockMedia(CDROM, @False) 

Pause("Check CDROM Drive","The CDROM drive %CDROM% should now be unlocked")
exit