I'm new to C# and I'm trying to create a simple brain training program using Windows Forms that I learnt when learning Android App development. I'm stuck on the Timer. I have it working and it triggers every second and updates the label on my form. When I add code after I have started the timer, the timer stops. It's like I doesn't run in the background. I've read lots about threading timers and from timers etc, but I've not managed to get anything to work. Like I said, I'm new to C# so please be gentle.... He's my code....
public partial class BrainTrainer : Form
{
// Set global timer variables & Create Timer
static int secondCounter = 10;
static bool play = false;
static Timer myTimer = new Timer();
public BrainTrainer()
{
// Set up form
InitializeComponent();
toggleLabels(false);
timerLbl.Text = secondCounter.ToString() + "s";
}
// Function to loop through labels and disabled them
private void toggleLabels(bool state)
{
var ansLabels = this.Controls.OfType<Label>()
.Where(c => c.Name.StartsWith("ans"))
.ToList();
foreach (var label in ansLabels)
{
label.Enabled = state;
}
}
// Event to run every second
private void TimerEventProcessor(Object myObject, EventArgs e)
{
if (secondCounter == 0)
{
//Stop Game
myTimer.Stop();
play = false;
}
else
{
// Countdown 1 and update label
secondCounter--;
timerLbl.Text = secondCounter.ToString()+"s";
}
}
private void startBtn_Click(object sender, EventArgs e)
{
// Hide button, set play to true and enable labels
startBtn.Hide();
play = true;
toggleLabels(true);
// Set up timer event, interval and start
myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Interval = 1000;
myTimer.Start();
// Run function to play
genEquation();
}
private void genEquation()
{
while (play)
{
Console.WriteLine(secondCounter);
}
}
}
Any help is greatly appreciate, or a link to a helpful tutorial would be great!
WPFand it is in factWinformsthat you are using