搜索按钮上的ProgressBar [英] ProgressBar on search button

查看:53
本文介绍了搜索按钮上的ProgressBar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下C#代码显示进度条:

I have this c# code to show a progressbar:

{
    public partial class FormPesquisaFotos : Form
    {
        public FormPesquisaFotos()
        {
            InitializeComponent();
        }

        private void FormPesquisaFotos_Load(object sender, EventArgs e)
        {
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Mostra a barra de progresso da pesquisa
            while (progressBar1.Value < 100)
            progressBar1.Value += 1;
            {
                //Criar um objeto (instância, cópia) da classe FormResultadosFotos
                FormResultadosFotos NovoForm = new FormResultadosFotos();
                NovoForm.Show();
            }
        }
    }
}

它仅在搜索结束时加载(单击按钮后).如何在搜索开始时运行进度条?

It only loads at the end of the search (after button click). How can I have progressbar running at the beginning of the search?

这是在新表格上显示结果的代码.进度栏停止在95%,几秒钟后显示结果.

Here is the code to show the results on a new form. Progressbar stops at 95% and after a few seconds it shows the results.

{
    public partial class FormResultadosFotos : Form
    {
        public FormResultadosFotos()
        {
            InitializeComponent();
        }
        private void FormFotos_Load(object sender, EventArgs e)
        {
            // se pretendermos pesquisar em várias pastas
            List<string> diretorios = new List<string>()
            {@"\\Server\folder01\folder02"};

            // se pretendermos pesquisar as várias extensões
            List<string> extensoes = new List<string>()
    {".jpg",".bmp",".png",".tiff",".gif"};

            DataTable table = new DataTable();
            table.Columns.Add("Nome e formato do ficheiro (duplo clique para visualizar a imagem)");
            table.Columns.Add("Caminho ( pode ser copiado Ctrl+C )");
            foreach (string diretorio in diretorios)
            {
                var ficheiros = Directory.EnumerateFiles(diretorio, "*", SearchOption.AllDirectories).
                    Where(r => extensoes.Contains(Path.GetExtension(r.ToLower())));
                foreach (var ficheiro in ficheiros)
                {
                    DataRow row = table.NewRow();
                    row[0] = Path.GetFileName(ficheiro);
                    row[1] = ficheiro;
                    table.Rows.Add(row);
                }
            }
            dataGridView1.DataSource = table;
            dataGridView1.Columns[1].Visible = true;
        }
        private void dataGridView1_DoubleClick(object sender, EventArgs e)
        {
            FormPictureBox myForm = new FormPictureBox();
            string imageName = dataGridView1.CurrentRow.Cells[1].Value.ToString();
            Image img;
            img = Image.FromFile(imageName);
            myForm.pictureBox1.Image = img;
            myForm.ShowDialog();
        }
    }
}

谢谢.

推荐答案

您必须在新线程而不是主线程上拥有它.

You must have it on a new thread and not on the main thread.

这是一个小例子:

private void buttonWorkerTest_Click(object sender, RoutedEventArgs e)
{
    this.progressBarWorkerTest.Value = 0;
    BackgroundWorker worker = new BackgroundWorker();
    // Event for the method that will run on the background
    worker.DoWork += this.Worker_DoWork;
    // Event that will run after the BackgroundWorker finnish
    worker.RunWorkerCompleted += this.Worker_RunWorkerCompleted;
    worker.RunWorkerAsync();


}

private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
    for (int i = 1; i <= 100; i++)
    {
        Dispatcher.Invoke(new Action(() =>
        {
            this.progressBarWorkerTest.Value = i;
        }));
        Thread.Sleep(100);
    }
}

private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // You can put the code here to open the new form and such
}

Dispacher.Invoke是因为它在WPF上,对于WinForm只需将其更改为this.Invoke

The Dispacher.Invoke is because its on WPF, for WinForm just change it to this.Invoke

这个例子是,当单击按钮BackgroundWorker时,它将启动,将for设置为1到100,它将休眠100毫秒并更新进度条.

This example, is when the button is clicked the BackgroundWorker it will start, there is a for to go from 1 to 100 and it will sleep 100 miliseconds and will update the progressbar.

希望这会有所帮助

编辑

现在在示例中包括了在BackgroundWorker完成时运行的事件,以防万一是否需要

Did include now on the example the event to run when the BackgroundWorker finnish, just in case if there is the need for it

