VLC ActiveX seek bar help in vb.net - vb.net

I am making a video player, using VLC ActiveX called AxVLCPlugin21, so want to make it real as possible. So i thought of putting a Trackbar1 to seek through a video, with a Label1 for the time in 0:0/0:0 format
What I know:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
' When the timer runs the, label text will be set to the return value of the function formattime()
With TrackBar1
.Minimum = 0
.Maximum = AxVLCPlugin21.input.Length
End With
Label1.Text = formatTime(AxVLCPlugin21.input.Time) & "/" & formatTime(AxVLCPlugin21.input.Length)
Try
TrackBar1.Value = AxVLCPlugin21.input.time
Catch ex As Exception
End Try
End Sub
Private Sub TrackBar1_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar1.Scroll
AxVLCPlugin21.input.Time = TrackBar1.Value
AxVLCPlugin21.playlist.play()
End Sub
Function formatTime(ByVal timeVal As Integer)
Dim timeHour As Integer
Dim timeSec As Integer
Dim timeMin As Integer
timeHour = Math.Round(timeVal \ 1000)
timeSec = timeHour Mod 60
If timeSec < 10 Then
timeSec = "0" & timeSec
timeHour = (timeHour - timeSec) \ 60
timeMin = timeHour Mod 60
End If
If timeMin < 10 Then
timeMin = "0" & timeMin
timeHour = (timeHour - timeMin) \ 60
End If
If timeHour < 0 Then
Return timeHour & ":" & timeMin & ":" & timeSec
Else
Return timeMin & ":" & timeSec
End If
End Function
Code cited from here
The seek bar works perfectly but the label containing the time does not, for example if the video a 5 minute and when playing the video, the time is in the 50th second the label will show 0.50/5.0, when the video time is 2 minutes and 55 seconds it will show 0.55/5.0.
My point is that when the video time reaches more than 60 seconds the minute resets to zero.
Is there a problem in the code? I have included some extra information like the Trackbar1_Scroll and Timer1_Tick.
And also I want the time to appear like 00:00/00.00 and the function does not have the code for hours so anyone can help me creating an hour in the function, and display the time as 00:00:00/00:00:00
Thank you
[shannon]

Related

Progress bar gets stuck at 100%

