There is a simple WinForms application. In the window is the ListBox component to which the item should be added periodically. It also displays intermittently MessageBox. It is done using System.Timers.Timer.
namespace TestWindowsFormsApplication { public partial class Form1 : Form { System.Timers.Timer timer = new System.Timers.Timer(1000); private int i = 0; delegate void GUIUpdate(int numb); void DoGUIUpdateListBox(int n) { if (this.InvokeRequired) { GUIUpdate d = new GUIUpdate(this.DoGUIUpdateListBox); this.BeginInvoke(d, n); } else listBox1.Items.Add(n); } public Form1() { InitializeComponent(); button1.Text = "Нажмите, чтобы начать"; timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); } void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { System.Windows.Forms.MessageBox.Show("i = " + i + "\r\n" + DateTime.Now.Second + ":" + DateTime.Now.Millisecond, "Timer Event Raised!"); DoGUIUpdateListBox(i); i++; } private bool begin = false; void button1_Click(object sender, EventArgs e) { if (!begin) { begin = true; button1.Text = "Закончить добавление"; timer.AutoReset = true; timer.Start(); } else { begin = false; button1.Text = "Начать добавление"; timer.Stop(); } } } }
But the timer handler calls only Message. Show, and then it doesn't work, the elements are not displayed, the variable is not incremented, how to do it correctly?