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

By FoxLearn 6/26/2017 9:01:21 PM   13.66K
How to make an alarm clock using timer control 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

alarm clock in c#Step 2: Design your form as below

c# alarm clock

Step 3: Add code to button click event handler 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)
        {
            timer = new System.Timers.Timer();
            timer.Interval = 1000;
            timer.Elapsed += Timer_Elapsed;
        }

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            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;
                //Update label control in mutiple thread
                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";
        }
    }
}

VIDEO TUTORIALS