I've programmed a "Please wait" form in which I inserted a progress bar. I looked around how to program a progress bar and this is what I did. First of all I programmed the button - Button3_Click - I press to start. Then I programmed the timer - Timer1_Tick -and so I wrote:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Timer1.Enabled = True
Timer1.Interval = 50
Timer1.Start()
*[calculus code]*
If Form18.ProgressBar1.Value = 100 Then
Form18.Hide()
hrrspkexcel.Visible = True
End If
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
iProgressBarValue += 1
Select Case iProgressBarValue
Case 1, 3, 5, 7, 9
Form18.ProgressBar1.ForeColor = Color.White
Form18.Label3.Text = Form18.ProgressBar1.Value & (" %")
Form18.ProgressBar1.Value = (iProgressBarValue * 10)
Case 2, 4, 6, 8
Form18.Label3.Text = Form18.ProgressBar1.Value & (" %")
Form18.ProgressBar1.Value = (iProgressBarValue * 10)
Case 10
Form18.ProgressBar1.Value = (iProgressBarValue * 10)
Form18.Label3.Text = Form18.ProgressBar1.Value & (" %")
Timer1.Stop()
Timer1.Enabled = False
End Select
End Sub
I can't understand why the progress bar gets stuck at 100% and neither form18 gets hidden, nor hrrspkexcel becomes visible. Where am I doing wrong? Thanks for any support. Best regards.
Edit: I tried to edit my code as comments say:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Timer1.Enabled = True
Timer1.Interval = 50
Timer1.Start()
[calculus code]
iProgressBarValue += 1
Select Case iProgressBarValue
Case 1, 3, 5, 7, 9
Form18.ProgressBar1.ForeColor = Color.White
Form18.Label3.Text = Form18.ProgressBar1.Value & (" %")
Form18.ProgressBar1.Value = (iProgressBarValue * 10)
Case 2, 4, 6, 8
Form18.Label3.Text = Form18.ProgressBar1.Value & (" %")
Form18.ProgressBar1.Value = (iProgressBarValue * 10)
Case 10
Form18.ProgressBar1.Value = (iProgressBarValue * 10)
Form18.Label3.Text = Form18.ProgressBar1.Value & (" %")
Timer1.Stop()
Timer1.Enabled = False
End Select
If Form18.ProgressBar1.Value = 100 Then
Form18.Hide()
hrrspkexcel.Visible = True
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If Form18.ProgressBar1.Value = 100 Then
Timer1.Stop()
Timer1.Enabled = False
End If
End Sub
In this case, progress bar gets stuck at 10%.
Edit II: Following suggestions in comment, I removed the timer and based my progress bar on the entity of the calculus code (Form18.ProgressBar1.Maximum). Anyway, what is reported under [calculus code] is an heavy Excel export so the progress bar freezes to 0% until exportation has ended and then start running (I set loading cursor to understand when exportation has ended), so maybe I'd need of a BackgroundWorker to make my bar progressing while exporting? (I'm a beginner programmer and I read somewhere something about this, but I don't know if this solution is suitable for me, so I'm asking).
At last, this is how I corrected my code:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Form18.ProgressBar1.Minimum = 0
Form18.ProgressBar1.Value = 0
Form18.ProgressBar1.Maximum = [if loop criteria based on my code]
Form18.ProgressBar1.Increment(1)
Form18.Show()
[calculus code - excel export]
If Form18.ProgressBar1.Value = Form18.ProgressBar1.Maximum Then
Form18.Hide()
hrrspkexcel.Visible = True
End If
End Sub
With this edit, my ProgressBar freezes at 0% even if exportation has already ended, so I'm obviously doing wrong somewhere. Thanks for all the support you're giving to me.
Edit III: I managed in making progressbar working using a for loop to increment its value, as you suggested me, with a proportional equation to percentage and to overcome the problem about the maximum value of the bar, that's always set on 100. So thanks all of you for your support. The last thing I want to ask you - if I'm not offtopic - is how to make my loading form - with the progressbar - on foreground and to "lock" interaction with all other forms.
Edit III BIS: I've tried to use Backgroundworker in order to overcome the loading-form freezing. This is the first time I'm using this command and I don't know if it's the right way to make it comunicating to a ShowDialog Form. This is what I wrote:
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Form18.ProgressBar1.Minimum = 0
Form18.ProgressBar1.Value = 0
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Form18.ShowDialog()
[excel calculus export]
If Form18.ProgressBar1.Value = Form18.ProgressBar1.Maximum Then
Form18.Hide()
hrrnativexcel.Visible = True
End If
End Sub
I'm always getting the same trouble: when Form18 appears, remains on 0% loading.
Edit IV: I'm having an issue about progressbar increment for the following situation: I have two for loops for exporting values in excel and the upper bound of this loops are different. So I've created a third for loop, whose upper bound is the sum of the upper bounds of the two abovementioned for loops, in order to increment the progressbar progress. When it reaches 100%, it starts again going in loop. How could I solve this issue? Here is the code I'm using:
For i = 1 To CInt(Form6.ListBox1.Items.Count)
For j = 1 To CInt(Form10.ListBox1.Items.Count)
For k = 0 To CInt(CInt(Form6.ListBox1.Items.Count) + CInt(Form10.ListBox1.Items.Count))
hrrspkexcel.Cells(j + 1, 1).value = Form10.ListBox2.Items(CInt(j + 1) - 2)
hrrspkexcel.Cells(i + 1, 2).value = Form6.ListBox1.Items(CInt(i + 1) - 2)
Form18.ProgressBar1.Value = CInt(100 * k / (CInt(Form6.Label9.Text) + CInt(Form10.ListBox1.Items.Count)))
Form18.Label3.Text = Form18.ProgressBar1.Value & (" %")
Next
Next
Next
Thanks in advance.
Edit V: I've updated my code following comments in order to solve the issue described in Edit IV. This is what I wrote:
Dim pbloop As Integer
pbloop = CInt(Form10.ListBox1.Items.Count) * CInt(Form6.ListBox1.Items.Count)
For p = 1 To pbloop
For i = 1 To CInt(Form6.ListBox1.Items.Count)
For j = 1 To CInt(Form10.ListBox1.Items.Count)
hrrspkexcel.Cells(i + 1, 4).value = Form6.ListBox1.Items(CInt(i + 1) - 2)
hrrspkexcel.Cells(i + 1, 3).value = Form6.ListBox2.Items(CInt(i + 1) - 2)
hrrspkexcel.Cells(j + 1, 1).value = Form10.ListBox1.Items(CInt(j + 1) - 2)
hrrspkexcel.Cells(j + 1, 2).value = Form10.ListBox2.Items(CInt(j + 1) - 2)
Form18.ProgressBar1.Value = CInt(100 * p / pbloop)
Form18.Label3.Text = Form18.ProgressBar1.Value & (" %")
Next
Next
I'm getting stuck always at 0% and progress bar that doesn't increase.
This is not the true answer of the problem but a sample to show you how to use a progress bar.
This code is not beautiful, I know, it's for the example. Please be careful when you use a textbox text as a number without check what is written.
Imports System.Threading
Public Class Form1
Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
' Initialisation of the progressbar
myProgressbar.Value = 0
myProgressbar.Maximum = tbxTo.Text
lbxInfos.Items.Clear() ' Clear the content in the listbox1 if it's not the first run
' This simulate your [calculus code], I just add an information in the listbox
For i As Integer = tbxFrom.Text To tbxTo.Text
myProgressbar.Value = i ' Set the progressbar avancement
lbxInfos.Items.Add("This is the loop n° " & i & " !")
lbxInfos.Refresh() ' Just because the listbox will not be refresh until the end of the sub
Thread.Sleep(200) ' The code is too fast, I add this to see the progress (= wait 200 ms)
Next
MsgBox("This is the end ! Now the form will be closed")
Me.Close()
End Sub
End Class
Try something more like this out:
Private Async Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Button3.Enabled = False
hrrspkexcel.Visible = False ' changed this to a Label next to the button just for demonstration
Dim f18 As New Form18
f18.ProgressBar1.Minimum = 0
f18.ProgressBar1.Value = 0
f18.ProgressBar1.Maximum = 100 ' <-- leave the maximum at 100!
f18.Show(Me)
Dim pct As Integer
Dim maximum As Integer = 319 ' <-- figure out the max value based on your "calculus code"
Await Task.Run(Sub()
' [calculus code - excel export]
For i As Integer = 0 To maximum
System.Threading.Thread.Sleep(50) ' <- some kind of processing going on
' calculate the percentage based on your loop value "i" and the "maximum":
pct = CDbl(i) / CDbl(maximum) * 100 ' <-- scale your loop value to 100
Try
f18.ProgressBar1.Invoke(Sub()
f18.ProgressBar1.Value = pct
End Sub)
Catch ex As Exception
' User closed the progressform, create another one
Me.Invoke(Sub()
f18 = New Form18
f18.ProgressBar1.Minimum = 0
f18.ProgressBar1.Value = 0
f18.ProgressBar1.Maximum = 100 ' <-- leave it at 100
f18.Show(Me)
' make progressbar immediately jump to the right spot
f18.ProgressBar1.Value = f18.ProgressBar1.Maximum
f18.ProgressBar1.Value = pct
End Sub)
End Try
Next
End Sub)
' when we hit here, the "calculus code" above completed
f18.Close()
hrrspkexcel.Visible = True ' changed this to a Label next to the button just for demonstration
Button3.Enabled = True
End Sub
Here's what it looks like in action:
You current code reads as if you want the Progress Bar to update on a button click a maximum of 10 times before hiding the form. Is that your intention? I would have expected that you want the "Please wait ..." form to stay visible with the progress bar updating every, say, second, then disappear?
Using a timer for the latter is fine but for the former, you can simply update the progress bar directly - as you are doing - without a timer.
Also, you don't need to multiply your progress bar value by 10; you can simply set the progress bar Maximum value to 10.
Also, since you change the ForeColor value on the first click, you can probably dispense with the Case Select {even|odd} test because the code is otherwise identical.
So without the timer or the color change and with Progress Bar Maximum = 10, all you need to do is:
Form18.ProgressBar1.Value = iProgressBarValue
Form18.Label3.Text = $"{iProgressBarValue} %")
No need for the Case Select.
Another option for the PB is to use the PerformStep() method to increment it. Just set the Step property to 1 for this approach.

