Call Form2 with Circular Progress Bar while another action is executed C#

Asked

Viewed 509 times

0

I have a question about a Windows Form call. In this application, through the button click event located in Form1, call a second Form, where in this form2 I present an animated Circular Progress Bar running until another method located in Form 1 called Carregargrid() is finalized.

At that time my application meets the following code:

Button Event located in Form 1: inserir a descrição da imagem aqui

public partial class frm_Painel_de_Producao : Form
{
 frm_Progress_Bar pb = frm_Progress_Bar();

    private async void btnAtualizaGrid_Click(object sender, EventArgs e)
    {

      pb.Show();

      //desabilita os botões enquanto a tarefa é executada.
      btnCancelar.Enabled = false;
      btnIncluir.Enabled = false;      
      btnAtualizaGrid.Enabled = false;

      // simply start and await the loading task
      await Task.Run(() => carregarGrid());
      pb.Close();

      // habilita os botões após  tarefa evento de loading.
      btnAtualizaGrid.Enabled = true;
      btnCancelar.Enabled = true;
      btnIncluir.Enabled = true;    

    }

 }

Form 2 code only Initialize:

public partial class frm_Progress_Bar : Form
{
    public frm_Progress_Bar()
    {
        InitializeComponent();

    }  
}

Form 2 Designer + Progress Bar:

inserir a descrição da imagem aqui

Property of Form 2: Back Color = Fuchsia Transparency Key = Fuchsia

Property of Circular Progress Bar:

inserir a descrição da imagem aqui

In this case in the properties already meets with Style: Mark Because Li somewhere that this property should be as Mark, "if I’m not mistaken to continue to give the effect of loading."

Form 1 Load Method:

public void carregarGrid()
    {

        timer.Interval = 1000;
        timer.Tick += meuRelogio;
        timer.Start();
        dgvProducao.AutoGenerateColumns = false;
        dgvProducao.DataSource = clsPPCP.painelProducao();
        MeuBD.AbreXML();
        if (MeuBD.RequerUsuario == "1")
        {
            txtOperador.Focus();
        }
        else
        {
            txtOperador.Hide();
            txtNomeOperador.Hide();
            label8.Hide();
            txtCartao.Focus();
        }
        colorirGrid();
        //MeuBDex.AbreXML();
        relogio();   
    }

With this information I now report the errors I found:

inserir a descrição da imagem aqui

This error is happening because in the click event I am putting the following code: await Task.Run(() => carregarGrid());

With this occurs the legendary error: Invalid threaded operation: 'control' accessed from a thread that is not the one in which it was created.

I tried to redo this application then using Thread and Delegates but also did not succeed for lack of experience with Threads.

And once again I redid this application trying to point out in the Form2 Load Event, call the Form1 method loadGrid. Respecting the Form 1 instance creation in Form2. But I also did not succeed.

So I’ve come humbly to ask you how can I resolve this application? Doubts:

1- How best to work with Circular Progress Bar?

2- Do I use Progressbar in another Form as in the example above? Or I can put Progress Bar in the same Form1.

3- It would also be possible in the Form 1 Load Event to be calling the Load method and once the method is finished, Progressbar with Form2 is terminated?

I already leave my thanks for all the help. Thank you!

  • Solved young ?

  • Good morning, thank you very much for the tips but not yet Rovann, I do not understand very well the example. I’m early in programming so I’ll even apologize if it’s not very clear to me.

  • Good morning, speak your question we try to help.

  • How can I enter a 2form or form 1 itself the plugin Circular Progress bar while I load the Grid by clicking the update grid button. this circular Progress bar will not load for example from 0 to 100% but will only run until the grid application is finished. I don’t know if I was too clear in my doubt?

  • yes, is implementing my example with backgroundworker ?

  • I am trying to implement it. backgroundWorker1 is a form 2 event?

  • don’t... forget form2... don’t have in my example... backgroundWorker1 is a control that you insert into Form1 by Toolbox

  • I changed my answer... look there

  • Thank you Rovann I’m understanding a little now, I’m with your reply and the macoratti website opened here talking about the backgroundworker.

  • As soon as you get it or have another question I put here, first I will understand about the backgroundworker and try to apply your answer in the application. Once again Thank you!

  • Okay, don’t forget to mark it as an answer if it helped you

  • Control.Checkforillegalcrossthreadcalls = false

Show 7 more comments

1 answer

2


There are several ways to make the progress bar, but I believe that when it comes to Windows Forms, the ideal is to use the BackgroundWorker that performs the work in the background, leaving the form thread free to show progress in the bar.

I made an example of how it works:

private void button1_Click(object sender, EventArgs e)
{
    if (!backgroundWorker1.IsBusy) //se o bw não estiver ocupado...
    {
        int arg = 100000;
        backgroundWorker1.RunWorkerAsync(arg); //você pode passar um argumento pro bw
    }
}


private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    //iniciou o processo em segundo plano
    int total = (int)e.Argument;
    int valor = 0;
    for (int i = 0; i <= total; i++)
    {
        valor += i;

        int p = i * 100 / total; //calcula percentual do progresso

        backgroundWorker1.ReportProgress(p); //informa o percentual do progresso
    }

    e.Result = valor;
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage; //exibe o percentual na barra
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    //evento quando o processo é finalizado
    if (e.Cancelled)
    {
        //processo foi cancelado
        //tem que definir o bw pra suportar cancelamento e verificar a flag e.Cancel dentro do processo...
    }
    else if (e.Error != null)
    {
        //deu erro e foi lançada exceção
    }
    else
    {
        int resultado = (int)e.Result;
        MessageBox.Show("Resultado: "+ resultado);
    }
}

The above example answers questions 1 and 2. A 3, just fire bw after you open the form. Close the other form with the progressiBar no longer need...

To insert the BackGroundWorker just drag it from Toolbar:

inserir a descrição da imagem aqui

And then place the events:

inserir a descrição da imagem aqui

  • Thanks for the help, I did not solve completely but with your reply I managed to open a north with these background work events.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.