+ 2
C# oriented object timer
hi, i try to learn C# oriented object with a new project : create a program which allow to create a new alarm with a datimetime. when the time is passed, i want the program show a window form with a message and a ringtone. My problem is how to create a class with a new instance of a timer because timer is a component... ? Thank you
7 Answers
+ 2
public class Alarm
{
double tempsInterval;
private static System.Timers.Timer MonAlarme; // DĂ©claration
public Alarm(double interval)
{
tempsInterval = interval;
}
private void TempsEcoulee(object sender, ElapsedEventArgs e)
{
MessageBox.Show("temps du timer " + tempsInterval + " est écoulé !!" + e.SignalTime);
}
public void Creer()
{
MonAlarme = new System.Timers.Timer(tempsInterval); //Instantiation
MonAlarme.Elapsed += TempsEcoulee;
MonAlarme.AutoReset = true;
}
public void Start()
{
MonAlarme.Start();
}
public void Stop()
{
MonAlarme.Stop();
MonAlarme.Dispose();
}
public void Afficher()
{
throw new System.NotImplementedException();
}
}
+ 1
hello sneeze,
thank's for your help. i progressed since your answer and i have a file alarm.cs which allow to create a new alarm, start, stop this alarm and display a message. I launch two alarms and both are ok (ringtone + message) but when i call stop function, the last alarm stop but the first alarm continue to show message and call ringtone. how can i make ?
+ 1
public partial class Form1 : Form
{
Alarm PremiereAlarm;
Alarm HAlarm;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
PremiereAlarm = new Alarm(Convert.ToDouble(textBox1.Text));
PremiereAlarm.Creer();
PremiereAlarm.Start();
}
private void button2_Click(object sender, EventArgs e)
{
PremiereAlarm.Stop();
}
private void button3_Click(object sender, EventArgs e)
{
HAlarm = new Alarm(Convert.ToDouble(textBox1.Text));
HAlarm.Creer();
HAlarm.Start();
}
private void button4_Click(object sender, EventArgs e)
{
HAlarm.Stop();
}
}
+ 1
Nice code!!
The problem is in this line
private static System.Timers.Timer MonAlarme; // DĂ©claration
This variable should not be static.
You want the Timer to be part of the instance (not static)
and not
shared with other instances of that same class (static)
Also I would create the timer in the constructor of the alarm class.
public Alarm(double interval)
{
tempsInterval = interval;
MonAlarme = new System.Timers.Timer(tempsInterval); //Instantiation
MonAlarme.Elapsed += TempsEcoulee;
MonAlarme.AutoReset = true;
}
+ 1
Hello sneeze,
I try to have a nice code syntax and simply code.
Ok thank you for your explanation, it's simply and good explanation.
i go test your solution i try to create two differents alarm.
thank you so much.
0
I am not sure, I do understand your question but I will try.
Can you use the timer object to time your alarm ?
https://msdn.microsoft.com/en-us/library/system.timers.timer.elapsed(v=vs.110).aspx
Please explain yourself a bit more.
0
Can you share the code in text with us ?