System.Timers.Timer

  • Thread starter Thread starter Guy Cohen
  • Start date Start date
G

Guy Cohen

Hi all
I need a sample with timers.
I read the samples on the net with consol output but I want to change (for
example) a text box content on my form and this sample is not good for
that...
TIA
Guy
 
Hi all
I need a sample with timers.
I read the samples on the net with consol output but I want to change (for
example) a text box content on my form and this sample is not good for
that...
TIA
Guy

For Windows forms you should (imo) use the System.Windows.Forms.Timer
object. Add the object to your form, set the interval property (in
milliseconds), and add an event handler to the timer's Tick event. In
that method you do any actions you want to occur when the timer
"ticks".

Let me know if you need further help.

Thanks,

Seth Rowe
 
Hi
I know that but I really want to use system.timers.timer for practice
purposes
The final solution is a service not a form...
TIA

Okay - this will be a bit more complicated than I had hoped. The
System.Timers.Timer's Elapsed event is raised on a thread separate
from the UI so we have to delegate access back to the form in order to
change the textbox. Most likely these cross-thread operations could be
ignored in a service, depending on what you are doing.

Copy and paste the below code into a new window's form and run it -
you should see the textbox on the form be incremented with every tick.

///////////////////
Imports System.Timers

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim timer As New Timer(1000)
AddHandler timer.Elapsed, AddressOf timer_Elapsed
Dim textBox As New TextBox()
textBox.Name = "TextBox1"
Me.Controls.Add(textBox)
timer.Start()
End Sub

Public Delegate Sub IncrementTextBoxDelegate()

Public Sub IncrementTextBox()
Dim textBox As TextBox =
DirectCast(Me.Controls.Find("TextBox1", True)(0), TextBox)
Dim ticks As Integer
If Integer.TryParse(textBox.Text.Replace(" Ticks", ""), ticks)
Then
ticks += 1
textBox.Text = String.Format("{0} Ticks", ticks)
Else
textBox.Text = "0 Ticks"
End If
End Sub

Private Sub timer_Elapsed(ByVal sender As Object, ByVal e As
ElapsedEventArgs)
If Me.InvokeRequired Then
Dim incrementTextBoxDelegate As New
IncrementTextBoxDelegate(AddressOf IncrementTextBox)
Me.BeginInvoke(incrementTextBoxDelegate)
Else
IncrementTextBox()
End If
End Sub

End Class
///////////////////

Thanks,

Seth Rowe
 
Hi
I know that but I really want to use system.timers.timer for practice
purposes
The final solution is a service not a form...
TIA
Guy
 
Back
Top