c# - 如何在 WinForms 中使用同一个按钮启动和停止计时器?

标签 c# winforms

<分区>

我是编程新手,我遇到了这个问题,这对我来说听起来很简单,但我太笨了,搞不懂。

所以...我想在我的窗体上制作一个Timer,它以一个Button开头,然后是相同的Button阻止它。并且在屏幕上有一个 Label,它只显示 Timer 已经进行了多少次滴答。

private void BtnStart_Click(object sender, EventArgs e)
{
    if (timer1.Enabled)
        timer1.Enabled = false;
    if (!timer1.Enabled)
        timer1.Enabled = true;
}
int c = 0;

private void Timer1_Tick(object sender, EventArgs e)
{
    c++;
    lblTimer.Text = c.ToString();
}

第一个按钮点击有效,它从 Timer 开始,Label 显示计数器,但我认为它进入了一个无限循环,阻止了按钮再次按下,因为我无法停止 Timer?有人可以启发我我做错了什么吗? 谢谢!

最佳答案

这是当您单击 Button 以停止 Timer 时发生的情况:

// If the timer is enabled, it will disable it.
if (timer1.Enabled) {
    timer1.Enabled = false;
    // Timer is now disabled. That's good, that's what you want.
}

// At this point, the timer is disabled, so the next test will re-enable it!
if (!timer1.Enabled) {
    timer1.Enabled = true;
    // The Timer just go re-enabled :/
}

使用 else 语句修复此问题:

if (timer1.Enabled)
    timer1.Enabled = false;
else
    timer1.Enabled = true;

这样两个 block 中只有一个运行。

关于c# - 如何在 WinForms 中使用同一个按钮启动和停止计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59084418/

相关文章:

c# - 带有 DTD 解析错误的 .NET Core Web API XML

c# - Windows Azure - 在 Windows Azure IIS 存储中提供未知 (mp4) MIME 类型

c# - 字符串到原始字节数组

c# - 如何获取表单上的所有绑定(bind)源

c# - 尝试使用另一种形式的功能但不工作

c# - 将表单从后台带到前台时如何更新数据 GridView ?

c# - 我如何做到这一点,以便用户单击“取消”时可以取消对话框?

c# - 毫秒值未保存在 SQL Server DateTime 列中

c# - 如何使用 asp.net 将我的值从 c# 发送到 javascript

c# - 如何在 Windows 窗体应用程序 (C#) 中制作垂直分隔符