wpf自定义计时器控件

本文介绍了一种自定义WPF计时控件的方法,包括控件的创建过程及其实现的功能。该控件具备开始、暂停和停止等功能,并通过代码详细展示了如何实现这些功能。

最近要用到一个计时功能,所以临时写了一个控件,以备以后再次使用,不够完善,但功能算是实现了.效果图如下:这里写图片描述
————————–分割线———————————————-
步骤:
1.新建一个类库,名为wpfCustomControls(或其它,下同)
这里写图片描述
删除默认的cs文件.添加一个Theme文件夹,在Theme文件夹下新建一个资源字典名为Generic.xaml .结构如下,右击项目,添加一个自定义控件(wpf),名为Timer.cs,最终目录结构为:
这里写图片描述
———————-注意注意—–要上代码了——————————–
2.Timer.cs内Timer类

public class Timer : Control
    {
        static Timer()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(Timer), new FrameworkPropertyMetadata(typeof(Timer)));
        }
        public Timer()
        {
            timer.Interval = per;
            timer.Tick += Timer_Tick1;
        }
        private void Timer_Tick1(object sender, EventArgs e)
        {
            TimeSpan temp = DateTime.Now - StartTime - pauseTime;
            _text = string.Format("{0}:{1}:{2}", temp.Minutes, temp.Seconds, temp.Milliseconds);
        }
        private TimeSpan per = new TimeSpan(0, 0, 0, 0, 45);//时间间隔
        DispatcherTimer timer=new DispatcherTimer();//计时器
        public int status = 0;//0初始状态  1  进行状态  2 暂停状态
        public string _text
        {
            get { return (string)GetValue(_textProperty); }
            set { SetValue(_textProperty, value); }
        }
        /// <summary>
        /// 界面绑定用于显示时间
        /// </summary>
        public static readonly DependencyProperty _textProperty =
            DependencyProperty.Register("_text", typeof(string), typeof(Timer), new PropertyMetadata("0:0:0"));
        public static readonly RoutedEvent StatusChangedEvent = EventManager.RegisterRoutedEvent("StatusChanged", RoutingStrategy.Bubble, typeof(RoutedPropertyChangedEventHandler<int>), typeof(Timer));
        public event RoutedPropertyChangedEventHandler<int> StatusChanged
        {
            add { AddHandler(StatusChangedEvent, value); }
            remove { RemoveHandler(StatusChangedEvent, value); }
        }

        private TimeSpan pauseTime=TimeSpan.Zero;//从开始到现在期间暂停的时间
        private DateTime pauseStartTime;// 暂停 开始的时间

        private DateTime startTime;
        public DateTime StartTime
        {
            get { return startTime; }
            set { startTime = value;}
        }
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            Button csBtn = base.GetTemplateChild("ChangeStatusButton") as Button;
            if (csBtn != null)
            {
                csBtn.Click += ChangedStatusButton_Click;
            }
            Button stopBtn = base.GetTemplateChild("StopButton") as Button;
            if(stopBtn!=null)
            {
                stopBtn.Click += StopBtn_Click;
            }
        }
        private void StopBtn_Click(object sender, RoutedEventArgs e)
        {
            int oldstatus = status;
            status = 0;
            timer.Stop();
            Button csBtn = base.GetTemplateChild("ChangeStatusButton") as Button;
            if (csBtn != null)
            {
                csBtn.Content = "开始";
            }
            RaiseStatusChangedEvent(oldstatus, status);
        }
        private void RaiseStatusChangedEvent(int oldvalue,int newvalue)
        {
            RoutedPropertyChangedEventArgs<int> args = new RoutedPropertyChangedEventArgs<int>(oldvalue, newvalue);
            args.RoutedEvent = StatusChangedEvent;
            this.RaiseEvent(args);
        }
        private void ChangedStatusButton_Click(object sender, RoutedEventArgs e)
        {
            Button csBtn = sender as Button;
            if (status == 0)
            {
                pauseTime = TimeSpan.Zero;
                _text = "0:0:0";
                int oldstatus = status;
                status = 1;
                startTime = DateTime.Now;
                timer.Start();
                csBtn.Content = "暂停";
                RaiseStatusChangedEvent(oldstatus, status);
            }
            else if (status == 1)
            {
                int oldstatus = status;
                status = 2;
                pauseStartTime = DateTime.Now;
                timer.Stop();
                csBtn.Content = "继续";
                RaiseStatusChangedEvent(oldstatus, status);
            }
            else  // if(status==2)//必然(继续)
            {
                int oldstatus = status;
                status = 1;
                pauseTime = pauseTime.Add(DateTime.Now - pauseStartTime);
                timer.Start();
                csBtn.Content = "暂停";
                RaiseStatusChangedEvent(oldstatus, status);
            }
        }
    }

