I recommend that you stop using System.Timers.Timer
and start using a System.Windows.Forms.Timer
component.
Begin by removing your myTimer
-related code (the entire body of checkBox1_CheckedChanged
will need to be replaced with code from below.)
Add a Timer
component to your form using the designer and name it myTimer
. This will add a System.Windows.Forms.Timer
field to your form called myTimer
.
Using the designer, set the Tick
event handler of myTimer
to DisplayTimeEvent
. (Or add a new handler and replace its code with the code of your DisplayTimeEvent
function.)
Then change your checkBox1_CheckedChange
function to look like this:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (int.TryParse(textBox5.Text, out int interval)) {
this.myTimer.Interval = interval;
}
this.myTimer.Enabled = checkBox1.Checked;
this.textBox5.Enabled = !checkBox1.Checked;
}
I also recommend adding the following handler to textBox5
to perform the bare minimum validation so you can't crash your app by entering an interval of 0
or the empty string, or some text that is not an integer.
private void textBox5_TextChanged(object sender, EventArgs e)
{
this.checkBox1.Enabled = (int.TryParse(textBox5.Text, out int interval) && interval > 0);
}
The System.Windows.Forms.Timer
's Tick
handler will be called in the UI thread, meaning it will be safe to do things like update labels of your form in that handler. In contrast to that, the System.Timers.Timer
will be called on a worker thread and will require that you take on some some thread-management responsibilities you likely don't want to incur, such as invoking your UI updates back to the main UI thread. See Why there are 5 Versions of Timer Classes in .NET? for more info.