How can i run as much as desired to Timer? [Vb.Net] - vb.net

I have 2 textbox and 2 timer. I first run it in timer1
if not textbox1.text = textbox2.text then
timer2.start
else
msgbox "finished"
end if
But timer1 skip reading when textbox1 is equal to textbox2 and always makes an error.
Do I have a chance to run timer2 as much as textbox2 instead?
For example, if textbox2 is 3, then timer2 runs 3 times. I can get rid of the textbox1 = textbox2 control and run the code that is actually correct and does not work. Please help me. Thank you.

I'm having a hard time understanding the question, but I understand that you want to run some timer multiple times, and then continue to run another timer after x amount of times. This can be accomplished using something like this (I haven't tested this code):
Private WithEvents Timer1, Timer2, Timer3 As New System.Timers.Timer() With {.AutoReset = False}
Private NbTimesRun As New Dictionary(Of System.Timers.Timer, Integer) From {
{Timer1, 0},
{Timer2, 0},
{Timer3, 0}
}
Private Sub Timer1_Elapsed(sender as Object, e As EventArgs) Handles Timer1.Elapsed
Debug.Print("Timer1 elapsed")
' Do some stuff here
NbTimesRun(Timer1) += 1
If NbTimesRun(Timer1) == 3 Then
Timer2.Start()
Else
Timer1.Start()
End If
End Sub
Private Sub Timer2_Elapsed(sender as Object, e As EventArgs) Handles Timer2.Elapsed
Debug.Print("Timer2 elapsed")
' Do some stuff here
NbTimesRun(Timer2) += 1
If NbTimesRun(Timer2) == 3 Then
Timer3.Start()
Else
Timer2.Start()
End If
End Sub
Etc.
This is a pretty bad design pattern, though, and you should instead use a single timer, check the number of times it has run and call a method depending on that number of times, for example. Timers need to be disposed, so override Dispose and call TimerX.Dispose().

Related

Infinite loop is causing the form to not show up vb

I have an infinite loop in this sub because I want the program to keep testing this process to see if the variable has changed. When I run the program in the debugger, nothing shows up, including the form however when I removed the infinite loop from the program, the form showed up again. Does anyone know why this is happening? I should also mention I've tried a DO LOOP as well. Can anyone help?
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim greenCount As Integer
Dim looptest As Boolean = True
While looptest = True
For Each control In Me.Controls.OfType(Of Button)
If control.BackColor = Color.Lime Then
greenCount += 1
End If
Next
txtFielder.Text = greenCount.ToString
End While
End Sub
You need to get rid of all that code regardless. Depending on how you're changing the BackColor of those Buttons in the first place, updating the lime count might be best done there. Otherwise, you should be handling the appropriate event, e.g.
Private limeButtonCount As Integer = 0
Private Sub Buttons_BackColorChanged(sender As Object, e As EventArgs) Handles Button3.BackColorChanged,
Button2.BackColorChanged,
Button1.BackColorChanged
If DirectCast(sender, Button).BackColor = Color.Lime Then
limeButtonCount += 1
Else
limeButtonCount -= 1
End If
TextBox1.Text = limeButtonCount.ToString()
End Sub
Note that this code assumes that there are only two possible BackColor values and that all Buttons are not lime by default. If your scenario is a bit more complex than that then you may need to change a code a little, e.g.
Private limeButtonCount As Integer = 0
Private Sub Buttons_BackColorChanged(sender As Object, e As EventArgs) Handles Button3.BackColorChanged,
Button2.BackColorChanged,
Button1.BackColorChanged
limeButtonCount = Controls.OfType(Of Button)().Count(Function(b) b.BackColor = Color.Lime)
TextBox1.Text = limeButtonCount.ToString()
End Sub
Form.Load occurs before a form is displayed for the first time.
This means that you'll never see your form as long as you loop in this event. You probably want to use the Shown event instead.

Open multiple URLs successively in WebBrowser control in VB.NET

