在Delphi中,我了解如何构建失效计时器。但我不确定如何为C ++ Builder编写代码。我找不到任何例子。
在Delphi中,我在下面编写了这段代码,来自某个地方的源代码: -
boost::thread
请在C ++中如何做同样的事情。 感谢
答案 0 :(得分:2)
试试这个:
....
class TFrame2 : public TFrame
{
__published:
TStatusBar *StatusBar1;
TTimer *Timer1;
...
void __fastcall Timer1Timer(TObject *Sender);
...
private:
TDateTime StartTime;
...
public:
__fastcall TFrame2(TComponent *TheOwner);
};
__fastcall TFrame2::TFrame2(TComponent *TheOwner)
: TFrame(TheOwner)
{
StartTime = Now();
Timer1->Enabled = true;
}
void __fastcall TFrame2::Timer1Timer(TObject *Sender) //This event occurs every second.
{
Timer1->Enabled = false;
TDateTime Diff = Now() - StartTime;
Word Hour, Min, Sec, MSec;
DecodeTime(Diff, Hour, Min, Sec, MSec);
StatusBar1->Panels->Items[1]->Text = String(Min)+" Minutes, "+String(Sec)+" Seconds.";
Timer1->Enabled = true;
}
...
或者,您可以将Timer1Timer()
简化为:
void __fastcall TFrame2::Timer1Timer(TObject *Sender) //This event occurs every second.
{
// this is not overhead-intense code, so
// stopping and re-starting the timer
// is wasting unnecessary processing time...
//Timer1->Enabled = true;
TDateTime Diff = Now() - StartTime;
StatusBar1->Panels->Items[1]->Text = Diff.FormatString("n' Minutes, 's' Seconds.'");
//Timer1->Enabled = true;
}
就个人而言,我根本不会使用系统时钟,以防用户更改时钟,或者在计时器运行时自动滚动DST。我会手动使用CPU滴答:
....
class TFrame2 : public TFrame
{
__published:
TStatusBar *StatusBar1;
TTimer *Timer1;
...
void __fastcall Timer1Timer(TObject *Sender);
...
private:
DWORD StartTime;
...
public:
__fastcall TFrame2(TComponent *TheOwner);
};
__fastcall TFrame2::TFrame2(TComponent *TheOwner)
: TFrame(TheOwner)
{
StartTime = GetTickCount();
Timer1->Enabled = true;
}
void __fastcall TFrame2::Timer1Timer(TObject *Sender) //This event occurs every second.
{
//Timer1->Enabled = false;
DWORD Diff = GetTickCount() - StartTime;
DWORD Mins = Diff / 60000; Diff %= 60000;
DWORD Secs = Diff / 1000;
StatusBar1->Panels->Items[1]->Text = String(Mins)+" Minutes, "+String(Secs)+" Seconds.";
//Timer1->Enabled = true;
}
...
或通过TStopWatch
:
#include <System.Diagnostics.hpp>
....
class TFrame2 : public TFrame
{
__published:
TStatusBar *StatusBar1;
TTimer *Timer1;
...
void __fastcall Timer1Timer(TObject *Sender);
...
private:
TStopwatch SW;
...
public:
__fastcall TFrame2(TComponent *TheOwner);
};
__fastcall TFrame2::TFrame2(TComponent *TheOwner)
: TFrame(TheOwner)
{
SW = TStopwatch::StartNew();
Timer1->Enabled = true;
}
void __fastcall TFrame2::Timer1Timer(TObject *Sender) //This event occurs every second.
{
//Timer1->Enabled = false;
SW.Stop();
TTimeSpan TS = SW.Elapsed;
StatusBar1->Panels->Items[1]->Text = String(TS.Minutes)+" Minutes, "+String(TS.Seconds)+" Seconds.";
SW.Start();
//Timer1->Enabled = true;
}