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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…