0

I have this problem.. I keep getting this error:

Cross-thread operation not valid: Control 'ListView1' accessed from a thread other than the thread it was created on.

Here is my code:

Imports System.IO.Directory
Imports System.IO
Public Class Video_to_Mp3
    Public folderopen As String
   
    Dim ofd As New OpenFileDialog
    Dim sizetext As String
    Dim length As Double
    Dim proc As New Process
    Dim avdcfile As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\AVDC Folder\convertlog.txt"
    Dim filepath As String = "C:\"
    Dim dirsave As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\AVDC Folder\Converted Files\Audio\" & Replace(Format(Now(), "dd/MM/yyyy"), "/", "_") & "\"


    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBack.Click
        Form1.Show()
        Me.Hide()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        dlgOpen.InitialDirectory = filepath
        dlgOpen.Title = "Please Select a File"
        dlgOpen.FileName = " "
        dlgOpen.Multiselect = True
        dlgOpen.ShowDialog()

    End Sub

    Private Sub Video_to_Mp3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        optStandard.Select()
        ListView1.Columns.Clear()
        ListView1.Columns.Add("File Name", 550, HorizontalAlignment.Center)
        ListView1.Columns.Add("Output Name", 150, HorizontalAlignment.Left)
        ListView1.Columns.Add("Video Length", 80, HorizontalAlignment.Center)
        ListView1.Columns.Add("Video Size", -2, HorizontalAlignment.Center)
        txtOutput.Text = dirsave
    End Sub

    Private Sub dlgOpen_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles dlgOpen.FileOk
        dlgOpen.CheckFileExists = True
        Dim i As Integer = 0
        Dim filename() As String = dlgOpen.FileNames
        Dim FileCount As Integer = dlgOpen.FileNames.Count

        While i < dlgOpen.FileNames.Count     
            Dim str(5) As String
            Dim itm As ListViewItem
            str(0) = dlgOpen.FileNames(i)
            str(1) = Path.GetFileNameWithoutExtension(dlgOpen.FileNames(i))         
            itm = New ListViewItem(str)
            ListView1.Items.Add(itm)
            i = i + 1
        End While
    End Sub

    Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click

        For Each lsvrow As ListViewItem In ListView1.SelectedItems
            ListView1.Items.Remove(lsvrow)
        Next

    End Sub

    Private Sub dlgSave_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles dlgSave.FileOk
        Me.txtOutput.Text = dlgSave.FileName
    End Sub

    Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click
        BackgroundWorker1.RunWorkerAsync()
        startconvert()
    End Sub

    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        startConvert()
    End Sub

    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
        If (txtOutput.Text = "") Then
            MsgBox("Please specify file to convert first!")
        Else
            Dim dir As New IO.DirectoryInfo(dirsave)
            If dir.Exists Then
                Dim savedate As String = (dirsave & "\Converted Files\Audio\" & Replace(Format(Now(), "dd/MM/yyyy"), "/", "_"))
                CreateDirectory(savedate)
                dlgSave.InitialDirectory = savedate
            End If

            dlgSave.Title = "Save As"
            dlgSave.ShowDialog()
        End If
    End Sub

    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ListView1.Items.Clear()
    End Sub

    Function startconvert()
        Dim quality As Integer

        Dim i As Integer = 0
        If optHigh.Checked Then
            quality = 20
        ElseIf optStandard.Checked Then
            quality = 10
        Else
            quality = 6
        End If


        While i < ListView1.Items.Count
            ListView1.Items(i).Selected = True
            ListView1.Select()

            Dim fO As New FileInfo(dlgOpen.FileName)
            Dim name = Path.GetFileNameWithoutExtension(ListView1.Items.Item(i).Text)
            Dim OpenfileName As String

            OpenfileName = fO.Name
            CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\AVDC Folder\Converted Files\Audio\" & Replace(Format(Now(), "dd/MM/yyyy"), "/", "_") & "\")
            Dim fbd As New FolderBrowserDialog
            Control.CheckForIllegalCrossThreadCalls = False
            Dim input As String = ListView1.Items.Item(i).Text
            Dim output As String = dirsave & name & ".mp3"
            Dim exepath As String = Application.StartupPath + "\bin\ffmpeg.exe"
            Dim startinfo As New System.Diagnostics.ProcessStartInfo
            Dim sr As StreamReader
            Dim cmd As String = " -i """ + input + """ -ar 22050 -qscale " & quality & " -y """ + output + """" 'ffmpeg commands -y replace
            Dim ffmpegOutput As String


            startinfo.FileName = exepath
            startinfo.Arguments = cmd
            startinfo.UseShellExecute = False
            startinfo.WindowStyle = ProcessWindowStyle.Normal
            startinfo.RedirectStandardError = True
            startinfo.RedirectStandardOutput = True
            startinfo.CreateNoWindow = True
            proc.StartInfo = startinfo
            proc.Start()

            sr = proc.StandardError 'standard error is used by ffmpeg
            Me.btnConvert.Enabled = False
            Me.btnAdd.Enabled = False

            Me.btnRemove.Enabled = False
            Me.btnOutput.Enabled = False

            Do
                If BackgroundWorker1.CancellationPending Then 'check if a cancellation request was made

                End If
                ffmpegOutput = sr.ReadLine
                Me.txtProgress.Text = ffmpegOutput

            Loop Until proc.HasExited And ffmpegOutput = Nothing Or ffmpegOutput = ""

            i = i + 1
        End While

        MsgBox("Finished Converting")
        proc.Close()
        btnConvert.Enabled = True
        btnAdd.Enabled = True
        btnRemove.Enabled = True
        btnOutput.Enabled = True
        Return 0
    End Function
End Class

Does anyone know how i could solve the problem?


Thanks

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by Unhnd_Exception
0
'Create a couple of delegates
    Private Delegate Sub ListViewItemDelegate(ByVal listView As ListView, ByVal itemIndex As Integer)
    Private Delegate Function ListViewDelegate(ByVal listView As ListView)

    'Create a method to set the selected item
    Private Sub SetSelectedListViewItem(ByVal Listview As ListView, ByVal itemIndex As Integer)
        ListView.Items(itemIndex).Selected = True
        ListView.Select()
    End Sub

    'create method to get count
    Private Function GetListViewCount(ByVal listView As ListView) As Integer
        Return Listview.Items.Count
    End Function

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        'start an operation on another thread
        BackgroundWorker1.RunWorkerAsync()

    End Sub

    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        'Create an instance of the delegates
        Dim ListViewCountDelegate As New ListViewDelegate(AddressOf GetListViewCount)
        Dim ListViewSetItemDelegate As New ListViewItemDelegate(AddressOf SetSelectedListViewItem)

        'Use the listview's invoke method to run the methods on the
        'listview's thread
        For i = 0 To ListView1.Invoke(ListViewCountDelegate, New Object() {ListView1})
            ListView1.Invoke(ListViewSetItemDelegate, New Object() {ListView1, i})
            System.Threading.Thread.Sleep(500)
        Next

    End Sub
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.