我在C#中有一个有4个按钮的表单。我希望在给定的持续时间后禁用所有4个按钮,例如1或2分钟。我在谷歌搜索并找到了这段代码,但它似乎不起作用:
private System.Timers.Timer aTimer = new System.Timers.Timer(60) { AutoReset = false };
protected void Timer2_Tick(object sender, EventArgs e)
{
aTimer = new System.Timers.Timer(60);
aTimer.Interval = 60;
double counter = aTimer.Interval;
counter++;
if (counter >= 60)
{
lib_bt.Enabled = false;
MessageBox.Show("Time Up!");
}
答案 0 :(得分:3)
tick方法将在您定义的间隔后执行。只需确保将Button.Enabled
设置为false。
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
lib_bt.Enabled = false;
MessageBox.Show("Time Up!");
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = false;
button4.Enabled = false;
}
button1
至button4
应替换为按钮的名称。
请注意:
60000
aTimer
定义了两次。为什么?答案 1 :(得分:2)
60秒== 60000毫秒.... fyi
以下是它的外观:
private static System.Timers.Timer myTimer;
public static void Main()
{
myTimer = new System.Timers.Timer(60000); // 60 seconds
myTimer.Elapsed += new ElapsedEventHandler(DisableButtons); // subscribe
myTimer.AutoReset = false; // if you don't want a reset
myTimer.Enabled = true; // enable it
}
// perform when event is fired off
private static void DisableButtons(object source, ElapsedEventArgs e)
{
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = false;
button4.Enbaled = false;
}
答案 2 :(得分:1)
我想在给定的持续时间后禁用所有4个按钮
我认为最简单的方法是使用C#5.0的async / await
async void DisableButtons(int seconds)
{
await Task.Delay(1000 * seconds);
//Your code to disable Buttons
}
只需在代码中的某处调用此方法,它将在 n 秒后禁用按钮。