VB.netでTimerをVBのように配列にして使用することはできないでしょうか?どなたか教えて下さい。
編集 削除Timerのインスタンスを、自前で配列に格納しておけば良いかと。
編集 削除以下のように組んでみたのですが、Tick
編集 削除以下のように組んでみたのですが、TickイベントがどのTimerでおきているのが分からないのですが...
-------------------------------------------------------------
Public myTimer(3) As System.Windows.Forms.Timer
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Dim ii As Integer
For ii = 0 To 2
myTimer(ii) = New Windows.Forms.Timer()
myTimer(ii).Interval = 5000
myTimer(ii).Enabled = False
'イベントハンドラに関連付け
AddHandler myTimer(ii).Tick, AddressOf subTimer_Tick
Next
End Sub
Private Sub subTimer_Tick(ByVal myObject As Object, _
ByVal e As EventArgs)
'各Timerの処理
End Sub
> TickイベントがどのTimerでおきているのが分からないのですが...
この場合は、
> Private Sub subTimer_Tick(ByVal myObject As Object, _
> ByVal e As EventArgs)
の「myObject」が指し示すTimerで起きている事になります。
識別用に、Timerを継承したクラスを作っておくと良いかも。
'「Indexプロパティ」を追加したTimerを定義
Class TimerEx
Inherits System.Windows.Forms.Timer
Public Index As Integer
Public Sub New(ByVal Index As Integer)
Me.Index = Index
End Sub
End Class
Public myTimer(2) As System.Windows.Forms.Timer
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ii As Integer
For ii = 0 To 2
myTimer(ii) = New TimerEx(ii)
myTimer(ii).Interval = 500
myTimer(ii).Enabled = False
AddHandler myTimer(ii).Tick, AddressOf subTimer_Tick
Next
myTimer(0).Start()
myTimer(1).Start()
myTimer(2).Start()
End Sub
Private Sub subTimer_Tick(ByVal myObject As Object, ByVal e As EventArgs)
Me.ListBox1.Items.Add("発生:" & DirectCast(myObject, TimerEx).Index)
End Sub
魔界の仮面弁士さんありがとうございました。さっそく試してみて動作確認を行いできました。できたのはいいのですが、例えばmyTimerが今は1つで配列を作成しましたが、myTimer1,myTimer2と2つあり2つとも配列にしたい場合、同じソースでいいのでしょうか?クラスというものがヘルプなどをみてもどういうものなのか分からないので一緒に教えてもらえればうれしいです。
----------------------------------------------------
Public myTimer1(2) As System.Windows.Forms.Timer
Public myTimer2(2) As System.Windows.Forms.Timer
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ii As Integer
For ii = 0 To 2
myTimer1(ii) = New TimerEx(ii)
myTimer1(ii).Interval = 500
myTimer1(ii).Enabled = False
AddHandler myTimer(ii).Tick, AddressOf subTimer1_Tick
Next
myTimer1(0).Start()
myTimer1(1).Start()
myTimer1(2).Start()
For ii = 0 To 2
myTimer2(ii) = New TimerEx(ii)
myTimer2(ii).Interval = 500
myTimer2(ii).Enabled = False
AddHandler myTimer(ii).Tick, AddressOf subTimer2_Tick
Next
myTimer2(0).Start()
myTimer2(1).Start()
myTimer2(2).Start()
End Sub
おそらくプログラム的には、その方法でも問題ないかと思います。
myTimer1, myTimer2、そして、subTimer1_Tick, subTimer2_Tickを
別々に管理してもよいですし、両者をまとめて一つの配列変数や
一つのイベントプロシージャで共用する事もできますし、あるいは
(CollectionBaseなどを使って)独自のTimerコレクションを作って
管理する事もできるでしょう。インスタンスをどのように管理するかは、
ZZZさん自身がやりやすい方法で決めてしまって構わないかと。
魔界の仮面弁士さんどうもありがとうございました。m(__)m
編集 削除