Using vb.net Count all occurrences of vbCrLf in TextBox

I have a TextBox that I am trying to count all the occurrences of vbCrLf.
The counting is working, the issue is every time a vbCrLf is issued I would like to subtract 33 from some Integer.
The code as written now only subtracts the number of vbCrLf, NOT the number + 33.
Question is how to subtract 33 every time the Enter Key is pressed and a vbCrLf is issued ?
I have posted Updated Code The Question Was Answered and Issues SOLVED
I have also added additional code that enhances the management of the TextBox
You will need these Imports
Imports System.IO
Imports System.Text
Public Class frmThree
Dim path As String = "C:/Users/Me/source/repos/TestForms/TestForms/Resource/"
Dim total As Integer
Dim vbLfTotal As Integer
Dim chrPermited As Integer = 333 'chrPermited
Private Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click
Me.Close()
frmOne.Show()
End Sub
Private Sub tbHaveOne_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbHaveOne.TextChanged
Dim spaceCount, letterCount, carReturn As Integer
spaceCount = 0
letterCount = 0
carReturn = 0
Dim str As String = tbHaveOne.Text
For Each chr As Char In str
If chr = vbLf Then
carReturn += 1
ElseIf Char.IsLetterOrDigit(chr) Then
letterCount += 1
ElseIf Char.IsWhiteSpace(chr) Then
spaceCount += 1
End If
Next
vbLfTotal = carReturn * 29
total = chrPermited - letterCount - spaceCount - vbLfTotal
tbHaveTwo.ForeColor = Color.Black
tbHaveTwo.Text = total & " More Character Can Be Entered"
While total < 10
tbHaveTwo.Clear()
tbHaveTwo.ForeColor = Color.Red
tbHaveTwo.Text = "Only " & total & " More Character Can Be Entered"
Exit While
End While
If total = 5 Then
PlaySystemSound()
End If
If total < 1 Then
tbHaveTwo.Clear()
tbHaveTwo.Text = "No More Data Entry" & total
Call ansQ()
End If
End Sub
Sub PlaySystemSound()
My.Computer.Audio.PlaySystemSound(
System.Media.SystemSounds.Hand)
End Sub
Public Sub ansQ()
Const Msg As String = "YES Save Data" + vbCrLf + vbNewLine + "NO CANCEL"
Const Title As String = "Save or Exit"
Const Style = vbYesNo + vbQuestion + vbDefaultButton2
Dim result = MsgBox(Msg, Style, Title)
If result = vbYes Then
Call writeDATA()
ElseIf result = vbNo Then
'tbHaveOne.ReadOnly = True
'tbHaveOne.Enabled = False
tbHaveTwo.Text = "NO Was Selected"
'result = 0
End If
End Sub
Public Shared Sub tbHaveOne_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles tbHaveOne.KeyDown
'NOTE this Sub is Shared It seems to run all the time like a listener
If e.KeyCode = Keys.Enter And frmThree.total < 40 Then
e.SuppressKeyPress = True
End If
End Sub
The TextBox.Lines.Count returns the count of the lines separated by newline characters (ControlChars.NewLine or Environment.NewLine when you hit the Enter key.) and not the count of the word-wrapped lines in a multiline TextBox. If you set the WordWrap property to False you will see the difference. See the TextBoxBase.Lines remarks section.
You could call the SendMessage method and the EM_GETLINECOUNT message if you need to get the count of the lines regardless whether they are word-wrapped or separated new lines:
Imports System.Runtime.InteropServices
Private Const EM_GETLINECOUNT As UInteger = &HBA
<DllImport("user32.dll")>
Private Shared Function SendMessage(ByVal hWnd As IntPtr,
ByVal msg As Integer,
ByVal wp As IntPtr,
ByVal lp As IntPtr) As IntPtr
End Function
Private Sub PrintCounts()
Dim c = tbHaveOne.Text.
Aggregate(New With {
.WhiteSpaces = 0, .Lf = 0, .NewLines = 0, .Lines = 0, .Others = 0
},
Function(x, y)
x.Lf += If(y = ControlChars.Cr, 1, 0)
x.WhiteSpaces += If(Char.IsSeparator(y), 1, 0)
x.Others += If(Not Char.IsWhiteSpace(y), 1, 0)
Return x
End Function)
c.NewLines = tbHaveOne.Lines.Count
c.Lines = SendMessage(tbHaveOne.Handle, EM_GETLINECOUNT,
IntPtr.Zero, IntPtr.Zero).ToInt32
tbHaveTwo.Text = $"WhiteSpaces: {c.WhiteSpaces} Lf: {c.Lf} " +
$"New Lines: {c.NewLines} Lines {c.Lines} Others: {c.Others}"
End Sub
Private Sub tbHaveOne_TextChanged(sender As Object,
e As EventArgs) Handles tbHaveOne.TextChanged
PrintCounts()
End Sub
Please note:
The Char.IsSeparator method is used to get the count of the white spaces since the Char.IsWhiteSpace method will return True when evaluating; vbCr, vbLf, vbCrLf, vbTab, ...etc. Alternatively, you can combine the Char.IsWhiteSpace and the Char.IsControl methods to evaluate the white spaces. The Remarks section has more.
The Others is the count of everything else including the letters, digits, punctuations, symbols...etc. You may wont to examine the other Char.IsXXX methods of the Char structure.
Check out the values of the Lines and NewLines fields as you type.
You can't check if the current character is vbcrlf because CRLF is two characters. Just check for the LF, this way if you ever use the logic on a file prepared by a unix system, it still works (unix has LF, Windows has CRLF)
Private Sub tbHaveOne_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbHaveOne.TextChanged
Dim spaceCount = 0
Dim letterCount = 0
Dim lineCount = 0
For Each c As Char In tbHaveOne.Text
If c = vbLf Then
lineCount += 1
ElseIf Char.IsLetterOrDigit(c) Then
letterCount += 1
ElseIf Char.IsWhiteSpace(c) Then
spaceCount += 1
End If
Next c
someInteger -= (lineCount * 33)
The System.Char has static methods that check characters are in certain Unicode ranges - for your letter count you were counting anything that wasn't a space, including carriage returns, punctuation and other things that aren't letters, as letters. You're free to carry on doing that if you want but it'll maybe lead to a bit of a confusing count if you triple count the newlines
The counting is working the issue is every time a vbCrLf is issued I would like to subtract 33 from some Integer
The code as written now only subtracts the number of vbCrLf NOT the number + 33
I didn't quite get this. You say you want to subtract 33 every time there is a new line, which is what I've done. The second sentence reads like the requirement is to subtract the (number of new lines + 33) from someInteger. If this is what you want to do, change the * on the last line to +
Question is how to subtract 33 every time the Enter Key is pressed and a vbCrLf is issued ?
This is a different thing entirely to "count all occurrences of"; it isn't to do with counting the lines in a textbox, and you can't do it from such code. Counting the number of times the user has ever pressed enter in a textbox needs a hook to the event raised when a user pressed a key while the box had focus. Add a handler for the KeyPress or KeyDown event:
Private Sub tbHaveOne_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tbHaveOne.KeyPress 'KeyEventArgs for KeyDown event
If e.KeyChar = vbCr Then 'use e.KeyCode = Keys.Enter in KeyDown event
someInteger -= 33
End If
End Sub
We have a lot of great Discussion and Fixed Answers on this question
One of the questions in the discussion was how to handle punctuation and special characters
We would like to offer this code as a way to manage both punctuation and special characters
Dim spaceCount, letterCount, carReturn, punCount, syCount As Integer
spaceCount = 0
letterCount = 0
carReturn = 0
punCount = 0
syCount = 0
Dim str As String = tbHaveOne.Text
For Each chr As Char In str
If chr = vbLf Then
carReturn += 1
ElseIf Char.IsLetterOrDigit(chr) Then
letterCount += 1
ElseIf Char.IsWhiteSpace(chr) Then
spaceCount += 1
ElseIf Char.IsPunctuation(chr) Then
punCount += 1
ElseIf Char.IsSymbol(chr) Then
syCount += 1
End If
Next
vbLfTotal = carReturn * 29
total = chrPermited - letterCount - spaceCount - vbLfTotal - punCount - syCount
tbHaveTwo.ForeColor = Color.Black
tbHaveTwo.Text = total & " More Character Can Be Entered"

