Oct 8, 2015

C# Basic] Timer




This post is for C# Timer.


Red box is my added item.

I added 2-buttons, 2-texts and 1 timer.

Start timer as click to button '시작'.

Finish timer as click to button '종료'.

First, make global variable 'timerCount'.

1
int timerCount = 0;

And button listener.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
 private void button1_Click(object sender, EventArgs e)
        {
            timer1.Start();
        }
         private void button2_Click(object sender, EventArgs e)
        {
            timer1.Stop();
            timerCount = 0;
            timerText.Text = "00:00:00";
        }

Line 1~4 : button '시작' 

Line 6~11 : button '종료'

Start timer as click button '시작'

Finish timer ans initialize variable as click button '종료'

Below code is timer tick.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
 private void timer_display(object sender, EventArgs e)
        {
            timerCount++;
            int sec = 0, min = 0, hour = 0;
            if (timerCount < 60)
            {
                sec = timerCount;
            }
             else if (timerCount < 3600)
            {
                min = timerCount / 60;
                sec = timerCount % 60;
            }
            else
            {
                hour = timerCount / 3600;
                min = (timerCount % 3600) / 60;
                sec = ((timerCount % 3600) % 60);
            }
                        timerText.Text = hour.ToString("00")+":"+min.ToString("00")+":"+sec.ToString("00");
        }

This code is increase variable and display text and calculate.

Line 20 : ToString() is  to string transfer method. 

Timer set using property window.

You just change Interval.


unit is millisecond. 

Icon spark is set for callback function.

Run~


Click to button '시작'.


Run to timer and display timer text.

No comments:

Post a Comment