Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I would like to make the same result but by using (date time) in if condition and count the rest time to alarm.

Thanks for the reply.
C#
using system.media;

//code in time tick
   private void timer1_Tick(object sender, EventArgs e)
        {
            label2.Text = DateTime.Now.ToString("hh:mm:ss") + " " + DateTime.Now.ToString("tt");

        }
//code in form_load 
   private void Form1_Load(object sender, EventArgs e)
        {
            soundplay snplayer= new soundplay (alarm_test.properties.resources.alarm);
            if (label2.text=="06:00:00 AM")
                snplayer.play();
        }
Posted
Updated 16-Aug-14 4:57am
v3
Comments
OriginalGriff 16-Aug-14 10:57am    
Don't "bump" your question: adding information is fine, but just changing it to get it back to the top of the queue is rude and unhelpful.
Bear in mind it is a weekend, so there are less people here than normal - have some patience!
Richard MacCutchan 16-Aug-14 11:23am    
There is no point in putting that test in your Form1_Load method, since that only gets executed once and that is before the timer tick will take. Add the test in the timer method, and just check the TimeOfday value of the DateTime object, not some string that is set elsewhere.
Peter M. Adeeb 18-Aug-14 7:36am    
great, when i put the code in form1_load it doesn't work well but, when i put it in time tick it's working well , thanks
Sergey Alexandrovich Kryukov 16-Aug-14 14:20pm    
Condition related to time based on comparison two strings, instead of DateTime? Very bad...
—SA

1 solution

There are a couple of things wrong with your code.

  1. Setting the text of label2 should be simplified to:
    label2.Text = DateTime.Now.ToString("hh:mm:ss tt");
  2. As others have already pointed out, move the if test to the timer tick handler, as in:
    if (DateTime.Now.TimeOfDay == TimeSpan.FromHours(6)) {
        snplayer.play();
    }
    
Warning: You may still find sndplayer.play() will never execute!  Can you guess why?

/ravi
 
Share this answer
 
v2
Comments
Peter M. Adeeb 18-Aug-14 7:39am    
I think you didn't define (sndplayer)
the miss code is
soundplay snplayer= new soundplay (alarm_test.properties.resources.alarm);
thanks for the replay ,
Ravi Bhavnani 18-Aug-14 7:46am    
No, I assumed you would define sndplayer outside the scope of my answer.

The problem is, it's very unlikely that your timer will fire when it's EXACTLY 6:00:00.000 am. For this reason, you should play the sound the first time the time (to the nearest minute only) is 6:00, and then disable the timer.

/ravi

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900