I have a VB.Net program that uses timer for 20 seconds. When the program runs, the timer works just fine until it finishes (for 20 seconds). My problem is if I close the program after 10 seconds, the timer stops as well. However, what I want is a code the allows the timer to continue running until it finishes the remaining 10 seconds. So my question is, is it possible to use a timer and make it run even after the program is closed? Alternatively, are there other ways to accomplish what I want to do (example: keep a Timeofday.Ticks run even if I close the program)? Your solutions will be greatly appreciated. Thanks, A-Tech
Asked
Active
Viewed 1,025 times
2 Answers
1
I'm not sure that you can continue to run it after closing, but you can postpone the application from closing with the following code.
Public Class Form1
Dim closer As Boolean = False
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Timer1.Enabled = True
Label1.Text = "Timer started"
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Timer1.Enabled = False
Label1.Text = "Timer stopped"
If closer Then
Application.Exit()
End If
End Sub
Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
If Timer1.Enabled Then
closer = True
e.Cancel = True
End If
End Sub
End Class

Pydigor
- 11
- 2
0
Create a new thread and run your code in the thread. The process won't actually exit until the thread does, even if the form is closed.
Of course you will now have to deal with a thread and all the trouble / fun those entail.
You could alternately implement the code you want to keep running as a windows service. Those will run continually, without a UI. You can then have a front-end UI that communicates with the service to schedule work and retrieve results.

Bradley Uffner
- 16,641
- 3
- 39
- 76