C++ Builder XE4, 10.2 Tokyo > TStopwatchを使った経過時間の表示


動作環境
C++ Builder XE4
RAD Studio 10.2 Tokyo Update 2 (追記: 2017/12/28)

イベント開始後の経過秒数を表示したい。

TStopwatchを使ってみた。

参考 http://www.gesource.jp/programming/bcb/110.html

  • 以下が必要
    • #include <System.Diagnostics.hpp> //
    • #include <TimeSpan.hpp> //
Unit1.h
//---------------------------------------------------------------------------

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
#include <Vcl.ExtCtrls.hpp>

#include <System.Diagnostics.hpp> //
#include <TimeSpan.hpp> //
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published:    // IDE で管理されるコンポーネント
    TTimer *Timer1;
    TLabel *Label1;
    TButton *B_start;
    TButton *B_stop;
    void __fastcall Timer1Timer(TObject *Sender);
    void __fastcall B_startClick(TObject *Sender);
    void __fastcall B_stopClick(TObject *Sender);
    void __fastcall FormClose(TObject *Sender, TCloseAction &Action);
private:    // ユーザー宣言
    TStopwatch m_stopwatch;
public:     // ユーザー宣言
    __fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif
Unit1.cpp
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
    m_stopwatch = TStopwatch::Create();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Timer1Timer(TObject *Sender)
{
    int elpsd_sec = m_stopwatch.ElapsedMilliseconds / 1000;

    String msg = IntToStr(elpsd_sec);
    Label1->Caption = msg;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::B_startClick(TObject *Sender)
{
    m_stopwatch.Reset();
    m_stopwatch.Start();

    Timer1->Interval = 1000;
    Timer1->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::B_stopClick(TObject *Sender)
{
    Timer1->Enabled = false;

    m_stopwatch.Stop();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
    m_stopwatch.Stop();
}
//---------------------------------------------------------------------------

m_stopwatchという1つのインスタンス変数で管理できるのは利点かもしれない。