The following code is making the Application to hang. No error are showed while debugging.
Private Sub SolarInitBtn_Click(sender As Object, e As EventArgs) Handles SolarInitBtn.Click
Try
SolarThread = New Thread(SolarThreadStart) With {
.IsBackground = True,
.Name = "SolarEnergyUpdateSystem"
}
SolarThread.Start()
Catch myError As Exception
End Try
End Sub
Public Sub SolarEnergyUpdate()
Dim Energy As Decimal = SolarStatsLbl.Text
Dim EnergyMax As Int32 = SolarMaxCapLbl.Text
If Energy <= EnergyMax Then
Dim Production As Int32 = SolarProdLbl.Text
Dim ProdTimeQt As Decimal = FormatNumber(CDec(Production / 3600), 3) + Energy
EnergyNowLbl.Text = ProdTimeQt
Thread.Sleep(15000)
Else
SolarThread.Abort()
End If
End Sub
What I try is to catch some numbers, do the maths and put the result into a label, I expected to do that each second or at least for less than 1 minute. Currently the application is hanging.
I catch for exceptions there is none. (Using vb.NET)
Related
Just for context;
I need to calculate the average of 5 numbers located in 5 textboxes.
Nummer means number
Gemiddelde means average
and
Bereken means calculate
What is causing it to crash?
Private Sub butBereken_Click(sender As Object, e As EventArgs) Handles butBereken.Click
'Variabelen'
Dim nummer1 As Decimal = txtNummer1.Text
Dim nummer2 As Decimal = txtNummer2.Text
Dim nummer3 As Decimal = txtNummer3.Text
Dim nummer4 As Decimal = txtNummer4.Text
Dim nummer5 As Decimal = txtNummer5.Text
Dim somNummers As Decimal = nummer1 + nummer2 + nummer3 + nummer4 + nummer5
Dim Gemiddelde As String = (somNummers) / 5
lblGemiddelde.Text = Gemiddelde
If Gemiddelde < 5.5 Then
lblGemiddelde.Text = Gemiddelde + " Dit is onvoldoende"
End If
If nummer1 = "" Or nummer2 = "" Or nummer3 = "" Or
nummer4 = "" Or nummer5 = "" Then
butBereken.Enabled = False
MessageBox.Show("your mom")
Else
butBereken.Enabled = True
End If
End Sub
I don't see what would crash the program but check to that the TextBoxes have values before assigning them to numeric variables. A Decimal value will never = "".
Private Sub butBereken_Click(sender As Object, e As EventArgs) Handles butBereken.Click 'Variabelen'
If Not IsNumeric(txtNummer1.Text) Or _
Not IsNumeric(txtNummer2.Text) Or _
Not IsNumeric(txtNummer3.Text) Or _
Not IsNumeric(txtNummer4.Text) Or _
Not IsNumeric(txtNummer5.Text) Then
MessageBox.Show ("your mom wants you to fill in all the number boxes")
Exit Sub
End If
Dim nummer1 As Decimal = CDec(txtNummer1.Text)
Dim nummer2 As Decimal = CDec(txtNummer2.Text)
Dim nummer3 As Decimal = CDec(txtNummer3.Text)
Dim nummer4 As Decimal = CDec(txtNummer4.Text)
Dim nummer5 As Decimal = CDec(txtNummer5.Text)
Dim somNummers As Decimal = nummer1 + nummer2 + nummer3 + nummer4 + nummer5
Dim Gemiddelde As String = (somNummers) / 5
lblGemiddelde.Text = Gemiddelde
If Gemiddelde < 5.5 Then
lblGemiddelde.Text = Gemiddelde + "Dit is onvoldoende"
End If
If nummer1 = 0 Or nummer2 = 0 Or nummer3 = 0 Or nummer4 = 0 Or nummer5 = 0 Then
butBereken.Enabled = False
MessageBox.Show ("your mom")
Else
butBereken.Enabled = True
End If
End Sub
If this doesn't work I would consider setting breakpoints in the could to determine what line is causing the crash.
If that doesn't work consider adding this line to the form's initialization:
butBereken.Caption = "Warning: Do not Click!"
Assuming the user populated all the textboxes with numeric only data, (and you have checked this) try replacing these lines in your code with this code
Dim nummer1 As Decimal = txtNummer1.Text
Dim nummer2 As Decimal = txtNummer2.Text
Dim nummer3 As Decimal = txtNummer3.Text
Dim nummer4 As Decimal = txtNummer4.Text
Dim nummer5 As Decimal = txtNummer5.Text
Dim somNummers As Decimal = nummer1 + nummer2 + nummer3 + nummer4 + nummer5
Dim Gemiddelde As Decimal = somNummers / 5
lblGemiddelde.Text = Gemiddelde.ToString("##0.0")
I'd do something more like:
Private Sub butBereken_Click(sender As Object, e As EventArgs) Handles butBereken.Click
Dim TBs() As TextBox = {txtNummer1, txtNummer2, txtNummer3, txtNummer4, txtNummer5}
Dim inputs() As String = TBs.Select(Function(x) x.Text).ToArray()
Dim values() As Decimal
Try
values = Array.ConvertAll(inputs, Function(s) Decimal.Parse(s))
Dim Gemiddelde As String = values.Average()
lblGemiddelde.Text = Gemiddelde & If(Gemiddelde < 5.5, " Dit is onvoldoende", "")
Catch ex As Exception
MessageBox.Show("your mom")
End Try
End Sub
I prefer this approach as it doesn't require repetitive lines of code, manually converting each TextBox to a Decimal. Since the TextBoxes are in an Array, we could also add another TextBox to the form and then add that name to the end of the Array. The rest of the code would not need to change at all; it would still just work as is.
From the Array of TextBox, we use a LINQ statement to extract the Text from each TextBox and add it to an Array of String called "inputs". From there, we convert every single String to a Decimal using Array.ConvertAll(), again avoiding repetitive code. If any of the input values is not a valid Decimal then an Exception will be thrown and we'll jump the the Catch block where the not so well written error message is displayed.
If there are no exceptions, then all String inputs were successfully converted to Decimals and stored in the "values" Array. Next we simply use the LINQ function Average() to get the average of all the values.
Lastly we display the computed average in the Label, adding the "Dit is onvoldoende" message if approapriate. The If() function used in this line is simply a shorthand version of a longer If...Else...End If statement.
In your original attempt, it looks like you wanted to disable the button if any of the values are blank (or maybe if they are invalid decimals?):
If nummer1 = "" Or nummer2 = "" Or nummer3 = "" Or nummer4 = "" Or nummer5 = "" Then
butBereken.Enabled = False
MessageBox.Show("your mom")
Else
butBereken.Enabled = True
End If
This makes no sense as if you disable the button, how would it get turned back on so that user could click it again?
A different approach would be to handle the TextChanged() event of all the TextBoxes and simply update your Label with the average in real-time whenever one of the TextBoxes is changed:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
UpdateAverage()
End Sub
Private Sub txtAll_TextChanged(sender As Object, e As EventArgs) Handles txtNummer5.TextChanged, txtNummer4.TextChanged, txtNummer3.TextChanged, txtNummer2.TextChanged, txtNummer1.TextChanged
UpdateAverage()
End Sub
Private Sub UpdateAverage()
Dim TBs() As TextBox = {txtNummer1, txtNummer2, txtNummer3, txtNummer4, txtNummer5}
Dim inputs() As String = TBs.Select(Function(x) x.Text).ToArray()
Try
Dim values() As Decimal = Array.ConvertAll(inputs, Function(s) Decimal.Parse(s))
Dim average As Decimal = values.Average
lblGemiddelde.Text = average & If(average < 5.5, " Dit is onvoldoende", "")
Catch ex As Exception
lblGemiddelde.Text = "{ Invalid Input }"
End Try
End Sub
End Class
Sample run:
I'm trying to create a program that can recognise what a user is saying, and make a decision on what to do based on that, but i can't seem to find any code on the internet for it in vb.net and a console application. Is it even possible to do it in a non-object orientated language and there not being any events in a console application?
I've tried converting c# console code to vb.net console code and it doesn't word due to the issues of converting from an object orientated programming langue to a non object-orientated one.
I've also tried to just get it to run in a form, and that doesn't work due to it locating the grammar file, but failing to recognise it as one
This is the code i've tried:
1. My VB form code
Imports System.Speech
Imports System.Speech.Recognition
Public Class Form1
Dim WithEvents recog As New Recognition.SpeechRecognitionEngine
Private Sub setcolo(ByVal colour As System.Drawing.Color)
Dim synth As New Synthesis.SpeechSynthesizer
Me.BackColor = colour
End Sub
2. My translated C# code
Imports System, System.Speech.Recognition, System.Speech.Synthesis, System.Globalization
Module Module1
Dim ss As New System.Speech.Synthesis.SpeechSynthesizer
Dim sre As Speech.Recognition.SpeechRecognitionEngine
Dim done As Boolean = False
Dim speechOn As Boolean = True
Sub Main(args As String)
Try
ss.SetOutputToDefaultAudioDevice()
Console.WriteLine("\n(Speaking: I am awake)")
ss.Speak("I am awake")
Dim ci = New CultureInfo("en-us")
sre = New Speech.Recognition.SpeechRecognitionEngine(ci)
sre.SetInputToDefaultAudioDevice()
'sre.SpeechRecognized = sre.SpeechRecognized + sre_SpeechRecognized()
Dim ch_StartStopCommands As Speech.Recognition.Choices = New Speech.Recognition.Choices
ch_StartStopCommands.Add("speech on")
ch_StartStopCommands.Add("speech off")
ch_StartStopCommands.Add("klatu barada nikto")
Dim gb_StartStop As Speech.Recognition.GrammarBuilder = New Speech.Recognition.GrammarBuilder()
gb_StartStop.Append(ch_StartStopCommands)
Dim g_StartStop As Speech.Recognition.Grammar = New Speech.Recognition.Grammar(gb_StartStop)
Dim ch_Numbers As Speech.Recognition.Choices = New Speech.Recognition.Choices()
ch_Numbers.Add("1")
ch_Numbers.Add("2")
ch_Numbers.Add("3")
ch_Numbers.Add("4")
Dim gb_WhatIsXplusY As Speech.Recognition.GrammarBuilder = New Speech.Recognition.GrammarBuilder()
gb_WhatIsXplusY.Append("What is")
gb_WhatIsXplusY.Append(ch_Numbers)
gb_WhatIsXplusY.Append("plus")
gb_WhatIsXplusY.Append(ch_Numbers)
Dim g_WhatIsXplusY As Speech.Recognition.Grammar = New Speech.Recognition.Grammar(gb_WhatIsXplusY)
sre.LoadGrammarAsync(g_StartStop)
sre.LoadGrammarAsync(g_WhatIsXplusY)
sre.RecognizeAsync(Speech.Recognition.RecognizeMode.Multiple)
While (done = False)
End While
Console.WriteLine("\nHit <enter> to close shell\n")
Console.ReadLine()
Catch ex As Exception
Console.WriteLine(ex.Message)
Console.ReadLine()
End Try
End Sub
Function sre_SpeechRecognized(sender As Object, e As Speech.Recognition.SpeechRecognizedEventArgs)
Dim txt As String = e.Result.Text
Dim confidence As Double = e.Result.Confidence
Console.WriteLine("\nRecognized: " & txt)
If (confidence < 0.6) Then Return ""
If (txt.IndexOf("speech on") >= 0) Then
Console.WriteLine("Speech is now ON")
speechOn = True
End If
If (txt.IndexOf("speech off") >= 0) Then
Console.WriteLine("Speech is now OFF")
speechOn = False
End If
If (speechOn = False) Then Return ""
If (txt.IndexOf("klatu") >= 0 And txt.IndexOf("barada") >= 0) Then
'((SpeechRecognitionEngine)sender).RecognizeAsyncCancel()
done = True
Console.WriteLine("(Speaking: Farewell)")
ss.Speak("Farewell")
End If
If (txt.IndexOf("What") >= 0 And txt.IndexOf("plus") >= 0) Then
Dim words() As String = txt.Split(" ")
Dim num1 As Integer = Int(words(2))
Dim num2 As Integer = Int(words(4))
Dim sum As Integer = num1 + num2
Console.WriteLine("(Speaking: " & words(2) & " plus " & words(4) & " equals " & sum & ")")
ss.SpeakAsync(words(2) & " plus " & words(4) & " equals " & sum)
End If
Return ""
End Function
End Module
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
recog.SetInputToDefaultAudioDevice()
Dim gram As New Recognition.SrgsGrammar.SrgsDocument("D:\Voiceregogform\Voiceregogform\bin\Debug\Voiceregogform.xml")
Dim colourr As Recognition.SrgsGrammar.SrgsRule
Dim colourlist As New Recognition.SrgsGrammar.SrgsOneOf("red", "yellow", "indigo", "aqua", "green")
colourr.Add(colourlist)
gram.Rules.Add(colourr)
gram.Root = colourr
recog.LoadGrammar(New Recognition.Grammar(gram))
recog.RecognizeAsync()
End Sub
Private Sub recog_RecognizeCompleted(sender As Object, e As RecognizeCompletedEventArgs) Handles recog.RecognizeCompleted
recog.RecognizeAsync()
End Sub
Private Sub recog_SpeechRecognized(sender As Object, e As SpeechRecognizedEventArgs) Handles recog.SpeechRecognized
Select Case e.Result.Text
Case "red"
setcolo(Color.Red)
Case "yellow"
setcolo(Color.Yellow)
Case "aqua"
setcolo(Color.Aqua)
Case "green"
setcolo(Color.Green)
Case "indigo"
setcolo(Color.Indigo)
Case "blue"
setcolo(Color.Blue)
End Select
End Sub
End Class
This is a translation of the example at https://learn.microsoft.com/en-us/dotnet/api/system.speech.recognition.speechrecognitionengine. I tried it out on my own Windows 10 PC, and can confirm that it works. I used Visual Studio Community 2019 and went with its defaults for a VB Console App on .NET FW. Hope this helps!
On a side note, VB comes in two flavors: (1) the old VBA/VB6; (2) and the latest VB.NET. VB.NET is a fully modern OOP language; VB.NET and C# are siblings "joined at the hip" by a common compilation platform known as Roslyn. VB6 is discontinued, and VBA lives on as a part of Microsoft Office.
About VBA/VB6 and OOP, check out Is VBA an OOP language, and does it support polymorphism?, it's a fun and thoughtful read.
' NOTE: Must target .NET Framework, 3.0 or later (not .NET Core!)
Imports System.Console
' Make reference to System.Speech (System.Speech.dll)
' https://learn.microsoft.com/en-us/dotnet/api/system.speech.recognition.speechrecognitionengine
Imports System.Speech.Recognition
Module Program
Sub Main()
' Create an in-process speech recognizer for the en-US locale.
Using recognizer As New SpeechRecognitionEngine(
New Globalization.CultureInfo("en-US"))
' Create and load a dictation grammar.
recognizer.LoadGrammar(New DictationGrammar())
' Add a handler for the speech recognized event.
AddHandler recognizer.SpeechRecognized,
AddressOf recognizer_SpeechRecognized
' Configure input to the speech recognizer.
recognizer.SetInputToDefaultAudioDevice()
' Start asynchronous, continuous speech recognition.
recognizer.RecognizeAsync(RecognizeMode.Multiple)
' Keep the console window open.
Do
ReadLine()
Loop
End Using
End Sub
' Handle the SpeechRecognized event.
Sub recognizer_SpeechRecognized(sender As Object, e As SpeechRecognizedEventArgs)
WriteLine("Recognized text: " + e.Result.Text)
End Sub
End Module
I have problem with serial data communication if I started a loop it is not updating the data from my weighing scale. I can't figure out how to continue the communication as well as to run the loop. The logic of my code will be in the loop so I could check the value from my integer and compare it to the data from serial data (Weighing Scale)
Private Sub conWeight_DataReceived(sender As System.Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles conWeight.DataReceived
receivedText(conWeight.ReadExisting())
End Sub
Private Sub receivedText(ByVal [text] As String)
If Me.lblWeight.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf receivedText)
Me.Invoke(x, New Object() {(text)})
Else
Dim reverseString As String = [text]
Dim revString As String = StrReverse(reverseString)
Dim clean As String
clean = revString.Replace("=", "")
Me.lblWeight.Text = clean 'append text
End If
End Sub
'this is part with loop
If binWeight = 0 Then
targetweight = CInt(txtbSilo1.Text) + CInt(txtbSilo2.Text) + CInt(txtbSilo3.Text) + CInt(txtbSilo4.Text)
If CInt(txtbSilo1.Text) > 0 Then
currentWeight = CInt(txtbSilo1.Text)
frmAutomaticControl.conControl.Open()
frmAutomaticControl.conControl.Write("motr1")
frmAutomaticControl.conControl.Close()
MsgBox("check")
Do
If binWeight >= currentWeight Then
frmAutomaticControl.conControl.Open()
frmAutomaticControl.conControl.Write("moto1")
frmAutomaticControl.conControl.Close()
Exit Do
End If
Loop
Else
End If
BunifuFlatButton1.Enabled = True
Else
MsgBox("Empty The Bin")
End If
just a couple of ideas.
1. Throw that part of the code into a background worker.
2. Cheese it and throw in an application.doevents.
3. Create a global variable that'll capture the output of each iteration of your loop that'll then feed it where it needs to go.
Just one line of code is all you need. In your loop put this above everything else.
Application.DoEvents()
Full disclosure, I'm working on an assignment for COP2170, but the additional feature isn't apart of the assignment just trying to stretch a little further...
I'm trying to add 5 test scores and output the average of the 5 scores, that part works just fine. In addition I'm trying to add an additional feature that will allow the user to enter less than 5 scores and the program will still output the average of whatever scores were entered.
So this works:
And this works:
The problem I'm running into is if the first score is omitted and the rest are filled in, it doesn't work:
Here's the code I've got so far:
Public Class frmTestScoreAverage
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim decScore1, decScore2, decScore3, decScore4, decScore5 As Double ' decScore1-5 to hold test scores1-5
Dim decScoreAverage As Double ' to hold test score average
Dim intDivideBy As Double = 5 ' declare intDivideBy variable with starting value of 5
lblStatusLabel.Text = String.Empty 'set error message to empty string
Try
' Read user input convert to double and assign value to variable
decScore1 = Convert.ToDouble(txtScore1.Text)
decScore2 = Convert.ToDouble(txtScore2.Text)
decScore3 = Convert.ToDouble(txtScore3.Text)
decScore4 = Convert.ToDouble(txtScore4.Text)
decScore5 = Convert.ToDouble(txtScore5.Text)
' Calculate average
decScoreAverage = (decScore1 + decScore2 + decScore3 + decScore4 + decScore5) / intDivideBy
'display result
lblResult.Text = CStr(decScoreAverage)
Catch
' Display error message, asks for all scores
lblStatusLabel.Text = "Please enter all test scores"
'Calculate average even without all scores
For Each c As TextBox In Me.Controls.OfType(Of TextBox)() 'loop through each textbox in form see: http://stackoverflow.com/a/13504361/1947286
If c.Text = String.Empty Then intDivideBy -= 1 'If text equals empty string, Then decrement intDivideBy
Next
'catch divide by zero error
Try
'calculate average
decScoreAverage = (decScore1 + decScore2 + decScore3 + decScore4 + decScore5) / intDivideBy 'add test scores and divide to find average
'display result
lblResult.Text = CStr(decScoreAverage)
Catch
lblStatusLabel.Text = "Please enter at least one test score"
End Try
End Try
End Sub
End Class
I'm pretty sure the problem has to do with the way I'm finding the average:
decScoreAverage = (decScore1 + decScore2 + decScore3 + decScore4 + decScore5) / intDivideBy
Is there a way to find the average that will allow for empty variables in any arrangement?
The problem you are having is that Convert.ToDouble(txtBox.text) (with empty string, will make Convert throw an Exception.
Add a validation that the string isn't empty or use TryParse to see if the Textbox value is parseable to a number.
Either
If not String.IsNullOrEmpty(txtBox.Text) then
Convert.ToDouble(txtBox.text)
Or
dim value as Double
if Double.TryParse(txtBox.Text, value) then
avg += value
When the first one is empty, it goes to the Catch part of the code, then you try to calculate the avg, but the values of the Txtbox are not assigned to the declarations you made, so when it tries to do the average
decScore1 = Convert.ToDouble(txtScore1.Text) // Exception here to Catch
decScore2 = Convert.ToDouble(txtScore2.Text) // Not evaluated
decScore3 = Convert.ToDouble(txtScore3.Text) // Not evaluated
decScore4 = Convert.ToDouble(txtScore4.Text) // Not evaluated
decScore5 = Convert.ToDouble(txtScore5.Text) // Not evaluated
Theses do not have any value, in return this doesn't do what you want
decScoreAverage = (decScore1 + decScore2 + decScore3 + decScore4 + decScore5) / intDivideBy
UPDATE
(Vb code not tested)
Function GetTextValue(dim score as string) as Double
dim value as Double = 0
if (Double.TryParse(score, value))
return value
else
return value
End Function
This
decScore1 = Convert.ToDouble(txtScore1.Text)
Becomes
decScore1 = GetTextValue(txtScore1.Text)
I suggest you store reference to each textbox in an array. You'll see why at the end of this example.
Public Class frmTestScoreAverage
Public Sub New()
Me.InitializeComponent()
Me.boxes = {Me.txtScore1, Me.txtScore2, Me.txtScore3, Me.txtScore4, Me.txtScore5}
End Sub
Private boxes As TextBox()
The common way to validate user input in winforms is to handle the Validating event, usually combined with the error provider class as mentioned by Hans Passant.
Private Sub HandleScoreValidating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles txtScore1.Validating, txtScore2.Validating, txtScore3.Validating, txtScore4.Validating, txtScore5.Validating
With DirectCast(sender, TextBox)
If ((Not String.IsNullOrEmpty(.Text)) AndAlso (Not Double.TryParse(.Text, 0.0R))) Then
e.Cancel = True
'Alert or set error provider:
'Me.ErrorProvider1.SetError(DirectCast(sender, Control), "Not double")
Else
e.Cancel = False
'Clear error provider:
'Me.ErrorProvider1.Clear()
End If
End With
End Sub
Now, back to the textbox array. Create a new list of double and iterate the textbox array. If the text isn't empty, parse and add the value to the list. At the end, use the Average extension method to get the average value.
Private Sub HandleCalculate(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim values As New List(Of Double)
For Each box As TextBox In Me.boxes
If (Not String.IsNullOrEmpty(box.Text)) Then
values.Add(Double.Parse(box.Text))
'Else
' values.Add(0.0R)
End If
Next
Dim average As Double = values.Average()
'....
End Sub
End Class
I'm very new to programming and vb.net, trying to self teach more so as a hobby, as I have an idea for a program that I would find useful, but I am having trouble getting past this issue and I believe it is to do with the timer.
I have a form of size.(600,600) with one button of size.(450,150) that is set location(100,50) on the form. When clicked I want to move down it's own height, then add a new button in it's place. The code included below works as desired for the first two clicks, but on the third click the button keeps moving and the autoscroll bar extends. I initially thought it was the autoscroll function or the location property, but realised that as the button keeps moving, the timer hasn't stopped. I am aware that the code is probably very clunky in terms of achieving the outcome, and that there are a few lines/variables that are currently skipped over by the compiler (these are from older attempts to figure this out).
I have looked around and can't find the cause of my problem. Any help would be greatly appreciated. Apologies if the code block looks messy - first go.
Public Class frmOpenScreen
Dim intWButtons, intCreateButtonY, intCreateButtonX 'intTimerTick As Integer
Dim arrWNames() As String
Dim ctrlWButtons As Control
Dim blnAddingW As Boolean
Private Sub btnCreateW_Click(sender As System.Object, e As System.EventArgs) Handles btnCreateW.Click
'Creates new Button details including handler
Dim strWName, strWShort As String
Dim intCreateButtonY2 As Integer
Static intNumW As Integer
Dim B As New Button
strWName = InputBox("Please enter the name name of the button you are creating. Please ensure the spelling is correct.", "Create W")
If strWName = "" Then
MsgBox("Nothing Entered.")
Exit Sub
End If
strWShort = strWName.Replace(" ", "")
B.Text = strWName
B.Width = 400
B.Height = 150
B.Font = New System.Drawing.Font("Arial Narrow", 21.75)
B.AutoSizeMode = Windows.Forms.AutoSizeMode.GrowAndShrink
B.Anchor = AnchorStyles.Top
B.Margin = New Windows.Forms.Padding(0, 0, 0, 0)
'Updates Crucial Data (w name array, number of w buttons inc Create New)
If intNumW = 0 Then
ReDim arrWNames(0)
Else
intNumW = UBound(arrWNames) + 1
ReDim Preserve arrWNames(intNumW)
End If
arrWNames(intNumW) = strWShort
intNumW = intNumW + 1
intWButtons = WButtonCount(intWButtons) + 1
'updates form with new button and rearranges existing buttons
intCreateButtonY = btnCreateW.Location.Y
intCreateButtonX = btnCreateW.Location.X
‘intTimerTick = 0
tmrButtonMove.Enabled = True
‘Do While intTimerTick < 16
‘ 'blank to do nothing
‘Loop
'btnCreateW.Location = New Point(intCreateButtonX, intCreateButtonY + 150)
B.Location = New Point(intCreateButtonX, intCreateButtonY)
Me.Controls.Add(B)
B.Name = "btn" & strWShort
intCreateButtonY2 = btnCreateW.Location.Y
If intCreateButtonY2 > Me.Location.Y Then
Me.AutoScroll = False
Me.AutoScroll = True
Else
Me.AutoScroll = False
End If
'MsgBox(intCreateButtonY)
End Sub
Function WButtonCount(ByRef buttoncount As Integer) As Integer
buttoncount = intWButtons
If buttoncount = 0 Then
Return 1
End If
Return buttoncount
End Function
Public Sub tmrButtonMove_Tick(sender As System.Object, e As System.EventArgs) Handles tmrButtonMove.Tick
Dim intTimerTick As Integer
If intTimerTick > 14 Then
intTimerTick = 0
End If
If btnCreateW.Location.Y <= intCreateButtonY + 150 Then
btnCreateW.Top = btnCreateW.Top + 10
End If
intTimerTick += 1
If intTimerTick = 15 Then
tmrButtonMove.Enabled = False
End If
End Sub
End Class
So my current understanding is that the tick event handler should be increasing the timertick variable every time it fires, and that once it has hits 15 it should diable the timer and stop the button moving, but it is not doing so.
Thanks in advance.
IntTimerTick is initialized to 0 at the beginning of every Tick event. This won't happen if you declare it to be static:
Static Dim intTimerTick As Integer