c# - 暂停/恢复定时器的问题

标签 c# winforms timer

我有一个迷宫游戏。回车后可以输入作弊码,同时计时器会暂停。但是输入代码后,我的计时器恢复了,但每秒递减 3 倍。这是按 Enter 的条件:

// gt.setTimer() is called at the moment the maze started
// I'm using getch to trap inputs

else if (move == 13) //Reads if Enter is pressed
            {
                pause = 1; //A Flag saying that the timer must be paused
                gt.setTimer(pause); //Calls my setTimer() method
                Console.Write("Enter Cheat: "); 
                cheat = Console.ReadLine();
                pause = 0; //A Flag saying that the timer should resume
                gt.setTimer(lives, pause); //Calls again the Timer
            }

这是我的 setTimer() 代码:

static System.Timers.Timer t = new System.Timers.Timer();
static int gTime = 300;

public void setTimer(int pause)
    {
        t.Interval = 1000; // Writes the time after every 1 sec
        if (pause == 1)
            t.Stop(); // Stop the timer if you press Enter
        else 
            t.Start(); // Starts the timer if not
        t.Elapsed += new ElapsedEventHandler(showTimer);                       
    }

    public static void showTimer(object source, ElapsedEventArgs e)
    {
        Console.Write("Time   " + gTime); //Writes time
        gTime--; //Decrements the time
    }

有什么问题吗?我错过了什么吗?

最佳答案

问题出在 setTimer 方法的最后一行。计时器处理程序应在调用构造函数后仅注册一次,而不是在 setTimer 中注册。在 elapsed timer 事件上,处理程序被调用它已注册的次数。因此,您使用 operator += 的次数越多,它被调用的次数就越多。

关于c# - 暂停/恢复定时器的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6722207/

相关文章:

c# - 将 JSON 字符串解析为 .NET 对象

c# - 无法从字符转换为字符串

vb.net - 避免打开重复的 mdi 子项

c# - 基于其他表单输入和验证显示/隐藏表单元素的最佳方法?

c# - 在 C# 中使用 TimeSpans 计算平均时间

c - 实现一般超时

javascript - 超时/间隔是基于 CPU 还是浏览器?

ios - 迅速3检查计时器是否正在运行

c# - 如何在 Azure 中为 .NEt 核心应用程序应用 woff 字体?

c# - 在 C# 桌面应用程序中漂亮地打印数学