我的建议是,在后台搜索照片时,将它们全部插入到DataTable中,因为您已经准备好搜索它们,并且也可以在此处完成工作,然后只需在FormResultadosFotos上构造一个构造函数,即可接收该构造函数数据表.

My advice is when searching for the photos on the background insert them into a DataTable all rdy, since your all ready searching for them and the work can be done here also, then just make a constructor on the FormResultadosFotos that will receive that DataTable.

根据我的理解,主要目标是以FormPesquisaFotos形式搜索它们(这就是为什么我们在那里有背景工作人员进行搜索并更新ProgressBar的原因),并以新的形式AKA FormResultadosFotos显示它们. >

From what I did understood the main goal to was to search them on the form FormPesquisaFotos (thats why we have the background worker there, to search for them and update the ProgressBar) and show them on the new form AKA FormResultadosFotos

// Lets create a DataTable variable to be access on the Worker_DoWork and then on the Worker_RunWorkerCompleted
private DataTable tableOfPhotos;

private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
    // Search for the photos here and then add them to the DataTable
    this.tableOfPhotos = new DataTable();
    tableOfPhotos.Columns.Add("Nome e formato do ficheiro (duplo clique para visualizar a imagem)");
    tableOfPhotos.Columns.Add("Caminho ( pode ser copiado Ctrl+C )");
    foreach (string diretorio in diretorios)
    {
        // se pretendermos pesquisar em várias pastas
        List<string> diretorios = new List<string>()
        {@"\\Server\folder01\folder02"};

        // se pretendermos pesquisar as várias extensões
        List<string> extensoes = new List<string>()
        {"*.jpg","*.bmp","*.png","*.tiff","*.gif"};

        var ficheiros = Directory.EnumerateFiles(diretorio, "*", SearchOption.AllDirectories).
            Where(r => extensoes.Contains(Path.GetExtension(r.ToLower())));
        foreach (var ficheiro in ficheiros)
        {
            DataRow row = tableOfPhotos.NewRow();
            row[0] = Path.GetFileName(ficheiro);
            row[1] = ficheiro;
            tableOfPhotos.Rows.Add(row);
        }
    }
}

private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // You can put the code here to open the new form and such
    FormResultadosFotos NovoForm = new FormResultadosFotos(this.tableOfPhotos);
    NovoForm.Show();
}


// Constructor that will receive the DataTable and put it into the dataGridView1, it should be added on the Form FormResultadosFotos
Public FormResultadosFotos(DataTable table)
{
    InitializeComponent();
    // In here we will tell the where is the source for the dataGridView1
    this.dataGridView1.DataSource = table;
}

在这里,您还可以通过在行this.dataGridView1.DataSource = table;上放置一个断点来查看表的内容,如果表为空,则表中没有任何内容(也许目录中没有照片?无法访问)可以吗?不用工作,也不需要任何IDE,只需根据自己的想法进行操作即可,但是如果需要,您还可以将文件保存在模拟代码中:

In here you could all also to see what the table bring's by puting a breakpoint on the line this.dataGridView1.DataSource = table;, if the table is empty there was nothing introduced into the table (maybe no photos on the directory ? Can't access to it? Not at work and don't have any IDE with me, just basing my anwser from what I have in my head, but you could also get the files on a simular code if needed:

List<string> tempList = new List<string>;
foreach (string entryExt in extensoes)
{
    foreach (string entryDir in diretorios)
    {
        //  SearchOption.AllDirectories search the directory and sub directorys if necessary
        // SearchOption.TopDirectoryOnly search only the directory
        tempList.AddRange(Directory.GetFiles(entryDir, entryExt, SearchOption.AllDirectories));
    }
}

// Here would run all the files that it has found and add them into the DataTable
foreach (string entry in tempList)
{
    DataRow row = tableOfPhotos.NewRow();
    row[0] = Path.GetFileName(entry);
    row[1] = entry;
    tableOfPhotos.Rows.Add(row);
}

更改代码

List<string> extensoes = new List<string>(){".jpg",".bmp",".png",".tiff",".gif"};

List<string> extensoes = new List<string>(){"*.jpg","*.bmp","*.png","*.tiff","*.gif"};

您需要在扩展名之前加*(例如.png)来搜索该扩展名的文件

You need the * before the extension (.png as example) to search files for that extension

这篇关于搜索按钮上的ProgressBar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