I'm trying to make a "rotator" on a form that cycles through a series of urls and displays the url in the WebBrowser control. The following code displays my form, but the form remains white/blank and then the last url in the array appears after a while. When I put a MessageBox in-between each url, to create a stop, it works and each url appears. I've tried putting a Sleep in place of the MessageBox, but that didn't work. I've also tried increasing the Sleep time, but that didn't work either. How can I make it work correctly?
Sub Rotate()
Dim Urls() As String = {"www.stackoverflow.com", "www.google.com", "www.yahoo.com"}
Dim counter As Integer = 0
Form3.Show()
Do Until counter = 3
Form3.WebBrowser1.ScriptErrorsSuppressed = True
Form3.WebBrowser1.Navigate(Urls(counter))
'MessageBox.Show("Next")
counter = counter + 1
System.Threading.Thread.Sleep(2000)
Loop
End Sub
You can call Application.DoEvents after changing the URL so that the control gets the chance to redraw itself.
However, a better approach would be to use a timer which fires every 2 seconds and then change the URL in the event handler so that your UI keeps responsive.
For example setup a new field myTimer in your form, init it in your form's loading event and in the Tick event you call your Rotate method. As Rotate is now called several times, we have to move the counter variable out of the method and make it a field so that we keep its value between the invocations. I usually write C# so hopefully I did not make some typos below :)
Private WithEvents myTimer As System.Windows.Forms.Timer
Private counter As Integer
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
' ... your existing code ...
counter = 0
myTimer = New System.Windows.Forms.Timer
myTimer.Interval = 2000
myTimer.Enabled = True
myTimer.Start()
End Sub
Private Sub myTimerTick() Handles myTimer.Tick
Rotate()
End Sub
Sub Rotate()
Dim Urls() As String = {"www.stackoverflow.com", "www.google.com", "www.yahoo.com"}
WebBrowser1.ScriptErrorsSuppressed = True
WebBrowser1.Navigate(Urls(counter))
counter = counter + 1
If counter > 3 Then myTimer.Stop()
End Sub

Dynamically updating a progress bar in VB

Hello I am a novice / mediocre VB programmer and I made a timer that simply need to update it self every second.
I started having doubts about weather or not it was working so I applied a msg box to my timers code it went off every second updating it self but the progress bar wont? why?
Dim power As PowerStatus = SystemInformation.PowerStatus
Dim percent As Single = power.BatteryLifePercent
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
ProgressBar1.Value = percent * 100
Label1.Text = percent * 100
End Sub
I have a power status and percent that takes the status and turn into a usable percentage then the progress bar uses that percentage but isnt updating like the msgBOX does why?
Well, your timer is probably working well and all, but you don't show where/how you get the updated value of SystemInformation.PowerStatus.BatteryLifePercent.
Maybe you're doing this somewhere else in your code, but as it is posted, you're always displaying the same value, so of course the progressbar is never going to change.
From what I can see from your question, everything should be working ok but I cant see that you have added Timer1.Interval = 1000 however you may have but this with the designer and not the coding side, however nevertheless here is how I did this project so you could see my working example just so you can be sure, If you have any problems let me know and i will do my best to help you out :)
Public Class Form1
Dim Timer1 As New Timer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer1.Enabled = True
Timer1.Interval = 1000
AddHandler Timer1.Tick, AddressOf Timer1_Tick
Timer1.Start()
End Sub
Private Sub Timer1_Tick()
Dim POWER As PowerStatus = SystemInformation.PowerStatus
Dim PERCENT As Single = POWER.BatteryLifePercent
Dim ONCHARGE As PowerStatus = SystemInformation.PowerStatus
ProgressBar1.Value = PERCENT * 100
Label1.Text = "Power Remaining: " & PERCENT * 100 & "%"
If ONCHARGE.PowerLineStatus = PowerLineStatus.Online Then
Label2.Text = "Currently: Charging"
Else
Label2.Text = "Currently: Not Charging"
End If
End Sub
End Class
I added a Progressbar and two labels to the form, one of which is the computer battery and another of which will tell the user if the cable is unplugged in or not, i know you didnt ask for the cable status but i added it just incase you needed it :)
Happy Coding

