Running a digital clock on your WinForm

Hi, I need to create a Windows Form with a simple text box. The text field contains a timer, such as text (format 00:00).

I want to refresh the page every second and change the contents of the text field accordingly. (Like a digital clock, for example, one hour!).

I realized that I needed to use the System.Windows.Forms.Timer class, and I removed the Timer element from the ToolBox in my form.

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

Here is the code I tried. I know where this happens incorrectly in the program, and the thread.sleep() even worsens my code to run. I tried Timer stuff in ToolBox but could not get through. (When I run the code, it compiles successfully, and then the application freezes for one hour due to dirty 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(); } } 
+4
source share
2 answers

Set a timer and update period. (1 second)

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

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

 private void timer1_Tick(object sender, EventArgs e) { DigiClockTextBox.Text = DateTime.Now.TimeOfDay.ToString(); } 
+16
source
Finally I knew where I had gone bad. Here is the corrected code that works just fine, as I wanted.
  public partial class Form1 : Form { Button b = new Button(); TextBox tb = new TextBox(); public Form1() { b.Click += new EventHandler(b_click); b.Text = "START"; tb.Text = "CLICK START TO BEGIN COUNTDOWN !!"; tb.Width = 300; tb.ReadOnly = true; tb.Location = new Point(10, 100); this.Controls.Add(tb); this.Controls.Add(b); InitializeComponent(); timer1.Interval = 1000; } public void b_click(object sender, EventArgs e) { timer1.Start(); } int tt = 0; int mm = 0; private void timer1_Tick(object sender, EventArgs e) { tb.Text = string.Format("{0:00} {1:00}",(mm), (tt)); tt += 1; if (tt % 60 == 0) { mm += 1; tt = 0; } if (tt > 3600) { timer1.Stop(); } } } 
-1
source

Source: https://habr.com/ru/post/1388576/


All Articles