C# Timer機能を使って、一定時間おきに処理を発生させる。なんちゃってアラームの実装


スポンサーリンク

Timerこっンポー念とは、Tickと呼ばれるイベントを一定時間ごとに発生させる。
intervalで周期を設定する(ミリ秒)

f:id:sho322:20151129235515j:plain

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 TimerExample
{
    public partial class Form1 : Form
    {
        bool alarmState = false;

        public Form1()
        {
            InitializeComponent();
        }

        private void StartButton_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Enabled = false;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            DateTime curTime = DateTime.Now;
            label1.Text = ((curTime.TimeOfDay.Hours).ToString()) + " : " + ((curTime.TimeOfDay.Minutes).ToString()) + " : "
                + ((curTime.TimeOfDay.Seconds).ToString());

            if (textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "")
            {
                DateTime alarmTime = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day,
                    System.Convert.ToInt16(textBox1.Text),System.Convert.ToInt16(textBox2.Text), System.Convert.ToInt16(textBox3.Text));

                if (DateTime.Now > alarmTime && alarmState)
                {
                    Console.Beep();
                }
                    

            }
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton1.Checked == true)
                alarmState = true;
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton2.Checked == true)
                alarmState = false;
        }

    }
}

C# ポケットリファレンス

C# ポケットリファレンス

  • 作者: WINGSプロジェクト,土井毅,高江賢,飯島聡,高尾哲朗,山田祥寛
  • 出版社/メーカー: 技術評論社
  • 発売日: 2011/12/03
  • メディア: 単行本(ソフトカバー)
  • 購入: 4人 クリック: 27回
  • この商品を含むブログ (5件) を見る