傻瓜的 Winforms 计时器 [英] Winforms Timer for Dummies

查看:24
本文介绍了傻瓜的 Winforms 计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让一个计时器在 winform 中每秒滴答一次,当我寻找有关如何执行此操作的建议时,我发现了大量有关线程的内容.好吧,我不在乎线程,因为我要做的就是在一分钟内将一个值从 60 倒数到 0,然后停止.我不认为我们需要进入云计算来解决这个问题,但我真的是一个网络表单人,所以我对这个问题有点生疏.谁能给我举个例子

I'm trying to get a timer to tick once a second in a winform, when I look for advice on how to do this I find loads of stuff about threads. Well I don't care about threads, because all I'm trying to do is make a value count down from 60 to 0 in one minute, then stop. I don't think we need to go into cloud computing to solve this one, but I am really a web forms bod, so I'm a bit rusty on this issue. Can anyone point me to an example

这是我尝试过的

private void button1_Click(object sender, EventArgs e)
    {
        this.timeLeft = 60;
        this.label1.Visible = false;
        this.button1.Visible = false;
        gt = new Timer();
        gt.Tick += new EventHandler(CountDown);
        gt.Interval = 1000;
        gt.Start();
    }

private void CountDown(object sender, EventArgs e)
{
    do
    {
        this.TimeBar.Value = timeLeft;                
        this.timeLeft -= 1;
    } while (this.timeLeft > 0);
    if (this.TimeBar.Value > 0) return;
    gt.Stop();
    this.label1.Visible = true;
    this.button1.Visible = true;
}

任何帮助将不胜感激.

推荐答案

发生的事情是您正在递减 timeLeft 变量,直到它在计时器的第一个滴答声中达到零.去掉 do...while 循环,你就会有一个基本工作的例子.

What's happening is that you're decrementing the timeLeft variable until it reaches zero on the very first tick of the timer. Take out the do...while loop and you'd have a basically working example.

但是,如果您要进行任何数量的 Windows 窗体工作,则需要了解线程以及它如何影响 UI.如果您没有遇到无用的异常和行为不端的 UI 组件的故事,您很快就会发现自己回到了这里.Jon Skeet 有一个出色的线程系列.我强烈推荐它.它有一个专门介绍计时器的部分,因此可能会给您一些额外的见解.

However if you're going to be doing any amount of Windows Forms work, you need to learn about threading and how that affects the UI. You'll very quickly find yourself back here if you don't with tales of unhelpful exceptions and misbehaving UI components. Jon Skeet has an excellent threading series. I highly recommend it. It has a section devoted to timers, so that might give you some additional insight.

这篇关于傻瓜的 Winforms 计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