Timer updating label
This is just one of many ways to do it. Of course, I would do it on background worker but this is legit way to get what you want:
Timer timer;
Stopwatch sw;
public Form1()
{
InitializeComponent();
}
private void btn_Import_Click(object sender, EventArgs e)
{
timer = new Timer();
timer.Interval = (1000);
timer.Tick += new EventHandler(timer_Tick);
sw = new Stopwatch();
timer.Start();
sw.Start();
// start processing emails
// when finished
timer.Stop();
sw.Stop();
lblTime.text = "Completed in " + sw.Elapsed.Seconds.ToString() + "seconds";
}
private void timer_Tick(object sender, EventArgs e)
{
lblTime.text = "Running for " + sw.Elapsed.Seconds.ToString() + "seconds";
Application.DoEvents();
}
MaylorTaylor
I am a highly skilled Full Stack Developer with 6+ years of experience in a real world work environment. I work well in a team environment, and am seasoned enough to accomplish projects with minimal direction and oversight. I am looking for a position with opportunity for growth, including leading a team of my own and learning new skills and languages. 5+ years with SQL and MySQL databases, C# language, Razor templates, and MVC framework 5+ years using .NET 4.6 and 4.7 4+ years of AngularJS development, HTML, CSS/LESS 2+ years using latest .NET Core and .NET Standard technologies and builds 2+ years experience with Node, Express, MEAN stack, and Angular 2+ Well versed on proper RESTful standards, HTML5 standards, ADA compliance standards, and C# coding patterns such as the “Visitor Pattern”
Updated on June 04, 2022Comments
-
MaylorTaylor almost 2 years
I know this is a common question but I can't seem to get it right. I have a form that goes out to gmail and processes some emails. I want to have a timer on the form to count how long the action has been running for. So once a user click the "start import" button I want the timer to start and once the "finished" messagebox appears it should stop. Here is what I have so far
Right now, the timer is just stays at the default text of "00";
namespace Import { public partial class Form1 : Form { Timer timer; public Form1() { InitializeComponent(); } private void btn_Import_Click(object sender, EventArgs e) { timer = new Timer(); timer.Interval = (1000); timer.Enabled = true; timer.Start(); timer.Tick += new EventHandler(timer_Tick); // code to import emails MessageBox.Show("The import was finished"); private void timer_Tick(object sender, EventArgs e) { if (sender == timer) { lblTimer.Text = GetTime(); } } public string GetTime() { string TimeInString = ""; int min = DateTime.Now.Minute; int sec = DateTime.Now.Second; TimeInString = ":" + ((min < 10) ? "0" + min.ToString() : min.ToString()); TimeInString += ":" + ((sec < 10) ? "0" + sec.ToString() : sec.ToString()); return TimeInString; } } } }
-
T.S. over 6 yearsOr, here,
..."Running for " + sw.Elapsed.Seconds.ToString()...
just useElapsed
and format it for your liking