Search code examples
c#formscountdown

get timer countdown from parent label


I have a countdown and it outputs to a label on the main form, I want to popout the countdown from the main form to a child form because the child form will be able to stay on top of all other windows (for game) I can't get it to updated the countdown on the child's label. I only get the second when i hit the popout button.

This is on the main form

    private void tmrMain_Tick(object sender, EventArgs e)
    {
        TimerSeconds = TimerSeconds - 1;
        if (TimerSeconds == 0)
        {
            tmrMain.Stop();
            if (chbxPlaySound.Checked)
            {
                System.Media.SystemSounds.Exclamation.Play();
            }
            if (chbxRepeat.Checked)
            {
                btnStartTimer.PerformClick();
            }
        }

        string dis_seconds = Convert.ToString(TimerSeconds);
        //
        // lblTimer is the label that shows the countdown seconds
        //
        lblTimer.Text = dis_seconds;

    }

This is my pop out button on the main form

    private void btnPopOut_Click(object sender, EventArgs e)
    {
        PopTimer ShowTimer = new PopTimer(TimerSeconds);
        ShowTimer.Show(this);
    }

This is my child form

public partial class PopTimer : Form
{
    public PopTimer(int countTimer)
    {
        InitializeComponent();
        //string dis_seconds = Convert.ToString(TimerSeconds);
        lblPopTimer.Text = Convert.ToString(countTimer); ;
    }
}

Solution

  • Your PopTimer form needs an accessible method, something like this:

    public void SetCountdown(int value) {
      lblPopTimer.Text = value.ToString();
    }
    

    Then your PopTimer needs to be accessible, so move the declaration:

    private PopTimer showTimer = null;
    
    private void btnPopOut_Click(object sender, EventArgs e)
    {
      showTimer = new PopTimer(timerSeconds);
      showTimer.Show(this);
    }
    

    Then in your tick event:

    if (showTimer != null) {
      showTimer.SetCountdown(timerSeconds);
    }