Tuesday 11 December 2012

Determine if a colour light

Below is a Delphi function to determine whether a colour is light, this is useful if a user can for example change the background colour of a control, you will need then to set the font colour correctly.


function ColourIsLight(Colour: TColor): boolean;
begin
    Colour := ColorToRGB(Colour);
    Result := ((Colour and $FF) + (Colour shr 8 and $FF) + (Colour shr 16 and    $FF)) >= $180;
end;

Tuesday 4 December 2012

How to copy files in Delphi

Here are 2 methods for copying files in Delphi.

Method 1:

procedure FileCopy(const SourceFilename, TargetFilename: string);
var   
 s, t: TFileStream;
begin
    s := TFileStream.Create(SourceFilename, fmOpenRead);
    try
      t := TFileStream.Create(TargetFilename, fmOpenwrite or fmCreate);
      try
        t.CopyFrom(s, s.size);
      finally
        t.free;
      end;
    finally
        s.free;
    end;
end;

Method 2:

procedure FileCopy(const SourceFilename, TargetFilename: string);
var   
  fromF,toF: file;
  numRead, numWritten: word;
  buf: array[1..2048] of char;
begin

  AssignFile(fromF, SourceFilename);
  Reset(fromF, 1);
  AssignFile(toF, TargetFilename);
  Rewrite(ToF, 1); 
  repeat 
    BlockRead(fromF, buf, SizeOF(Buf), numRead);
    BlockWrite(toF, buf, numRead, numWritten);
  until (numRead = 0) or (numWritten <> numRead);
  CloseFile(fromF);
  CloseFile(toF); 
end;