1

我首先進入一個Wi​​nForm項目,現在我已經將應用程序類型更改爲「控制檯應用程序」,我刪除了form1.vb,將啓動對象更改爲此「Module1。 VB「,但現在我無法運行該應用程序。 以及應用程序運行,但計時器滴答聲是什麼都不做,代碼是完全一樣的,我只是做了一個變化的副主/ Form1_Load的控制檯應用程序與計時器未運行

我做錯了什麼?

PS:我測試過,如果錯誤是在鎖定方法的條件下,並且一切都很好,問題出在ticker事件上,但我不知道爲什麼。

#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 

UPDATE

我做了這些改變就像在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 

但週期/過去了仍無所事事......

+1

而不去深瞭解所有的代碼。 'System.Windows.Forms.Timer'對象不能在控制檯應用程序中工作。你需要一個System.Timer – Steve

+0

哦謝謝,但現在的問題是與滴答事件,你能告訴我這種類型的定時器是相當於什麼? – ElektroStudios

+0

該事件被稱爲Elapsed,請參閱下面我的答案中的示例... – Steve

回答

3

FROM 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 
+0

謝謝你,我已經遵循MSDN的例子,但已過的事件在我的應用程序中什麼也沒做! :(我看不到我的代碼中是否有其他錯誤 – ElektroStudios

+0

您是否更改了Lock_Tick的簽名以與Elapsed事件兼容? – Steve

+0

我認爲不是,我該如何改變這種情況?但反正另一個計時器(可執行計時器已經發生的事件)運行良好,我不明白爲什麼這個定時器沒有運行 – ElektroStudios

1

你可以在控制檯應用程序中使用Windows.Forms.Timer如果你在結尾處添加Application.Run()main()

如果您正在使用任何屏外Windows.Forms對象 - 即:用於屏外渲染 - 這些對象不能簡單地從System.Timer訪問,因爲它在單獨的線程上觸發(比其中Windows.Forms對象創建於其上)。

否則一切手段使用System.Timers.TimerSystem.Threading.Timer

相關問題