Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

c# - Run a Digital Clock on your WinForm

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!).

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.

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

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

    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...