Private _locked As Boolean
Private Const INVALID_HANDLE_VALUE As Short = -1
Private Const OPEN_EXISTING As Short = 3
Private Const FILE_ATTRIBUTE_NORMAL As Short = &H80S
Private Const FILE_SHARE_READ As Short = &H1S
Private Const FILE_SHARE_WRITE As Short = &H2S
Private Const GENERIC_READ As Integer = &H80000000
Private Const IOCTL_STORAGE_MEDIA_REMOVAL As Integer = 2967556
'We use CreateFile to get a handle to the drive
Private Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" _
(ByVal lpFileName As String, _
ByVal dwDesiredAccess As Integer, _
ByVal dwShareMode As Integer, _
ByRef lpSecurityAttributes As SECURITY_ATTRIBUTES, _
ByVal dwCreationDisposition As Integer, _
ByVal dwFlagsAndAttributes As Integer, _
ByVal hTemplateFile As Integer) As Integer
'We use this to send PREVENT_MEDIA_REMOVAL to the drive using the handle
Private Declare Function DeviceIoControl Lib "kernel32" ( _
ByVal hDevice As Integer, _
ByVal dwIoControlCode As Integer, _
ByRef lpInBuffer As Boolean, _
ByVal nInBufferSize As Integer, _
ByRef lpOutBuffer As Integer, _
ByVal nOutBufferSize As Integer, _
ByRef lpBytesReturned As Integer, _
ByRef lpOverlapped As OVERLAPPED) As Integer
'Required structure, wil be passed blank
Private Structure OVERLAPPED
Public Internal As Integer
Public InternalHigh As Integer
Public offset As Integer
Public OffsetHigh As Integer
Public hEvent As Integer
End Structure
'Required structure, wil be passed blank
Private Structure SECURITY_ATTRIBUTES
Dim nLength As Integer
Dim lpSecurityDescriptor As Integer
Dim bInheritHandle As Integer
End Structure
'Close the handle we got by using CreateFile to open the drive
Private Declare Function CloseHandle Lib "kernel32" ( _
ByVal hObject As Integer) As Integer
Private Function LockMedia(ByRef DriveLetter As String, ByRef Lock As Boolean) As Boolean
'convert drive letter to a device path
Dim FullDrivePath As String = "//./" & DriveLetter
Dim hDrive As Integer
hDrive = CreateFile(FullDrivePath, GENERIC_READ, FILE_SHARE_READ Or FILE_SHARE_WRITE, _
New SECURITY_ATTRIBUTES, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)
If hDrive <> INVALID_HANDLE_VALUE Then
LockMedia = CBool(DeviceIoControl(hDrive, IOCTL_STORAGE_MEDIA_REMOVAL, _
Lock, 1, 0, 0, New Integer, New OVERLAPPED))
Call CloseHandle(hDrive)
End If
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If _locked Then
'pass the drive letter and a colon, then true to lock, false to unlock.
'if you lock n times then you have to unlock n times to get control back.
LockMedia("E:", False)
Button1.Text = "Lock"
Me.Text = "Drive E is unlocked"
Else
LockMedia("E:", True)
Button1.Text = "Unlock"
Me.Text = "Drive E is locked"
End If
_locked = Not _locked
End Sub