在 WinForm 上运行数字时钟 [英] Run a Digital Clock on your WinForm
问题描述
我必须设计一个带有简单文本框的 Windows 窗体.文本框包含一个类似文本的计时器(00:00 格式).
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!).
我发现我需要使用 System.Windows.Forms.Timer
类,并且我已将 Timer
项从 ToolBox 拖放到我的表单中.
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.
接下来……我需要使用 Thread.Sleep(1000)
函数吗……有什么想法吗?
What next... Do I need to use Thread.Sleep(1000)
function.. any ideas ?
这是我一直在尝试的代码片段.我知道程序哪里出错了,thread.sleep()
部分甚至让我的代码运行起来更糟.我尝试了 ToolBox 中的 Timer 东西,但无法通过.(当我运行代码时,它编译成功,然后应用程序由于 For-Loops 脏而冻结一小时)帮助!!
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();
}
}
推荐答案
设置定时器和刷新周期.(1 秒)
Set the timer and the refresh period. (1 second)
timer1.Enabled = true;
timer1.Interval = 1000;
然后你需要实现你希望定时器每 1 秒做的事情:
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();
}
这篇关于在 WinForm 上运行数字时钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!