Einzelnen Beitrag anzeigen

Schokohase
(Gast)

n/a Beiträge
 
#5

AW: Countdown mit Stunden/Minuten

  Alt 6. Jun 2019, 09:33
Hier ein dreckiges Beispiel
Delphi-Quellcode:
uses
  Winapi.Windows,
  Winapi.Messages,
  System.SysUtils,
  System.Variants,
  System.Classes,
  System.TimeSpan,
  System.Diagnostics,
  Vcl.Graphics,
  Vcl.Controls,
  Vcl.Forms,
  Vcl.Dialogs,
  Vcl.StdCtrls,
  Vcl.ExtCtrls;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Button1: TButton;
    Button2: TButton;
    Timer1: TTimer;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
  private
    FDuration: TTimeSpan;
    FStopwatch: TStopwatch;
  public
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function ParseCountdownTime(const s: string): TTimeSpan;
var
  parts: TArray<string>;
  Hours, Minutes: Integer;
begin
  parts := s.Split([':']);
  if Length(parts) <> 2 then
    raise EArgumentException.Create('Fehlermeldung');

  if not Integer.TryParse(parts[0], Hours) then
    raise EArgumentException.Create('Fehlermeldung');
  if (Hours < 0) then
    raise EArgumentException.Create('Fehlermeldung');

  if not Integer.TryParse(parts[1], Minutes) then
    raise EArgumentException.Create('Fehlermeldung');
  if (Minutes < 0) or (Minutes >= 60) then
    raise EArgumentException.Create('Fehlermeldung');

  Result := TTimeSpan.Create(Hours, Minutes, 0);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  FDuration := ParseCountdownTime(Edit1.Text);
  FStopwatch := TStopwatch.StartNew();
  Edit1.ReadOnly := True;
  Button1.Enabled := False;
  Button2.Enabled := True;
  Timer1.Enabled := True;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  Timer1.Enabled := False;
  Button2.Enabled := False;
  Button1.Enabled := True;
  Edit1.ReadOnly := False;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
var
  remain: TTimeSpan;
  Hours, Minutes: Integer;
begin
  remain := FDuration - FStopwatch.Elapsed;
  Hours := Trunc(remain.TotalHours);
  Minutes := remain.Minutes;
  if remain.Seconds > 0 then
    Inc(Minutes);
  Edit1.Text := string.Format('%d:%2.2d', [Hours, Minutes]);
end;
  Mit Zitat antworten Zitat