Click here to Skip to main content
15,881,092 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Simple C# Winform I have a Timer that close the From. I would like to have a Message box popup saying its closing.
If no response then close if user clicks cancel then the Timer restarts. This is what I have so far that closes the Form.

What I have tried:

using Timer = System.Windows.Forms.Timer;
    
  private void Form1_Load(object sender, EventArgs e)
         {        
             // Timer to Close App
             Timer MyTimer = new Timer();   
             MyTimer.Interval = (1 * 60 * 1000); // 1 mins
             MyTimer.Tick += new EventHandler(timer1_Tick);
             MyTimer.Start();
         }
                  
    
         private void timer1_Tick(object sender, EventArgs e)
         {
               
             label9.Text = (int.Parse(label9.Text) - 1).ToString();
             if (int.Parse(label9.Text) == 0)  //if the countdown reaches '0', we stop it
                        
             //  MessageBox.Show("The form will now be closed.", "Time Elapsed");
    
             this.Close();
    
         }
    
    
     }
 }
Posted
Updated 20-Feb-21 21:24pm

Try it like this :
C#
private int[] myTimer = new[] { 10, 1, 3 };

private void Timer1_Tick(System.Object sender, System.EventArgs e)
{
    Label9.Text = myTimer[0].ToString() + " " + myTimer[1].ToString() + " " + myTimer[2].ToString();

    if (myTimer[0] > 0)
        myTimer[0] -= 1;
    else if (myTimer[1] > 0)
    {
        myTimer[1] -= 1;
        DialogResult Result = MessageBox.Show("The form will now be closed.", "Time Elapsed", MessageBoxButtons.OKCancel);
        if (Result == Windows.Forms.DialogResult.Cancel)
        {
            myTimer[0] = 10;
            myTimer[1] = 1;
            myTimer[2] = 3;
        }
        else
            this.Close();
    }
    else if (myTimer[2] > 0)
        myTimer[2] -= 1;
    else if (myTimer[2] == 0)
        SendKeys.Send(Constants.vbCr);
}


Code modified after clarification ...
 
Share this answer
 
v3
Comments
Member 12349103 20-Feb-21 15:55pm    
Ralf If the user does nothing the form still stays open
RickZeeland 20-Feb-21 16:15pm    
Don't use a messagebox but a form which will not block and will be closed with the main application.
Member 12349103 20-Feb-21 16:36pm    
do you have an example
Ralf Meier 20-Feb-21 18:21pm    
I have modified my cide-snippet - please take a look and try once more ...
RickZeeland 22-Feb-21 1:14am    
5d as you did most of the work :)
MessageBox won't let you do that, because it's a Modal form - your UI thread is effectively suspended until the you closes the MessageBox so your timer will not function.

Instead of using a MessageBox, you need to create your own form which contains it's own Timer, and which closes itself when that expires. You then display that from your first form using myNewForm.ShowDialog.
 
Share this answer
 
For some reason Ralfs solution did not work when I tested it, here is my modified version.
I would not recommend using the forms Timer btw. it can lead to problems with e.g. threading, better use a system Timer.
using System;
using System.Windows.Forms;

namespace WinFormsTimer1
{
    public partial class Form1 : Form
    {
        private int[] myTimer = new[] { 10, 1, 3 };

        public Form1()
        {
            InitializeComponent();

            // Timer to Close App
            System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();
            MyTimer.Interval = (5000); // 5 seconds
            MyTimer.Tick += new EventHandler(Timer1_Tick);
            MyTimer.Start();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Initializing myTimer here does not work ???
        }

        private void Timer1_Tick(Object myObject, EventArgs myEventArgs)
        {
            this.label1.Text = myTimer[0].ToString() + " " + myTimer[1].ToString() + " " + myTimer[2].ToString();

            if (myTimer[0] > 0)
            {
                myTimer[0] -= 1;
            }
            else if (myTimer[1] > 0)
            {
                myTimer[1] -= 1;
                DialogResult Result = MessageBox.Show("The form will now be closed.", "Time Elapsed", MessageBoxButtons.OKCancel);

                if (Result == DialogResult.Cancel)
                {
                    myTimer[0] = 10;
                    myTimer[1] = 1;
                    myTimer[2] = 3;
                }
                else
                {
                    this.Close();
                }
            }
            else if (myTimer[2] > 0)
            {
                myTimer[2] -= 1;
            }
            else if (myTimer[2] == 0)
            {
                SendKeys.Send("\r");
            }
        }
    }
}
 
Share this answer
 
Comments
Ralf Meier 21-Feb-21 3:56am    
Hi Rick,
where is the difference between your code and mine ?
Of course ... I only provided the Timer-part assuming that the rest is still working ...
RickZeeland 21-Feb-21 7:38am    
Hi Ralf, your routine is fine, but OP probably calls it from Form1_Load() and then it won't work (at least not in my test application).
Member 12349103 21-Feb-21 17:47pm    
this is working for me, but way are the 3 times show in the label?
RickZeeland 22-Feb-21 1:15am    
That's the "final countdown" :)
Ralf Meier 22-Feb-21 6:14am    
It is a kind of Statemachine - I made it as follows :
The first time is your time before showing the Messagebox.
The next (2nd) time is for showing the Messagebox.
the 3rd time is the time you cvanmn see the Messagebox before it shuts down automaticly ...

My Timer-Tick was 1 Second - so that is also the base of this times.
And in case you want to try the solution without a MessageBox:
using System;
using System.Drawing;
using System.Windows.Forms;

namespace WinFormsTimer1
{
    public partial class Form1 : Form
    {
        System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();

        private Form form2 = new Form();

        bool form2Shown;

        public Form1()
        {
            InitializeComponent();

            // Timer to Close App
            MyTimer.Interval = (5000); // 5 seconds
            MyTimer.Tick += new EventHandler(Timer1_Tick2);
            MyTimer.Start();
            this.label1.Text = MyTimer.Interval / 1000 + " seconds remaining";
        }

        /// <summary>
        /// Closes the main form and form2 on the second Tick if needed.
        /// </summary>
        private void Timer1_Tick2(Object myObject, EventArgs myEventArgs)
        {
            if (form2Shown)
            {
                this.Close();
            }
            else
            {
                ShowForm2("Time Elapsed", "The form will now be closed.");
                form2Shown = true;
            }
        }

        /// <summary>
        /// MessageBox replacement.
        /// </summary>
        private void ShowForm2(string caption, string message)
        {
            form2.StartPosition = FormStartPosition.CenterScreen;
            form2.ClientSize = new Size(300, 200);
            form2.TopMost = true;
            form2.Text = caption;

            Label label1 = new Label();
            label1.Location = new Point(50, 50);
            label1.AutoSize = true;
            label1.Text = message;

            Button buttonOk = new Button();
            buttonOk.Location = new Point(140, 150);
            buttonOk.Anchor = AnchorStyles.Bottom;
            buttonOk.Text = "Ok";
            buttonOk.Click += new EventHandler(CloseForm);

            form2.Controls.Add(label1);
            form2.Controls.Add(buttonOk);
            form2.Show();
        }

        private void CloseForm(Object myObject, EventArgs myEventArgs)
        {
            this.Close();
        }
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900