函数isValidTime仅在一天中的几小时检查时间。
如下所示,您可以使用模块化运算法封装您的密码。
对我来说,以下工作:
private int currentPassword = -1;
private int[] passwords = new int[]{111111,222222,333333,444444,555555};
private DateTime startTime = new DateTime(2012, 7, 18, 22, 0, 0);
private DateTime endTime = new DateTime(2012, 7, 18, 22, 15, 0);
private void button1_Click(object sender, EventArgs e)
{
if (isValidTime(DateTime.Now))
{
currentPassword++;
currentPassword = currentPassword % passwords.Length;
MessageBox.Show(passwords[currentPassword].ToString());
}
else
{
MessageBox.Show("Try again at a different time");
}
}
private bool isValidTime(DateTime now)
{
if (startTime.TimeOfDay.CompareTo(now.TimeOfDay) <= 0)
{
if (now.TimeOfDay.CompareTo(endTime.TimeOfDay) <= 0)
{
return true;
}
}
return false;
}
刚开始一个新的Windows窗体中添加一个按钮1,这个代码应工作。
您正在索引第4个元素数组FYI中的第五个元素。你的代码示例会崩溃。 – 2012-07-19 00:54:56
[如何检查当前时间是否在一个时间范围之内?](http://stackoverflow.com/questions/592248/how-can-i-check-if-the-current-time-is-between在一个时间帧) – zimdanen 2012-07-19 00:58:33