VB.net - Timer isn't updating

I'm trying to add an uptime counter so that from the moment my application launches it starts a timer that increments by the second until the application is closed or I stop it on purpose.
Currently the timer counts the first second and then stops. This might be me not understanding the tick function? I assume that the interval I set for the timer will refresh or loop the code within the tick sub? (Could me massively wrong).
I have timer1 and I've set it to "Enabled" and the interval to "1000" for one second.
In my Timer1_Tick Sub I have this:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim seconds, minutes, hours As Integer
If seconds = 60 Then
seconds = 0
minutes = minutes + 1
End If
If minutes = 60 Then
If seconds = 60 Then
seconds = 0
minutes = 0
hours = hours + 1
End If
End If
seconds = seconds + 1
Label44.Text = Format(hours, "00") & "." & Format(minutes, "00") & "." & Format(seconds, "00")
End Sub
In Form1_Load I have Timer1.Start()
Please can you tell me what I'm missing? Thanks.
For up time in my applications I just log the time and date it was started, then use a label to show difference in time since the time was logged. It's a lot simpler than running a time ticking all the time.
The approaches given are highly inaccurate because they assume that the tick event fires exactly at the specified interval, and that doesn't happen.
The tick event should be used only to update the label from a more precise time measurement. In the code below a stopwatch is used.
Dim appruntime As Stopwatch = Stopwatch.StartNew
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Label1.Text = appruntime.Elapsed.ToString("d\ hh\:mm\:ss")
End Sub
You need to declare the variables within Form1.
Public Class Form1
Private seconds, minutes, hours As Integer
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
If seconds = 60 Then
seconds = 0
minutes = minutes + 1
End If
If minutes = 60 Then
If seconds = 60 Then
seconds = 0
minutes = 0
hours = hours + 1
End If
End If
seconds = seconds + 1
Label44.Text = Format(hours, "00") & "." & Format(minutes, "00") & "." & Format(seconds, "00")
End Sub
End Class

