简体   繁体   中英

How to make a Windows Form application run automatically?

I have a Windows Form application in C# that right now is working by clicking a button. How I can make it run automatically every 1 minute?

I have added a timer and tried to run Form1 from Main and also I put the code in the Form_Load but it is not running.

Program.cs code:

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);
}

you could use a timer, and have buttons that start and stop it

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;

As answered by Gent , you can use a timer to do something at a preset interval. I would recommend using System.Timers.Timer , as it is the most accurate, but you may also choose to use the System.Windows.Forms.Timer instead.

You can implement a System.Timers.Timer with this:

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
}

You can learn more about timers here .

You can use Timer component from the toolbox. It's a simple drop-in that is not drawn and you can set both timing and event that will be fired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM