1

Eu tenho uma caixa de listagem em um temporizador com itens e eu preciso passar todos os itens um por um até o final e depois ir para o primeiro índice e parar o temporizador. Mas isso me dá fora do alcance quando ele passa no último. Como posso resolver esta exceção? Eu pesquisei no google mas não consigo encontrar qualquer solução. Obrigado antecipadamente.

Este é o meu código

If (ListBox1.SelectedItem = Nothing) Then
        ListBox1.SelectedIndex = 0
        Timer1.Stop()
    Else
        ListBox1.SelectedIndex += 1
        gethash()
    End If

I have also try like this

If (ListBox1.SelectedIndex >= ListBox1.Items.Count) Then
        ListBox1.SelectedIndex = 0
        Timer1.Stop()
    Else
        ListBox1.SelectedIndex += 1
        gethash()
    End If

E o resultado é o mesmo

Este é todo o código

Imports System
Imports System.IO
Imports System.Security
Imports System.Security.Cryptography
Imports System.Text
Imports System.Net
Public Class Form1
Dim SourceFileOpen As New System.Windows.Forms.OpenFileDialog
Dim md5hashindexer = 1
Dim percent = 0
Dim red
Dim i As Integer
Dim str As String = ""
Dim ix As Integer = 0

#Region "Atalhos para o principal hash_generator função"


Function md5_hash(ByVal file_name As String)

    Return hash_generator("md5", file_name)

End Function

Function sha_1(ByVal file_name As String)

    Return hash_generator("sha1", file_name)

End Function

Function sha_256(ByVal file_name As String)

    Return hash_generator("sha256", file_name)

End Function

#End Region
Function hash_generator(ByVal hash_type As String, ByVal file_name As String)


    Dim hash
    If hash_type.ToLower = "md5" Then

        hash = MD5.Create
    ElseIf hash_type.ToLower = "sha1" Then

        hash = SHA1.Create()
    ElseIf hash_type.ToLower = "sha256" Then

        hash = SHA256.Create()
    Else
        MsgBox("Type de hash inconnu : " & hash_type, MsgBoxStyle.Critical)
        Return False
    End If


    Dim hashValue() As Byte


    Dim fileStream As FileStream = File.OpenRead(file_name)

    fileStream.Position = 0

    hashValue = hash.ComputeHash(fileStream)

    Dim hash_hex = PrintByteArray(hashValue)


    fileStream.Close()


    Return hash_hex

End Function


Public Function PrintByteArray(ByVal array() As Byte)

    Dim hex_value As String = ""


    Dim i As Integer
    For i = 0 To array.Length - 1


        hex_value += array(i).ToString("X2")

    Next i


    Return hex_value.ToLower

End Function
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    FolderBrowserDialog1.ShowDialog()
    TextBox2.Text = FolderBrowserDialog1.SelectedPath
    For Each Dir As String In Directory.GetDirectories(FolderBrowserDialog1.SelectedPath)
        ListBox2.Items.Add(Dir)
    Next

End Sub
Public Function Main()
    ' Make a reference to a directory.
    Dim di As New DirectoryInfo(FolderBrowserDialog1.SelectedPath)
    ' Get a reference to each file in that directory.
    Dim fiArr As FileInfo() = di.GetFiles()
    ' Display the names of the files.
    Dim fri As FileInfo
    For Each fri In fiArr
        ListBox1.Items.Add(fri.Name)
    Next
End Function 'Main
Public Function Main2()
    If ListBox2.SelectedItem = Nothing Then
        MsgBox("Please Select A Directory From the List...")

    Else
        ' Make a reference to a directory.
        Dim di As New DirectoryInfo(ListBox2.SelectedItem.ToString)
        ' Get a reference to each file in that directory.
        Dim fiArr As FileInfo() = di.GetFiles()
        ' Display the names of the files.
        Dim fri As FileInfo
        For Each fri In fiArr
            ListBox1.Items.Add(ListBox2.SelectedItem & "/" & fri.Name)
        Next
        TextBox1.Text = ListBox1.Items.Count.ToString()
    End If
