【发布时间】:2011-12-30 09:46:32
【问题描述】:
您好,我必须设计一个具有简单文本框的 Windows 窗体。文本框包含一个类似文本的计时器(00:00 格式)。
我想每秒刷新一次页面并相应地更改文本框的内容。 (就像一个数字时钟,运行一个小时!)。
我发现我需要使用 System.Windows.Forms.Timer 类,并且我已将一个 Timer 项目从工具箱放到我的表单中。
下一步……我需要使用Thread.Sleep(1000) 函数吗……有什么想法吗?
这是我一直在尝试的代码片段。我知道程序哪里出了问题,thread.sleep() 部分甚至让我的代码运行起来更糟。我在 ToolBox 中尝试了 Timer 的东西,但无法通过。(当我运行代码时,它编译成功,然后应用程序由于脏 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();
}
}
【问题讨论】: