Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a Digital Clock on your WinForm

Tags:

c#

winforms

timer

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

    }
}
like image 387
LetsKickSomeAss in .net Avatar asked Dec 30 '11 09:12

LetsKickSomeAss in .net


People also ask

How do you make a clock in Visual Basic?

First of all you need to insert a timer control into your form and set its interval to 1000, which is equivalent to 1 second. Next, insert a label, clear its text and set an appropriate size(you need to disable autosize). Execute the code and you have your clock up and running.


1 Answers

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();
}
like image 119
ediblecode Avatar answered Oct 08 '22 21:10

ediblecode