#author("2019-12-15T16:20:25+09:00","","") #author("2019-12-15T16:21:37+09:00","","") #navi(../) * タイマーイベントを発行する・Timer [#g22a0415] 「指定した時間間隔で指定した処理をしたい!」~ このような場合はタイマーを使うと簡単に実現できます。~ 以下に、C#とVisual Basic(VB)のサンプルコードと実際に実行した時のキャプチャを記します。 #htmlinsert(windev-top.html) #contents * 参考サイト [#z1067e72] -[[Microsoft|.NET Timer クラス>https://docs.microsoft.com/ja-jp/dotnet/api/system.timers.timer?view=netframework-4.8]] -[[Microsoft|.NET ElapsedEventArgs クラス>https://docs.microsoft.com/ja-jp/dotnet/api/system.timers.elapsedeventargs?view=netframework-4.8]] * 使用環境 [#f757ec0e] - Windows 10 ver.1909 - Visual Studio 2019 - .NET Core - コンソールアプリケーション * サンプルコードの説明 [#o19cffca] 以下に紹介するC#,Visual Basicのサンプルコードの説明をします。~ -Main~ Mainで自分自身(Program)をNewし、Timerの設定を行い、キー入力待ちにしています。 -runTimer~ runTimerでTimerクラスをNewし各設定を行っています。~ Timer.Elapsedでは、時間になったら実行するメソッド(timerEventMethod)を指定しています。~ Timer.Enabledでタイマーが実行されます。 -timerEventMethod~ 経過時間を表示させています。 * Timerのサンプルコード [#xe4fd620] 以下にC#とVisual BasicでTimerを使ったサンプルコードを紹介します。~ C#ではClassでVisual BasicではModuleで作成しました。 ** C# [#q47265de] using System; class Program { static void Main(string[] args) { Program me = new Program(); me.runTimer(2000); Console.WriteLine("Press Enter to end this process."); Console.ReadLine(); } public void runTimer(int msec) { System.Timers.Timer tm = new System.Timers.Timer(msec); tm.Elapsed += timerEventMethod; tm.AutoReset = true; tm.Enabled = true; } public void timerEventMethod(Object source, System.Timers.ElapsedEventArgs e) { Console.WriteLine("ElapsedEventArgs.SignalTime: " + e.SignalTime.ToString()); } } ** Visual Basic [#ta94962f] Imports System Module Program Sub Main(args As String()) runTimer(2000) Console.WriteLine("Press Enter to end this process.") Console.ReadLine() End Sub Sub runTimer(msec As Integer) Dim tm As System.Timers.Timer = New System.Timers.Timer(msec) AddHandler tm.Elapsed, AddressOf timerEventMethod tm.AutoReset = True tm.Enabled = True End Sub Sub timerEventMethod(source As Object, e As System.Timers.ElapsedEventArgs) Console.WriteLine("ElapsedEventArgs.SignalTime: " & e.SignalTime.ToString()) End Sub End Module ** 実行結果 [#d238859e] 上記サンプルコードを実行した時のキャプチャになります。 #ref(01.png) 以上、指定した時間毎にイベントを発生させるタイマークラスのサンプルコードでした。 #htmlinsert(windev-btm.html)