VB.net basic error with String <-> Char Conversion

I was programming a little game to pratice myself and i went on an error I weren't able to fix :S. This is the start of an hanging game. (Dont know if its the correct name in english :) ) I need to take a word from a file, 1 per line, and let the player guess the word with a limited numbers of try.
I think my error is related to string/char comparaison and manipulation or, what i write in the text label. I tryed to find some tutorial or problem already solved on internet but nothing was really the same as this ... :(
I change the type of variable many time, read the debugger line per line but I never finded what was wrong .. :S If you are good with VB, plz help me fix that :O (you can also give your comment/improve)
Thx, TheFlame
Code:
Imports System.IO
Public Class Pendu
Public Structure StructMot
Public MotSecret() As Char
Public LettreDecouverte() As Char
End Structure
Dim Mot As StructMot
Dim i As Integer = 0
Private Sub ButtonA_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonA.Click, ButtonB.Click,
ButtonC.Click, ButtonD.Click, ButtonE.Click, ButtonF.Click, ButtonG.Click, ButtonH.Click, ButtonI.Click, ButtonJ.Click,
ButtonK.Click, ButtonL.Click, ButtonM.Click, ButtonN.Click, ButtonO.Click, ButtonP.Click, ButtonQ.Click, ButtonR.Click,
ButtonS.Click, ButtonT.Click, ButtonU.Click, ButtonV.Click, ButtonW.Click, ButtonX.Click, ButtonY.Click, ButtonZ.Click
i = i + 1
ActiveControl.Visible = False
PictureBox1.Image = ImageList1.Images(i - 1)
Dim j As Integer = 0
For j = 0 To Mot.MotSecret.Length - 1
If ActiveControl.Text = Mot.MotSecret(j) Then
Mot.LettreDecouverte(j) = Mot.MotSecret(j)
End If
Next j
Label1.Text = ""
For j = 0 To Mot.MotSecret.Length - 1
Label1.Text = Label1.Text + " "
If Mot.LettreDecouverte(j).Equals("") Then
Label1.Text = Label1.Text + "_"
Else
Label1.Text = Label1.Text + Mot.LettreDecouverte(j)
End If
Next j
End Sub
Private Sub JouerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles JouerToolStripMenuItem.Click
GenereMot()
End Sub
Private Sub Pendu_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
GenereMot()
End Sub
Function GenereMot()
Dim NbItems As Integer
Dim Aleatoire As New Random()
Dim NbAleatoire As Integer
ListBox1.Items.AddRange(System.IO.File.ReadAllLines("listemot.txt"))
NbItems = ListBox1.Items.Count
NbAleatoire = Aleatoire.Next(NbItems)
Mot.MotSecret = ListBox1.Items(NbAleatoire)
Return Mot
End Function
End Class
the Mot.LettreDecouverte can be Nothing i.e. not initialized as you don't set any value for it.
This can cause error to happen both in Mot.LettreDecouverte(j) = Mot.MotSecret(j) line and also in If Mot.LettreDecouverte(j).Equals("") Then... line of your code.
change your ButtonA_Click event handler code as following:
i = i + 1
ActiveControl.Visible = False
PictureBox1.Image = ImageList1.Images(i - 1)
Dim j As Integer = 0
If Mot.LettreDecouverte Is Nothing OrElse Mot.LettreDecouverte.Length < Mot.MotSecret.Length Then
Mot.LettreDecouverte = Space(Mot.MotSecret.Length) '* initiate it by enough number of space chars
End If
For j = 0 To Mot.MotSecret.Length - 1
If ActiveControl.Text = Mot.MotSecret(j) Then
Mot.LettreDecouverte(j) = Mot.MotSecret(j)
End If
Next j
Label1.Text = ""
For j = 0 To Mot.MotSecret.Length - 1
Label1.Text = Label1.Text + " "
If Mot.LettreDecouverte(j).Equals(" "c) Then '*Note: i use space char, not empty string
Label1.Text = Label1.Text + "_"
Else
Label1.Text = Label1.Text + Mot.LettreDecouverte(j)
End If
Next j
Note that the value of Mot.LettreDecouverte(j) is always a char and a char can not be an empty string as you typed in Mot.LettreDeciouverte(j).Equals(""). i initiate the LettreDeciouverte with an array of space chars such that we can check its elements comparing against " "c char.

Create a simple timer to count seconds, minutes and hours

I'm trying to create a pretty simple program that basically is a timer.
I have three sets of labels, lbl_seconds, lbl_minutes and lbl_hours.
These labels have the default value of 00:00 and I want the timer to change that for each label. I have googled this but I cannot seem to find any good info on it.
Do I need three separate timers? I have also noticed that the timers have their own tick event handler. I guess it's in this that I need to change the value of the label. How to do just that?
Here is an example of this
Dim timercount As Integer = 60 'The number of seconds
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Timer1.Interval = 1000 'The number of miliseconds in a second
Timer1.Enabled = True 'Start the timer
End Sub
Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click
Timer1.Enabled = False 'Stop the timer
timercount = 60 'Reset to 60 seconds
lblOutput.Text = timercount.ToString() 'Reset the output display to 60
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
lblOutput.Text = timercount.ToString() 'show the countdown in the label
If timercount = 0 Then 'Check to see if it has reached 0, if yes then stop timer and display done
Timer1.Enabled = False
lblOutput.Text = "Done"
Else 'If timercount is higher then 0 then subtract one from it
timercount -= 1
End If
End Sub
I think you need something of this sort
Public Function GetTime(Time as Integer) As String
Dim Hrs As Integer 'number of hours '
Dim Min As Integer 'number of Minutes '
Dim Sec As Integer 'number of Sec '
'Seconds'
Sec = Time Mod 60
'Minutes'
Min = ((Time - Sec) / 60) Mod 60
'Hours'
Hrs = ((Time - (Sec + (Min * 60))) / 3600) Mod 60
Return Format(Hrs, "00") & ":" & Format(Min, "00") & ":" & Format(Sec, "00")
End Function
You pass the time (in seconds) you'd like to display on the label's text and the time will be formatted as you like it.
e.g.
lblTime.Text = GetTime(90)
This will display 00:01:30 on the label.
For reference, you can see this project I submitted on FreeVBCode some time ago. The only caveat is the project is in VB6. You should be able to open it in Visual Studio though.
Start off by adding a timer. Call it whatever you like, in this example I will be keeping it as Timer1. Add a label and set the text as: 00:00.
In the code after the class has been set (usually it is Public Class Form1) make a variable as a stopwatch: Dim stopwatch As New Stopwatch
In the timer tick event code, put the following: (Please note that my 00:00 label is called Label1)
Label1.Text = String.Format("{0}:{1}:{2}", watch.Elapsed.Hours.ToString("00"), watch.Elapsed.Minutes.ToString("00"), watch.Elapsed.Seconds.ToString("00"))
Use one timer and in event sub change value of your labels.
You need one timer and three counter for seconds, minutes and hours.
Count minutes, then modulo minutes / 60, if return 0 then start count minutes.
Modulo minutes/60, if return 0 then start count hours.