——————–又要上了—————————————————–

Timer.xaml内容如下:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:WpfCustomControls">
    <Style TargetType="{x:Type local:Timer}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:Timer}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Padding="0" Margin="0" Width="{TemplateBinding Width}"
                            Height="{TemplateBinding Height}"
                            CornerRadius="5">
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="4*"></ColumnDefinition>
                                <ColumnDefinition Width="1.6*"></ColumnDefinition>
                                <ColumnDefinition Width="1.6*"></ColumnDefinition>
                            </Grid.ColumnDefinitions>
                            <TextBlock HorizontalAlignment="Left" Margin="10 0 0 0" VerticalAlignment="Center" Grid.Column="0" Text="{TemplateBinding _text}"></TextBlock>
                            <Button Name="ChangeStatusButton" Grid.Column="1" Width="40" Content="开始" Background="Transparent" HorizontalAlignment="Center" Margin="1" BorderThickness="0"></Button>
                            <Button Name="StopButton" Grid.Column="2" Content="结束" Background="Transparent" HorizontalAlignment="Center" Margin="1" BorderThickness="0">
                            </Button>
                        </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

—————————-完成后先生成项目—————————————

右击解决方案,新建一个wpf应用程序 ,
添加wpfCustomControls的引用,
双击打开MainWindow.xaml
添加下图标注内容:这里写图片描述

—————————–ok——————————–
好了,现在已经可以运行了.
分享经验,为小白指路,虽然我自己也是小白^_^
如有不懂,欢迎留言.

