制作一个简单时钟,使用一个Label控件和一个Timer控制(Interval属性设置为1000ms),控件命名为默认。首先,参考代码如下:
public Form1()
{
InitializeComponent(); }
{
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Enabled = true;
label1.Font = new Font("Times New Roman", 25, FontStyle.Bold);
}
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
}
执行结果:
timer1_Tick函数并未执行,原因是没有加载Form1_Load()方法,需要在Form1()函数中加载。
public Form1()
{
InitializeComponent();
//增加一句代码加入这句代码即可解决
this.Load += new EventHandler(Form1_Load);
}
执行结果: