您好,我必须设计一个具有简单文本框的 Windows 窗体。文本框包含一个类似文本的计时器(00:00 格式)。
我想每秒刷新一次页面,让文本框的内容随之变化。 (就像一个数字时钟,运行一小时!)。
我发现我需要使用 System.Windows.Forms.Timer
类,并且我已将 Timer
项从工具箱放到我的表单中。
接下来...我需要使用 Thread.Sleep(1000)
函数吗...有什么想法吗?
这是我一直在尝试的代码片段。我知道程序哪里出错了,thread.sleep()
部分甚至让我的代码运行起来更糟。我尝试了 ToolBox 中的 Timer 东西,但无法通过。(当我运行代码时,它编译成功,然后由于肮脏的 For 循环,应用程序卡住了一小时)帮助!!
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();
}
}
最佳答案
设置定时器和刷新周期。 (1 秒)
timer1.Enabled = true;
timer1.Interval = 1000;
然后您需要实现您希望计时器每 1 秒执行的操作:
private void timer1_Tick(object sender, EventArgs e)
{
DigiClockTextBox.Text = DateTime.Now.TimeOfDay.ToString();
}
关于c# - 在 WinForm 上运行数字时钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8678162/