上传图片时显示进度条(Windows窗体C#)
本文关键字:Windows 窗体 显示 | 更新日期: 2023-09-27 18:25:51
我遇到了一种情况。我有一个windows形式的图片框,我允许用户使用openfileupload控件浏览图片,然后我将所选图片设置到图片框中。这是我的代码:
namespace Employee_Card_Manager
{
public partial class Form1 : Form
{
string Chosen_File = "";
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
selectpic.Title = "Browse Employee Picture!";
selectpic.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
selectpic.FileName = "";
selectpic.Filter = "JPEG Images|*.jpg|GIF Images|*.gif|BITMAPS|*.bmp";
if (selectpic.ShowDialog() != DialogResult.Cancel)
{
progressBar1.Enabled = true;
Chosen_File = selectpic.FileName;
pictureBox1.Image = Image.FromFile(Chosen_File);
progressBar1.Enabled = false;
}
}
}
}
它运行得很好!我需要对这个代码添加一些修改,这样当用户浏览图片并按下"打开"按钮时,我的应用程序会向他显示一个进度条,显示该图片正在同时上传。。。我发现以下代码显示进度条:
namespace ProgressBarSampleCSharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void CreateButton_Click(object sender, EventArgs e)
{
ProgressBar pBar = new ProgressBar();
pBar.Location = new System.Drawing.Point(20, 20);
pBar.Name = "progressBar1";
pBar.Width = 200;
pBar.Height = 30;
//pBar.Dock = DockStyle.Bottom;
pBar.Minimum = 0;
pBar.Maximum = 100;
pBar.Value = 70;
Controls.Add(pBar);
}
}
}
但我不知道如何将这些代码放入我的课堂,以便在上传图片的同时显示进度条!有什么想法吗??
我有一个旧代码可以用来回答您的问题
为了清楚起见,我让ProgressBar控件离开了InitializeComponent
然而,我认为当您运行此代码时,您将完全删除进度条。
namespace Employee_Card_Manager
{
public partial class Form1 : Form
{
ProgressBar pBar = new ProgressBar();
string Chosen_File = "";
public Form1()
{
InitializeComponent();
CreateProgressBar();
}
private void CreateProgressBar()
{
pBar.Location = new System.Drawing.Point(20, 20);
pBar.Name = "progressBar1";
pBar.Width = 200;
pBar.Height = 30;
pBar.BackColor = Color.Transparent;
pBar.Minimum = 0;
pBar.Maximum = 100;
pBar.Value = 0;
Controls.Add(pBar);
}
private void button1_Click(object sender, EventArgs e)
{
selectpic.Title = "Browse Employee Picture!";
selectpic.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
selectpic.FileName = "";
selectpic.Filter = "JPEG Images|*.jpg|GIF Images|*.gif|BITMAPS|*.bmp";
if (selectpic.ShowDialog() != DialogResult.Cancel)
{
Chosen_File = selectpic.FileName;
pictureBox1.LoadCompleted += new AsyncCompletedEventHandler(pictureBox1_LoadCompleted);
pictureBox1.LoadProgressChanged += new ProgressChangedEventHandler(pictureBox1_LoadProgressChanged);
pictureBox1.WaitOnLoad = false;
pictureBox1.LoadAsynch(Chosen_file);
}
}
private void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e)
{
pBar.Value = 0;
}
private void pictureBox1_LoadProgressChanged(object sender, ProgressChangedEventArgs e)
{
pBar.Value = e.ProgressPercentage;
}
}
}
如果"上传"确实需要很长时间,则可以使用FileSystemWatcher的更改事件。每次启动它时,您都会将进度条增加到已知文件总大小的一小部分。