windowsformapp帮我写个计时器
时间: 2024-01-22 16:03:27 浏览: 25
好的,以下是一个简单的计时器的Windows Form App程序代码:
```csharp
using System;
using System.Windows.Forms;
namespace TimerApp
{
public partial class Form1 : Form
{
private int _counter = 0;
private Timer _timer = new Timer();
public Form1()
{
InitializeComponent();
_timer.Interval = 1000; // 设置定时器的间隔为1秒
_timer.Tick += new EventHandler(timer_Tick); // 绑定定时器事件
}
private void timer_Tick(object sender, EventArgs e)
{
_counter++;
label1.Text = "计时器:" + _counter.ToString() + " 秒";
}
private void button1_Click(object sender, EventArgs e)
{
_timer.Start(); // 启动定时器
}
private void button2_Click(object sender, EventArgs e)
{
_timer.Stop(); // 停止定时器
_counter = 0; // 计数器清零
label1.Text = "计时器已重置";
}
}
}
```
在窗体设计器中,添加一个 `Label` 控件和两个 `Button` 控件,分别命名为 `label1`、`button1` 和 `button2`。然后将 `button1_Click` 和 `button2_Click` 事件绑定到 `Button` 控件的 `Click` 事件上。
运行程序,单击 `button1` 开始计时,单击 `button2` 停止计时并重置计时器。`Label` 控件将会显示计时器的当前时间。