Reputation: 133
var startTime = DateTime.Now;
var timer = new Timer() { Interval = 1000 };
timer.Tick += (obj, args) =>
label14.Text =
(TimeSpan.FromMinutes(Convert.ToDouble( comboBox3.Text)*60) - (DateTime.Now - startTime))
.ToString("hh\\:mm\\:ss");
MessageBox.Show("Timer started");
timer.Enabled = true;
im strating a timer in a specific form when pressing a button, i want the timer to continue counting time after closing the form in order to give me a notification. but when closing the form the timer stops, any ideas?
Upvotes: 1
Views: 1761
Reputation: 2540
A quick hit: call "Hide()" instead - that will keep the timer running.
Now that's out the way, You can still make your timer static - ideally put it in a completely separate class, or, if you insist, make it static on your main form. Then have your notification code sit on your main form.
You can still add a listener to the Tick event on that specific form and just remember to remove it when you hide the form (i.e. Tick -= your_label_event_handler
)
Upvotes: 0
Reputation: 582
You can't "Close" the form and have the Timer object still work (if you're calling the timer on the main form). (That's like saying I can't click the button and have a function run after closing the form). However, on the OnFormClosing argument, you could have the form.Visible = false
and cancel the actual closing of the form. See here: Timer doesn't fire after Form closed
If you want to truly close the form and have it run, one option could be to look at possibly creating a Task Scheduler object that would complete the task at a certain time.
Upvotes: 2