在WinForm上运行数字时钟 [英] Run a Digital Clock on your WinForm

查看:299
本文介绍了在WinForm上运行数字时钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi I have to design a Windows Form which has a simple textbox. The textbox contains a timer like text (00:00 format).

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

I want to refresh the page every second and make the content of the textbox change accordingly. (Just like a digital clock, running for say, one hour!).

我发现我需要使用 System.Windows.Forms .Timer 类,我已经将 Timer 项从工具箱中放到了我的窗体中。

I figured out I need to use the System.Windows.Forms.Timer class and I have dropped a Timer item from the ToolBox to my Form.

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

What next... Do I need to use Thread.Sleep(1000) function.. any ideas ?

这是我一直在尝试的代码段。我知道程序中哪里出了问题, thread.sleep()部分甚至使我的代码运行更糟。我在工具箱中尝试了Timer的内容,但无法通过。(当我运行代码时,它成功编译,然后由于肮脏的循环,应用程序冻结了一个小时)!!

Here is the code-piece i have been trying. I know where it goes wrong in the program, and the thread.sleep() part even makes it worse for my code to Run. I tried the Timer stuff in the ToolBox, but could not get through.(When i run the code, it compiles successfully and then the application freezes for one Hour due to the dirty For-Loops) Help !!

  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();

    }
}


推荐答案

设置计时器和刷新时间。 (1秒)

Set the timer and the refresh period. (1 second)

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

然后,您需要实现希望计时器每1秒执行的操作:

Then you need to implement what you want the timer to do every 1 second:

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

这篇关于在WinForm上运行数字时钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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