【发布时间】:2014-05-02 05:04:41
【问题描述】:
我的问题是控制台应该保持打开状态。在 Console.ReadLine() 等待输入时,计时器无法将任何内容写入控制台。如何在不使用 Console.ReadLine()、Console.ReadKey() 或 system("pause") 的情况下防止控制台关闭?
这是我的代码:
namespace Closer {
public static class Program {
public static void Main () {
// Define timer
var t = new Windows.Forms.Timer() {
Enabled = true,
Interval = 30000
};
// Give timer the tick function
t.Tick += (object tSender, EventArgs tE) => {
// If it is half past eleven
if (DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() == "2330") {
// Close all osu!.exe's --- works
foreach (Process p in Process.GetProcessesByName("osu!")) {
p.Kill();
}
// Write a msg
Console.WriteLine("Done!");
}
};
// Prevent the console from closing --- Here's the problem
Console.ReadLine();
}
}
}
【问题讨论】:
-
System.Windows.Forms.Timer似乎有问题。我用System.Timers.Timer更新了我的答案。 -
问题不在于 Windows 窗体计时器,而在于您尝试使用它的方式。
System.Windows.Forms.Timer期望在 Windows 窗体应用程序中使用。更具体地说,必须有一个 Windows 消息循环在运行。这不会发生在控制台应用程序中。您会注意到System.Timers.Timer,您的程序与Console.ReadLine配合得很好。 -
@JimMischel 您不应该那样更改 OP 中的代码。这里的具体问题是因为他使用的是 winforms 计时器。将他的代码更改为不同的计时器并因此解决问题会使问题无效。您应该将其发布为答案,而不是对问题的编辑。
-
@Servy:感谢您指出这一点。我误读了 Imran 的评论,说他更改了代码。出于某种原因,我认为 OP 说过 he 更改了代码。伙计,我的脸红了。