c# - 如何让Windows窗体应用程序自动运行?

标签 c# winforms timer

我有一个 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/

相关文章:

c# - 处理刷

.net - 有没有办法静默或自动安装 .NET?

c - 在 C 中创建周期性 Linux 线程的最佳方法是什么

Android 计时器滴答一次后停止

java - 如何用Java制作倒计时器?

c# - 谷歌日历 iCal 提要

c# - 获取类库中的当前目录

c# - 如何在 C# 中使用 EWS 从 Exchange 获取 HTML 和文本格式的电子邮件正文?

c# - 公开可用操作的正确模式

c# - 确定表单是否完全不在屏幕上