目前我正在从Java转向c#,我充满了疯狂的问题.我正在Windows窗体应用程序上尝试新的东西,现在,我想创建一个循环,它每1分钟执行一次代码,问题是我不知道在哪里放这个代码.例如,表单结构如下:
using System;
namespace Tray_Icon
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
notifyIcon1.ShowBalloonTip(5000);
}
private void notifyIcon1_BalloonTipClicked(object sender, EventArgs e)
{
label1.Text = "Baloon clicked!";
}
private void notifyIcon1_BalloonTipClosed(object sender, EventArgs e)
{
label1.Text = "baloon closed!";
}
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
}
private void option1ToolStripMenuItem_Click(object sender, EventArgs e)
{
//some code here
}
private void option2ToolStripMenuItem_Click(object sender, EventArgs e)
{
//some code here
}
private void option3ToolStripMenuItem_Click(object sender, EventArgs e)
{
label1.Text = "Option 3 clicked!";
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
option1ToolStripMenuItem_Click(this, null);
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnWrite_Click(object sender, EventArgs e)
{
//code here
}
}
}
Run Code Online (Sandbox Code Playgroud)
我应该在哪里放置循环代码?:(
在此先感谢任何重播!
在表单中添加一个Timer:

其设置Interval属性为60000(以毫秒为单位一分钟),并Enabled于True:

并将事件处理程序附加到Timer.Tick事件,例如通过双击窗体设计器中的计时器:

private void timer1_Tick(object sender, EventArgs e)
{
// do something here. It will be executed every 60 seconds
}
Run Code Online (Sandbox Code Playgroud)
您必须添加一个计时器,并将间隔设置为1000毫秒,并在OnTick事件中添加您的循环代码
Timer tmr = null;
private void StartTimer()
{
tmr = new Timer();
tmr.Interval = 1000;
tmr.Tick += new EventHandler<EventArgs>(tmr_Tick);
tmr.Enabled = true;
}
void tmr_Tick(object sender, EventArgs e)
{
// Code with your loop here
}
Run Code Online (Sandbox Code Playgroud)