S_pot

Winform_타이머 본문

C#/C# Winform

Winform_타이머

S_pot 2021. 6. 2. 15:40

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            
        }
        private int iNum;

        private void timer1_Tick(object sender, EventArgs e)
        {
            
            textBox1.Text = iNum.ToString();
            ++iNum;
        }

        private void button1_Click(object sender, EventArgs e)
        {   // 타이머가 움직이고 있다면 멈추고, 움직이지 않고 있다면 움직이게 한다.
            if(timer1.Enabled == true)
            {
                timer1.Enabled = false;
            }
            else
            {
                timer1.Enabled = true;
            }
        }
    }

 

 

시:분:초 나타내기

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            textBox1.Text = "00:00:00";
            
        }
        private int iNum;

        private void timer1_Tick(object sender, EventArgs e)
        {
            ++iNum;
            textBox1.Text = string.Format($"{((iNum/3600)%60).ToString("00")}:{((iNum / 60)%60).ToString("00")}:{(iNum % 60).ToString("00")}"); //:{iNum%60}
             // .ToString("00"): 00 형식으로 초를 표시한다.
             // Console.WriteLine을 쓰지않는 대신 string.Format을 쓴다고 생각하면 쉽다.

        }

        private void button1_Click(object sender, EventArgs e)
        {   // 타이머가 움직이고 있다면 멈추고, 움직이지 않고 있다면 움직이게 한다.
            if(timer1.Enabled == true)
            {
                timer1.Enabled = false;
            }
            else
            {
                timer1.Enabled = true;
            }
        }
    }

 

 

리셋버튼 추가

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            textBox1.Text = "00:00:00";
            
        }
        private int iNum;

        private void timer1_Tick(object sender, EventArgs e)
        {
            ++iNum;
            textBox1.Text = string.Format("{0,2:00}:{1,2:00}:{2,2:00}", (iNum / 3600), (iNum / 60) % 60, iNum % 60);
            //textBox1.Text = string.Format($"{((iNum/3600)%60).ToString("00")}:{((iNum / 60)%60).ToString("00")}:{(iNum % 60).ToString("00")}"); //:{iNum%60}
            // .ToString("00"): 00 형식으로 초를 표시한다.
            // Console.WriteLine을 쓰지않는 대신 string.Format을 쓴다고 생각하면 쉽다.

        }

        private void button1_Click(object sender, EventArgs e)
        {   // 타이머가 움직이고 있다면 멈추고, 움직이지 않고 있다면 움직이게 한다.
            if(timer1.Enabled == true)
            {
                timer1.Enabled = false;
                button1.Text = "재시작";
                
            }
            else
            {
                timer1.Enabled = true;
                button1.Text = "중지";
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            textBox1.Text = "00:00:00";
            iNum = 0;
            button1.Text = "시작";
        }
    }