WPF-计时器

WPF-计时器(自学记录)

用的wpf 为vs2017,应公司要求在采数时加入计时器,并一并保存下来。做个记录,主要为在WPF中,计时器的用法。

xaml中主要用到:textblock 和 textbox;

添加完界面显示后在主界面代码,添加using System.Timers;
主要用的是DispatcherTimer

using System.Timers;
     DispatcherTimer m_Timer1s = null; //定义1S计时器
        TimeSpan _timeSpan = new TimeSpan(0, 0, 0, 0, 0);
        /// 
        /// 状态
        /// 
        enum State
        {
            Start,
            Pause,
            End
        }
        /// 
        /// 状态
        /// 
        State _state = State.End;
         private void Window_Loaded(object sender, RoutedEventArgs e) //初始化
        {
			   m_Timer1s = new DispatcherTimer();      
            m_Timer1s.Interval = new TimeSpan(0, 0, 0, 1);
             m_Timer1s.Tick += Timer1s_Tick; 
            m_Timer1s.IsEnabled = true;
            //m_Timer1s.Stop();
            m_Timer1s.Start();
        }
          private void Timer1s_Tick(object sender, EventArgs e)//计时执行的程序
        {
            switch (_state)
            {
                case State.Start: //开始
                    {
                        _timeSpan += new TimeSpan(0, 0, 0, 1);
                    }
                    break;
                case State.Pause: //暂停
                    {

                    }
                    break;
                case State.End: //结束
                    {
                        _timeSpan = new TimeSpan(); //结束完就归零,重新开始
                        //_timeSpan = new TimeSpan(0, 23, 12, 45, 54);
                    }
                    break;
            }
                    var time = string.Format("{0:00}:{1:00}:{2:00}", _timeSpan.Hours, _timeSpan.Minutes, _timeSpan.Seconds);
                     tb_timer.Text = time;
  
        }

代码就是怎么多,其中State.Start,State.End;类似与 DispatcherTimer这个类,设置一个新的对象,如我的: m_Timer1s = new DispatcherTimer();
然后 m_Timer1s.Start(); m_Timer1s.Stop();
start和stop,我都放在串口打开和关闭处,方便看到接受数据用了多长时间。

代码来自于:https://www.cnblogs.com/simonryan/p/3678581.html

你可能感兴趣的:(WPF-计时器)