【问题标题】:Run a Digital Clock on your WinForm在 WinForm 上运行数字时钟
【发布时间】:2011-12-30 09:46:32
【问题描述】:

您好,我必须设计一个具有简单文本框的 Windows 窗体。文本框包含一个类似文本的计时器(00:00 格式)。

我想每秒刷新一次页面并相应地更改文本框的内容。 (就像一个数字时钟,运行一个小时!)。

我发现我需要使用 System.Windows.Forms.Timer 类,并且我已将一个 Timer 项目从工具箱放到我的表单中。

下一步……我需要使用Thread.Sleep(1000) 函数吗……有什么想法吗?

这是我一直在尝试的代码片段。我知道程序哪里出了问题,thread.sleep() 部分甚至让我的代码运行起来更糟。我在 ToolBox 中尝试了 Timer 的东西,但无法通过。(当我运行代码时,它编译成功,然后应用程序由于脏 For-Loops 而冻结一小时)帮助!!

  public  partial class Form1 : Form
{
    Button b = new Button();
    TextBox tb = new TextBox();
    //System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();

    public Form1()
    {
        b.Click += new EventHandler(b_click);
        b.Text = "START";
        tb.Text = "00 : 00";
        //timer1.Enabled = true;
        //timer1.Interval = 1000;
        tb.Location = new Point(100, 100);
        this.Controls.Add(tb);
        this.Controls.Add(b);
        InitializeComponent();
    }

    private void refreshTimer_Tick()
    {

       for (int i = 0; i < 60; i++)
        {
            for (int j = 0; j < 60; j++)
            {
                Thread.Sleep(500);
                string TempTime = string.Format("{0:00} : {1:00}",i,j);
                tb.Text = TempTime;                    
                Thread.Sleep(500);

            }
        }
    }
    public void b_click(object sender, EventArgs e)
    {
        refreshTimer_Tick();

    }
}

【问题讨论】:

    标签: c# winforms timer


    【解决方案1】:

    设置定时器和刷新周期。 (1 秒)

    timer1.Enabled = true;
    timer1.Interval = 1000;
    

    那么你需要实现你想让定时器每1秒做的事情:

    private void timer1_Tick(object sender, EventArgs e)
    {
        DigiClockTextBox.Text = DateTime.Now.TimeOfDay.ToString();
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-13
      • 2018-09-22
      • 1970-01-01
      • 2019-04-17
      • 1970-01-01
      • 2014-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多