ProgressBar在搜索按钮上

我有这个c#代码来显示进度条:

{ 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(); } } } } 

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

以下是在新表单上显示结果的代码。 进度条停止在95%,几秒钟后显示结果。

 { public partial class FormResultadosFotos : Form { public FormResultadosFotos() { InitializeComponent(); } private void FormFotos_Load(object sender, EventArgs e) { // se pretendermos pesquisar em várias pastas List diretorios = new List() {@"\\Server\folder01\folder02"}; // se pretendermos pesquisar as várias extensões List extensoes = new List() {".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(); } } } 

谢谢。

您必须在新线程上而不是在主线程上。

这是一个小例子:

 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

这个例子,当单击按钮时它将启动BackgroundWorker,有一个for从1到100,它将睡眠100毫秒,并将更新进度条。

希望这会有所帮助

编辑

现在在示例中包含了BackgroundWorker芬兰语时运行的事件,以防万一需要它

编辑2:

我的建议是,当在背景上搜索照片时,将它们插入DataTable all rdy,因为您已经准备好搜索它们并且也可以在这里完成工作,然后在FormResultadosFotos上创建一个将接收该DataTable的构造函数。

从我所理解的主要目标是在FormPesquisaFotos表单上搜索它们(这就是为什么我们在那里有后台工作者,搜索它们并更新ProgressBar)并在新表格上显示它们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 diretorios = new List() {@"\\Server\folder01\folder02"}; // se pretendermos pesquisar as várias extensões List extensoes = new List() {"*.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;上放置一个断点来查看表带来了什么this.dataGridView1.DataSource = table; ,如果表是空的,表中没有任何内容(可能目录上没有照片?无法访问它?没有工作,没有任何IDE与我,只是基于我的anwser从我所拥有的我的头,但如果需要你也可以在simular代码上获取文件:

 List tempList = new List; 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); } 

编辑3:

改变您的代码

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

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

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

你在这里描述的是一个multithreading问题。 您的循环在UI有机会更新之前运行。

您应该查看https://stephenhaunts.com/2014/10/14/using-async-and-await-to-update-the-ui-thread/,了解有关如何更新用户界面的说明和示例在一个循环中。

问候