Public Class FrmBarraProgressoGenerica
    Private pReportaProgresso As ReportaProgresso
    Private pAcaoPraExecutar As Action
    Public pMensagem As String

    Public Sub New()
        InitializeComponent()
    End Sub

    Public Sub New(reportaProgresso As ReportaProgresso, acaoPraExecutar As Action)
        Me.New()
        pAcaoPraExecutar = acaoPraExecutar
        pReportaProgresso = reportaProgresso

        AddHandler reportaProgresso.ProgressoReportado, AddressOf ReportaProgresso_ProgressoReportado
    End Sub

    Public Sub New(acaoPraExecutar As Action)
        Me.New()
        pAcaoPraExecutar = acaoPraExecutar
        pgProgresso.Style = ProgressBarStyle.Marquee
        pgProgresso.MarqueeAnimationSpeed = 0
        pgProgresso.MarqueeAnimationSpeed = 5
    End Sub


    Private Sub FrmBarraProgresso_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
        Try
            If IsNothing(pReportaProgresso) Then
                bgConsulta.RunWorkerAsync()
            Else
                pAcaoPraExecutar.Invoke()
            End If

        Finally

            Do While bgConsulta.IsBusy
                Application.DoEvents()
                Label2.Text = pMensagem
            Loop

            Me.Close()
        End Try
    End Sub

    Private Sub ReportaProgresso_ProgressoReportado(sender As Object, e As ReportaProgressoEventArgs)
        pgProgresso.Minimum = pReportaProgresso.ValorInicial
        pgProgresso.Maximum = pReportaProgresso.ValorFinal
        pgProgresso.Value = e.Progresso

        If Not String.IsNullOrWhiteSpace(e.Mensagem) Then
            Label2.Text = e.Mensagem
        End If

        Me.Refresh()
    End Sub

    Private Sub bgConsulta_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgConsulta.DoWork
        Try
            pAcaoPraExecutar.Invoke()
            If bgConsulta.CancellationPending Then
                e.Cancel = True
                Return
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Erros", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub bgConsulta_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgConsulta.RunWorkerCompleted
        If e.Cancelled Then
            pgProgresso.MarqueeAnimationSpeed = 0
            pgProgresso.Style = ProgressBarStyle.Blocks
            pgProgresso.Value = 0
        ElseIf Not IsNothing(e.Error) Then
            pgProgresso.MarqueeAnimationSpeed = 0
            pgProgresso.Style = ProgressBarStyle.Blocks
            pgProgresso.Value = 0
        Else
            pgProgresso.MarqueeAnimationSpeed = 0
            pgProgresso.Style = ProgressBarStyle.Blocks
            pgProgresso.Value = 0
        End If
    End Sub

End Class