c#中定時器的實現。


c/s結構下定時器的實現

在c/s結構下我就是想把時間實時更新出來。我用個lable顯示出來。

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 計時器
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text = DateTime.Now.ToString();
            System.Timers.Timer t = new System.Timers.Timer(1000);//實例化Timer類,設置間隔時間為1000毫秒 就是1秒;
            t.Elapsed += new System.Timers.ElapsedEventHandler(theout);//到達時間的時候執行事件;
            t.AutoReset = true;//設置是執行一次(false)還是一直執行(true);
            t.Enabled = true;//是否執行System.Timers.Timer.Elapsed事件;
           
        }
        public void theout(object source, System.Timers.ElapsedEventArgs e)
        {
            this.Invoke(new TextOption(f));//invok 委托實現跨線程的調用
        }

        delegate void TextOption();//定義一個委托

        void f()
        {
            label1.Text = DateTime.Now.ToString();//調用內容,並用lable1顯示出來。。。
        }

       
    }
}

 

SilverLight中定時器的實現:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Sample
{
    public partial class _94頁例子 : UserControl
    {
        public _94頁例子()
        {
            InitializeComponent();
            DispatcherTimer timer = new DispatcherTimer();
            //設置間隔1秒
            timer.Interval = new TimeSpan(0, 0, 1);
            //創建事件處理
            timer.Tick += new EventHandler(timer_Tick);
            //開始計時
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            tbkTimer.Text = "當前時間:" + DateTime.Now.ToLongTimeString();
        }
    }
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM