如何使Windows窗体应用程序自动运行

本文关键字:运行 应用程序 窗体 何使 Windows | 更新日期: 2023-09-27 18:02:16

我在c#中有一个Windows窗体应用程序,现在通过点击按钮工作。如何让它每1分钟自动运行一次?

我添加了一个计时器,并试图从主运行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);
}

如何使Windows窗体应用程序自动运行

正如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
}

你可以使用计时器,并有启动和停止按钮

http://msdn.microsoft.com/en-us/library/system.timers.timer%28v=vs.110%29.aspx

 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;

您可以使用工具箱中的Timer组件。它是一个简单的插件,没有绘制,你可以设置时间和事件,将触发