我想在文本字段中指定要添加到表單中的多少個定時器,並指定應該放入定時器的代碼。例如:我的文本框中顯示「2」,然後點擊一個按鈕,它會創建兩個定時器併爲兩個定時器添加特定的源代碼。如何使用源代碼添加編程定時器和其他控件VB.net
我嘗試過不同的代碼,雖然他們工作,我無法指定要創建的窗體上的控件的數量。
我該如何有效實現這一目標?
由於
我想在文本字段中指定要添加到表單中的多少個定時器,並指定應該放入定時器的代碼。例如:我的文本框中顯示「2」,然後點擊一個按鈕,它會創建兩個定時器併爲兩個定時器添加特定的源代碼。如何使用源代碼添加編程定時器和其他控件VB.net
我嘗試過不同的代碼,雖然他們工作,我無法指定要創建的窗體上的控件的數量。
我該如何有效實現這一目標?
由於
在這種情況下,我使用的形式conatining一個的NumericUpDown控制研究元件,一個按鈕和一個標籤,再加上兩個標籤僅包含文本。 See this picture
要創建定時器,我用的是功能add_timers(timercount)
,它看起來像這樣:
Function add_timers(timercount As Integer)
'Using a loop to creat <timercount> timers
For g As Integer = 1 To timercount
'Creating new timer 't'
Dim t As New Timer()
'setting interval of t
t.Interval = 1000
'Enabling timer
t.Enabled = True
'Code which runs when t ticks
AddHandler t.Tick, AddressOf TimerTick
Next
End Function
時Button1
,啓動按鈕按下獲取該功能被調用。它使用NumericUpDown1.Value
作爲該函數的參數。該函數使用循環創建新的定時器t
,設置它們的間隔和代碼以在打勾時運行。
不幸的是,我沒有找到動態創建代碼的方法,因此每個計時器都執行相同的操作。以巧妙的方式使用數組和循環可能使您可以爲每個計時器使用不同的值。要爲計時器使用創建代碼子:
Sub TimerTick(ByVal sender As Object, e As EventArgs)
'Add your code here
Label1.Text += 1
End Sub
我使用的完整的代碼是:
Public Class Form1
Function add_timers(timercount As Integer)
'Using a loop to creat <timercount> timers
For g As Integer = 1 To timercount
'Creating new timer 't'
Dim t As New Timer()
'setting interval of t
t.Interval = 1000
'Enabling timer
t.Enabled = True
'Code which runs when t ticks
AddHandler t.Tick, AddressOf TimerTick
Next
End Function
Sub TimerTick(ByVal sender As Object, e As EventArgs)
'Add your code here
Label1.Text += 1
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
add_timers(NumericUpDown1.Value)
End Sub
End Class
包裝定時器到一個數組是可能的,這樣你可以很容易地訪問每個定時器其指數。在互聯網上搜索它,如果你不知道如何去做,請在評論中告訴我。
這看起來不錯,但我需要解決不同的計時器實例。例如,我想用我的第二個計時器和第三個計時器(如禁用他們等)做什麼,我怎麼會打電話給他們呢?我如何命名我的計時器並在上面的代碼中啓動它們? –
看到我的編輯,它是在完整代碼後 – Tgrelka
我正在絞盡腦汁關於你的評論與「訪問每個計時器的索引」 - 怎麼樣?!事情是這樣的:我需要每個新的計時器有一個數字whcih增量如 第一個計時器 - >「計時器1」,第二個「計時器2」這樣我可以訪問他們。 那麼,我想從每個定時器內向TimerTick(CurrentNoOfTimer As Integer)發出定時器的號碼,以便它爲調用該功能的每個定時器做些微不同的事情。 –
只需創建一個定時器
Public Class Form1
private _timer as Windows.Forms.Timer
...
Public Sub New()
...
_timer = New Timer(Me)
_timer.Interval = 1000 'Timer will trigger one second after start
AddHandler _timer.tick, AddressOf Timer_tick 'Timer will call this sub when done
End Sub
Sub Button_click(sender as Object, e as EventArgs)
_timer.Start() 'Start the timer
...
End Sub
Private Sub Timer_tick(sender as Object, e as EventArgs)
MessageBox.Show("Timerrr!!")
End Sub
...
End Class
現在,如果你想創建多個定時器,可以使用定時器陣列。
請檢查:[如何提問](http://stackoverflow.com/help/how-to-ask) – JazzCat
你有點混亂。你需要澄清你的問題。你想製作計時器,控制器還是可視計時器來統計或倒數用戶的時間? – Claudius
我想創建一個動態計時器(當我點擊一個按鈕時,計時器被創建)。該計時器應該有一個特定的源代碼就像「Msgbox(」Timerrr !!「)」 –