我在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);
}
答案 0 :(得分:2)
你可以使用计时器,并有按钮启动和停止它
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;
答案 1 :(得分:2)
如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。
答案 2 :(得分:1)
您可以使用工具箱中的Timer
组件。这是一个未绘制的简单插件,您可以设置将被触发的时间和事件。