VB.NET loop timer, multiple "IF" conditions

Writing the title to try and explain my query I think was harder than the problem I'm actually facing :) - Anyway on to the question.
So I have a 20 second timer but I want two different things to happen on the first and second 10 seconds. Specifically to change the active tab.
So I thought to myself I'll just write an if Statement in the timer tick event that if it = 10 seconds to change to the second tab and when it hits 0 to switch back to the first, then to restart the timer.
Below is my code but nothing happens, I think the problem lies with reading the current remaining time.
Private timeLeft2 As Integer
Private Sub timerCountdown2()
timeLeft2 = 20
End Sub
Private Sub tabTimer_Tick(sender As Object, e As EventArgs) Handles tabTimer.Tick
If timeLeft2 = 10 Then
TabControlVertical1.SelectTab(1)
End If
If timeLeft2 = 0 Then
TabControlVertical1.SelectTab(0)
tabTimer.Stop()
tabTimer.Start()
End If
End Sub
The properties of my timer are enabled = true and Interval = 1000
What am I doing wrong?
You should set the timer to trigger the Tick event every 10 seconds, not every 20 (or 1 as by your edit above).
Every time the Tick event is triggered, you look at the value of a global boolean variable.
If this variable is true you execute the code reserved for the first 10 seconds and invert the value of the boolean. When the timer triggers again, you execute the code for the second case and invert again the value of the boolean
So, somewhere in your code or in the designer set the tabTimer interval to 10 seconds
tabTimer.Interval = 10000
and declare a global boolean variable (In the same forms class probably)
Private tabSwitcher as Boolean = True
Now the Tick event could be written as:
(no need to stop the timer if this process needs to continue)
Private Sub tabTimer_Tick(sender As Object, e As EventArgs) Handles tabTimer.Tick
If tabSwitcher = True Then
TabControlVertical1.SelectTab(1)
else
TabControlVertical1.SelectTab(0)
End If
tabSwitcher = Not tabSwitcher
End Sub
This is what I think you are asking:
do something in 10 timer ticks - timer set to 1000
do something else 10 timer ticks later
repeat
Try this
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Static ct As Integer = 0
ct += 1
If ct = 10 Then
'do 10 stuff here
Debug.WriteLine("10")
ElseIf ct = 20 Then
'do 20 stuff here
Debug.WriteLine("20")
'then reset ct <<<<<<<<<<<<
ct = 0
End If
End Sub
Friend Class timerCtrl : Inherits Timer
Private ReadOnly tickFunc As EventHandler = Nothing
Friend Sub New(ByRef theFunc As EventHandler, ByVal theInterval As Integer, Optional ByVal autoStart As Boolean = True)
tickFunc = theFunc
Interval = theInterval
AddHandler Tick, tickFunc
If (autoStart) Then Start()
End Sub
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
RemoveHandler Tick, tickFunc
End If
MyBase.Dispose(disposing)
End Sub
End Class
Friend Class TabClass
Private timerStep As Boolean = False
Private timerTabs As timerCtrl = Nothing
Friend Sub New()
timerTabs = New timerCtrl(AddressOf timerTabsTick, 10000)
End Sub
Private Sub timerTabsTick(ByVal sender As Object, ByVal e As EventArgs)
timerStep = Not timerStep
If timerStep Then
' condition 1
Else
' condition 2
End If
End Sub
End Class
a simple timer helper class for abstraction. to kill the timer, not just .Stop it, use timerTabs.Dispose(). eliminates the need to detach the event handler separately.
Seems to me that your timer is never getting to the value you are asking for in the if statements due to the fact that you have set the timer to the value of 20.
Also, I've use visual basics and am not to sure but doens't it need to be timeleft2.value?
Also, by stoping and starting the timer, it isn't actually restarting the timer, when you stop it say on 15 secs, and the restart, the timer restarts from 15 secs.
Try this.
If timeLeft2.Value = 10 Then
TabControlVertical1.SelectTab(1)
else if timeLeft2.Value = 0 Then
TabControlVertical1.SelectTab(0)
tabTimer.Stop()
timeLeft2.value = 0
tabTimer.Start()
End If

