Thursday, August 18, 2011

Iterate Table

// uses DB

procedure TForm1.ToolButton1Click(Sender: TObject);
var
i: integer;
begin
with Table1 do
begin
  DisableControls;
  try
    First;
    while not Table1.EOF do
    begin
        // your code here, process record
      Next;
      Application.ProcessMessages;
    end;
  finally
    EnableControls;
  end;
end; // with Table1 do
end;

Wednesday, August 17, 2011

Run On Startup


// uses TRegistry
procedure SetRunOnStartup(sProgTitle, sCmdLine: string;
RunType: TRunOnStartupAction);
var
reg: TRegIniFile;
sStartupRegKey: string;
begin
try
  sStartupRegKey := 'Software\Microsoft\Windows\CurrentVersion\Run';
  reg := TRegIniFile.Create('');
  reg.RootKey := HKEY_CURRENT_USER; //works for win7
  if RunType = rsRunOnce then
    reg.WriteString(sStartupRegKey + 'Once'#0, sProgTitle, sCmdLine)
  else if RunType = rsRunAllways then
    reg.WriteString(sStartupRegKey + #0, sProgTitle, sCmdLine)
  else
    reg.DeleteKey(sStartupRegKey + #0, sProgTitle);
  reg.Free;
except
  ShowMessage('Error!');
end;
end;
procedure TForm1.ToolButton1Click(Sender: TObject);
begin
SetRunOnStartup(Application.Title, Application.ExeName, rsRunAllways);
Showmessage('Program will run on windows startup!');
end;

procedure TForm1.ToolButton2Click(Sender: TObject);
begin
SetRunOnStartup(Application.Title, Application.ExeName, rsRunNever);
Showmessage('Program will NOT run on windows startup!');
end;

Escape Process

// Press Esc to break out of a process
Application.ProcessMessages;
If GetKeyState(VK_Escape) and 128 = 128 then
begin
if MessageDlg('Stop process?',
  mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
  break;
end;
end;

Format Bytes

// Return a formatted string from bytes
function FormatByteSize(const bytes: Longint): string;
const
B = 1; // byte
KB = 1024 * B; // kilobyte
MB = 1024 * KB; // megabyte
GB = 1024 * MB; // gigabyte
begin
if bytes > GB then
  result := FormatFloat('#.## GB', bytes / GB)
else if bytes > MB then
  result := FormatFloat('#.## MB', bytes / MB)
else if bytes > KB then
  result := FormatFloat('#.## KB', bytes / KB)
else
  result := FormatFloat('#.## bytes', bytes);
end;