定时器在日志中写入两次

时间:2013-05-24 18:43:27

标签: c# winforms timer

除了一件事,一切都很好。我的程序打印“玩家命中”2次然后“暴徒命中”2次,然后“玩家命中”2次再打印等等。我希望它输入“玩家命中”“暴徒命中”“玩家命中”“暴徒命中”等等。我不知道为什么它会输入2次。

我的代码如下所示:

public partial class Form1 : Form
{
    public Form1()
    {
        int Rase1 = 0;

        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 buttonChoseRase_Click(object sender, EventArgs e)
    {
        if (Rase1 == 0)
        {
            Rase1 = 1;
            Rase Rase = new Race(this);
            Rase.Show();
        }
        else if (Race1 >= 1)
        {
            buttonChoseRase.Enabled = false;

            Rebirth Reb = new Rebirth(this);
            Reb.Show();
        }
    }

    private void buttonStart_Click(object sender, EventArgs e)
    {
        textBoxCombatLog.Text = "";

        buttonStart.Enabled = false;
        buttonStop.Enabled = true;

        timer1.Start();

        timer2.Stop();
    }

    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 \n");

        timer1.Stop();

        timer2.Start();
    }

    private void timer2_Tick(object sender, EventArgs e)
    {
        LogWrite(TimeDate + "Mob Hit \n");

        timer2.Stop();

        timer1.Start();
    }

    private string TimeDate
    {
        get { return "[" + DateTime.Now.ToString("HH:mm:ss") + "]" + ": "; }
    }
}

这就是跑步的样子,无论我做什么,一切都会出现两次:

enter image description here

1 个答案:

答案 0 :(得分:2)

除了通过代码文件本身,您还通过设计器将事件处理程序附加到计时器的Tick事件。您需要删除其中一个。 在代码中附加事件处理程序或通过设计器附加它。