Try this defined as a separate .cs file: Note we are using a separate NameSpace:
namespace ClassWithTimer
{
using System;
using System.Timers;
public class TimerInClass
{
public Timer TheTimer = new Timer();
private int timerCount;
public TimerInClass(double interval, bool startNow)
{
timerCount = 0;
TheTimer.AutoReset = true;
TheTimer.Interval = interval;
TheTimer.Elapsed += new ElapsedEventHandler(TheTimer_Elapsed);
TheTimer.Enabled = startNow;
}
public void TheTimer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine(timerCount);
timerCount++;
}
public void StartTimer()
{
TheTimer.Enabled = true;
}
public void StopTimer()
{
TheTimer.Enabled = false;
}
}
}
Now: let's test in a Form:
using System;
using System.Windows.Forms;
using System.Threading;
namespace TestTimerInClass_Form
{
public partial class Form1
{
private void Form1_Load(object sender, EventArgs e)
{
ClassWithTimer.TimerInClass InstanceOfTimer = new ClassWithTimer.TimerInClass(10, false);
InstanceOfTimer.StartTimer();
for(int x = 0; x < 100; x++)
{
Thread.Sleep(10);
}
InstanceOfTimer.StopTimer();
}
}
}
Run this code, and examine the results in the Output Window in Visual Studio to verify the Timer is being called repeatedly.
... edit #1 ... Feb. 18, 2012 ... added the bracketing of the NameSpace of the Form test-bed, and 'partial Form1 bracketing, so the reason for using the fully qualified name of the Timer class in another NameSpace is more clear, and the code is hopefully more readable to a "new user."
... edit #2 ... Feb. 18, 2012 ... added setting the 'AutoReset Property of the System.Timer tp 'true ... even though this is not necessary since it's default value is true: just thought it might increase the "educational value" of the answer.