函数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 窗体,添加一个 button1,这段代码就可以工作了。