I'm coding this app that pulls your battery % and shows it to the user periodically. I've made it work so far as a console app, but as I re-write it in Windows Forms it gives me some issues when using the labels to display the value.
Edit: I have included the changes Niranjan Kala pointed out as I was using more than one label for this, but it still doesn't work
Also, as he has requested, I have added more of the program layout so as to provide some context and maybe find the error
This is what it looks like:
public partial class Form1 : Form
{
public Form1()
{ InitializeComponent();
// Imagine all the visual stuff going here (icons and menus, etc.)
//I start the thread
batThing = new Thread(new ThreadStart(batThing));
batThing.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
Type power = typeof(PowerStatus);
PropertyInfo[] pi = power.GetProperties();
#region Cargador
//0 = PowerLineStatus --> Charger on or not?
object EdeCargador = pi[0].GetValue(SystemInformation.PowerStatus, null);
//turns charger state into int
int edc = Convert.ToInt32(EdeCargador);
int On = Convert.ToInt32(PowerLineStatus.Online);
On = 1;
int Off = Convert.ToInt32(PowerLineStatus.Offline);
Off = 0;
int Unk = Convert.ToInt32(PowerLineStatus.Unknown);
Unk = 255;
if (edc == On)
{
string CargadorConectado = "-Cargador Conectado-";
label2.Text = CargadorConectado;
string EdeBateria2 = "-Cargando-";
label4.Text = EdeBateria2;
}
else
{
string CargadorDesconectado = "-Cargador Desconectado-";
label2.Text = CargadorDesconectado;
#endregion
#region Cantidad de Bateria
//3 = BatteryLifePercent --> tells the % of bat available
object CantdeBat = pi[3].GetValue(SystemInformation.PowerStatus, null);
//string to float , then * 100 to get a %
float num = (Single.Parse(CantdeBat.ToString())) * 100;
// shows a % and says if battery is full or low
string EdeBateria = num.ToString() + "%";
if (num == 100)
{
EdeBateria = "-Batería Completa-";
label4.Text = EdeBateria;
}
else if (num <= 25)
{
EdeBateria = "-Batería Baja. Conecte el cargador-";
label4.Text = EdeBateria;
}
else if (num > 25 & num < 100)
{
//nada
}
if (num <= 0)
{
EdeBateria = "No tenes bateria gil";
label4.Text = EdeBateria;
}
}
#endregion
#region Tiempo Restante
//4 = BatteryLifeRemaining --> Indicates the remaining battery time
object TdeBat = pi[4].GetValue(SystemInformation.PowerStatus, null);
double tiempobat = (Double.Parse(TdeBat.ToString()));
if (tiempobat == -1)
{
string NoHayBat = "El equipo no está operando a través de una batería";
label5.Text = NoHayBat;
}
else if (tiempobat != -1)
{
//gets time in seconds and turns it into hours , min and secs
TimeSpan t = TimeSpan.FromSeconds(tiempobat);
string TiempoRestante = string.Format("El tiempo de uso restante es de: {0:D1} horas, {1:D2} minutos y {2:D2} segundos",
t.Hours,
t.Minutes,
t.Seconds
);
label5.Text = TiempoRestante ;
}
#endregion
} // fin de form1
Edit: I have found that there are certain issues when jumping from one method from another, for instance, the problem I originally had, which was with 'label 4' I came to find that was due to the logic in the charger state, so I added this:
string EdeBateria2 = "-Cargando-";
label4.Text = EdeBateria2;
After adding this when I have the charger connected it displays so nicely, but when I disconnect the charger entering the 'else' where I coded the conditionals for label 4 the problems begin.
The strings in both label 2 and label 5 change dinamically as I disconnect the charger out of the laptop PC with no problems whatsoever, the issue is with label 4 still. As I disconnect the charger it stops displaying the message I define as '-Cargando-' and it just shows its name 'label4'.
I'm stuck, any ideas?
I'm using C# in VS 2015.
If you want to display status then it should be like this. Create status of the battery and then update to the label. check this sample snippet and then update it according to your requirement..
object BatQuantity= pi[3].GetValue(SystemInformation.PowerStatus, null);
//convert the value I get from PowerStatus class to %
float num = (Single.Parse(CantdeBat.ToString())) * 100;
//shows battery % and if battery is full says it's full if not it says it's low
string batteryStatus = num.ToString() + "%";
if (num == 100)
{
batteryStatus = "-Full Battery-";
}
else if (num <= 25)
{
batteryStatust = "-Low Battery-";
}
label4.Text = batteryStatust;
Hope this help.
Related
The label must change when the page loads. I don't get any errors but the label stays what I named the label.
my code:
private void Form1_Load(object sender, EventArgs e)
{
DateTime curTime = DateTime.Now;
int one = 5; //times of day
int two = 12;
int three = 20;
string ogg = "Oggend";
string mid = "Middag";
string aan = "Aand";
if (curTime.Hour >= one && curTime.Hour <= two)
{
timelbl.Text = ogg;
}
else if (curTime.Hour > two && curTime.Hour < three)
{
timelbl.Text = mid;
}
else
{
timelbl.Text = aan;
}
}
I tried to put timelbl.Text = "Oggend" in aswell but it didn't work.
Oggend means Morning, Middag means Day and aand means Night
Using variables for "times of day" is redundant. You may keep them if that's what you want, but it won't be the best thing to do.
private void Form1_Load(object sender, EventArgs e) {
DateTime curTime = DateTime.Now;
int one = 5; //times of day
int two = 12;
int three = 8;
string ogg = "Oggend";
string mid = "Middag";
string aan = "Aand";
if (curTime.Hour >= one && curTime.Hour <= two)
{
timelbl.Text = ogg;
}
else if (curTime.Hour > two && curTime.Hour < three)
{
timelbl.Text = mid;
}
else
{
timelbl.Text = aan;
}
}
Your code seems to be fine. You just need to make sure that page load event fires so that the variable value assigned to the label. You should add a break point in page load event and ensure that the event fires properly.
I'm working in C# (2013) Windows Forms. My instructor wanted us to ensure that the txtStateInput is upperCase when we hit the calculate button. However when I input a two character string such as "wi" and then hit calculate, it throws the message "enter valid state" and clears out the textbox. When I enter the "wi" in a second time then it works. I can't figure out why this is happening, the code would lead me to believe that it would check to ensure the string in txtStateInput is two characters and then when calculate is clicked it would uppercase the string. I can't figure out why it only works once I enter in the state "wi" a second time.
private void btnCalc_Click(object sender, EventArgs e)
{
//declare variables.
int startPop = 0;
int endPop = 0;
string Message = "Error";
decimal Percent = 0.0m;
string State = "";
string City = String.Empty;
int dTimes = 0;
try
{
City = txtCityInput.Text;
//System Globalization was initialized so this method works.
TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
txtCityInput.Text = myTI.ToTitleCase(City);
if(txtStateInput.Text.Length != 2)
{
MessageBox.Show("Enter valid State");
txtStateInput.Focus();
txtStateInput.SelectAll();
}
else
{
State = txtStateInput.Text.ToUpper();
txtStateInput.Text = State;
if ((int.TryParse(txtStartPopInput.Text, out startPop)) && int.TryParse(txtEndPopInput.Text, out endPop))
{
if ((startPop > 0) && (endPop > 0))
{
//if population has decreased.
if ((startPop > endPop))
{
Percent = ((decimal.Parse(endPop.ToString()) - decimal.Parse(startPop.ToString())) / decimal.Parse(startPop.ToString()));
Message = "Pop. Decrease of " + Percent.ToString("p");
}
//if population has increased.
if ((startPop < endPop))
{
Percent = ((decimal.Parse(endPop.ToString()) - decimal.Parse(startPop.ToString())) / decimal.Parse(startPop.ToString()));
Message = "Pop. Increase of " + Percent.ToString("p");
}
//if population has not changed.
if ((startPop == endPop))
{
Percent = ((decimal.Parse(endPop.ToString()) - decimal.Parse(startPop.ToString())) / decimal.Parse(startPop.ToString()));
Message = "No Change in Population";
}
}
else
{
MessageBox.Show("Please enter valid population figures.");
}
}
if (int.TryParse(txtDisplayTimes.Text, out dTimes))
{
if (dTimes > 0)
{
lstResults.Items.Clear();
int iSum = 0;
int iLoopCount = dTimes;
//displays the results according to value in txtDisplayTimes.
for (iSum = 1; iSum <= iLoopCount; iSum++)
{
lstResults.Items.Add(Message);
}
}
}
}
}
catch
{
MessageBox.Show("Something went wrong.");
}
}
Alright so doing just a quick code to get the idea of using check and radio boxes in my code. Here is what I have got so far ( at the bottom ). So, I figured I can just set up a string of if statements and starting with seeing if all 3 are checked, if not it would go through and see if the first one is checked if not ect. Though, it does kind of work for only checking one check box, when I checked all three it displays the final calculation. So in my case if I have had 3 checked, it would only display the Volt + NonExploding calculation making it show $50,100 instead of $51,600 for if it added it all up. Can I get some quick help as to what to do so it notices that all three are checked instead of just going to the final checked calculation? Thanks for the help, very much appreciated.
private void button_Calculate_Click(object sender, EventArgs e)
{
//Validating options
if (radioButton_ChevVolt.Checked || radioButton_FordPinto.Checked)
{
//no code needed
}
else
{
MessageBox.Show("Please Choose One of the Vehicles");
return;
}
//Processing Input
double SunRoof = 1000;
double DVD = 500;
double NonExploding = 100;
double Volt = 50000;
double Pinto = 1000;
double TotalCost = 0;
if (radioButton_ChevVolt.Checked)
{
TotalCost = Volt;
textBox_TotalCost.Text = TotalCost.ToString();
{
if (checkBox_SunRoof.Checked || checkBox_DVD.Checked || checkBox_NonExploding.Checked)
{
TotalCost = Volt + DVD + SunRoof + NonExploding;
textBox_TotalCost.Text = TotalCost.ToString();
}
if (checkBox_SunRoof.Checked)
{
TotalCost = Volt + SunRoof;
textBox_TotalCost.Text = TotalCost.ToString();
}
if (checkBox_DVD.Checked)
{
TotalCost = Volt + DVD;
textBox_TotalCost.Text = TotalCost.ToString();
}
if (checkBox_NonExploding.Checked)
{
TotalCost = Volt + NonExploding;
textBox_TotalCost.Text = TotalCost.ToString();
}
}
}
}
}
}
What your code is doing is running all of the if statements - it's not just going to the final one. It's just that the final one is last so it appears that way.
Here's the easy fix:
if (checkBox_SunRoof.Checked && checkBox_DVD.Checked && checkBox_NonExploding.Checked)
{
TotalCost = Volt + DVD + SunRoof + NonExploding;
textBox_TotalCost.Text = TotalCost.ToString();
}
else if (checkBox_SunRoof.Checked)
{
TotalCost = Volt + SunRoof;
textBox_TotalCost.Text = TotalCost.ToString();
}
else if (checkBox_DVD.Checked)
{
TotalCost = Volt + DVD;
textBox_TotalCost.Text = TotalCost.ToString();
}
else if (checkBox_NonExploding.Checked)
{
TotalCost = Volt + NonExploding;
textBox_TotalCost.Text = TotalCost.ToString();
}
It also seems to me that the initial || should be && to make this work.
I would also be inclined to look at this calculation using the ternary operator ?:. Your code might look like this:
TotalCost += radioButton_ChevVolt.Checked ? Volt : 0.0;
TotalCost += checkBox_SunRoof.Checked ? SunRoof : 0.0;
TotalCost += checkBox_DVD.Checked ? DVD : 0.0;
TotalCost += checkBox_NonExploding.Checked ? NonExploding : 0.0;
textBox_TotalCost.Text = TotalCost.ToString();
And, finally, another hint. Don't use double for currency amounts as it is designed for scientific values. Use decimal instead.
I am trying to work with if else statements for different things. I need one that pulls the value of a dropdown list to determine what the calculation will be, another that pulls the value of a check box and assigns a calculation, another for input validation for if the number exceeds 32, and the last to give me a value determined by the amount (up to 32) entered into the textbox. I think i've gotten the checkbox statement corrected (guideFee), and the input validation and the one that goes with it seem to be correct already, but I am having trouble assigning the constant decimal values to the dropdown list values and I don't understand why. I have the basetourRate = Convert.ToDecimal(riverTour) and the if statement that follows, but when I run the program I get an error page. I have pasted the whole code. If anyone could help me out i'd greatly appreciate it, thank you!
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void butCalculate_Click(object sender, EventArgs e )
{
//1. Declare Variables
decimal totalBaseTourFee;
decimal totalGuideFee;
decimal totalWeekendSurcharge;
decimal subtotal;
decimal salesTaxCharge;
decimal totalCharge;
decimal baseTourRate;
decimal guideFee = 0m;
bool isGuidedTour;
int numberOfRafters;
int numberOfRaftsNeeded;
string riverTour;
string timeOfWeek;
string displayTotalBaseTourFee;
string displayNumberOfRaftsNeeded;
string displayTotalGuideFee;
string displayTotalWeekendSurcharge;
string displaySubtotal;
string displaySalesTaxCharge;
string displayTotalCharge;
const decimal FRENCH_BROAD = 40m;
const decimal NANTAHALA = 30m;
const decimal TUCK = 20m;
const decimal WEEKEND_SURCHARGE = 10M;
const decimal GUIDE_FEE = 35M;
const decimal SALES_TAX_RATE = .07M;
//2. Get Values
numberOfRafters = Convert.ToInt32(txtNumberOfRafters.Text);
riverTour = ddlTour.SelectedValue;
isGuidedTour = chkGuided.Checked;
timeOfWeek = rblDay.SelectedValue;
Trace.Warn("numberOfRafters = " + numberOfRafters);
Trace.Warn(("isGuidedTour = " + isGuidedTour));
Trace.Warn("riverTour = " + riverTour);
Trace.Warn("timeOfWeek = " + timeOfWeek);
//Input Validation
if (numberOfRafters > 32)
{
Console.WriteLine("Sorry, we can't handle this large of a group!");
return;
}
//3. Do Calculations
baseTourRate = Convert.ToDecimal(riverTour);
if (riverTour == "FB")
{
baseTourRate = FRENCH_BROAD;
}
else if (riverTour == "NH")
{
baseTourRate = NANTAHALA;
}
else if (riverTour == "TK")
{
baseTourRate = TUCK;
}
if (isGuidedTour == true)
{
guideFee = GUIDE_FEE;
}
else if (!isGuidedTour == false)
{
guideFee = 0;
}
totalBaseTourFee = numberOfRafters * baseTourRate;
numberOfRaftsNeeded = numberOfRafters;
if (numberOfRafters <= 8)
{
numberOfRaftsNeeded = 1;
}
else if (numberOfRafters <= 16)
{
numberOfRaftsNeeded = 3;
}
else if (numberOfRafters <= 24)
{
numberOfRaftsNeeded = 3;
}
else if (numberOfRafters <=32)
{
numberOfRaftsNeeded = 4;
}
totalGuideFee = numberOfRaftsNeeded * guideFee;
totalWeekendSurcharge = numberOfRafters * WEEKEND_SURCHARGE;
subtotal = totalBaseTourFee + totalGuideFee + totalWeekendSurcharge;
salesTaxCharge = subtotal * SALES_TAX_RATE;
totalCharge = subtotal + salesTaxCharge;
//4. Display Results
displayTotalBaseTourFee = totalBaseTourFee.ToString("C") + "<br>";
displayNumberOfRaftsNeeded = numberOfRaftsNeeded.ToString("C") + "<br>";
displayTotalGuideFee = totalGuideFee.ToString("C") + "<br>";
displayTotalWeekendSurcharge = totalWeekendSurcharge.ToString("C") + "<br>";
displaySubtotal = subtotal.ToString("C") + "<br>";
displaySalesTaxCharge = salesTaxCharge.ToString("C") + "<br>";
displayTotalCharge = totalCharge.ToString("C") + "<br>";
lblTotalBaseTourFee.Text = displayTotalBaseTourFee;
lblNumberOfRafts.Text = displayNumberOfRaftsNeeded;
lblTotalGuideFee.Text = displayTotalGuideFee;
lblTotalWeekendSurcharge.Text = displayTotalWeekendSurcharge;
lblSubtotal.Text = displaySubtotal;
lblSalesTaxCharge.Text = displaySalesTaxCharge;
lblTotalCharge.Text = displayTotalCharge;
}
protected void butClear_Click(object sender, EventArgs e)
{
//Clear TextBox and Label
txtNumberOfRafters.Text = "";
lblTotalBaseTourFee.Text = "";
lblNumberOfRafts.Text = "";
lblTotalGuideFee.Text = "";
lblTotalWeekendSurcharge.Text = "";
lblSubtotal.Text = "";
lblSalesTaxCharge.Text = "";
lblTotalCharge.Text = "";
ddlTour.SelectedIndex = -1;
rblDay.SelectedIndex = -1;
chkGuided.Checked = false;
//Set focus back to name textbox
txtNumberOfRafters.Focus();
}
}
The one thing that sticks out to me is the Convert.ToDecimal(...) call.
baseTourRate = Convert.ToDecimal(riverTour);
if (riverTour == "FB")
{
baseTourRate = FRENCH_BROAD;
}
else if (riverTour == "NH")
{
baseTourRate = NANTAHALA;
}
else if (riverTour == "TK")
{
baseTourRate = TUCK;
}
You are attempting to convert a string to a decimal but then you are comparing that string to a string. My guess is that riverTour is not really a decimal and therefore you are getting an exception. Basically, the logic does not make sense. Convert.ToDecimal will throw an exception if it is not a valid decimal. Therefore, riverTour cannot contain a convertible value to decimal and a comparable value to FB/NH/TK. What exactly are you trying to accomplish? If you are trying to convert to decimal if it is valid and then check those 3 cases if it is not then you should look into decimal.TryParse(string, out decimal) https://msdn.microsoft.com/en-us/library/9zbda557(v=vs.110).aspx. This might help you achieve what you are trying to do.
If the input is always numeric, then you should consider using NumericUpDown. Or, at the very least, use TryParse methods so you can tell if the input is valid or invalid.
numberOfRafters = Convert.ToInt32(txtNumberOfRafters.Text);
Is also unsafe.
I have my own solution to import monthly sales data in my windows form application. When a user click on import button, the program is actually running but it looks like it's not responding. The process takes a long time about 5 minutes.
So, I'd like to implement a progress bar with status strip label to display as an user interface and let the users know how much the task is done. This is also my first time using a progress bar in my program. So, I read through some tutorials which show how to use it. Some people use progress bar with background worker and timer.
But I don't understand where I should use the solution that I have. In background worker DoWork() event? I don't want to fake it by abusing the progress bar like setting the progressBar.Maximum = 100, progressBar.Value = 0 and as long as the timer is ticking increasing the value by 5. The progress bar must report the actual progress while the program is running.
The following is the solution I am using now to import the data:
private void btnImport_Click(object sender, EventArgs e)
{
if (lsbxBrowsedFiles.Items.Count != 0)
{
ArrayList salesHeaderArr = new ArrayList();
ArrayList salesDetailArr = new ArrayList();
int i = 0;
while (i < browsedXmlFileList.Count)
{
if (browsedXmlFileList[i].ToUpper().EndsWith("SALESHEADER.XML"))
{
salesHeaderArr.Add(browsedXmlFileList[i]);
}
if (browsedXmlFileList[i].ToUpper().EndsWith("SALESDETAIL.XML"))
{
salesDetailArr.Add(browsedXmlFileList[i]);
}
i++;
}
if (selectedFileIsNotInDestinationFolder(salesHeaderArr, salesDetailArr) == true)
{
i = 0;
while (i < salesHeaderArr.Count)
{
SalesHeader salesHeader = new SalesHeader();
string sourceFilePath = salesHeaderArr[i].ToString();
readXMLFiles(sourceFilePath, SALES_HEADER);
SalesHeader salesCheck = (SalesHeader)salesHeaderList[0];
string checkOutletCode = salesCheck.OutletCode;
DateTime checkBusDate = salesCheck.BusinessDate.Value;
if (SalesHeader.IsThisRowAlreadyImportedInSalesHeader(checkOutletCode, checkBusDate) == false)
{
salesHeader.ImportSalesHeader(salesHeaderList);
salesHeader.CreateImportDataLog(getDestinationFilePath(sourceFilePath),
DateTime.Now, salesHeaderList.Count, SALES_HEADER);
}
else
{
string errorDate = checkBusDate.ToString("dd MMMM, yyyy");
MessageBox.Show("Selected XML File with BusinessDate: " + errorDate + " has been already imported.",
"ABC Cafe Import Sales Wizard");
MessageBox.Show("Please select a file which has not been imported!",
"ABC Cafe Import Sales Wizard");
return;
}
MoveXMLFiletoDestinationFolder(sourceFilePath);
i++;
}
i = 0;
while (i < salesDetailArr.Count)
{
SalesDetail salesDetail = new SalesDetail();
string sourceFilePath = salesDetailArr[i].ToString();
readXMLFiles(sourceFilePath, SALES_DETAIL);
SalesDetail salesCheck = (SalesDetail)salesDetailList[0];
string checkOutletCode = salesCheck.OutletCode;
DateTime checkBusDate = salesCheck.BusinessDate.Value;
if (SalesDetail.IsThisRowAlreadyImportedInSalesDetail(checkOutletCode, checkBusDate) == false)
{
salesDetail.ImportSalesDetail(salesDetailList);
salesDetail.GenerateCarryForward(salesDetailList);
salesDetail.CalculateImportInventoryBalance(salesDetailList);
salesDetail.CreateImportDataLog(getDestinationFilePath(sourceFilePath), DateTime.Now, salesDetailList.Count, SALES_DETAIL);
}
else
{
string errorDate = checkBusDate.ToString("dd MMMM, yyyy");
MessageBox.Show("Selected XML File with BusinessDate: " + errorDate + " has been already imported.",
"ABC Cafe Import Sales Wizard");
MessageBox.Show("Please select a file which has not been imported!",
"ABC Cafe Import Sales Wizard");
return;
}
MoveXMLFiletoDestinationFolder(sourceFilePath);
i++;
}
MessageBox.Show("Import has been successfully completed!",
"ABC Cafe Import Sales Wizard");
clearListBoxItems();
lblMessage.Visible = false;
}
//Abort the import operation here!
else
{
MessageBox.Show("Please select a file which has not been imported!",
"ABC Cafe Import Sales Wizard");
clearListBoxItems();
lblMessage.Visible = false;
}
}
else
{
MessageBox.Show("Please select XML files to import!",
"ABC Cafe Import Sales Wizard");
}
}
Any help will be very much appreciated!
This is how I have used Progress Bar in my application.
private void btnNext_Click(object sender, EventArgs e)
{
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.ProgressChanged += (se, eventArgs) => {
this.progressBar.Maximum = 100;
this.progressBar.Minimum = 0;
this.progressBar.Value = eventArgs.ProgressPercentage;
lblStatus.Text = eventArgs.UserState as String;
lblPercentage.Text = String.Format("Progress: {0} %", eventArgs.ProgressPercentage);
};
worker.DoWork += (se, eventArgs) => {
int progress = 0;
((BackgroundWorker)se).ReportProgress(progress, "Initializing the files...");
//Process that takes a long time
//Formula to calculate Progress Percentage
//This is how I calculated for my program. Divide 100 by number of loops you have
int findPercentage = ((i + 1) * 100) / salesHeaderArr.Count;
progress = 0;
progress += findPercentage / 2;
//Report back to the UI
string progressStatus = "Importing Sales Header... (" + getSourceFileName(sourceFilePath) + ")";
((BackgroundWorker)se).ReportProgress(progress, progressStatus);
//After Iterating through all the loops, update the progress to "Complete"
((BackgroundWorker)se).ReportProgress(100, "Complete...");
};
worker.RunWorkerCompleted += (se, eventArgs) =>
{
//Display smth or update status when progress is completed
lblStatus.Location = new Point(20, 60);
lblStatus.Text = "Your import has been completed. \n\nPlease Click 'Finish' button to close the wizard or \n'Back' button to go back to the previous page.";
lblPercentage.Visible = false;
progressBar.Visible = false;
btnBack.Enabled = true;
btnFinish.Enabled = true;
};
worker.RunWorkerAsync();
}
Your program has many loops,since it will be difficult to get the increment value and increment the progress bar value in each loop iteration.You could set the progress bar maximum to 100,Then divide 100 by the number of loops you have say X.
So the trick would be to fill the progress bar by this value when each loops completes
and yes you should put this code in backgroundworker's DoWork() otherwise it will freeze the form.Also there is no need for a timer.
You can use a ManualResetEvent, Now while you are processing, let the Progressbar Increase until it meets a certain point and wait for a Set.
Example:
you have this 2 fields
private int progress = 0;
private ManualResetEvent reset = new ManualResetEvent(false);
// Sets it to unsignalled
private ManualResetEvent reset2 = new ManualResetEvent(false);
while(progress < 40)
{
progress ++;
}
reset.WaitOne();
while(progress < 90)
{
progress ++;
}
reset2.WaitOne();
while(progress < 100)
{
progress ++;
}
// This finishes the progress, Now on your actual Work, you have to signal those wait.
DoWork()
{
// long process here. . . .
reset.Set();
// Another long process
reset2.Set();
}