Archive

Posts Tagged ‘file’

How to Get a Unique File Name

December 15th, 1999 m3Rlin 1 comment

You want to save data to a temporary file but you don’t what to file name to use? Well, this function does all the work for you.

function CreateUniqueFileName(sPath: string): string;
var
  chTemp: Char;
begin
  repeat
    Randomize;
    repeat
      chTemp := Chr(Random(43) + 47);
      if Length(Result) = 8 then
        Result := Result + '.'
      else if chTemp in ['0'..'9', 'A'..'Z'] then
        Result := Result + chTemp;
    until Length(Result) = 12;
  until not FileExists(sPath + Result);
end;

How to Print Text

December 15th, 1999 m3Rlin No comments

This is the harder way to print text in Delphi :-) If you want to do it the easier way check out tip 4.1. Well, if for some reasons you may want to print using the Windows API here’s the code:

Code 1:

uses
  Printers, WinSpool;
...
var
  aDriver, aPort, aPrinterName: array[0..255] of Char; { aDriver and aPort won't be used }
  iSize, iN: Integer;
  Info: PAddJobInfo1;
  fPrinter: TextFile;
  hPrinter: THandle;
begin
  Printer.GetPrinter(aPrinterName, aDriver, aPort, hPrinter);
  OpenPrinter(aPrinterName, hPrinter, nil);
  try
    AddJob(hPrinter, 1, nil, 0, iSize); { Get buffer size }
    GetMem(Info, iSize);
    try
      { This function will return the name of the file we can write to }
      AddJob(hPrinter, 1, Info, iSize, iN);
      { Now write to the file }
      AssignFile(fPrinter, Info^.Path);
      Rewrite(fPrinter);
      try
        WriteLn(fPrinter, 'Hello world!');
        WriteLn(fPrinter, 'This is text will be printed...');
      finally
        CloseFile(fPrinter);
      end;
      { Put the file into the printing line, after that Windows will delete it }
      ScheduleJob(hPrinter, Info^.JobId);
    finally
      FreeMem(Info);
    end;
  finally
    ClosePrinter(hPrinter);
  end;
end;

Code 2:

{ Will work only if the printer is on LPT1 (almost always:-) }
...
LPTHandle := CreateFile('LPT1', GENERIC_WRITE, 0, PSecurityAttributes(nil),
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
...

Then use WriteFile() to send text or:

...
while not TransmitCommChar(LPTHandle, CharToSend) do
  Application.ProcessMessages;
(* This code will send characters to the printer waiting for each one of them
** to be taken care of.
*)