搜索按钮上的进度条

2023-12-02

我有这个 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<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();
        }
    }
}

谢谢。


您必须将其放在新线程上,而不是主线程上。

这是一个小例子:

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
}

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

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

希望这会有所帮助

Edit

现在在示例中包含了当BackgroundWorker完成时要运行的事件,以防万一需要它

Edit 2:

我的建议是,在搜索背景上的照片时,将它们全部插入到 DataTable 中,因为您已经准备好搜索它们,并且工作也可以在这里完成,然后只需在 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<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,只是根据我所拥有的内容进行回答我的头脑,但如果需要,您也可以通过类似代码获取文件:

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

Edit 3:

更改您的代码

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

to

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

搜索按钮上的进度条 的相关文章

随机推荐

  • ' aria-label='腌制错误:无法腌制 '> 腌制错误:无法腌制

    我想知道这个错误可能意味着什么 PicklingError Can t pickle
  • 类似于 MySQL 中 Explode 工作的功能

    MySQL中有没有函数可以分解某列的数据然后检索它 就像如果列数据是 P 12 那么可以将数据分解在 上然后读取吗 这里有很多关于SPLITmysql 中的问题 http dev mysql com doc refman 5 0 en st
  • AWS Cognito - 我可以在自定义身份验证流程中使用迁移触发器吗

    我正在调查最近发布的认知用户池迁移触发器 要启用触发器 您需要将 InitiateAuthRequest 中的 AuthFlow 类型设置为 USER PASSWORD AUTH 请参见此处 https docs aws amazon co
  • 由于非对象字段错误而导致错误对齐或重叠

    我正在尝试创建以下结构 StructLayout LayoutKind Explicit Size 14 public struct Message FieldOffset 0 public ushort X FieldOffset 2 M
  • 如何在asp.net中读取excel文件

    我正在使用 Epplus 库来从 Excel 文件上传数据 我使用的代码非常适合具有标准形式的 Excel 文件 即 如果第一行是列 其余所有数据对应于列 但现在我是定期获取具有不同结构的 excel 文件 我无法阅读 excel文件如下图
  • g++ 如何使用给定的代码不报告错误?

    这是我的回答的延续为什么 elapsedtime 的输出为 1 我能够使用 g 4 7 3 成功编译和构建以下程序 include
  • (节点:3341)弃用警告:猫鼬:妥协

    我试图用我的自定义方法在猫鼬的顶部开发一个类 所以我用我自己的类扩展了猫鼬 但是当我调用创建一个新的汽车方法时 它可以工作 但是它的条带和错误 在这里我让你看看我想做什么 我收到此警告 node 3341 DeprecationWarnin
  • 将 String 转换为 Int 检查是否溢出

    当我尝试将一个很长的整数转换为Int 令我惊讶的是没有抛出错误 Prelude gt read 123456789012345678901234567890 Int 4362896299872285998 readMaybe from Te
  • Intel 处理器的虚拟操作处理

    诚然 我有一个有点愚蠢的问题 基本上 我想知道是否 英特尔处理器提供了一些特殊的机制来有效地 执行一系列虚拟指令 即 NOP 指令 例如 我可以想象那里 可能是某种识别 NOPS 并丢弃它们的预取机制 并尝试获取一些有用的指令 或者这些 N
  • Android - 删除 Google 地图片段 onPause 并重新添加 onResume

    我需要删除 Activity onPause 事件上的 Google 地图片段并将其添加回 onResume 事件 我怎样才能做到这一点
  • 如何使用对讲辅助功能 android 禁用视图中的“双击”消息?

    当视图有事件时 单击并启用对讲 我需要在视图中禁用音频 双击 我在 Android 开发中使用辅助功能 请问我该怎么做 如果您检查谷歌对讲源代码this线和here 字符串资源 双击 已被使用here and here 所以 你应该删除Ac
  • 椭圆的标准形式

    我得到椭圆作为拟合数据集的水平曲线 选择特定椭圆后 我想将其报告为中心点 半长轴和短轴长度以及旋转角度 换句话说 我想将我的椭圆方程转换为 使用mathematica Ax 2 By 2 Cx Dy Exy F 0 更标准的形式 xCos
  • IdentityServer4 AddSignerCredentials RSA 示例

    准备将 IdentityServer4 设置从开发版移至测试版 我需要从 AddDeveloperCredentials 迁移 AddSignerCredentials 部分 我可以生成私有和公共 RSASecurityKey 但我不清楚将
  • 非法参数:未定义、字符串

    注册用户时出现此错误 节点 13225 UnhandledPromiseRejectionWarning 错误 非法 参数 未定义 字符串 在 Object bcrypt hashSync home admin Desktop projec
  • Scala 编译 OptionBuilder 时出错

    我正在使用 Apache commons cli 1 2 进行命令行解析 我的代码中有以下内容 import org apache commons cli OptionBuilder OptionBuilder withLongOpt db
  • 为什么 ghci 找不到我尝试编译的 hs 文件?

    我是第一次学习 Haskell 我不明白为什么 ghci 找不到我正在尝试编译的文件 特别是因为我保存了文件 这是我的文件 import System IO trueAndFalse True False 现在这就是我在编译器中运行的内容
  • 防止双击按钮

    我一直遇到用户双击网络应用程序上的操作按钮的问题 这意味着重复的记录被添加到我的数据库中 有时用户会被收取两次费用 因为该操作运行了两次 在 ASP NET 中防止双击的最佳方法是什么 我发现您在面对未启用 JavaScript 的用户时对
  • 如何在 Pyqt5 setcentralWidget 中取回我的主窗口? [复制]

    这个问题在这里已经有答案了 如何取回我的主窗口 从我的主窗口 如果我按 打开左边的盒子 按钮或 打开右边的盒子 按钮 它起作用了 同时 如果我按下 Back 从左框按钮 什么也不会发生 如何获取主窗口 简单来说 我想知道如何设置布局和删除布
  • Room 为离线应用程序创建备份的最佳方法?

    所以我可以说正在使用非常复杂的数据库many to many数据库设计与foreign keys并连接表 它是Room数据库 我想为其创建备份系统 因为它是离线应用程序 我需要导出数据库并将其存储到谷歌驱动器的应用程序文件夹中 最近几天我读
  • 搜索按钮上的进度条

    我有这个 C 代码来显示进度条 public partial class FormPesquisaFotos Form public FormPesquisaFotos InitializeComponent private void Fo