C# 視窗程式範例 -- 計時器

專案下載:TimerDemo.zip

介面設計

請從工具箱中拉出一個 label 與一個 Timer,如下圖所示。

TimerDesign.png

程式內容

然後將 Form1.cs 的程式改成如下內容。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace TimerDemo
{
    public partial class Form1 : Form
    {
        int counter = 0;
        public Form1()
        {
            InitializeComponent();
            timer1.Interval = 1000; // 設定每秒觸發一次
            timer1.Enabled = true; // 啟動 Timer
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            counter++;
            label1.Text = counter.ToString();
        }
    }
}
	

執行結果

計數器會從 0 開始一直往上數,下圖是數到 4 的畫面。

TimerRun.png

改進:變碼錶

執行畫面

TimerCounter.png

程式碼

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        int counter = 0;
        public Form1()
        {
            InitializeComponent();
        }
        private void timer_Tick(object sender, EventArgs e)
        {
            counter++;
            labelTimer.Text = ""+counter;
        }
        private void buttonStart_Click(object sender, EventArgs e)
        {
            timer.Enabled = true;
        }
        private void buttonStop_Click(object sender, EventArgs e)
        {
            timer.Enabled = false;
        }
    }
}
	

文章來源:陳鍾誠 (2010年09月28日),(網頁標題) C# 視窗程式範例 — 計時器,(網站標題) 免費電子書:C# 程式設計,2010年09月28日,取自 http://cs0.wikidot.com/timerdemo ,網頁修改第 8 版。

arrow
arrow

    Johnson峰 發表在 痞客邦 留言(0) 人氣()