int millisecondi = 0;
public Form1()
{
InitializeComponent();
player.Top = screen.Height - player.Height;
player.BackgroundImage = Properties.Resources.stand;
if (mario)
{
label1.Text = "Mario";
}
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
progressBar1.Value = 100;
}
private void timer1_Tick(object sender, EventArgs e)
{
index++;
//replay gif
millisecondi++;
if (millisecondi == 1000)
{
progressBar1.Value = progressBar1.Value - 1;
if (progressBar1.Value <= 0)
{
MessageBox.Show("Sei Morto");
}
}
}
The problem is in the timer1_Tick.
It is enabled automatically and its interval is 1 millisecond.
Every second I want the progress bar to be "Progressbar value - 1" for example.
When it reaches 0 I want it to say "You died".
It enters in this cycle after 1 second, but it just doesn't work:
if (millisecondi == 1000)
{
progressBar1.Value = progressBar1.Value - 1;
if (progressBar1.Value <= 0)
{
MessageBox.Show("Sei Morto");
}
}
Timer ticks once and then it stops: To make it tick constantly, change the Tick event to:
private void timer1_Tick(object sender, EventArgs e)
{
index++;
millisecondi++;
timer1.Stop();
if (millisecondi == 1000)
{
progressBar1.Value = progressBar1.Value - 1;
if (progressBar1.Value <= 0)
{
MessageBox.Show("Sei Morto");
}
}
else
{
timer1.Start(); // will 'retick' if millisecondi != 1000
}
}
As you mentioned that code execution reaches to if (millisecondi == 1000) then there wouldn't be any problem with execution scenario so you should take care of other things like following:
Timer NameSpace : Make sure that your timer namespace is System.Windows.Forms.Timer
if It's ok that would work anyway your code looks correct to me, but if you still encounter this problem again try this code :
index++;
//replay gif
millisecondi++;
if (millisecondi == 1000)
{
if (progressBar1.InvokeRequired)
{
progressBar1.Invoke((MethodInvoker)
delegate
{
progressBar1.Value = progressBar1.Value - 1;
}
);
}
else
{
progressBar1.Value = progressBar1.Value - 1;
}
if (progressBar1.Value <= 0)
{
MessageBox.Show("Sei Morto");
}
}
Related
I'm setting up a background worker for the first time. It is mostly working as the code runs and my stop/cancel button is working. However, I am also trying to report progress to update a progress bar but I cannot get this to fire at all.
I start the code from a button click which runs this code:
backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.RunWorkerAsync();//this invokes the DoWork event
My Do_Work method:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
int j = 0;// Count cumulative imported files
int countDupFiles = 0;// Count number of previously imported csv files
int countImportedFiles = 0;// Count imported files
foreach (string folderPath in csvDirList)
{
string[] csvFileNames = Directory.GetFiles(#folderPath, "*.csv");
frmImportCsvData.replaceAll(csvFileNames, folderPath + "\\", "");
for (int i = 0; i < csvFileNames.Length; i++, j++)
{
string csvFilePath = folderPath + "\\" + csvFileNames[i];
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
if (dataLayer.ImportCsvDataBkgrnd(this, csvFilePath, compIdValue, csvFileCount, i))//new method processes subdirectories if tick box selected
{
countImportedFiles = countImportedFiles + 1;
}
else
{
countDupFiles = countDupFiles + 1;
}
System.Threading.Thread.Sleep(500);
}
worker.ReportProgress(j);//tried using worker and backgroundWorker1 but neither works
backgroundWorker1.ReportProgress(j);
//string proj = j.ToString();
//MessageBox.Show(proj);//Displays incrementing j as expected when not commented out
}
}
if (countImportedFiles > 0)
MessageBox.Show(countImportedFiles + " files were imported.");
if (countDupFiles > 0)
MessageBox.Show(countDupFiles + " files were not imported. Matches all ready in Database.");
}
Trying to fire either of these ProgressChanged events:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
string tbProgress = (e.ProgressPercentage.ToString() + "%");
MessageBox.Show(tbProgress + "backgroundWorker1");
importProgressBar(e.ProgressPercentage);
}
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
string tbProgress = (e.ProgressPercentage.ToString() + "%");
MessageBox.Show(tbProgress + "worker");
importProgressBar(e.ProgressPercentage);
}
Finally, I want the ProgressChanged event to trigger this method to update my progress bar:
public void importProgressBar(int i)
{
progressTableLayoutPanel.Visible = true;//display progress bar
int percProgress = 100 * (i + 1) / csvFileCount;
if (percProgress <= 99)// Required to prevent values above 100 that crash the code
progressBar.Value = percProgress + 1;//hack that makes the progress bar update when progress value decreases
progressBar.Value = percProgress;
percProgressLabel.Text = percProgress.ToString();
progressTableLayoutPanel.Update();//Required to display all progress bar table contents
//Thread.Sleep(200);
if (percProgress >= 100)
{
Thread.Sleep(200);
progressTableLayoutPanel.Visible = false;
}
}
The cancel button code, which works, looks like this:
private void stopImportButton_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
The messageboxes in my ProgressChanged events never show up and my progress bar is never set to visible. Any ideas what the problem could be?
Check this example:
BackgroundWorker bgw = new BackgroundWorker();
public Form1()
{
InitializeComponent();
label1.Text = "";
label2.Text = "";
}
private void button1_Click_1(object sender, EventArgs e)
{
if (bgw == null)
{
bgw = new BackgroundWorker();
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
}
bgw.WorkerReportsProgress = true;
bgw.WorkerSupportsCancellation = true;
bgw.RunWorkerAsync();
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
int total = 57; //some number (this is your variable to change)!!
for (int i = 0; i <= total; i++) //some number (total)
{
System.Threading.Thread.Sleep(100);
int percents = (i * 100) / total;
bgw.ReportProgress(percents, i);
//2 arguments:
//1. procenteges (from 0 t0 100) - i do a calcumation
//2. some current value!
}
}
void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label1.Text = String.Format("Progress: {0} %", e.ProgressPercentage);
label2.Text = String.Format("Total items transfered: {0}", e.UserState);
}
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//do the code when bgv completes its work
}
}
Maybe this helps you with your problem...
And try to put the progress to visible just after you call the background.doWork in the button click event.
I am using below code to display time left in hh:mm:ss format for example if duration is 30min, it will show like this 00:30:00 and after 1 min it will show 00:29:00, how can i also display the remaining seconds and decrease them accordingly.,
Edit
I tried timer1.Interval = 1000; and
examTime = examTime.Subtract(TimeSpan.FromSeconds(1));
But its not showing me seconds reducing each second, How do i do it ?
public SubjectExamStart()
{
InitializeComponent();
examTime = TimeSpan.FromMinutes(double.Parse(conf[1]));
label1.Text = examTime.ToString();
timer1.Interval = 60 * 1000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (sender == timer1)
{
if (examTime.TotalMinutes > 0)
{
examTime = examTime.Subtract(TimeSpan.FromMinutes(1));
label1.Text = examTime.ToString();
}
else
{
timer1.Stop();
MessageBox.Show("Exam Time is Finished");
}
}
}
Instead of Subtracting TimeSpan.FromMinutes you need to subtract from TimeSpan.FromSeconds
public SubjectExamStart()
{
InitializeComponent();
examTime = TimeSpan.FromSeconds(double.Parse(conf[1]));
label1.Text = examTime.ToString();
timer1.Interval = 1000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (sender == timer1)
{
if (examTime.TotalMinutes > 0)
{
examTime = examTime.Subtract(TimeSpan.FromSeconds(1));
label1.Text = examTime.ToString();
}
else
{
timer1.Stop();
MessageBox.Show("Exam Time is Finished");
}
}
}
If you want to format the Time Span value while assigning to Label... You can use below..
label1.Text = examTime.ToString(#"dd\.hh\:mm\:ss");
To do this properly, you will need to keep a track of when the timer was started
DateTime examStartTime;
System.Windows.Forms.Timer runTimer;
TimeSpan totalExamTime = new TimeSpan(1, 30, 0); // Set exam time to 1 hour 30 minutes.
if (runTimer == null)
runTimer = new System.Windows.Forms.Timer();
runTimer.Interval = 200;
runTimer.Tick -= new EventHandler(runTimerTick);
runTimer.Tick += new EventHandler(runTimerTick);
examStartTime = DateTime.Now;
runTimer.Start();
Then in the event handler you can do:
public void runTimerTick(object sender, EventArgs e)
{
TimeSpan currentExamTime = DateTime.Now - examStartTime;
if (currentExamTime > totalExamTime)
{
MessageBox.Show("Exam Time is Finished");
runTimer.Stop();
runTimer.Tick -= new EventHandler(runTimerTick);
runTimer.Dispose();
}
}
I hope this helps.
try this hope this will work for u
set timer interval=1000
minremain=1200000; //Should be in milisecond
timerplurg.satrt();
private void timerplurg_Tick(object sender, EventArgs e)
{
minremain = minremain - 1000; //substring One second from total time
string Sec = string.Empty;
if (minremain <= 0)
{
lblpurgingTimer.Text = "";
timerplurg.Stop();
return;
}
else
{
var timeSpan = TimeSpan.FromMilliseconds(Convert.ToDouble(minremain));
var seconds = timeSpan.Seconds;
if (seconds.ToString().Length.Equals(1))
{
Sec = "0" + seconds.ToString();
}
else
{
Sec = seconds.ToString();
}
string Totaltime = "Remaing Second: " + Sec;
lblpurgingTimer.Text = Totaltime;
}
I created a function that gets number of milliseconds and then runs the progress bar but the result is that the progress bar run less time than defined.
this.timerProgress.Tick += new System.EventHandler(this.timerProgress_Tick);
public void AnimateProgBar(int milliSeconds)
{
if (!timerProgress.Enabled)
{
this.Invoke((MethodInvoker)delegate { pbStatus.Value = 0; });
timerProgress.Interval = milliSeconds / 100;
timerProgress.Enabled = true;
}
}
private void timerProgress_Tick(object sender, EventArgs e)
{
if (pbStatus.Value < 100)
{
pbStatus.Value += 1;
pbStatus.Refresh();
}
else
{
timerProgress.Enabled = false;
}
}
using AnimateProgBar(100), will end up creating a Interval of 1 millisecond.
timerProgress.Interval = milliSeconds; //do not divide by 100
this.timerProgress.Tick += new System.EventHandler(this.timerProgress_Tick);
public void AnimateProgBar(int milliSeconds)
{
if (!timerProgress.Enabled)
{
this.Invoke((MethodInvoker)delegate { pbStatus.Value = 0; });
timerProgress.Interval = milliSeconds; //do not divide by 100
timerProgress.Enabled = true;
}
}
private void timerProgress_Tick(object sender, EventArgs e)
{
if (pbStatus.Value < 100)
{
pbStatus.Value += 1;
pbStatus.Refresh();
}
else
{
timerProgress.Enabled = false;
}
}
A call to AnimateProgBar(1000) will result in the following calculation: 1000 / 100. That equals 10.
The Timer interval is already in milliseconds. So you're effectively setting the interval to 10ms.
I would like to know how to create a label that adds sum + 1 every 5 seconds? I've tried with an if loop but unfortunately it resets one second later.
Thank you in advantage for your attention
using System.Diagnostics;
// using system.diagnotics voor stopwatch
namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Stopwatch sw = new Stopwatch();
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
sw.Start();
if (timer1.Enabled == true) { button1.Text = "stop"; }
else { button1.Text = "false"; sw.Stop(); }
}
private void timer1_Tick(object sender, EventArgs e)
{
int hours = sw.Elapsed.Hours;
int minutes = sw.Elapsed.Minutes;
int seconds = sw.Elapsed.Seconds;
int sum = 0;
label1.Text = hours + ":" ;
if (minutes < 10) { label1.Text += "0" + minutes + ":"; }
else { label1.Text += minutes + ":"; }
if (seconds < 10) { label1.Text += "0" + seconds ; }
else { label1.Text += seconds ; }
if (seconds ==5) { sum = sum +=1; }
label2.Text = Convert.ToString(sum);
}
}
}
sum should be a class field. Also you can use custom format string for elapsed TimeSpan.
int sum = 0;
private void timer1_Tick(object sender, EventArgs e)
{
// int sum = 0; local variable will be set to zero on each timer tick
label1.Text = sw.Elapsed.ToString(#"hh\:mm\:ss");
// btw this will not update sum each five seconds
if (sw.Elapsed.Seconds == 5)
sum++; // same as sum = sum +=1;
label2.Text = sum.ToString();
}
Your current implementation will increase sum only if current elapsed timeout's second value is five. Which could never happen (depending on your timer interval). If you have timer interval set to 1000 milliseconds, then you can increase sum on each tick, but set label2.Text = (sum % 5).ToString().
every time your stopwatch TICKS, sum is inside TICK and it will reset and start from
int sum=0;
so try to make sum variable GLOBAL outside timer1_Tick event and it will continue increasing.
You will have to move sum out of the timer callback as you are setting it to 0 each time the timer elapses
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int sum = 0;
private DateTime lastUpdate;
private Stopwatch sw = new Stopwatch();
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = string.Format("{0:00}:{1:00}:{2:00}",
sw.Elapsed.Hours, sw.Elapsed.Minutes, sw.Elapsed.Seconds);
if (DateTime.Now >= lastUpdate.AddSeconds(5))
{
sum++;
lastUpdate = DateTime.Now;
label2.Text = sum.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
sw.Stop();
button1.Text = "stop";
}
else
{
sum = 0;
lastUpdate = DateTime.Now;
timer1.Enabled = true;
sw.Start();
button1.Text = "Start";
}
}
I'm trying to make a timer tick for 80 minutes while the progress bar keeps track of the current time, but the progress bar in C# Forms will not be accurate to the timer ticks. I have it set up for the timer to tick once every 1000 ms and in that tick it will add a step to the progress bar. The progress bar will not act as it should with the timer, does anyone know how to fix this?
public Form1()
{
InitializeComponent();
initTimers();
}
public void timer1_Tick(object sender, EventArgs e)
{
progressBar1.Increment(1);
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Go")
{
timer1.Start();
button1.Text = "Stop";
}
else
{
timer1.Stop();
button1.Text = "Go";
}
}
public void initTimers()
{
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
}
public void progressTimers()
{
progressBar1.Value = 0;
progressBar1.Minimum = 0;
progressBar1.Maximum = 2;
progressBar1.Step = 1;
progressBar1.Visible = true;
}
You need to change this line:
progressBar1.Maximum = 2;
to:
progressBar1.Maximum = 80 * 60; // minutes * 60
And make sure you call progressTimers() :).