您的代码是完全错误的使用方式TThread
。尝试更多类似的东西:
timer_01.h:
class timer_01 : public TThread
{
private:
TButton *fButton;
String fValue;
String __fastcall GetButtonCaption();
void __fastcall DoGetButtonCaption();
void __fastcall SetButtonCaption(const String &AValue);
void __fastcall DoSetButtonCaption();
protected:
void __fastcall Execute();
public:
__fastcall timer_01(TButton *AButton);
};
timer_01.cpp:
__fastcall timer_01::timer_01(TButton *AButton)
: TThread(true), fButton(AButton)
{
FreeOnTerminate = true;
}
void __fastcall timer_01::Execute()
{
if (GetButtonCaption() == "Flash")
{
for(int i = flash_time; (i > 0) && (!Terminated); --i)
{
SetButtonCaption(i);
if (!Terminated)
Sleep(1000);
}
}
}
String __fastcall timer_01::GetButtonCaption()
{
Synchronize(&DoGetButtonCaption);
return fValue;
}
void __fastcall timer_01::DoGetButtonCaption()
{
fValue = fButton->Caption;
}
void __fastcall timer_01::SetButtonCaption(const String &AValue)
{
fValue = AValue;
Synchronize(&DoSetButtonCaption);
}
void __fastcall timer_01::DoSetButtonCaption()
{
fButton->Caption = fValue;
}
主程序.cpp
#include "timer_01.h"
timer_01 *timer = NULL;
void __fastcall TForm1::Button4Click(TObject *Sender)
{
if (timer)
{
timer->Terminate();
do
{
CheckSynchronize();
Sleep(10);
}
while (timer);
}
timer = new timer_01(Button4);
timer->OnTerminate = &TimerTerminated;
timer->Resume();
}
void __fastcall TForm1::TimerTerminated(TObject *Sender)
{
timer = NULL;
}
话虽如此,你真的不需要TThread
这么简单的计时器。ATTimer
也可以:
void __fastcall TForm1::Button4Click(TObject *Sender)
{
Timer1->Interval = 1000;
Timer1->Tag = flash_time;
Timer1->Enabled = true;
}
void __fastcall TForm1::Timer1Timer(TObject *Sender)
{
if (Timer1->Tag > 0)
{
Button4->Caption = Timer1->Tag;
Timer1->Tag = Timer1->Tag - 1;
}
else
Timer1->Enabled = false;
}