定期的な処理を行うにはTimerコントロールを使います。
TimerコントロールをFormにドラッグ&ドロップすると
デザイン画面の下のほうにtimer1が現れます。
主なプロパティーは2つ。
Enabledでタイマーが有効か無効かを設定します。(初期値はFalseで無効)
Intervalでタイマーイベントが発生する周期をミリ秒単位で指定します。
後はタイマーイベントが発生すると呼び出される
Tickイベントハンドラを追加し、(イベント一覧でTickの欄をダブルクリックで自動生成)
定期的に行いたい処理をTickイベントハンドラ内に記述します。
下記例では1秒毎に秒数をカウントし、
VisualStudioの出力画面に経過病数を表示します。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { // 秒数 private int sec = 0; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // 1秒単位でイベントを発生させる timer1.Interval = 1000; // タイマーを有効に timer1.Enabled = true; } private void timer1_Tick(object sender, EventArgs e) { sec++; Console.WriteLine(sec.ToString() + "秒経過..."); } } }
コメントを残す