新书推介:《语义网技术体系》
作者:瞿裕忠,胡伟,程龚
   XML论坛     W3CHINA.ORG讨论区     计算机科学论坛     SOAChina论坛     Blog     开放翻译计划     新浪微博  
 
  • 首页
  • 登录
  • 注册
  • 软件下载
  • 资料下载
  • 核心成员
  • 帮助
  •   Add to Google

    >> 本版讨论.NET,C#,ASP,VB技术
    [返回] 中文XML论坛 - 专业的XML技术讨论区计算机技术与应用『 Dot NET,C#,ASP,VB 』 → C# Timer范例教程 查看新帖用户列表

      发表一个新主题  发表一个新投票  回复主题  (订阅本版) 您是本帖的第 5617 个阅读者浏览上一篇主题  刷新本主题   树形显示贴子 浏览下一篇主题
     * 贴子主题: C# Timer范例教程 举报  打印  推荐  IE收藏夹 
       本主题类别:     
     卷积内核 帅哥哟,离线,有人找我吗?
      
      
      威望:8
      头衔:总统
      等级:博士二年级(版主)
      文章:3942
      积分:27590
      门派:XML.ORG.CN
      注册:2004/7/21

    姓名:(无权查看)
    城市:(无权查看)
    院校:(无权查看)
    给卷积内核发送一个短消息 把卷积内核加入好友 查看卷积内核的个人资料 搜索卷积内核在『 Dot NET,C#,ASP,VB 』的所有贴子 访问卷积内核的主页 引用回复这个贴子 回复这个贴子 查看卷积内核的博客楼主
    发贴心情 C# Timer范例教程

    这是一个关于Timer的例子,我们将创建一个简单的应用程序,使用Timer对象来倒计时一个由自己设定的时间并循环播放一段音乐,直到重设Timer控件。

    Timer对象基础

            首先你要知道的是,使用Timer对象你需要访问如下命名空间:

            using System.Threading;
            using System.Timers;

            接下来,介绍一下创建一个Timer的要点以及为这个timer对象的Elapsed事件设定事件委派。
            先创建一个Timer对象,这里定义使用的timer为timerClock。接下来设定Elapsed事件委派,当事件被触发时,指定的委派将被调用,这里定义使用的委派名称为OnTimer()。
            接着,设定Interval属性,使用毫秒数值指示希望Elapsed事件被调用的间隔,这意味着,当定义Interval属性为1000毫秒时,定义的委派OnTimer()将每隔1000毫秒被调用一次,或者说是每隔1秒。
            最后,需要设定Enabled属性为true,以使这个timer对象开始工作。接下来,剩下的只是一个小问题—创建一个委派,在这个timer对象的Elapsed属性被触发时调用。如果以前没有使用过委派,不用担心,它们很容易使用,只需要创建一个方法,用来接收适合你捕获事件的一些变量。
            针对Elapsed事件,这个委派需要接收一个普通对象和一个ElapsedEventArgs对象。

    private System.Timers.Timer timerClock = new System.Timers.Timer();    
    timerClock.Elapsed += new ElapsedEventHandler(OnTimer);
    timerClock.Interval = 1000;
    timerClock.Enabled = true;


    public void OnTimer( Object source, ElapsedEventArgs e )
    {
        //Your code here
    }

    在报警程序中使用Timer控件

            介绍了这些基础,现在来看在实际应用中的代码。注意,这里并不包括播放音乐和显示最小化图标的代码。
            在下面的代码中,可以看到,将实例化Timer对象的方法放在初始化方法InitializeTimer()中,这个方法将被类构造调用。并且创建了两个方法,inputToSeconds()和secondsToTime()用来将字符串格式的时间格式转换为正型,以及一个反处理过程。这些方法只是用来帮助我们在TextBox控件中显示日期格式,这在整个应用的结构中,并不十分重要。其他的那些代码,是标准的Visual Studio.NET为Win Form程序生成的样板文件。


       收藏   分享  
    顶(0)
      




    ----------------------------------------------
    事业是国家的,荣誉是单位的,成绩是领导的,工资是老婆的,财产是孩子的,错误是自己的。

    点击查看用户来源及管理<br>发贴IP:*.*.*.* 2009/9/5 13:47:00
     
     卷积内核 帅哥哟,离线,有人找我吗?
      
      
      威望:8
      头衔:总统
      等级:博士二年级(版主)
      文章:3942
      积分:27590
      门派:XML.ORG.CN
      注册:2004/7/21

    姓名:(无权查看)
    城市:(无权查看)
    院校:(无权查看)
    给卷积内核发送一个短消息 把卷积内核加入好友 查看卷积内核的个人资料 搜索卷积内核在『 Dot NET,C#,ASP,VB 』的所有贴子 访问卷积内核的主页 引用回复这个贴子 回复这个贴子 查看卷积内核的博客2
    发贴心情 
    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using System.Threading;
    using System.Timers;
    using System.IO;
    using System.Reflection;


    namespace timerAlarm
    {
        public class TimerForm : System.Windows.Forms.Form
        {
            //Controls and Components
            private System.Windows.Forms.TextBox timerInput;
            private System.Windows.Forms.Button StartButton;
            private System.Windows.Forms.Button ResetButton;
            private System.ComponentModel.IContainer components;
            //Timer and associated variables
            private System.Timers.Timer timerClock = new System.Timers.Timer();
            private int clockTime = 0;
            private int alarmTime = 0;


            public TimerForm()
            {
                InitializeComponent();
                InitializeTimer();
            }


            protected override void Dispose( bool disposing )
            {
                if( disposing )
                {
                    if (components != null)
                    {
                        components.Dispose();
                    }
                }
                base.Dispose( disposing );
            }


            #region Windows Form Designer generated code
           #endregion


            public void InitializeTimer()
            {
                this.timerClock.Elapsed += new ElapsedEventHandler(OnTimer);
                this.timerClock.Interval = 1000;
                this.timerClock.Enabled = true;
            }


            [STAThread]
            static void Main()
            {
                Application.Run(new TimerForm());
            }


            private void TimerForm_Resized(object sender, System.EventArgs e)
            {
                if( this.WindowState == FormWindowState.Minimized )
                {
                    this.Hide();
                }
            }


            private void StartButton_Click(object sender, System.EventArgs e)
            {
                this.clockTime = 0;
                inputToSeconds( this.timerInput.Text );
            }


            private void ResetButton_Click(object sender, System.EventArgs e)
            {
                try
                {
                    this.clockTime = 0;
                    this.alarmTime = 0;
                    this.timerInput.Text = "00:00:00";
                }
                catch( Exception ex )
                {
                    MessageBox.Show("ResetButton_Click(): " + ex.Message );
                }
            }


            public void OnTimer(Object source, ElapsedEventArgs e)
            {
                try
                {
                    this.clockTime++;
                    int countdown = this.alarmTime - this.clockTime ;
                    if( this.alarmTime != 0 )
                    {
                        this.timerInput.Text = secondsToTime(countdown);
                    }


                    //Sound Alarm
                    if( this.clockTime == this.alarmTime )
                    {
                        MessageBox.Show("Play Sound");
                    }
                }
                catch( Exception ex )
                {
                    MessageBox.Show("OnTimer(): " + ex.Message );
                }        
            }


            private void inputToSeconds( string timerInput )
            {
                try
                {
                    string[] timeArray = new string[3];
                    int minutes = 0;
                    int hours = 0;
                    int seconds = 0;
                    int occurence = 0;
                    int length = 0;


                    occurence = timerInput.LastIndexOf(":");
                    length = timerInput.Length;


                    //Check for invalid input
                    if( occurence == -1 || length != 8 )
                    {
                        MessageBox.Show("Invalid Time Format.");
                        ResetButton_Click( null, null );
                    }
                    else
                    {
                        timeArray = timerInput.Split(':');


                        seconds = Convert.ToInt32( timeArray[2] );
                        minutes = Convert.ToInt32( timeArray[1] );
                        hours = Convert.ToInt32( timeArray[0] );


                        this.alarmTime += seconds;
                        this.alarmTime += minutes*60;
                        this.alarmTime += (hours*60)*60;
                    }
                }
                catch( Exception e )
                {
                    MessageBox.Show("inputToSeconds(): " + e.Message );
                }
            }


            public string secondsToTime( int seconds )
            {
                int minutes = 0;
                int hours = 0;


                while( seconds >= 60 )
                {
                    minutes += 1;
                    seconds -= 60;
                }
                while( minutes >= 60 )
                {
                    hours += 1;
                    minutes -= 60;
                }


                string strHours = hours.ToString();
                string strMinutes = minutes.ToString();
                string strSeconds = seconds.ToString();


                if( strHours.Length < 2 )
                    strHours = "0" + strHours;
                if( strMinutes.Length < 2 )
                    strMinutes = "0" + strMinutes;
                if( strSeconds.Length < 2 )
                    strSeconds = "0" + strSeconds;


                return strHours + ":" + strMinutes + ":" + strSeconds;
            }
        }
    }


            实际的执行代码比上面的要多,本范例演示了Timer在实际环境中的一个简单应用,仅仅使用了一些简单的基础知识来创建一个简单的应用。

    ----------------------------------------------
    事业是国家的,荣誉是单位的,成绩是领导的,工资是老婆的,财产是孩子的,错误是自己的。

    点击查看用户来源及管理<br>发贴IP:*.*.*.* 2009/9/5 13:47:00
     
     GoogleAdSense
      
      
      等级:大一新生
      文章:1
      积分:50
      门派:无门无派
      院校:未填写
      注册:2007-01-01
    给Google AdSense发送一个短消息 把Google AdSense加入好友 查看Google AdSense的个人资料 搜索Google AdSense在『 Dot NET,C#,ASP,VB 』的所有贴子 访问Google AdSense的主页 引用回复这个贴子 回复这个贴子 查看Google AdSense的博客广告
    2024/5/2 22:13:21

    本主题贴数2,分页: [1]

    管理选项修改tag | 锁定 | 解锁 | 提升 | 删除 | 移动 | 固顶 | 总固顶 | 奖励 | 惩罚 | 发布公告
    W3C Contributing Supporter! W 3 C h i n a ( since 2003 ) 旗 下 站 点
    苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
    4,015.625ms