This example uses the DeviceIoControl API function to lock and unlock the CD drive.

The generic code is:
VB Code:
  1. Option Explicit
  2.  
  3. Private Type PREVENT_MEDIA_REMOVAL
  4.    PreventMediaRemoval As Byte
  5. End Type
  6.  
  7. Private Declare Function CreateFile Lib "kernel32.dll" Alias "CreateFileA" (ByVal lpFileName As String, ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, lpSecurityAttributes As Any, ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile As Long) As Long
  8. Private Declare Function DeviceIoControl Lib "kernel32.dll" (ByVal hDevice As Long, ByVal dwIoControlCode As Long, lpInBuffer As Any, ByVal nInBufferSize As Long, lpOutBuffer As Any, ByVal nOutBufferSize As Long, lpBytesReturned As Long, lpOverlapped As Any) As Long
  9. Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
  10. Private Const INVALID_HANDLE_VALUE As Long = -1&
  11. Private Const GENERIC_READ As Long = &H80000000
  12. Private Const FILE_SHARE_READ As Long = &H1
  13. Private Const FILE_SHARE_WRITE As Long = &H2
  14. Private Const OPEN_EXISTING As Long = 3
  15. Private Const FILE_ATTRIBUTE_NORMAL As Long = &H80
  16. Private Const ERROR_ACCESS_DENIED As Long = 5&
  17. Private Const IOCTL_STORAGE_MEDIA_REMOVAL As Long = &H2D4804
  18. Private hDevice As Long
  19.  
  20. '--------------------------------------------------------------------------
  21. 'ToggleDrive()
  22. 'sDrive = Drive letter we want to prevent from ejecting
  23. 'bLock = lock mode. TRUE = locked, FALSE = unlocked
  24. '--------------------------------------------------------------------------
  25. Private Sub ToggleDrive(ByVal sDrive As String, bLock As Boolean)
  26.     Dim dwRetval As Long
  27.     Dim pmr As PREVENT_MEDIA_REMOVAL
  28.     Dim hDevice As Long
  29.    
  30.     pmr.PreventMediaRemoval = bLock
  31.     hDevice = 0
  32.     dwRetval = 0
  33.    
  34.     'Get a handle to the drive
  35.     hDevice = CreateFile("\\.\" & sDrive & ":", GENERIC_READ, FILE_SHARE_READ Or FILE_SHARE_WRITE, ByVal 0, OPEN_EXISTING, 0, 0)
  36.     If hDevice = INVALID_HANDLE_VALUE Then
  37.         MsgBox "Unable to find drive"
  38.         Exit Sub
  39.     End If
  40.    
  41.     'Lock the drive
  42.     If DeviceIoControl(hDevice, IOCTL_STORAGE_MEDIA_REMOVAL, pmr, Len(pmr), 0, 0, dwRetval, 0) = 0 Then
  43.         MsgBox "Error accessing drive"
  44.     End If
  45.    
  46.     CloseHandle hDevice
  47. End Sub

Call the ToggleDrive routine to lock/unlock the drive.
VB Code:
  1. 'Lock the D drive
  2. ToggleDrive "D", True
  3.  
  4. MsgBox "Drive is locked. Press OK to unlock"
  5.  
  6. 'Unlock the D drive
  7. ToggleDrive "D", False