End Function 'Main

Private Sub FolderBrowserDialog1_Disposed(sender As Object, e As EventArgs) Handles Button2.Click
    TextBox2.Text = FolderBrowserDialog1.SelectedPath
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Main()
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Main2()
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Button2.Image = My.Resources._2_Documents_icon
    Button2.BackgroundImageLayout = ImageLayout.Zoom
End Sub

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click



    Dim path As String = ListBox1.SelectedItem.ToString

    TB_path.Text = path


    LB_md5.Text = md5_hash(path)
    LB_sha1.Text = sha_1(path)
    LB_sha256.Text = sha_256(path)
    ListBox3.Items.Add(LB_md5.Text)
    'ListBox3.Items.Add(ListBox1.SelectedItem.ToString)
    ListBox3.SelectedIndex += 1
    Dim itemmd5 = LB_sha256.Text





    Dim sb As New System.Text.StringBuilder()

    For Each o As Object In ListBox3.Items
        sb.AppendLine(o)
    Next



    'System.IO.File.WriteAllText("c:\checkedfilesmd5.txt", sb.ToString())
End Sub

Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click

    Timer1.Start()


End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

    If (ListBox1.SelectedIndex = ListBox1.SelectedIndex) Then
        ListBox1.SelectedIndex = 0





        Timer1.Stop()
    Else
        ListBox1.SelectedIndex += 1
        gethash()
    End If
End Sub
Public Sub gethash()
    str = str & " " & ListBox1.SelectedItems(i).ToString



    'My.Settings.itemsmd5 = itemmd5
    Dim path As String = ListBox1.SelectedItem

    TB_path.Text = path


    LB_md5.Text = md5_hash(path)
    LB_sha1.Text = sha_1(path)
    LB_sha256.Text = sha_256(path)
    ListBox3.Items.Add(LB_md5.Text)
    'ListBox3.Items.Add(str)
    ListBox3.SelectedIndex += 1
    Dim itemmd5 = LB_sha256.Text





    Dim sb As New System.Text.StringBuilder()

    For Each o As Object In ListBox3.Items
        sb.AppendLine(o)
    Next

    md5hashindexer += 1
End Sub

Private Sub ShowWindowToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ShowWindowToolStripMenuItem.Click
    Me.Show()
End Sub

Private Sub nfi_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles nfi.MouseDoubleClick
    Me.Show()
    Me.BringToFront()
End Sub

Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
    'First minimize the form
    Me.WindowState = FormWindowState.Minimized

    'Now make it invisible (make it look like it went into the system tray)
    Me.Visible = False

    'Cancel the closing of the application
    'e.Cancel = True

    nfi.Visible = True

    MsgBox("Md Antivirus rogram has been minimized to the task bar.")
End Sub
End Class

1 Resposta 1

3

Não precisa desse código todo, apenas da parte problemática e que tem relação com ela.

No C# ou VB.net, os índices começam no 0, logo a última posição é igual a quantidade de itens - 1.

Exemplo:

Item:    1, 2, 3, 4, 5, 6
Índice:  0, 1, 2, 3, 4, 5

Nessa situação, a propriedade Count será 6, mas o índice máximo, 5. Portanto seu if nunca entrará na condição verdadeira:

if (ListBox1.SelectedIndex >= ListBox1.Items.Count)

Assim, entra no else e incrementa o SelectedIndex, que só pode ir até 5. Na tentativa de ir até o 6, o erro acontece.

A comparação deveria ser:

if (ListBox1.SelectedIndex == ListBox1.Items.Count-1) //Se está no último item
1
  • Obrigado pela ajuda de facto eu tinha percibido o porque do erro mas ainda nao tinha visto de essa maneira. 3/08/2018 às 2:32

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .