[C#] 纯文本查看 复制代码
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
namespace TimerApp
{
public class TimerApp : Form
{
private readonly int[] minutes = { 1, 5, 10, 15, 20, 25, 30, 45, 60,90,120 };
private Label countdownLabel; // 用于显示剩余时间
private Button activeButton; // 当前正在计时的按钮
public TimerApp()
{
this.Text = "老师专用定时器";
this.Size = new Size(200, 700);
this.StartPosition = FormStartPosition.Manual;
this.Location = new Point(650, 200);
this.FormBorderStyle = FormBorderStyle.FixedToolWindow;
// 创建主布局面板
var mainPanel = new TableLayoutPanel
{
Dock = DockStyle.Fill,
RowCount = 2,
ColumnCount = 1,
};
mainPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 40)); // 倒计时标签高度
mainPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); // 按钮面板占用剩余空间
this.Controls.Add(mainPanel);
// 创建顶部倒计时标签
countdownLabel = new Label
{
Text = "倒计时:",
Font = new Font("微软雅黑", 12),
TextAlign = ContentAlignment.MiddleCenter,
Dock = DockStyle.Fill
};
mainPanel.Controls.Add(countdownLabel, 0, 0);
// 创建按钮面板
FlowLayoutPanel buttonPanel = new FlowLayoutPanel
{
Dock = DockStyle.Fill,
FlowDirection = FlowDirection.TopDown,
WrapContents = false,
AutoScroll = true
};
mainPanel.Controls.Add(buttonPanel, 0, 1);
foreach (int minute in minutes)
{
Button button = new Button
{
Text = $"{minute:00} 分钟",
Font = new Font("微软雅黑", 12),
Size = new Size(120, 50),
Tag = minute
};
button.Click += (sender, e) => StartTimer((Button)sender, minute);
buttonPanel.Controls.Add(button);
}
}
private void StartTimer(Button button, int minutes)
{
if (activeButton != null)
{
// 如果有计时器正在运行,提示用户
MessageBox.Show("已有计时器在运行,请等待完成后再启动新的计时器。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
// 设置当前活动按钮
activeButton = button;
button.BackColor = Color.LightBlue;
int totalSeconds = minutes * 60;
new Thread(() =>
{
while (totalSeconds > 0)
{
// 更新倒计时标签
this.Invoke(new Action(() =>
{
countdownLabel.Text = $"倒计时:{totalSeconds / 60:00}:{totalSeconds % 60:00}";
}));
Thread.Sleep(1000);
totalSeconds--;
}
// 计时结束
this.Invoke(new Action(() =>
{
countdownLabel.Text = "倒计时:完成!";
MessageBox.Show($"{minutes}分钟已到!", "计时完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
// 恢复按钮状态
button.BackColor = SystemColors.Control;
activeButton = null;
}));
}).Start();
}
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new TimerApp());
}
}
}