设置一个起床闹钟,让用户输入时间,如果时间达到,则弹出消息框:“天选之子,起床了迎接朝阳!”
时间: 2024-01-04 17:02:46 浏览: 141
好的,以下是一个实现起床闹钟的示例代码:
1. 在窗体上添加一个 DateTimePicker 控件和一个 Button 控件。
2. 在窗体的 Load 事件处理程序中,将 DateTimePicker 控件的格式设置为 Time,这样用户只能选择时间:
```csharp
private void Form1_Load(object sender, EventArgs e)
{
alarmTimePicker.Format = DateTimePickerFormat.Time;
}
```
3. 在 Button 控件的 Click 事件处理程序中,获取用户选择的时间,并计算时间差。如果时间差小于等于 0,则弹出错误消息框。否则,启动计时器,并设置计时器的间隔时间为时间差:
```csharp
private void setAlarmButton_Click(object sender, EventArgs e)
{
DateTime selectedTime = alarmTimePicker.Value;
TimeSpan timeSpan = selectedTime - DateTime.Now;
if (timeSpan.TotalMilliseconds <= 0)
{
MessageBox.Show("请选择未来的时间!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
alarmTimer.Interval = (int)timeSpan.TotalMilliseconds;
alarmTimer.Start();
MessageBox.Show("闹钟设置成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
```
4. 在计时器的 Tick 事件处理程序中,弹出消息框:
```csharp
private void alarmTimer_Tick(object sender, EventArgs e)
{
MessageBox.Show("天选之子,起床了迎接朝阳!", "闹钟提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
alarmTimer.Stop();
}
```
完整的代码示例:
```csharp
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
alarmTimePicker.Format = DateTimePickerFormat.Time;
}
private void setAlarmButton_Click(object sender, EventArgs e)
{
DateTime selectedTime = alarmTimePicker.Value;
TimeSpan timeSpan = selectedTime - DateTime.Now;
if (timeSpan.TotalMilliseconds <= 0)
{
MessageBox.Show("请选择未来的时间!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
alarmTimer.Interval = (int)timeSpan.TotalMilliseconds;
alarmTimer.Start();
MessageBox.Show("闹钟设置成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void alarmTimer_Tick(object sender, EventArgs e)
{
MessageBox.Show("天选之子,起床了迎接朝阳!", "闹钟提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
alarmTimer.Stop();
}
}
```
注意:在实际使用中,为了提高用户体验,可以考虑在弹出消息框之前播放提示音或震动等来提醒用户。
阅读全文
相关推荐









