I have a situation here. I have a picture box in windows form and i let user to browse a picture by using openfileupload control and after that i set selected picture into picture box. Here is my code:
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;
}
}
}
}
It is working perfectly! I need to add some modification to this code so that when user browse a picture and presses Open button my application will show him a progress bar that this picture is being uploaded in mean time...
I have found the following code to show a progress bar:
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);
}
}
}
But i have no idea how to fit this code into my class so that it will show progress bar in the mean time when picture is being uploaded!
any ideas??
I have an old code adapted to answer your question.
I let the ProgressBar control out of the InitializeComponent just for clarity.
However, I think that when you run this code, you'll remove the progress bar completely.
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;
}
}
}
If it truly is taking a long time to 'upload' you could use the FileSystemWatcher's changed event. Every time it is fired you increment the progressbar some fraction of the total known file size.
Related
I am using Visual Studio .Net Framework to create a slideshow that operates on its own after clicking the "play" button. My current issue is that I do not know how to go about making the application go to the next file in the document after the video has ended. At the moment I have it setup for the user to select a time period for how long they want each image displayed, but I would rather have this feature automated.
This is my current code :
{
public partial class TVDisplay : Form
{
// Time f3 = new Time();
public TVDisplay()
{
//f3.Show();
InitializeComponent();
//both listview and listbox clear at initilize//
listBox1.Items.Clear();
listView1.Items.Clear();
//xml file from first application is read for department information, and that path and department are placed in textbox3 to be read by the listbox//
var xd = new XmlDocument();
string pathz = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filepath = pathz + #"\Assigned_Television.xml";
xd.Load(filepath);
// var list = xd.GetElementsByTagName("Television");
textBox3.Text = xd.GetElementsByTagName("Path")[0].InnerText;
}
protected override bool ProcessDialogKey(Keys keyData)
{
//when esacpe is pressed, the display screen is windowed instead of fullscreen//
if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
{
FormBorderStyle = FormBorderStyle.Sizable;
WindowState = FormWindowState.Normal;
return true;
}
return base.ProcessDialogKey(keyData);
}
//Page load//
private void Form1_Load(object sender, EventArgs e)
{
axWindowsMediaPlayer1.stretchToFit = true;
axWindowsMediaPlayer1.uiMode = "none"; //disables the play, pause, etc. buttons at the bottom of the windows media player//
listView1.Items.Clear(); //clears listview items//
Repopulate(); //calls repopulate function//
refreshtimer.Interval = 5 * 60 * 1000;
//timer for when images need to be displayed//
Timer tmr = new Timer();
int result = int.Parse(textBox2.Text);
tmr.Interval = result * 60 * 1001;
tmr.Tick += new EventHandler(timer1_Tick);
tmr.Start();
}
private void Repopulate()
{
foreach (var d in System.IO.Directory.GetFiles(textBox3.Text))
{
var dirName = new DirectoryInfo(d).Name;
listView1.Items.Add(dirName);
}
foreach (ListViewItem item in listView1.Items)
{
item.Selected = true;
listBox1.Items.Add(item.Text);
}
}
//hidden button that acts as a "play" button, taking url from textbox 1, playing the video, and looping it until it is time for the next image//
private void button1_Click(object sender, EventArgs e)
{
// MessageBox.Show(textBox4.Text);
axWindowsMediaPlayer1.URL = textBox4.Text;
axWindowsMediaPlayer1.Ctlcontrols.play();
axWindowsMediaPlayer1.settings.setMode("loop", true);
}
// timer that clicks button one//
private void timer1_Tick(object sender, EventArgs e)
{
button1.PerformClick();
}
private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
}
//when the tvdisplay is shown, start button is clicked and button 1 (play button) is clicked//
private void TVDisplay_Shown(object sender, EventArgs e)
{
startbutton.PerformClick();
button1.PerformClick();
}
//hidden behind windows media player//
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Timer tmr = new Timer();
int result = int.Parse(textBox2.Text);
tmr.Interval = result * 60 * 1000;
//int result = int.Parse(textBox3.Text);
// tmr.Interval = 1 * 60 * 1000;
//tmr.Interval = 180000;
tmr.Tick += new EventHandler(timer2_Tick);
tmr.Start();
//textBox2.Clear();
var path = textBox3.Text;
textBox4.Text = path + listBox1.SelectedItem.ToString();
}
private void refreshtimer_Tick(object sender, EventArgs e)
{
listBox1.BeginUpdate();
int x = listBox1.SelectedIndex;
listBox1.Items.Clear();
listView1.Items.Clear();
Repopulate();
//selects the first index once files are repopulated//
listBox1.SelectedIndex = x;
listBox1.EndUpdate();
}
//hidden behind windows media display//
private void startbutton_Click(object sender, EventArgs e)
{
startbutton.Enabled = false;
timer3.Interval = 10000; //time in milliseconds
timer3.Tick += timer3_Tick;
timer3.Start();
//startbutton.Enabled = false;
if(listBox1.Items != null)
{
MessageBox.Show("There is no content entered for display.", "Error");
Application.Exit();
}
else {
listBox1.SelectedIndex = (listBox1.SelectedIndex + 1) % listBox1.Items.Count;
}
}
private void timer2_Tick(object sender, EventArgs e)
{
startbutton.PerformClick();
}
private void timer3_Tick(object sender, EventArgs e)
{
startbutton.Enabled = true;
timer3.Stop();
}
}
}
Image/Video is displayed by Windows Media Player.
I have two forms, form1 and credentials. I want the data in my textbox (can be filled by user) to be transferred to the data grid view in form1.
Also, in form1, I want the data in my labels to be also transferred into the data grid view, which is also in form1. The labels I want to be transferred are: score, timer, level
I have tried and research for multiple solutions, yet none can really solve my problem. however, I tried to combine the solutions from websites and here is what i can do that kind of make sense to me. following are the codes for form1 and credentials.
form1 source code:
public partial class Form1 : Form
{
Snake mySnake;
Board mainBoard;
Rewards apples;
string mode;
Timer clock;
int duration; //How long the game has been running
int speed = 500; //500ms
int score;
int highscore;
int level;
public Form1()
{
InitializeComponent();
//button2.Text = Char.ConvertFromUtf32(0x2197);
//You don't have to worry about the auto-size
this.AutoSize = true; //The size of the Form will autoadjust.
boardPanel.AutoSize = true; //The size of the panel grouping all the squares will auto-adjust
//Set up the main board
mainBoard = new Board(this);
//Set up the game timer at the given speed
clock = new Timer();
clock.Interval = speed; //Set the clock to tick every 500ms
clock.Tick += new EventHandler(refresh); //Call the refresh method at every tick to redraw the board and snake.
duration = 0;
score = 0;
highscore = 0;
level = 1;
modeLBL.Text = mode;
gotoNextLevel(level);
scoresDGV.ColumnCount = 4;
scoresDGV.Columns[0].HeaderText = "Name";
scoresDGV.Columns[1].HeaderText = "Level";
scoresDGV.Columns[2].HeaderText = "Score";
scoresDGV.Columns[3].HeaderText = "Timer";
scoresDGV.AllowUserToAddRows = false;
scoresDGV.AllowUserToDeleteRows = false;
scoresDGV.MultiSelect = false;
scoresDGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
scoresDGV.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}
private void refresh(Object myObject, EventArgs myEventArgs)
{
//increment the duration by amount of time that has passed
//this method is called every speed millisecond
duration += speed;
timerLBL.Text = Convert.ToString(duration / 1000); //Show time passed
//Check if snke is biting itself. If so, call GameOver.
if (mySnake.checkEatItself() == true)
{
GameOver();
}
else if (apples.checkIFSnakeHeadEatApple( mySnake.getHeadPosition()) == true)
{
score += apples.eatAppleAtPostion(mySnake.getHeadPosition());
scoreLBL.Text = Convert.ToString(score);
if (apples.noMoreApples() == true)
{
clock.Stop();
level++;
levelLBL.Text = Convert.ToString(level);
gotoNextLevel(level);
MessageBox.Show("Press the start button to go to Level " + level, "Congrats");
}
else
{
//Length the snake and continue with the Game
mySnake.extendBody();
}
}
if (score > highscore)
{
highscoreLBL.Text = Convert.ToString(highscore);
}
}
private void startBTN_Click(object sender, EventArgs e)
{
clock.Start();
}
private void pauseBTN_Click(object sender, EventArgs e)
{
clock.Stop();
}
private void restartBTN_Click(object sender, EventArgs e) //snapBTN
{
duration = 0;
mySnake.draw();
}
private void backBTN_Click(object sender, EventArgs e)
{
// hides the form from the user. in this case, the program hides the HowToPlay form
this.Hide();
MainMenu mM = new MainMenu();
mM.ShowDialog();
this.Close();
}
private void GameOver()
{
clock.Stop();
MessageBox.Show("Your time taken is " + duration/1000 + " seconds. Bye Bye", "Game Over");
this.Close();
addCurrentScoresToDatabase();
//updateScoreBoard();
}
private void modeLBL_Click(object sender, EventArgs e)
{
}
private void addCurrentScoresToDatabase()
{
Credentials c = new Credentials();
c.ShowDialog();
}
}
credentials source code:
public partial class Credentials : Form
{
public static string SetValueForName = "";
public Credentials()
{
InitializeComponent();
}
private void saveBTN_Click(object sender, EventArgs e)
{
SetValueForName = enternameTB.Text;
Form1 frm1 = new Form1();
frm1.Show();
}
private void cancelBTN_Click(object sender, EventArgs e)
{
}
}
Because part of your code is made in the designer (and not shown here in your post) it is difficult to understand how it works. I assume you have a simple dialog form which is shown in your form1
Credentials is shown modal. So if you have some properties in your credentials dialog, you may data transfer via the properties.
private void addCurrentScoresToDatabase()
{
Credentials c = new Credentials();
// initialize c here
c.ShowDialog();
// read data from c here
}
If you want get data from the credential dialog while it is shown, you should use events.
https://learn.microsoft.com/en-us/dotnet/standard/events/
If you want to transfer score, timer, level to datagridview and transfer Name from credentials to datagridview, you can refer to the following code:
Code in Form1:
int index;
public void AddScore_Click(object sender, EventArgs e)
{
index = scoresDGV.Rows.Add();
scoresDGV.Rows[index].Cells[1].Value = label1.Text;
scoresDGV.Rows[index].Cells[2].Value = label2.Text;
scoresDGV.Rows[index].Cells[3].Value = label3.Text;
Credentials c = new Credentials();
c.FormClosed += c_FormClosed;
c.Show();
}
void c_FormClosed(object sender, FormClosedEventArgs e)
{
scoresDGV.Rows[index].Cells[0].Value = Credentials.SetValueForName;
}
Code in Credentials:
public partial class Credentials : Form
{
public static string SetValueForName = "";
public Credentials()
{
InitializeComponent();
}
private void saveBTN_Click(object sender, EventArgs e)
{
SetValueForName = enternameTB.Text;
this.Close();
}
}
Here is the test result:
I am working on a simple mediaplayer application. It works great but I want to add some extra features. I have added a trackbar control.How can i set trackbar length the same as the music's length ?
Like if the song is halfways the trackbars halfways.This is what I have so far
string[] files, indexed_files;
private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;
if (ofd.ShowDialog() == DialogResult.OK) {
files = ofd.SafeFileNames;
indexed_files = ofd.FileNames;
for (int i = 0; i < files.Length; i++)
{
listBox1.Items.Add(files[i]);
}
}
button4.Enabled = true;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = indexed_files[listBox1.SelectedIndex];
progressBar1.Maximum =(int) axWindowsMediaPlayer1.currentMedia.duration;
axWindowsMediaPlayer1.PlayStateChange += axWindowsMediaPlayer1_PlayStateChange;
}
void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
trackBar1.Value = (int)axWindowsMediaPlayer1.Ctlcontrols.currentPosition;
}
int index = 0;
private void button4_Click(object sender, EventArgs e)
{
if (listBox1.Items.Count != 0) {
axWindowsMediaPlayer1.URL = indexed_files[index];
trackBar1.Maximum = (int)axWindowsMediaPlayer1.currentMedia.duration;
index++;
index = (index % listBox1.Items.Count);
}
}
This will bring you the desired outcome.In my example i just placed the url in the form load for demonstration purposes.The openstatechanged event its to set the trackbar maximum since you need to wait for the player to load the file,after that the code its pretty self-explanatory:
public partial class Form1 : Form
{
Timer t;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = "YourUrlHere";
t = new Timer();
t.Interval = 1000;
t.Tick += new EventHandler(t_Tick);
}
void t_Tick(object sender, EventArgs e)
{
trackBar1.Value = (int)this.axWindowsMediaPlayer1.Ctlcontrols.currentPosition;
}
private void axWindowsMediaPlayer1_OpenStateChange(object sender, AxWMPLib._WMPOCXEvents_OpenStateChangeEvent e)
{
if (axWindowsMediaPlayer1.openState == WMPLib.WMPOpenState.wmposMediaOpen)
{
trackBar1.Maximum = (int)axWindowsMediaPlayer1.currentMedia.duration;
t.Start();
}
}
}
Yes its a timer:),and probably it is best to set it bellow 1000 for reasons of delay.
So you should now add a timer and insert the following code in timer Tick event handler:
trackbar.Value = this.axWindowsMediaPlayer1.ctlControls.CurrentPosition;
I don't have a thorough knowledge about controlling threads in c#. I want to create a progress bar while running a method.
I have two forms:
Form1 is the form which show up as you run the app. It has a button called btnScrape. When it is clicked the method should be called, the form with the progress bar should show up. Form1 should be disabled to the user until the progress bar is completed.
ProgressBarForm - this has the progress bar and a label.
The code is as follows.
//In Form1.cs I have a button.
private void btnScrape_Click(object sender, EventArgs e)
{
//gather data for folloeing parameters from the form.
Controller cntrlr = new Controller(urlFilePath, destinationPath, destinationfilename,cmbDepth.SelectedIndex);
cntrlr.Vmain(); // this is the method in controller class. while this is running i want show the progress bar.
}
// in Contrller class
class Controller{
List<string> urlList = null;
URLFileReader urlFileReader = null;
HTTPWorker httpWorker = null;
SourceReader srcreader = null;
ReportWriter reportWriter = null;
string urlFilePath, destinationPath, destinationFileName;
int depth;
public Controller(string urlFilePath,string destinationPath,string destinationFileName,int depth)
{
this.urlFilePath = urlFilePath;
this.destinationPath = destinationPath;
this.destinationFileName = destinationFileName;
this.urlList = new List<string>();
this.urlFileReader = new URLFileReader();
this.httpWorker = new HTTPWorker(this.destinationPath);
this.reportWriter = new ReportWriter(this.destinationPath,this.destinationFileName);
this.srcreader = new SourceReader(this.reportWriter);
this.depth = depth;
}
//this is the method
public void Vmain(){
this.urlFileReader.ReadURL(urlFilePath);
this.urlList = urlFileReader.geturlList();
string pageSrc;
foreach (string requestUrl in urlList)
{
//do sruff for requestUrl
//the progressbar should move as the urlList iterate.
//additionally i want the label on the top of progress bar to display the current "requestUrl"
//as the urlList is over i want quit from the progressbar window and come back to Form1. Till the progrss bar is completed Form1 should be disabled for the user.
}
}
}
Please explain what is happening there and give a working code if you can. Thank you in advance. There were not any perfect answer that worked for me, even though I spent two days for this. I tried with BackgroundWorkerand threads. But no solution found. :(
In the main form you could use this code:
private Progressfrm _loadForm;
private void ShowProgress()
{
ToggleForm();
_loadForm = new Progressfrm();
_loadForm.ShowDialog();
var tcheck = new Thread(CheckLoadedProgress);
tcheck.Start();
//do stuff here
}
private void CheckLoadedProgress()
{
while (_loadForm.IsAccessible) { }
ToggleForm();
}
private void ToggleForm()
{
Invoke(new Action(() => Enabled = !Enabled));
}
private void btnScrape_Click(object sender, EventArgs e)
{
var tform = new Thread(ShowProgress);
tform.Start();
}
Then the Progress-Form will appear until it is filled:
private ProgressBar _progressBar;
private void Progressfrm_Shown(object sender, EventArgs e)
{
_progressBar = new ProgressBar { Size = new Size(100, 20), Location = new Point(10, 10) };
Controls.Add(_progressBar);
_progressBar.Show();
Refresh();
LoadProgress();
}
private void LoadProgress()
{
while (_progressBar.Value < 100)
{
_progressBar.Value++;
Thread.Sleep(100);
}
Close();
}
On this Form you have to add the Event Shown and add the code like in my example. Hope this helps.
Use BackgroundWorker class to output progressBar and statusLabel changes:
BackgroundWorker bgw;
private void btnScrape_Click(object sender, EventArgs e)
{
bgw = new BackgroundWorker();
bgw.WorkerReportsProgress = true;
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
bgw.RunWorkerAsync();
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
Thread.Sleep(100);
bgw.ReportProgress(i);
}
}
private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
This is only an example how to update controls in an asynchron way.
my main problem is when i add dynamically a progressbar on flowLayoutPanel1 for each request then how can i increase right progressbar value frombackgroundWorker1_ProgressChanged event
when user click on start button then i will call RunWorkerAsync function of background worker....it is fine. here i am writing a sample code and try to show my problem.
my form has one textbox, one button and one flowLayoutPanel1 with FlowDirection topdown.
when user enter any url in textbox and click on start button then i will start file download with BackGroundWorker and add one progress bar dynamically on flowLayoutPanel1. 10 file can be downloaded at a time. so when user enter ten url one after after one and click on submit button then ten file will be downloading in background.
my problem is how to increment 10 progress bar progress properly from backgroundWorker1_ProgressChanged event another issue is when any file download will complete then the progress bar for which it has been created will be removed from panel
here is my full code. please have a look and tell me what i need to do to achieve my task. if anyone see there is problem in my code for which a dead lock may appear then also please guide me how to avoid dead lock. here is my code
public partial class Form1 : Form
{
static int pbCounter = 1;
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
ProgressBar pb = new ProgressBar();
if (pbCounter <= 10)
{
pb.Width = txtUrl.Width;
flowLayoutPanel1.Controls.Add(pb);
pbCounter++;
System.ComponentModel.BackgroundWorker backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Get the BackgroundWorker that raised this event.
System.ComponentModel.BackgroundWorker worker = sender as System.ComponentModel.BackgroundWorker;
// Assign the result of the computation
// to the Result property of the DoWorkEventArgs
// object. This is will be available to the
// RunWorkerCompleted eventhandler.
//#e.Result = ComputeFibonacci((int)e.Argument, worker, e);
}
// This event handler deals with the results of the
// background operation.
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// First, handle the case where an exception was thrown.
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else if (e.Cancelled)
{
//# "Canceled";
}
else
{
pbCounter--;
// Finally, handle the case where the operation
// succeeded.
//#resultLabel.Text = e.Result.ToString();
}
}
// This event handler updates the progress bar.
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
}
MY UPDATED PART
public partial class Form1 : Form
{
static int pbCounter = 1;
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
ProgressBar pb = new ProgressBar();
if (pbCounter <= 10)
{
//pb.Step = 10;
pb.Minimum = 0;
//pb.Maximum = 100;
pb.Width = txtUrl.Width;
flowLayoutPanel1.Controls.Add(pb);
pbCounter++;
MyBackgroundWorker backgroundWorker1 = new MyBackgroundWorker();
backgroundWorker1.pbProgress = pb;
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
backgroundWorker1.RunWorkerAsync(txtUrl.Text);
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int input = int.Parse(e.Argument.ToString());
for (int i = 1; i <= input; i++)
{
Thread.Sleep(2000);
(sender as MyBackgroundWorker).ReportProgress(i * 10);
if ((sender as MyBackgroundWorker).CancellationPending)
{
e.Cancel = true;
return;
}
}
}
// This event handler deals with the results of the
// background operation.
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// First, handle the case where an exception was thrown.
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else if (e.Cancelled)
{
//# "Canceled";
}
else
{
ProgressBar pb = (sender as MyBackgroundWorker).pbProgress;
if (pb != null)
{
//pb.Value = 100;
//pb.Update();
while (pb.Value <= pb.Maximum)
{
//Thread.Sleep(1000);
flowLayoutPanel1.Controls.Remove(pb);
break;
}
}
// Finally, handle the case where the operation
// succeeded.
}
}
// This event handler updates the progress bar.
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
ProgressBar pb = (sender as MyBackgroundWorker).pbProgress;
pb.Refresh();
//if (e.ProgressPercentage < pb.Maximum)
// pb.Value = e.ProgressPercentage + 10;
pb.Value = e.ProgressPercentage ;
Application.DoEvents();
}
}
public class MyBackgroundWorker : System.ComponentModel.BackgroundWorker
{
public ProgressBar pbProgress = null;
public MyBackgroundWorker()
{
}
public MyBackgroundWorker(string name)
{
Name = name;
}
public string Name { get; set; }
}
This is one way of doing it -
Create your own class inherited from BackgroundWorker, Add a public variable of type ProgressBar.
Each time you add a BackgroundWorker and Progressbar dynamically, pass the progressbar object to your class.
Your derived Class -
public class MyBackgroundWorker : BackgroundWorker
{
public ProgressBar pbProgress = null;
public void BackgroundWorker()
{
}
}
Button Event Code -
private void btnStart_Click(object sender, EventArgs e)
{
ProgressBar pb = new ProgressBar();
if (pbCounter <= 10)
{
pb.Width = txtUrl.Width;
flowLayoutPanel1.Controls.Add(pb);
pbCounter++;
MyBackgroundWorker backgroundWorker1 = new MyBackgroundWorker();
backgroundWorker1.pbProgress = pb;
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
backgroundWorker1.RunWorkerAsync();
}
}
Progress Changed Event -
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
(sender as MyBackgroundWorker).pbProgress.Value = e.ProgressPercentage;
}
First declare a global dictionary and a GetInstance Method to access the form instance
public partial class Form1 : Form
{
Dictionary<String, ProgressBar> progressBars = new Dictionary<String, ProgressBar>();
static Form1 _form1 = null;
static int pbCounter = 1;
public Form1()
{
InitializeComponent();
_form1 = this;
}
public static Form1 GetInstance() {
return _form1;
}
Then with each url you get and you must be creating pb for each of them, just add them in this dictionary too
progressBars.Add("file1", pb1);
progressBars.Add("file2", pb2);
progressBars.Add("file3", pb3);
progressBars.Add("file4", pb4);
Create a function in form.cs in which you can pass the progressbar and then you can manually set the value of it.
public void ProgessReport(ProgressBar pb, int value)
{
if (pb.InvokeRequired)
{
pb.Invoke(new MethodInvoker(delegate { ProgessReport(pb, value); }));
} else
{
pb.Value = value;
}
}
now from where you are downloading the file you just have to call
Form1.GetInstance().ProgessReport(Form1.GetInstance().progressBars["file1"], 10);
Form1.GetInstance().ProgessReport(Form1.GetInstance().progressBars["file1"], 20);
Form1.GetInstance().ProgessReport(Form1.GetInstance().progressBars["file1"], 100);
and when your second file downloads then
Form1.GetInstance().ProgessReport(Form1.GetInstance().progressBars["file2"], 10);
Form1.GetInstance().ProgessReport(Form1.GetInstance().progressBars["file2"], 20);
Form1.GetInstance().ProgessReport(Form1.GetInstance().progressBars["file2"], 100);
like this ..