我有一个 C# 语言的 Windows 窗体应用程序,现在可以通过单击按钮来工作。如何让它每 1 分钟自动运行一次?
我添加了一个计时器并尝试从 Main 运行 Form1,并且我将代码放入 Form_Load 但它没有运行。
Program.cs代码:
private static System.Timers.Timer aTimer;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
Form1.cs:
private void Form1_Load(object sender, EventArgs e)
{
string id = GetApprecord();
GetDecisionrecord();
GetRecordFromBothTable();
passXML(xml);
}
最佳答案
正如 Gent 所回答的,您可以使用计时器按照预设的时间间隔执行某些操作。我建议使用 System.Timers.Timer
,因为它是最准确的,但您也可以选择使用 System.Windows.Forms.Timer
相反。
您可以使用以下方法实现System.Timers.Timer
:
private static System.Timers.Timer timer;
private void Form1_Load(object sender, System.EventArgs e)
{
timer = new System.Timers.Timer(); // Create a new timer instance
timer.Elapsed += new ElapsedEventHandler(Button1_Click); // Hook up the Elapsed event for the timer.
timer.AutoReset = true; // Instruct the timer to restart every time the Elapsed event has been called
timer.SynchronizingObject = this; // Synchronize the timer with this form UI (IMPORTANT)
timer.Interval = 1000; // Set the interval to 1 second (1000 milliseconds)
timer.Enabled = true; // Start the timer
}
您可以了解有关计时器的更多信息 here .
关于c# - 如何让Windows窗体应用程序自动运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23506661/