본문 바로가기

Project/SMI

[C#] Timer 사용


//버튼 클릭 시 타이머 시작
private void beforebt_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true; // timer1_Tick 실행시 먼저 true로 설정
            timer1.Tick += new EventHandler(timer1_Tick);
            if (BeforeCompare)
            {
                BeforeSettingProc();
            }
        }

void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Interval = 1000;
            TimerSecond++;
           
            if (t3.Minutes == TimerMin && t3.Hours == TimerHour)
            {
                //Sound play todo
                MessageBox.Show("sound ok");
                TimeReInit();// 다시 시간을 초기화 (timer1.Enabled = false로 설정)
            }
            else
            {
                if (TimerSecond == 60)
                {
                    TimerMin++;
                    TimerSecond = 0;
                    if (TimerMin == 60)
                    {
                        TimerHour++;
                        TimerMin = 0;
                    }
                }
            }
        }

Timer1_Tick 이벤트 함수 호출전 Enabled를 제일 먼저 True로 바꿔줘야 Tick함수가 호출된다.

이와 같은 코드는 타이머 이벤트 발생 X (버튼을 두번 누르면 발생 할 수도 ???)
잘못된 코드방식이다.

timer1.Tick += new EventHandler(timer1_Tick);
timer1.Enabled = true;