重要なお知らせ

「教えて! goo」は2025年9月17日(水)をもちまして、サービスを終了いたします。詳細はこちら>

【GOLF me!】初月無料お試し

Timerを使用して5秒までに応答電文がこなかったらエラーメッセージを出すプログラムを作成しています。
.Netは初心者なものでTimerの使い方がよくわかりません。
クラスからTimerを動かすことはできないのでしょうか?
作成しているプログラムはFormがいらないので、TimerだけFormにおいて非表示で使おうかなと思っています。
どうしたらよいでしょうか?
また、この場合だとTimerではない方がいいですか?

A 回答 (2件)

画面を持たないなら、時間を独自で計測しっちゃった方が、シンプルのような気もします。



Module Module1
  Private Declare Function timeGetTime Lib "winmm.dll" Alias "timeGetTime" () As Integer
  Private Const LIMIT_TIME As Integer = 5000

  Sub Main()
    Dim intTime As Integer = timeGetTime

    Do
      Application.DoEvents()
      If (timeGetTime - intTime > LIMIT_TIME) Then
        MsgBox("タイムアウト")
        Exit Sub
      End If

      '応答電文受信確認処理コール
      'if 正常受信 then
      '  exit do
      'end if
    Loop

  End Sub
End Module






クラスでタイマを派生させるサンプルも置いておきます。

※Module1.vb

Module Module1
  Private Const LIMIT_TIME As Integer = 5000

  Sub Main()
    Dim objClass1 As New Class1()

    objClass1.TimerStart(LIMIT_TIME)

    Do
      Application.DoEvents()
      If Not objClass1.Status = Class1.TimerStatus.timRun Then
        MsgBox("タイムアウト")
        GoTo PGMEND
      End If

      '応答電文受信確認処理コール
      'if 正常受信 then
      '  exit do
      'end if
    Loop

PGMEND:
    objClass1 = Nothing
  End Sub
End Module




※Class1.vb

Public Class Class1
  Enum TimerStatus
    timFree
    timRun
    timEnd
  End Enum

  Private stsTimer As TimerStatus

  WithEvents objTimer As System.Timers.Timer


  Protected Overrides Sub Finalize()
    If Not (objTimer Is Nothing) Then
      objTimer.Enabled = False
    End If
    objTimer = Nothing

    MyBase.Finalize()
  End Sub

  Public Sub New()
    stsTimer = TimerStatus.timFree
  End Sub


  Public ReadOnly Property Status() As TimerStatus
    Get
      Return stsTimer
    End Get
  End Property



  Public Sub TimerStart(ByVal inInterval As Integer)
    objTimer = New System.Timers.Timer()
    With objTimer
      .Interval = inInterval
      .Enabled = True
    End With
    stsTimer = TimerStatus.timRun
  End Sub

  Private Sub objTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles objTimer.Elapsed
    Debug.WriteLine("タイマイベント発生")
    objTimer.Enabled = False
    stsTimer = TimerStatus.timEnd
  End Sub
End Class
    • good
    • 0
この回答へのお礼

詳しい説明ありがとうございました!
動く様になりました。
とても助かりました!ありがとうございます!!

お礼日時:2005/03/23 10:21

System.Windows.Forms.TimerではなくSystem.Timers.Timerがよろしいかと

    • good
    • 0
この回答へのお礼

ありがとうございます!
調べてやってみたいと思います。

お礼日時:2005/03/23 10:20

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!