Reputation: 25
Hi i have problem it stopped my progress
I need to starttimer 200seconds to 0 (countdown in caption) by click on button, i have 48 buttons which are timers On google i found some about threads but dunno how to use it
timer_01.cpp:
__fastcall timer_01::timer_01(bool CreateSuspended)
: TThread(CreateSuspended)
{
}
void __fastcall timer_01::Execute(TButton* buton)
{
if(buton->Caption=="Flash"){
for(int i=flash_time;i>0;i--){
buton->Caption=i;
Sleep(1000);
};
}
}
//---------------------------------------------------------------------------
and my button in main_program.cpp
void __fastcall TForm1::Button4Click(TObject *Sender)
{
Execute(Button4);
}
and include in main_program.cpp
#include "timer_01.h"
my main_program.h constructor i added:
void __fastcall Execute(TButton* buton);
Upvotes: 0
Views: 1684
Reputation: 596457
Your code is the completely wrong way to use TThread
. Try something more like this instead:
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;
}
main_program.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;
}
With that said, you don't really need a TThread
for such a simple timer. A TTimer
would work just as well:
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;
}
Upvotes: 1