现在的位置: 首页 > 综合 > 正文

c# 动态获取系统当前日期和时间

2013年09月20日 ⁄ 综合 ⁄ 共 893字 ⁄ 字号 评论关闭

1、新建一个windows form 窗体应用程序。

2、在该窗体加载时,输入如下代码

Thread P_thread = new Thread(
                () => //lambda表达式(参数列表)=>{执行语句}  lambda表达式是比匿名方法更加简洁的一种匿名函数语法
                {
                    while (true)
                    {//public Object Invoke (Delegate method)在(拥有此控件的基础窗口句柄的)线程上执行指定的委托。
                     //关于为何使用invoke方法,参见C#中跨线程调用控件的线程安全性方法一文

                        this.Invoke(
                            (MethodInvoker)delegate()//methodinvoke 表示一个委托,该委托可执行托管代码中声明为 void 且不接受任何参数的任何方法。
                                                      //在对控件的 Invoke 方法进行调用时或需要一个简单委托又不想自己定义时可以使用该委托。 
                            {
                                this.Refresh();
                                Graphics P_Graphics = CreateGraphics();
                                // Control.CreateGraphics方法,为控件创建 Graphics。
                                //public Graphics CreateGraphics () 返回值为控件的Graphics。Graphics 类提供将对象绘制到显示设备的方法


                                //public void DrawString(
                                //    string s,
                                //    Font font,
                                //    Brush brush,
                                //    PointF point
                                //)在指定位置point并且用指定的 Brush 和 Font 对象绘制指定的文本字符串s。

                                P_Graphics.DrawString("系统时间:" + DateTime.Now.ToString("yyyy年MM月dd日HH时mm分ss秒"),
                                new Font("宋体", 15),
                                Brushes.Blue,
                                new Point(10, 10));
                            });//this.invoke
                        Thread.Sleep(1000);
                    }//while
                });//new thread
            P_thread.IsBackground = true;
            P_thread.Start();

结果如图:动态显示当前系统的日期和时间

抱歉!评论已关闭.