Bradley William Elko Bradley William Elko - 2 months ago 11
C# Question

Resting A Button or Going Back To A Previous Void

I have been trying multiple attempts to make this snippet of code work but I can't find a solution. Here it is:

private void buttonTwo_Click(object sender, EventArgs e)
{
sayingTwo.Visible = true;
buttonTwo.Text = "Click To Hide Saying";
buttonTwo.Click += new EventHandler(buttonTwo_Click2);
}
System.Windows.Forms.Timer tm2 = new System.Windows.Forms.Timer();
private void buttonTwo_Click2(object sender, EventArgs e)
{
if(sayingTwo.Visible == true)
{
buttonTwo .Enabled = false;
sayingTwo.Visible = false;
buttonTwo.Text = "Reactivating in 5 seconds";
tm2.Interval = (1000);
tm2.Tick += new EventHandler(timer2_Tick);
tm2.Enabled = true;
}
}
int ii = 4;
private void timer2_Tick(object sender, EventArgs e)
{
while (ii != 0)
{
buttonTwo.Text = "Reactivating in " + ii + " seconds";
ii -= 1;
}
if (ii == 0)
{
ii += 4;
tm2.Enabled = false;
buttonTwo.Enabled = true;
}
}


Here is what the code will do so far: When the button is clicked a
saying/label
will appear. The name of the button will change to
"Click To Hide Saying"
. When it is clicked again, the label will disappear and the text will say
"Reactivating in (ii) seconds"
(ii is the time left on the reactivation).

What I want it to do is to go back to
buttonTwo_Click
Event when
ii = 0
(or when the button delay is up). If you have a solution to this problem or another way of doing it I would really appreciate it.

Answer

For ease and reusability, take the actual work out of the event and put it in a function. This can be then used by the event and when the timer hits 0

Edit: You had a While instead of an If too.

public void Form1_Load(object sender, EventArgs e)
{
    tm2.Interval = 1000;
    tm2.Tick += timer2_Tick;
}

private void buttonTwo_Click(object sender, EventArgs e)
{
    DoClickWork();
}
System.Windows.Forms.Timer tm2 = new System.Windows.Forms.Timer();


private void DoClickWork()
{
    buttonTwo.Text = "Reactivating in 5 seconds";
    buttonTwo.Enabled = false;
    tm2.Enabled = true;
    sayingTwo.Visible = false;

}
int ii = 4;
private void timer2_Tick(object sender, EventArgs e)
{
    if (ii != 0)
    {
        ii -= 1;
        buttonTwo.Text = "Reactivating in " + ii + " seconds";
    }
    if (ii == 0)
    {
        ii += 4;
        tm2.Enabled = false;
        buttonTwo.Enabled = true;
        buttonTwo.Text = "Click To Hide Saying";
        sayingTwo.Visible = true;

    }
}

}