WPF—DispatcherTimer

作者:追风剑情 发布于:2019-8-20 21:55 分类:C#

示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;//DispatcherTimer

namespace WpfApp6
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        //WPF专用Timer
        private DispatcherTimer timer;

        public MainWindow()
        {
            InitializeComponent();

            timer = new DispatcherTimer();
            timer.Tick += new EventHandler(OnTick);
            timer.Interval = new TimeSpan(0, 0, 1);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //判断timer是否已启动
            if (!timer.IsEnabled)
            {
                timer.Start();
            }
        }

        private void OnTick(object sender, EventArgs e)
        {
            Console.WriteLine("Second: {0}", DateTime.Now.Second);
            //DispatcherTimer的回调函数里可访问UI元素
            textBlock.Text = DateTime.Now.Second.ToString();
        }

        // 窗口关闭事件
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (timer != null)
                timer.Stop();
        }
    }
}

运行测试

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号