Hello Everyone!
I am somehow what new to coding and stumbled across a problem. I managed to find a solution myself but I am of certain there are better solutions for it!
I will try to descripe my problem as good as my bad english skills allow me to and my solution right after. The point is, I would like to know if there is any solution in generel since my solution seems to be very specificly suited for this case only.
Okay folks, here we go!
Program description
The Program itself is set up by three Forms, the main form being a "control centre" or menu so to say, the other two being timers displayed by labels, as you can see here. The blue Timer is incremending while the green one does the opposite.
The moment I open the program the two timer forms open aswell, I need them even though they are not running. Obviously, I use the FormMain_Load Method in order to display them:
private void FormMain_Load(object sender, EventArgs e)
{
Form1 timerUp = new Form1();
timerUp.Show();
Form2 timerBreak = new Form2();
timerBreak.Show();
}
The Question
Now, exsactly that is my problem! The second someone clicks on one of those two start buttons I would like to start the timer on the form (since i put the timer for each timer on its own form). But if i use
private void buttonStart_Click(object sender, EventArgs e)
{
timerUp.timer1.Start();
}
in order to accsess the "timerUp" Variable I can not access the local variable "Form1 timerUp" inside FormMain_Load. It says "Variable does not exist in the current context".
I would be awfully glad if someone knew about a possible solution to simply turn on the timer on the already open form from another class.
My solution
As already spoilert, I managed to find a solution even though I am not happy about its setup.
In order to maintain my solution, the two timers start the second the forms open, for example inside Form1 (first timer):
private void Form1_Load(object sender, EventArgs e)
{
timer1.Start();
}
However, there is some logic behind it. I've set up some public static booleans inside mainForm and let them be change by clicking on buttons. For example:
public partial class FormMain : Form
{
public static bool timer1 = false;
public static bool timer2 = false;
....
private void buttonStart_Click(object sender, EventArgs e)
{
timer1 = true;
}
}
Now, inside Form1 again, I've added a few if-statements to check for those booleans. Just like that:
private void timer1_Tick(object sender, EventArgs e)
{
if (FormMain.timer1)
{
....
}
}
Obviously, that solution does have some performance issues:
- Timers are always running
- If-statements have to be checked each tick
Even though those are basicly of no matter for such a small program as I made, I am eager to learn how to adress such a problem the proper way.
Thanks in advance for any response!