Timer headaches

bfsog

Well-known member
Joined
Apr 21, 2005
Messages
50
Location
UK
Programming Experience
5-10
I am trying to move a textbox around a form, every time the timer reaches it interval. It only does or once, or twice, but never constantly.

Heres timers properties

VB.NET:
AutoReset = True
Enabled = True
Interval = 1000

And code:

[code]
   Private Sub tmrMove_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles tmrMove.Elapsed

		Dim width As Integer
		Dim height As Integer
		height = RandomNumber(0, 500)
		width = RandomNumber(0, 500)
		lblTitle.Location = New Point(width, height)
		tmrMove.AutoReset = True
	End Sub

Any help is greatly appreciated. Thanks
 
Try a different type of Timer.

Unless you have a specific reason for using a System.Timers.Timer object, I suggest you add a System.Windows.Forms.Timer object to your Form from the VS toolbox instead. This class is easy to use because you get properties window support. Double-click the object in the design window to automatically generate an event handler for the Tick event and paste in the code you want to execute. Set the interval in the properties window and Call Timer.Start() and Timer.Stop() to start and stop the timer. This is the method I use and I've never had an issue. Note that you must call Stop() or set the Enabled property to False to stop the timer, which you can do in the Tick event handler.
 
So where do I find that control? The timer I used was under the Components panel.

Where do I get the timer you mentioned?
 
Thanks for the help. Now, the textbox is moving on every interval of the timer, which is what I was after.

However, it only moves in between 2 places, going back and forth.. I wanted it to be random, cany anyone help?

my random function
VB.NET:
   Public Function RandomNumber(ByVal MaxNumber As Integer, _
	Optional ByVal MinNumber As Integer = 0) As Integer

		'initialize random number generator
		
		Dim r As New Random(System.DateTime.Now.Millisecond)
		
		'if passed incorrect arguments, swap them
		'can also throw exception or return 0

		If MinNumber > MaxNumber Then
			Dim t As Integer = MinNumber
			MinNumber = MaxNumber
			MaxNumber = t
		End If

		Return r.Next(MinNumber, MaxNumber)
		Application.DoEvents()
	End Function
 
I have a project that uses random numbers and I use the Randomize statement in conjunction with the Rnd() function with perfect results. Randomize initialises the random number generator and only needs to be used once, so I use it in the projects Main procedure. To create a random number between lowerbound and upperbound, use this code:
VB.NET:
 CInt(Int((upperbound - lowerbound + 1) * Rnd() + lowerbound))
which is straight out of the help topic for Rnd().
 
Last edited:
Back
Top