• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

WPF使用Timer实现计时器

武飞扬头像
无敌小朱哥
帮助1

  1.  
    <Window x:Class="time2.MainWindow"
  2.  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.  
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.  
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5.  
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6.  
    xmlns:local="clr-namespace:time2"
  7.  
    mc:Ignorable="d"
  8.  
    Title="MainWindow" Height="450" Width="800">
  9.  
    <Grid>
  10.  
    <Label Name="Label_OtherResult" HorizontalAlignment="Left" Margin="0,28,0,0" VerticalAlignment="Top" Height="300" Width="800" FontSize="120" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Background="CadetBlue" FontWeight="Bold"/>
  11.  
    <Button Content="开始" HorizontalAlignment="Left" Margin="197,359,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1" />
  12.  
    <Button Content="结束" HorizontalAlignment="Left" Margin="509,359,0,0" VerticalAlignment="Top" Click="Button_Click" Width="75"/>
  13.  
     
  14.  
    </Grid>
  15.  
    </Window>
学新通

上面是界面代码,布局比较简单,没有太多的花里胡哨

  1.  
    public partial class MainWindow : Window
  2.  
    {
  3.  
    System.Timers.Timer timer;
  4.  
    public MainWindow()
  5.  
    {
  6.  
    InitializeComponent();
  7.  
    if (timer == null)
  8.  
    {
  9.  
    timer = new System.Timers.Timer();
  10.  
    timer.Interval = 1;
  11.  
    timer.Elapsed = timer_Elapsed;
  12.  
    }
  13.  
     
  14.  
    }
  15.  
     
  16.  
    void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
  17.  
    {
  18.  
     
  19.  
    this.Dispatcher.BeginInvoke(new Action(() =>
  20.  
    {
  21.  
    this.Label_OtherResult.Content = DateTime.Now.ToString("%H:mm:s:fff");
  22.  
    }), null);
  23.  
    }
  24.  
     
  25.  
    private void Button_Click_1(object sender, RoutedEventArgs e)
  26.  
    {
  27.  
     
  28.  
    timer.Start();
  29.  
    }
  30.  
     
  31.  
    private void Button_Click(object sender, RoutedEventArgs e)
  32.  
    {
  33.  
    timer.Close();
  34.  
    ; }
学新通

这一块主要是使用了System.Timers.Timer而不是使用DispatcherTimer(distime),在刷新频率很高的情况下distime会有卡顿出现

tostring中是以小时:分钟:秒:毫秒的形式转换,正好做到的项目需求是毫秒后3位,时间格式这一块就不多赘述了

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfiiaea
系列文章
更多 icon
同类精品
更多 icon
继续加载