AQC (Another Qaility Code):
function ProtectFile(sFilename : string) : hFile;
var
hf: hFile;
lwHFileSize, lwFilesize: longword;
ofs : TOFStruct;
begin
if FileExists(sFilename) then
begin
hf := OpenFile(pchar(sFilename), ofs, OF_READ or OF_WRITE or OF_SHARE_EXCLUSIVE);
if hf <> 0 then
begin
lwFilesize := GetFileSize(hf, @lwHFileSize);
if LockFile(hf, 0, 0, lwFilesize, lwHFilesize) then
Result := hf else Result := 0;
end
else Result := 0;
end
else Result := 0;
end;
function UnProtectFile(hf: hFile): boolean;
begin
if hf <> 0 then
CloseHandle(hf);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
protectedFile := ProtectFile(ExtractFilePath(Application.Exename)+'test.txt');
if protectedFile = 0 then
MessageBox(Handle, 'Error locking file!', '', MB_OK or MB_ICONERROR) else
Button1.Enabled := False;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
plik: TextFile;
data: string;
begin
UnProtectFile(protectedFile);