我正在创建一个程序,其中timer1应该激活另一个timer2然后停止,在timer2中我再次激活timer1并停止timer2然后继续然后我有一个文本日志,它写下进度。这是问题所在,首先它以2的Timer1滴答开始然后2的定时器2然后它再乘以2所以它的4下一次然后是8然后16这样,我只想要它是1个timer1而不是1个timer2然后它重新开始,我看不出有什么问题。
private void buttonStart_Click(object sender, EventArgs e)
{
buttonStart.Enabled = false;
buttonStop.Enabled = true;
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = (1000);
timer1.Enabled = true;
timer1.Start();
}
private void buttonStop_Click(object sender, EventArgs e)
{
buttonStart.Enabled = true;
buttonStop.Enabled = false;
timer1.Stop();
timer2.Stop();
}
private void LogWrite(string txt)
{
textBoxCombatLog.AppendText(txt + Environment.NewLine);
textBoxCombatLog.SelectionStart = textBoxCombatLog.Text.Length;
}
private void timer1_Tick(object sender, EventArgs e)
{
LogWrite(TimeDate + "player hit");
timer1.Stop();
timer2.Tick += new EventHandler(timer2_Tick);
timer2.Interval = (1000);
timer2.Enabled = true;
timer2.Start();
}
private void timer2_Tick(object sender, EventArgs e)
{
LogWrite(TimeDate + "mob hit");
timer2.Stop();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = (1000);
timer1.Enabled = true;
timer1.Start();
}
答案 0 :(得分:2)
在timer1_tick
上您将事件添加到timer2.tick
事件,因此每次timer1_tick
函数引发时,您都会向timer2
添加一个事件侦听器,但永远不会删除旧事件处理程序,与timer2_tick相同的情况。
我的建议是将这些行添加到构造函数中,并从其他函数中删除这些行:
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = (1000);
timer1.Enabled = true;
timer2.Tick += new EventHandler(timer2_Tick);
timer2.Interval = (1000);
timer2.Enabled = true;
如果你这样做,你的计时器每次打勾只会调用一次。
答案 1 :(得分:1)
我确定这就是@ Epsil0neR的意思......
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = (1000);
timer1.Enabled = false;
timer2.Tick += new EventHandler(timer2_Tick);
timer2.Interval = (1000);
timer2.Enabled = false;
}
private void buttonStart_Click(object sender, EventArgs e)
{
buttonStart.Enabled = false;
buttonStop.Enabled = true;
timer1.Start();
}
private void buttonStop_Click(object sender, EventArgs e)
{
timer1.Stop();
timer2.Stop();
buttonStart.Enabled = true;
buttonStop.Enabled = false;
}
private void LogWrite(string txt)
{
textBoxCombatLog.AppendText(txt + Environment.NewLine);
textBoxCombatLog.SelectionStart = textBoxCombatLog.Text.Length;
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
LogWrite(TimeDate + "player hit");
timer2.Start();
}
private void timer2_Tick(object sender, EventArgs e)
{
timer2.Stop();
LogWrite(TimeDate + "mob hit");
timer1.Start();
}
private string TimeDate
{
get { return DateTime.Now.ToString("HH:mm:ss") + ": "; }
}
}