Waiting in vb2008 / vb.net

I am a VB6 coder and I'm making the move to VB8 / VB.NET
I know how to wait in VB6, but my problem is that I don't know how to wait in VB8/VB.NET. I have a TextBox called textbox2 that contains the number of seconds I want to wait. I used to use wait 60 in VB6, but of course VB2008 is different.
Can anyone help me to do this?
I know this is an old question, but I thought there were so many conflicting answers and I thought the solution I use is simple and straightforward enough.
Also, I wrote this when I switched from VB6 to .net, for the same reason as OP.
Private Sub Wait(ByVal seconds As Long)
Dim dtEndTime As DateTime = DateTime.Now.AddSeconds(seconds)
While DateTime.Now < dtEndTime
Application.DoEvents()
End While
End Sub
Use this do that your UI does not hang.
For i = 1 to 300
threading.thread.sleep(i * 1000)
application.doevents
next
[edit: I re-read the question and see it was specifically asking about a TextBox named textbox2 so I've updated the answer to reflect that.]
Well, I think one answer would be to use:
System.Threading.Thread.Sleep(Int32.Parse(textbox2.Text) * 1000);
if your text box contains the number of seconds to wait. However if you aren't in a background thread, this will hang your application up for the amount of time you are waiting.
You could also do something like:
Dim StartTime As DateTime
StartTime = DateTime.Now
While (DateTime.Now - StartTime) < TimeSpan.FromSeconds(Int32.Parse(textbox2.Text))
System.Threading.Thread.Sleep(500)
Application.DoEvents()
End While
which would not hang up the UI while you wait. (Also, you could use Convert.Int32(textbox2.Text) to convert the data in the textbox.)
Oh, and in certain cases, another way you can avoid the issues with the UI locking up would be do implement a timer callback instead. (see http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx for some more detail.) To do this, you
do whatever processing you need to do before the pause
create a function that picks up processing where you left off
create a timer that calls your function afterward
Code:
Public Class MyClass
Public MyTimer As System.Timers.Timer
Public Sub OnWaitCompleted(source As Object, e As ElapsedEventArgs)
MyTimer.Stop()
MyTimer = Nothing
DoSecondPartOfProcessing()
End Sub
Public Sub DoFirstPartOfProcessing()
' do what you need to do before the wait
MyTimer = New System.Timers.Timer(Int32.Parse(textbox2.Text))
AddHandler MyTimer.Elapsed, AddressOf OnWaitCompleted
MyTimer.Start()
End Sub
Public Sub DoSecondPartOfProcessing()
' do what you need to do after the wait
End Sub
End Class
try to use a timer
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim interval As Integer = 0
If Integer.TryParse(Me.TextBox2.Text, interval) Then
Timer1.Enabled = True
Timer1.Interval = interval
Timer1.Start
End If
End Sub
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
'your code here
End Sub
In the 'event of the timer ticks then implements the logic to invoke the method Timer.Stop (), but this depends on what you do.
Regards.
Use Thread.Sleep:
Thread.Sleep(60000)
Update, following comment:
To retrieve and convert the value of the text box use:
Dim sleepValue As Integer = Integer.Parse(textbox2.Text)
This will throw an exception if the value cannot be converted.
I don't know why do you want it and and why you don't use threads, but this sleep function act similar wait in vb6:
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
MsgBox("begin")
Sleep(2000)
MsgBox("end")
End Sub