我是 C++/CLI 的新手,想在按下按钮后短时间内禁用按钮。 我已经实现了一个计时器事件,但它被触发的次数比我预期的要多。我不知道。
private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e)
{
timer1Count++;
timer1->Stop();
this->timer1->Enabled = false;
MessageBox::Show("Timer1 Event Triggered. timer1Count = " + System::Convert::ToString(timer1Count));
this->button1->Enabled = true;
}
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
this->button1->Enabled = false;
this->timer1->Enabled = true;
this->timer1->Interval = 2000;
timer1->Tick += gcnew EventHandler(this, &MyForm::timer1_Tick);
timer1->Start();
}
以上是我的定时器事件的核心。我的问题是
被触发的事件次数不断增加。 我想只按一次按钮触发一次事件。
顺便说一句,我的 IDE 是 Visual Studio Community 2017。
谢谢
Daydream_eug
答案 0 :(得分:0)
我通过稍微修改我的代码解决了我的问题。最终代码是
this->timer1->Interval = 2000;
timer1->Tick += gcnew EventHandler(this, &MyForm::timer1_Tick);
private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e)
{
timer1Count++;
timer1->Stop();
this->timer1->Enabled = false;
MessageBox::Show("Timer1 Event Triggered. timer1Count = " + System::Convert::ToString(timer1Count));
this->button1->Enabled = true;
}
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
this->button1->Enabled = false;
this->timer1->Enabled = true;
timer1->Start();
}
关键问题是下面这行
timer1->Tick += gcnew EventHandler(this, &MyForm::timer1_Tick);
应该在 button1_click 函数之外。如果这条线 位于函数内部,timer1_Tick 事件额外触发。
谢谢
Daydream_Eug