计时器未运行的控制台APP

时间:2013-04-02 09:49:20

标签: vb.net visual-studio visual-studio-2012 timer console-application

我首先进入WinForm项目,现在我已将应用程序类型更改为“控制台应用程序”,我删除了form1.vb,将启动对象更改为此“Module1.vb”,但现在我可以运行应用程序。 应用程序运行,但计时器滴答无效,代码完全相同,我只对 sub main / form1_load 名称进行了一次更改

我做错了什么?

PS:我已经测试过错误是否在锁定方法的条件下并且一切都很好,问题在于自动收报机事件,但我不知道为什么。

#Region " Vars "

    Dim Running As Boolean = False
    Dim Errors As Boolean = False

    Dim Executable_Name As String = Nothing

    Dim Toogle_Key As System.Windows.Forms.Keys = Nothing
    Dim WithEvents Toogle_Key_Global As Shortcut = Nothing

    Dim Executable_Timer As New Timer
    Dim Lock_Timer As New Timer
    Dim Lock_Interval As Int32 = 10
    Dim Lock_Sleep As Int32 = Get_Milliseconds(3)

    Dim Screen_Center_X As Int16 = (Screen.PrimaryScreen.Bounds.Width / 2)
    Dim Screen_Center_Y As Int16 = (Screen.PrimaryScreen.Bounds.Height / 2)

#End Region

    ' Load
Sub main()
    Pass_Args()
    Sleep()
    Lock()
End Sub

    ' Lock
Private Sub Lock()
    If Process_Is_Running(Executable_Name) Then
        AddHandler Lock_Timer.Tick, AddressOf Lock_Tick
        AddHandler Executable_Timer.Tick, AddressOf Executable_Tick
        Lock_Timer.Interval = Lock_Interval
        Lock_Timer.Start()
        Executable_Timer.Start()
        Running = True
    Else
        Terminate()
    End If
End Sub

' Lock Tick
Private Sub Lock_Tick()
    Console.WriteLine("test")
    If Running Then Cursor.Position = New Point(Screen_Center_X, Screen_Center_Y)
End Sub
  

更新

我在MSDN的例子中做了这些更改:

Dim Executable_Timer As New System.Timers.Timer
Dim Lock_Timer As New System.Timers.Timer

AddHandler Lock_Timer.Elapsed, AddressOf Lock_Tick
AddHandler Executable_Timer.Elapsed, AddressOf Executable_Tick

但是,滴答/已过去仍无所作为......

2 个答案:

答案 0 :(得分:3)

来自MSDN

Windows.Forms.Timer

  

实现以用户定义的间隔引发事件的计时器。   此计时器已针对Windows窗体应用程序进行了优化,并且必须   在窗口中使用。

您需要System.Timer
当然这需要不同的事件处理 (从MSDN获取的示例)

    ' Create a timer with a ten second interval.
    Dim aTimer = new System.Timers.Timer(10000)

    ' Hook up the Elapsed event for the timer.
    AddHandler aTimer.Elapsed, AddressOf OnTimedEvent

    ....

    Private Shared Sub OnTimedEvent(source As Object, e As ElapsedEventArgs)
         Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime)
    End Sub 

答案 1 :(得分:1)

如果您在Windows.Forms.Timer的末尾添加Application.Run(),则可以在控制台应用中使用main()

如果您使用任何屏幕外Windows.Forms对象,这种计时器在某些控制台应用程序中可能很有用 - 即:用于屏幕外渲染 - 这些对象无法从System.Timer简单地访问,因为它在单独的线程上触发(而不是创建Windows.Forms对象的线程)。

否则,请务必使用System.Timers.TimerSystem.Threading.Timer