Click here to Skip to main content
15,608,738 members
Articles / Desktop Programming / XAML
Posted 6 Oct 2014


33 bookmarked

Alarm in C#

Rate me:
Please Sign up or sign in to vote.
4.94/5 (14 votes)
6 Oct 2014CPOL1 min read
This code sample demonstrates how to set an alarm notification.


This code sample demonstrates how to set an alarm notification. Alarm Clock supports unlimited number of alarms so that you are not restricted to the number of alarms you can have. Alarms that you set will sound even if the computer goes to sleep. For this, you have to create a new blank app.

Step 1

Create new blank App name AlarmApp:

Image 1

Step 2

Click on Package.appxmanifest and set toast capable to yes and lock screen notification to badge.

Before an app can be selected as an alarm app, the app manifest must be properly configured. If the manifest doesn’t include the required features, then attempting to set the app as the alarm app in code will generate an error and the user won’t have the option to set the app manually.

Image 2

Image 3

Any app that has lock screen notifications enabled must also declare a background task in the app manifest. The interesting part of this requirement is that you don’t need to actually implement a background task in a lock screen app; it just has to be declared.

Image 4

The final step in configuring the app manifest is to identify the app as an alarm app. Right click on app manifest and select view code and add this code:

  <Extension Category="windows.backgroundTasks" 
      <Task Type="timer" />
  <m2:Extension Category="windows.alarm" />

Step 3

Set MainPage UI as per below:

Image 5

Write this code in MainPage.xaml:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Name="alarm_stack">
        <TextBlock FontSize="40" Margin="140,0,0,0" Text="Set Alarm"></TextBlock>
        <StackPanel Margin="0,10,0,0" Orientation="Horizontal">
            <TextBlock Text="Set Alarm Date:" FontSize="20" Foreground="White"></TextBlock>
            <DatePicker Name="datepicker" Margin="50,0,0,0" Width="323" ></DatePicker>
        <StackPanel Margin="0,10,0,0" Orientation="Horizontal" Visibility="Visible">
            <TextBlock Width="200" Text="Set Alarm Time:" FontSize="22"></TextBlock>
            <TimePicker Name="timepicker"   ClockIdentifier="12HourClock" Width="319"  />
        <StackPanel Orientation="Horizontal" Margin="0,10,0,0">
            <TextBlock Text="Alarm Message" FontSize="20" 
            Width="150" Foreground="White"></TextBlock>
            <TextBox x:Name="alm_msg" Width="318" MaxLength="50" 
            Margin="50,0,0,0" Height="77" BorderBrush="Black" AcceptsReturn="True"/>
        <StackPanel Orientation="Horizontal" Margin="0,10,0,0">
            <TextBlock Width="200" Grid.Column="1" Grid.Row="2" 
            Text="Snooze Time"  FontSize="22" VerticalAlignment="Top" 
            HorizontalAlignment="Stretch" Height="30"/>
            <ComboBox  Grid.Row="2" x:Name="CustomSnoozeTime" 
            VerticalAlignment="Top" HorizontalAlignment="Left"  Height="32" Width="64">
        <StackPanel Orientation="Horizontal" Margin="0,10,0,0">
            <TextBlock Width="200" Grid.Column="1" 
            Grid.Row="2" Text="Choose Sound:"  
            FontSize="22" VerticalAlignment="Top" 
            HorizontalAlignment="Stretch" Height="30"/>
            <ComboBox Name="alrm_sound">
                <ComboBoxItem >Default</ComboBoxItem>
                <ComboBoxItem Content="Reminder"></ComboBoxItem>
        <StackPanel Orientation="Horizontal" Margin="0,20,0,0">
            <Button Content="Add alarm" 
            Margin="108,7,0,0"  Click="add_alarm_Click"/>

Step 4

Add alarm button click and write this code in MainPage.xaml.cs page.

Add namespace using Windows.UI.Popups; for message dailogbox.

Find time between current time and alarm time. If time is invalid, then it shows messages otherwise it sets alarm with sound and message. For this, we have to use sheduledtoastnotification.

    int snooze;
    string audioSrc;
    int year = datepicker.Date.Year;
    int month = datepicker.Date.Month;
    int day = datepicker.Date.Day;
    int hour = timepicker.Time.Hours;
    int min = timepicker.Time.Minutes;
    int sec = timepicker.Time.Seconds;
//   string audioSrc = alrm_sound.SelectionBoxItem.ToString();
    DateTime myDate1 = new DateTime(year, month, day, hour, min, sec);
    DateTime myDate2 = DateTime.Now;
    TimeSpan myDateResult = new TimeSpan();
    myDateResult = myDate1 - myDate2;
    if (myDate2 > myDate1)
        var x = new MessageDialog("Invalid date or time");
        await x.ShowAsync();
        string title = "Alarm!";
        string message = alm_msg.Text;
        string imgURL = "ms-appx:///Assets/Capture.PNG";
        string toastXmlString =
         "<toast><visual version='1'>
         <binding template='toastImageAndText02'><text id='1'>" 
       + title + "</text><text id='2'>"
            + message + "</text><image id='1' src='" + 
            imgURL + "'/></binding></visual>\n" +
          "<commands scenario=\"alarm\">\n" +
                "<command id=\"snooze\"/>\n" +
                "<command id=\"dismiss\"/>\n" +
            "</commands>\n" +
                  "<audio src='ms-winsoundevent:Notification." + audioSrc + "'/>" +
        Windows.Data.Xml.Dom.XmlDocument toastDOM = new Windows.Data.Xml.Dom.XmlDocument();
        var toastNotifier1 = Windows.UI.Notifications.ToastNotificationManager.CreateToastNotifier();
        double x1 = myDateResult.TotalSeconds;
        int customSnoozeSeconds = snooze * 60;
        TimeSpan snoozeInterval = TimeSpan.FromSeconds(customSnoozeSeconds);
        var customAlarmScheduledToast = new Windows.UI.Notifications.ScheduledToastNotification
        (toastDOM, DateTime.Now.AddSeconds(x1), snoozeInterval, 0);
        var x = new MessageDialog("Alarm Set!");
        await x.ShowAsync();

Step 5

Output of this code is:

Image 6


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

Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

QuestionWindows 10 project type for this Pin
Robert Everett4-Dec-16 3:27
Robert Everett4-Dec-16 3:27 
GeneralMy vote of 5 Pin
E. Scott McFadden7-Oct-14 13:19
professionalE. Scott McFadden7-Oct-14 13:19 
QuestionVery good article! Pin
Volynsky Alex7-Oct-14 12:05
professionalVolynsky Alex7-Oct-14 12:05 
QuestionAwesome - 5 Stars Pin
AlbertMcLa7-Oct-14 3:17
AlbertMcLa7-Oct-14 3:17 
QuestionNice demonstration how to set an alarm notification. Pin
Volynsky Alex6-Oct-14 10:40
professionalVolynsky Alex6-Oct-14 10:40 
GeneralMy vote of 5 Pin
Afzaal Ahmad Zeeshan6-Oct-14 9:29
professionalAfzaal Ahmad Zeeshan6-Oct-14 9:29 
Nice one! Smile | :)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.