WPF 秒表 计时器 定时关机 到计时关机 public const uint WM_SYSCOMMAND = 0x0112; public const uint SC_MONITORPOWER = 0xF170; [DllImport("user32")] public static extern IntPtr SendMessage(IntPtr hWnd, uint wMsg, uint wParam, int lParam); /// /// 关闭显示器 /// public void CloseScreen() { IntPtr windowHandle = Process.GetCurrentProcess().MainWindowHandle; SendMessage(windowHandle, WM_SYSCOMMAND, SC_MONITORPOWER, 2); // 2 为关闭显示器, -1则打开显示器 } 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; using IniFiles; namespace StopWatch { /// /// shutdonwCtrl.xaml 的交互逻辑 /// public partial class shutdonwCtrl : UserControl { DispatcherTimer timer1; DispatcherTimer timer2; public shutdonwCtrl() { InitializeComponent(); timer1 = new DispatcherTimer(); timer1.Tick += new EventHandler(OnTimer1); timer1.Interval = new TimeSpan(0, 0, 1); timer2 = new DispatcherTimer(); timer2.Tick += new EventHandler(OnTimer2); timer2.Interval = new TimeSpan(0, 0, 1); btn_cancel.IsEnabled = false; cancel1.IsEnabled = false; } IniFile INI = new IniFile(IniFile.AppIniName); public void LoadIni() { cbo_hour.Text = INI.ReadString("定时关机", "时", "0"); cbo_Minute.Text = INI.ReadString("定时关机", "分", "0"); cbo_Second.Text = INI.ReadString("定时关机", "秒", "0"); cbo1.Text = INI.ReadString("到计时关机", "分", "0"); //combobox1.Text = INI.ReadString("到计时", "时", "0"); //combobox2.Text = INI.ReadString("到计时", "分", "0"); //combobox3.Text = INI.ReadString("到计时", "秒", "0"); } public void SaveIni() { INI.WriteString("定时关机", "时", cbo_hour.Text); INI.WriteString("定时关机", "分", cbo_Minute.Text); INI.WriteString("定时关机", "秒", cbo_Second.Text); INI.WriteString("到计时关机", "分", cbo1.Text); } private void ShutDown() { System.Diagnostics.Process.Start("shutdown.exe", "-s -t 1"); } private void OnTimer1(object sender,EventArgs e) { if (second > 0) second--; label1.Content = string.Format("Windows将在 {0} 关机", TimerClass.GetTimeString1(second)); if (second <= 0 && !cbo1.IsEnabled) { ShutDown(); } } int second = 0; private void Button_Click(object sender, RoutedEventArgs e) { second = Convert.ToInt32(cbo1.Text) * 60; if (second <= 0) { MessageBox.Show("数值必须大于0!"); return; } timer1.Start(); cbo1.IsEnabled = false; cancel1.IsEnabled = true; start1.IsEnabled = false; } private void Button_Click_1(object sender, RoutedEventArgs e) { label1.Content = " "; timer1.Stop(); second = 0; cbo1.IsEnabled = true; cancel1.IsEnabled = false; start1.IsEnabled = true; } private void OnTimer2(object sender, EventArgs e) { if ( DateTime.Now.Hour == Convert.ToInt32(cbo_hour.Text) && DateTime.Now.Minute == Convert.ToInt32(cbo_Minute.Text) && DateTime.Now.Second == Convert.ToInt32(cbo_Second.Text) ) { ShutDown(); } } private void Button_Click_2(object sender, RoutedEventArgs e) { int s = Convert.ToInt32(cbo_hour.Text) * 3600 + Convert.ToInt32(cbo_Minute.Text) * 60 + Convert.ToInt32(cbo_Second.Text); timer2.Start(); label2.Content = string.Format("Windows将在 {0} 关机", TimerClass.GetTimeString1(s)); btn_start.IsEnabled = false; btn_cancel.IsEnabled = true; cbo_hour.IsEnabled = false; cbo_Minute.IsEnabled = false; cbo_Second.IsEnabled = false; } private void btn_cancel_Click(object sender, RoutedEventArgs e) { label2.Content = ""; timer2.Stop(); btn_start.IsEnabled = true; btn_cancel.IsEnabled = false; cbo_hour.IsEnabled = true; cbo_Minute.IsEnabled = true; cbo_Second.IsEnabled = true; } } } 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.Threading.Tasks; using System.Runtime.InteropServices; using System.Windows.Threading; using IniFiles; namespace StopWatch { /// /// TimerCtrl.xaml 的交互逻辑 /// public partial class TimerCtrl : UserControl { private DispatcherTimer timer1 = null; private DispatcherTimer timer2 = null; int SND_SYNC = 0x0000; /* play asynchronously */ //异步 int SND_ASYNC = 0x0001; int SND_LOOP = 8; [DllImport("winmm")] public static extern bool PlaySound(string szSound, IntPtr hMod, int flags); private void playSound3() { Task tsk = new Task(new Action(proc)); tsk.Start(); } private void proc() { PlaySound(@"Sound\2.wav", IntPtr.Zero, SND_SYNC); PlaySound(@"Sound\2.wav", IntPtr.Zero, SND_SYNC); PlaySound(@"Sound\2.wav", IntPtr.Zero, SND_SYNC); } public TimerCtrl() { InitializeComponent(); timer1 = new DispatcherTimer(); timer1.Tick += new EventHandler(OnTimer1); timer1.Interval = new TimeSpan(0, 0, 1); timer2 = new DispatcherTimer(); timer2.Tick += new EventHandler(OnTimer2); timer2.Interval = new TimeSpan(0, 0, 1); btn_reset1.IsEnabled = false; btn_pause1.IsEnabled = false; } int h = 0; int m = 0; int s = 0; int seconds = 0; private void OnTimer1(object sender, EventArgs e) { if (seconds < 1) { PlaySound(@"Sound\2.wav", IntPtr.Zero, SND_ASYNC); btn_start.IsEnabled = false; btn_reset1.IsEnabled = true; btn_pause1.IsEnabled = false; combobox1.IsEnabled = true; combobox2.IsEnabled = true; combobox3.IsEnabled = true; return; } seconds--; label1.Content = TimerClass.GetTimeString1(seconds); } private void btn_start_Click(object sender, RoutedEventArgs e) { h = Convert.ToInt32(combobox1.Text); m = Convert.ToInt32(combobox2.Text); s = Convert.ToInt32(combobox3.Text); seconds = h * 3600 + m * 60 + s; label1.Content = TimerClass.GetTimeString1(seconds); timer1.Start(); btn_start.IsEnabled = false; btn_reset1.IsEnabled = true; btn_pause1.IsEnabled = true; combobox1.IsEnabled = false; combobox2.IsEnabled = false; combobox3.IsEnabled = false; } private void btn_reset_Click(object sender, RoutedEventArgs e) { seconds = 0; label1.Content = TimerClass.GetTimeString1(seconds); timer1.Stop(); btn_start.IsEnabled = true; btn_reset1.IsEnabled = false; btn_pause1.IsEnabled = false; combobox1.IsEnabled = true; combobox2.IsEnabled = true; combobox3.IsEnabled = true; } private void pause1_Click(object sender, RoutedEventArgs e) { if (btn_pause1.Content.ToString() == "暂停") { timer1.Stop(); btn_pause1.Content = "继续"; } else { timer1.Start(); btn_pause1.Content = "暂停"; } } int SEC = 0; private void OnTimer2(object sender, EventArgs e) { if (SEC < 1) { timer2.Stop(); playSound3(); btn_quick.IsEnabled = true; btn_cancel2.IsEnabled = false; combobox4.IsEnabled = true; return; } SEC--; label4.Content = TimerClass.GetTimeString1(SEC); } private void Button_Click(object sender, RoutedEventArgs e) { SEC = Convert.ToInt32(combobox4.Text) * 60; timer2.Start(); combobox4.IsEnabled = false; btn_quick.IsEnabled = false; btn_cancel2.IsEnabled = true; } private void Button_Click_1(object sender, RoutedEventArgs e) { SEC = 2; label4.Content = "00:00:00"; timer2.Stop(); combobox4.IsEnabled = true; btn_quick.IsEnabled = true; } IniFile INI = new IniFile(IniFile.AppIniName); public void LoadIni() { combobox1.Text = INI.ReadString("到计时", "时", "0"); combobox2.Text = INI.ReadString("到计时", "分", "0"); combobox4.Text = INI.ReadString("快速计时", "分", "0"); } public void SaveIni() { INI.WriteString("到计时", "时", combobox1.Text); INI.WriteString("到计时", "分", combobox2.Text); INI.WriteString("到计时", "秒", combobox3.Text); INI.WriteString("快速计时", "分", combobox4.Text); } } } 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.Threading; using System.Windows.Threading; namespace StopWatch { /// /// WatchCtrl.xaml 的交互逻辑 /// public partial class WatchCtrl : UserControl { public WatchCtrl() { InitializeComponent(); timer1 = new DispatcherTimer(); timer1.Tick += new EventHandler(OnTimer1); timer1.Interval = new TimeSpan(0, 0, 1); timer1_1 = new DispatcherTimer(); timer1_1.Tick += new EventHandler(OnTimer1_1); timer1_1.Interval = new TimeSpan(0, 0, 0, 100); timer2 = new DispatcherTimer(); timer2.Tick += new EventHandler(OnTimer2); timer2.Interval = new TimeSpan(0, 0, 1); } private DispatcherTimer timer1 = null; private DispatcherTimer timer1_1 = null; private DispatcherTimer timer2 = null; private void OnTimer1(object sender, EventArgs e) { second++; label1.Content = TimerClass.GetTimeString1(second) ;//DateTime.Now.ToString("h:mm:ss"); } public int second = 0; private int second1 = 0; public int count = 0; private void OnTimer1_1(object sender, EventArgs e) { //label1.Content = TimerClass.GetTimeString1(second) + "." + count.ToString();//DateTime.Now.ToString("h:mm:ss"); //count++; //if (count > 9) // count = 0; } private void OnTimer2(object sender, EventArgs e) { second1++; label2.Content = TimerClass.GetTimeString1(second1) ;//.ToString("h:mm:ss"); } private void btn_start_Click(object sender, RoutedEventArgs e) { timer1.Start(); timer2.Start(); if (btn_start.Content.ToString() == "停止") { btn_start.Content = "开始"; btn_reset.Content = "复位"; timer1.Stop(); timer2.Stop(); } else { btn_start.Content = "停止"; btn_reset.Content = "计次"; } } private int counter = 0; private void btn_reset_Click(object sender, RoutedEventArgs e) { if (btn_reset.Content.ToString() == "复位") { second = 0; second1 = 0; label1.Content = "00:00:00"; label2.Content = "00:00:00"; timer1.Stop(); timer2.Stop(); } else { if (second1 > 0) { counter++; listbox1.Items.Add(string.Format(" {0}\t{1}", counter, label2.Content)); } second1 = 0; label2.Content = "00:00:00"; } if (btn_reset.Content.ToString() == "复位" && btn_start.Content.ToString()=="开始") { listbox1.Items.Clear(); } } } }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值