函數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