当前位置:编程学习 > C#/ASP.NET >>

c#窗体编程之建立时钟程序显示当前时间

很简单,初学者使用
题目:在窗体中显示当前时间,模拟时钟
程序运行如下所示:

步骤:
1.打开vs2010,File->new->project->WindowsForm application
2.将在form的properties串口中的text属性改为“时钟”
4.从toolbox中选择为窗体添加一个label控件和一个Timer控件
5.进入代码页面,添加获取当前时间的代码,并将label的text属性设置为时间的显示格式
6.双击Timer,编写timer的Tick事件,在其中显示时间的方法
8.双击窗体,填写load事件,将timer启动;
9.Form3.cs的代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace form1
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }
        public void GetTime()
        {
            DateTime time = DateTime.Now;//获取系统当前时间
            /*
             * 如果直接用time的hour,minute,second属性来表示时间,就会有当hour(或minute,second)为
             * 个位数时,如2时11分6秒,就会显示2:11:6,显示出来格式有些不符常规;所以,为了让其显示02:11:06
             * 的格式,需要修改代码;
             * 如下,让hour用两个数h1h2来表示;当hour为个位数时,h2=hour,h1=0,显示正常;
             * 如果hour为两位数时,h1=hour/10,h2=hour%10,同样显示正常;
             * 同理,minute,second也同样显示
             * 代码如下:
             * */
            int hour = time.Hour;//获取当前的hour值
            int h1 = 0;
            int h2 = hour; ;
            if (hour >= 10)
            {
                h1 = hour / 10;
                h2 = hour % 10;
            }
            int minute = time.Minute;
            int m1 = 0;
            int m2 = minute;
            if (minute >= 10)
            {
                m1 = minute / 10;
                m2 = minute % 10;
            }
            int second = time.Second;
            int s1 = 0;
            int s2 = second;
            if (second >= 10)
            {
                s1 = second / 10;
                s2 = second % 10; www.zzzyk.com
            }
            label1.Text=string.Format("{0}{1}:{2}{3}:{4}{5}",h1,h2,m1,m2,s1,s2);//label控件显示时间
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            this.GetTime();//time1控件的Tick事件调用显示控件时间的代码
        }
        private void Form3_Load(object sender, EventArgs e)
        {
            this.timer1.Interval = 1000;//设置timer1的Interval属性为1000,即计时器开始计时之间的间隔为1000ms
            this.timer1.Start();//启动计时器
        }
    }
}
 

补充:软件开发 , C# ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,