Is it possible to lock a drive, write something on it and unlock it...?

Ok, but there are programs which do that. For example Norton Ghost.
So it's doable...

I found a function: DeviceIoControl. But it has one problem: doesn't work with USB drives.

So far I have tried this:

Const
   FSCTL_LOCK_VOLUME = $00090018;
   FSCTL_UNLOCK_VOLUME = $0009001C;

........
function LockDrive(Drive: AnsiChar): Boolean;
var
   H: THandle;
   OldMode: UINT;
   BytesReturned: Cardinal;
begin
   Result := False;

   OldMode := SetErrorMode(SEM_FAILCRITICALERRORS);
   try
      H := CreateFile(PChar(Format('\\.\%s:', [AnsiLowerCase(string(Drive))])), 0, FILE_SHARE_READ or FILE_SHARE_WRITE, nil,
         OPEN_EXISTING, 0, 0);
      if H <> INVALID_HANDLE_VALUE then
      begin
         try
            Result := DeviceIoControl(H, FSCTL_LOCK_VOLUME, nil, 0, nil, 0, BytesReturned, nil);
         finally
            CloseHandle(H);
         end;
      end;
   finally
      SetErrorMode(OldMode);
   end;
end;

function UnlockDrive(Drive: AnsiChar): Boolean;
var
   H: THandle;
   OldMode: UINT;
   BytesReturned: Cardinal;
begin
   Result := False;

   OldMode := SetErrorMode(SEM_FAILCRITICALERRORS);
   try
      H := CreateFile(PChar(Format('\\.\%s:', [AnsiLowerCase(string(Drive))])), 0, FILE_SHARE_READ or FILE_SHARE_WRITE, nil,
         OPEN_EXISTING, 0, 0);
      if H <> INVALID_HANDLE_VALUE then
      begin
         try
            Result := DeviceIoControl(H, FSCTL_UNLOCK_VOLUME, nil, 0, nil, 0, BytesReturned, nil);
         finally
            CloseHandle(H);
         end;
      end;
   finally
      SetErrorMode(OldMode);
   end;
end;

I tried with USB HDD and CDROM but it's not working.
GetLastError is returning 1 (ERROR_INVALID_FUNCTION).

Does anyone have an idea on how to make it work...?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.