如何在使用windows应用程序时每5分钟自动运行一次C#代码.已打开
本文关键字:一次 代码 运行 windows 应用程序 5分钟 | 更新日期: 2023-09-27 18:00:41
我想要一个代码,当用户打开我的程序时,代码每5分钟开始执行一次操作。例如,每5分钟屏幕上就会出现一条消息提醒。我想要一个代码来阻止这种情况。例如,当用户单击某个按钮时,该循环将不再执行。当做
与前面提到的其他方法一样,如果使用WinForms,请使用System.Windows.Forms.Timer。您可以将Timer从工具箱拖动到表单,然后它会出现在表单下方。设置Interval = 300000
(5*60*1000转换为毫秒)和Enabled = true
public class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
MessageBox.Show("Annoying message");
}
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Interval = 300000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// button1
//
this.button1.Location = new System.Drawing.Point(89, 49);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "stop timer";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.Button button1;
}
您可以使用Timer类并绑定Elapsed事件来完成工作。
假设操作可以由用户正在运行的同一程序执行,请检查Timer控件。(确切的名称和方法可能因您的平台而异,但您没有告诉我们。)
对于基本解决方案,请查看Timers和MessageBox.Show.