我每隔2秒使用一个计时器将文本输出到文本框。但似乎它不起作用。任何想法有什么不对。这是我的代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static System.Timers.Timer aTimer;
public void BtnGenData_Click(object sender, EventArgs e)
{
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;
}
public static void OnTimedEvent(object source, ElapsedEventArgs e)
{
string GenData = "Welcome";
Form1 frm1 = new Form1();
frm1.TboxData.AppendText(GenData.ToString());
}
}
实际上我没有看到任何输出。
答案 0 :(得分:1)
问题出在这个方法中:
public static void OnTimedEvent(object source, ElapsedEventArgs e)
{
string GenData = "Welcome";
Form1 frm1 = new Form1();
frm1.TboxData.AppendText(GenData.ToString());
}
通过调用new Form1();
,您可以创建一个新表单。此表单创建为隐藏,您更改文本,但它不显示,并且在此方法的末尾它是垃圾收集。你想要的是重用你现有的。完全删除此行并使用现有表单。默认情况下,名称应为form1
public static void OnTimedEvent(object source, ElapsedEventArgs e)
{
string GenData = "Welcome";
form1.TboxData.AppendText(GenData.ToString());
}
答案 1 :(得分:1)
虽然这与代码中的问题没有直接关系,但是......
来自MSDN System.Timers.Timer:
基于服务器的Timer设计用于a中的工作线程 多线程环境。
在Windows窗体中,您可以使用System.WindowsForms.Timer:
System.Windows.Forms.Timer timer;
public Form1()
{
InitializeComponent();
timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(timer_Tick);
}
public void BtnGenData_Click(object sender, EventArgs e)
{
BtnGenData.Enabled = false;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
timer.Stop();
BtnGenData.Enabled = true;
//do what you need
}
至于你的代码,为什么让计时器静止?试着用这个:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public System.Timers.Timer aTimer;
public void BtnGenData_Click(object sender, EventArgs e)
{
aTimer = new System.Timers.Timer(10000);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 2000;
aTimer.Enabled = true;
}
public void OnTimedEvent(object source, ElapsedEventArgs e)
{
this.TboxData.AppendText("Welcome");
}
}
另外你应该考虑一下,如果按下按钮两次会发生什么......