Windows Forms: How to make an Alarm clock with sound in C#

By FoxLearn 8/9/2017 10:29:17 AM   7.7K
How to make an Alarm clock with sound using timer in C#

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "AlarmClock" and then click OK

c# alarm clockStep 2: Design your form as below

alarm clock in c#

Step 3: Add code to handle your form as below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AlarmClock
{
    public partial class Form1 : Form
    {
        System.Timers.Timer timer;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Init timer
            timer = new System.Timers.Timer();
            timer.Interval = 1000;
            timer.Elapsed += Timer_Elapsed;
        }

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //Update timer
            DateTime currentTime = DateTime.Now;
            DateTime userTime = dateTimePicker.Value;
            if (currentTime.Hour == userTime.Hour && currentTime.Minute == userTime.Minute && currentTime.Second == userTime.Second)
            {
                timer.Stop();
                UpdateLable upd = UpdateDataLable;
                if (lblStatus.InvokeRequired)
                    Invoke(upd, lblStatus, "Stop");
                MessageBox.Show("Ring ring ring...", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        //Update label control
        delegate void UpdateLable(Label lbl, string value);
        void UpdateDataLable(Label lbl,string value)
        {
            lbl.Text = value;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            timer.Start();
            lblStatus.Text = "Running...";
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            timer.Stop();
            lblStatus.Text = "Stop";
        }
    }
}

The System.Timers.Timer component raises the Elapsed event, based on the value of the Interval property. You can handle this event to perform the processing you need.

The System.Timers.Timer class has the same resolution as the system clock. This means that the Elapsed event will fire at an interval defined by the resolution of the system clock if the Interval property is less than the resolution of the system clock

VIDEO TUTORIALS