본문 바로가기
프로그래밍/C# (WinForms)

C#, WinForms ] 스탑워치, Stopwatch 클래스, DateTime 구조체, Timer 활용

by eteo 2023. 2. 20.
 

 

 

 

 

 

using System.Diagnostics;

//...

private Stopwatch stopwatch = new Stopwatch();

public Form1()
{
    InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
    // textBox 초기값
    this.textBox2.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
    this.textBox2.Text = "";
}

private void button1_Click(object sender, EventArgs e)
{
    // Stopwatch, Timer 스타트
    stopwatch.Start();
    this.timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    TimeSpan duration = stopwatch.Elapsed;
    //this.textBox1.Text = duration.ToString("hh\\:mm\\:ss\\.fff");
    this.textBox1.Text = duration.ToString(@"hh\:mm\:ss\.fff");
}

private void timer2_Tick(object sender, EventArgs e)
{
    // 1초 간격 현재시간 표시
    this.textBox2.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}

private void button2_Click(object sender, EventArgs e)
{        
    // Stopwatch, Timer 스탑
    stopwatch.Stop();
    timer1.Stop();
}

 

 

using System.Diagnostics;

하고

Stopwatch 객체 통해 Elapsed time 추적. 1ms 인터벌 Timer_tick 이벤트 통해서 Timespan으로 구한 두 시간사이 간격을 화면에 표시

 

 

https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch?view=net-7.0 

 

Stopwatch Class (System.Diagnostics)

Provides a set of methods and properties that you can use to accurately measure elapsed time.

learn.microsoft.com