const
FILE_READ_ACCESS = 1;
METHOD_BUFFERED = 0;
FILE_DEVICE_MASS_STORAGE = $2D;
IOCTL_STORAGE_BASE = FILE_DEVICE_MASS_STORAGE;
IOCTL_STORAGE_MEDIA_REMOVAL = $002D4804;
IOCTL_STORAGE_EJECT_MEDIA = (IOCTL_STORAGE_BASE
shl 16)
or ($0202
shl 2)
or
(METHOD_BUFFERED)
or (FILE_READ_ACCESS
shl 14);
type
_PREVENT_MEDIA_REMOVAL =
packed record
PreventMediaRemoval: ByteBool;
end;
PREVENT_MEDIA_REMOVAL = _PREVENT_MEDIA_REMOVAL;
procedure TestUnmount;
var
hDisk: THandle;
written: DWORD;
PMR: PREVENT_MEDIA_REMOVAL;
begin
hDisk := CreateFile('
\\.\N:', GENERIC_READ
or GENERIC_WRITE, FILE_SHARE_READ
or FILE_SHARE_WRITE,
nil, OPEN_EXISTING, 0, 0);
if hDisk = INVALID_HANDLE_VALUE
then
raise Exception.Create('
opening failed');
if not LockVolume(hDisk)
then
Showmessage('
not locked!!');
if not DeviceIOControl(hDisk, FSCTL_DISMOUNT_VOLUME,
nil, 0,
nil, 0, written,
nil)
then
Showmessage('
dismounting failed');
PMR.PreventMediaRemoval := False;
if not DeviceIOControl(hDisk, IOCTL_STORAGE_MEDIA_REMOVAL, @PMR, SizeOf(PMR),
nil, 0, written,
nil)
then
Showmessage('
couldn''
t set removal = false');
if not DeviceIOControl(hDisk, IOCTL_STORAGE_EJECT_MEDIA,
nil, 0,
nil, 0, written,
nil)
then
RaiseLastOSError;
CloseHandle(hDisk);