如何制作一个计时器,强制应用程序在C#中的指定时间关闭?我有这样的事情:
void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (++counter == 120)
this.Close();
}
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,应用程序将在计时器运行后的120秒内关闭.我需要一个计时器,它将关闭应用程序,例如23:00:00.有什么建议?
您必须解决的第一个问题是System.Timers.Timer将无法正常工作.它在线程池线程上运行Elapsed事件处理程序,这样的线程无法调用Form或Window的Close方法.简单的解决方法是使用同步计时器,System.Windows.Forms.Timer或DispatcherTimer,从问题中应用哪个不清楚.
您唯一需要做的就是计算计时器的Interval属性值.这是相当简单的DateTime算法.如果你总是希望窗口在晚上11点关闭,那么写下这样的代码:
public Form1() {
InitializeComponent();
DateTime now = DateTime.Now; // avoid race
DateTime when = new DateTime(now.Year, now.Month, now.Day, 23, 0, 0);
if (now > when) when = when.AddDays(1);
timer1.Interval = (int)((when - now).TotalMilliseconds);
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e) {
this.Close();
}
Run Code Online (Sandbox Code Playgroud)
我假设你在这里谈论Windows Forms.然后这可能会工作(编辑更改代码所以this.Invoke使用,因为我们在这里讨论多线程计时器):
void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (DateTime.Now.Hour >= 23)
this.Invoke((Action)delegate() { Close(); });
}
Run Code Online (Sandbox Code Playgroud)
如果切换到使用Windows窗体Timer,则此代码将按预期工作:
void myTimer_Elapsed(object sender, EventArgs e)
{
if (DateTime.Now.Hour >= 23)
Close();
}
Run Code Online (Sandbox Code Playgroud)
如果我理解你的要求,让计时器检查每秒的时间似乎有点浪费,你可以做这样的事情:
void Main()
{
//If the calling context is important (for example in GUI applications)
//you'd might want to save the Synchronization Context
//for example: context = SynchronizationContext.Current
//and use if in the lambda below e.g. s => context.Post(s => this.Close(), null)
var timer = new System.Threading.Timer(
s => this.Close(), null, CalcMsToHour(23, 00, 00), Timeout.Infinite);
}
int CalcMsToHour(int hour, int minute, int second)
{
var now = DateTime.Now;
var due = new DateTime(now.Year, now.Month, now.Day, hour, minute, second);
if (now > due)
due.AddDays(1);
var ms = (due - now).TotalMilliseconds;
return (int)ms;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18945 次 |
| 最近记录: |