Reputation: 125
I've a class with all my methods implemented , doing its job , etc. Then i have my Form1 - where i have a FileSystemWatcher component and some buttons\checkboxes instances.
I've been reading about BackgroundWorker , ProgressBar , but i can't figure out who should i implement in order to show the progress.
Since "everything happens" inside the .cs file (my class), is there an way to display its output ? And how is the FileSystemWatcher going to interact with it (everything happens after i call the watch method - before that nothing is done).
example: On my class, i've a function to Read Files , then another function for converting those files to XML. I would like to show the progress for each file being readed, then each file being converted. I got it done when i had a Console Application (found an method that did its job) but i can't understand how to implement it on a WinForm application.
If everything was inside the Form1.cs code sure it would be easier. I tried to make an "sample" because my original code is too big.
Code example:
public class Foo
{
//foo vars and methods...
}
And then, the form method
public partial class Form1 : Form
{
private Foo prg;
public Form1()
{
InitializeComponent();
prg = new Foo();
prg.LoadConfig();
FillTextBox();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
//Do some checkbox verifications....
//after verification is done calls the Watcher (ProgramProcessing)
prg.ProgramProcessing(textBox1.Text);
}
What i want is to show a progress bar based on this watcher. Everything happens after he's triggered.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// do some long-winded process here
// this is executed in a separate thread
int maxOps = 1000000;
for (int i = 0; i < maxOps; i++)
{
rtbText.AppendText(i.ToString() + "\r\n");
// report progress as a percentage complete
bgWorker.ReportProgress(100 * i / maxOps);
}
}
private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// update the progress bar
pbProgress.Value = e.ProgressPercentage;
}
private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// return to "normal" mode of operation
this.Cursor = Cursors.Default;
//btnGo.Enabled = true;
}
Upvotes: 0
Views: 1060
Reputation: 82
If you want to use the latest .NET libraries, you can use IProgress interface and basically just call IProgress.Report(). This interface will save you the lines of code to implement the necessary event handlers using BackgroundWorker.
https://msdn.microsoft.com/en-us/library/hh138298(v=vs.110).aspx
Upvotes: 1