Hello.
You can do this by using event handlers.
First create a class to store the event data you want to transfer:
public class TimerEventArgs : EventArgs
{
public string TickTime;
}
Then in your Device class add a EventHandler:
public event EventHandler<timereventargs> OnTick;</timereventargs>
And use it to notify an update:
if (OnTick != null)
{
OnTick(this, new TimerEventArgs() {TickTime = DateTime.Now.ToLongTimeString()});
}
All that's left to do is to use the event handler, so in you form when you create your Device instance assign it an handler:
Devices[1].OnTick += new EventHandler<timereventargs>(Form1_OnTick);
</timereventargs>
And when the handler is fired up just update the label you want:
void Form1_OnTick(object sender, TimerEventArgs e)
{
if (sender == Devices[0])
{
label1.Text = e.TickTime;
}
if (sender == Devices[1])
{
label2.Text = e.TickTime;
}
}
Here is a complete code sample:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Devices = new Device[2];
Devices[0] = new Device();
Devices[1] = new Device();
Devices[0].OnTick += Form1_OnTick;
Devices[1].OnTick += Form1_OnTick;
}
void Form1_OnTick(object sender, TimerEventArgs e)
{
if (sender == Devices[0])
{
label1.Text = e.TickTime;
}
if (sender == Devices[1])
{
label2.Text = e.TickTime;
}
}
public Device[] Devices;
}
public class Device
{
public Device()
{
t1 = new Timer();
t1.Interval = new Random().Next(100, 200);
t1.Tick += new EventHandler(t1_Tick);
t1.Start();
}
private Timer t1;
private int iOnTime = 0;
public event EventHandler<TimerEventArgs> OnTick;
void t1_Tick (object sender, EventArgs e)
{
t1.Interval = new Random().Next(10, 20) * 100;
t1.Stop();
t1.Start();
if (OnTick != null)
{
OnTick(this, new TimerEventArgs() {TickTime = DateTime.Now.ToLongTimeString()});
}
}
}
public class TimerEventArgs : EventArgs
{
public string TickTime;
}
Valery.