I having problem on the C# Windows Forms. I have created a timer and a button to act as a timer lamp. Now I have created the timer and the timer value can get successfully. But I dont know why the button backcolor cannot change as the setted on the code.
Below is my whole codes.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace TimerLamp
{
public partial class Form1 : Form
{
System.Timers.Timer t;
int s, c, x;
String sec;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
t = new System.Timers.Timer();
t.Interval = 1000; //1s
t.Elapsed += OnTimeEvent;
//t.Enabled = true;
}
private void OnTimeEvent(object sender, System.Timers.ElapsedEventArgs e)
{
s += 1;
sec = s.ToString();
if (s == 23)
{
s = 0;
c += 1;
}
TimerTextBox.Invoke((MethodInvoker)(() => TimerTextBox.Text = s.ToString()));
TimerTextBox.Invoke((MethodInvoker)(() => CounterTextBox.Text = c.ToString()));
sec = s.ToString();
}
private void TurnOnLamp_CheckedChanged(object sender, EventArgs e)
{
if (TurnOnLamp.Checked == true)
{
x = Convert.ToInt16(sec);
if (x >= 0 && x <7)
{
btnLamp.BackColor = Color.Green;
}
if (x > 8 && x < 19)
{
btnLamp.BackColor = Color.Red;
}
else if (x >= 19)
{
btnLamp.BackColor = Color.Green;
}
else
{
btnLamp.BackColor = Color.Red;
}
}
if (TurnOnLamp.Checked == false)
{
btnLamp.BackColor = Color.Red;
}
}
private void btnStart_Click(object sender, EventArgs e)
{
if (btnStart.Text == "Start")
{
t.Start();
if (c >= 30)
{
MessageBox.Show("Limit reached");
return;
}
btnStart.Text = "Stop";
}
else if (btnStart.Text == "Stop")
{
t.Stop();
btnStart.Text = "Start";
}
}
private void btnLamp_Click(object sender, EventArgs e)
{
}
private void TimerTextBox_TextChanged(object sender, EventArgs e)
{
}
private void CounterTextBox_TextChanged(object sender, EventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
t.Stop();
Application.DoEvents();
}
}
}
Can someone help me to solve this problem?