c# how to have a Timer Close a Winform

Booney 166 Reputation points
2021-02-20T19:50:43.367+00:00

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 starts. This is what I have so far that closes the Form.

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();

        }


    }
}
Developer technologies | Windows Forms
Developer technologies | C#
{count} votes

Accepted answer
  1. Castorix31 90,681 Reputation points
    2021-02-21T11:00:45.947+00:00

    A way with a Countdown =>

    (add a Label label1...)

    70346-formclosecountdown.gif

    public partial class Form1 : Form  
    {  
        [DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Unicode)]  
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);  
      
        [DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Unicode)]  
        public static extern bool EndDialog(IntPtr hDlg, int nResult);  
      
        [DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Unicode)]  
        public static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);  
      
        public const int GW_HWNDFIRST = 0;  
        public const int GW_HWNDLAST = 1;  
        public const int GW_HWNDNEXT = 2;  
        public const int GW_HWNDPREV = 3;  
        public const int GW_OWNER = 4;  
        public const int GW_CHILD = 5;  
        public const int GW_ENABLEDPOPUP = 6;  
      
        [DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Unicode)]  
        private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);  
      
        [DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Unicode)]  
        private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);  
      
        [DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Unicode)]  
        public static extern bool SetWindowText(IntPtr hWnd, string Text);  
      
        [DllImport("User32.dll", EntryPoint = "GetWindowLong", CharSet = CharSet.Unicode)]  
        private static extern long GetWindowLong32(IntPtr hWnd, int nIndex);  
      
        [DllImport("User32.dll", EntryPoint = "GetWindowLongPtr", CharSet = CharSet.Unicode)]  
        private static extern long GetWindowLongPtr64(IntPtr hWnd, int nIndex);  
      
        public static long GetWindowLong(IntPtr hWnd, int nIndex)  
        {  
            if (IntPtr.Size == 4)  
            {  
                return GetWindowLong32(hWnd, nIndex);  
            }  
            return GetWindowLongPtr64(hWnd, nIndex);  
        }  
      
        public const int GWL_STYLE = (-16);  
        public const int GWL_EXSTYLE = (-20);  
      
        public const int SS_ICON  =  0x00000003;  
      
      
        System.Timers.Timer timer1;  
        System.Timers.Timer timerMessageBox;  
        double nCurrentTime = 0, nTotalTime = 20 * 1000, nCountDown = 10 * 1000;  
        // Choose an unique title...  
        string sTitle = "Information";  
        int nResult = (int)DialogResult.Cancel;  
      
        public Form1()  
        {  
            InitializeComponent();  
        }  
      
        private void Form1_Load(object sender, EventArgs e)  
        {  
            label1.Text = "";  
            timer1 = new System.Timers.Timer(1 * 1000);  
            timer1.Elapsed += OnTimedEvent;  
            timer1.Start();  
        }  
      
        private void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)  
        {  
            nCurrentTime += timer1.Interval;  
            label1.Invoke((Action)(() => label1.Text = (nCurrentTime/1000).ToString()));  
            if (nCurrentTime >= nTotalTime - nCountDown)  
            {  
                IntPtr hWndDest = FindWindow(null, sTitle);  
                if (hWndDest == IntPtr.Zero && nResult != (int)DialogResult.OK)  
                {  
                    timerMessageBox = new System.Timers.Timer(nCountDown);  
                    timerMessageBox.Elapsed += OnTimedMessageBoxEvent;  
                    timerMessageBox.Start();                     
                    nResult = (int)System.Windows.Forms.MessageBox.Show("The form will close in 10 seconds", sTitle, MessageBoxButtons.OKCancel, MessageBoxIcon.Question);  
                    timerMessageBox.Stop();  
                    if (nResult == (int)DialogResult.Cancel)  
                    {  
                        nCurrentTime = 0;  
                        timer1.Stop();  
                        timer1.Start();  
                    }  
                    //else if (nResult == (int)DialogResult.OK)  
                    //{  
                    //    //timer1.Stop();  
                    //    //Application.Exit();  
                    //}  
                }  
                else  
                {  
                    IntPtr hWndChild = GetWindow(hWndDest, GW_CHILD);  
                    bool bFound = false;  
                    while (!bFound && hWndChild != IntPtr.Zero)  
                    {  
                        StringBuilder sbBufferClass = new StringBuilder(260);  
                        GetClassName(hWndChild, sbBufferClass, sbBufferClass.Capacity);  
                        if (sbBufferClass.ToString() == "Static")  
                        {  
                            long nStyle = GetWindowLong(hWndChild, GWL_STYLE);  
                            if ((nStyle & SS_ICON) != 0)  
                            {  
                                StringBuilder sbBufferText = new StringBuilder(260);  
                                GetWindowText(hWndChild, sbBufferText, sbBufferText.Capacity);  
                                if (sbBufferText.ToString() != null)  
                                    bFound = true;  
                            }  
                        }                         
                        hWndChild = GetWindow(hWndChild, GW_HWNDNEXT);  
                    }  
                    if (bFound)  
                    {  
                        string sMessage = string.Format("The form will close in {0} seconds", (nTotalTime - nCurrentTime)/1000);  
                        SetWindowText(hWndChild, sMessage);  
                    }  
                    if (nCurrentTime >= nTotalTime)  
                    {  
                        if (nResult == (int)DialogResult.OK)  
                        {  
                            timer1.Stop();  
                            Application.Exit();  
                        }  
                    }  
                }  
            }             
        }  
      
        private void OnTimedMessageBoxEvent(object source, System.Timers.ElapsedEventArgs e)  
        {  
            nResult = (int)DialogResult.OK;  
            IntPtr hWndDest = FindWindow(null, sTitle);            
            EndDialog(hWndDest, nResult);             
        }  
    }  
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-02-21T02:41:05.72+00:00

    Hello,

    You can interject in the Closing event and if there is a need to cancel use e.Cancel from the argument in the Closing event.

    Code sample from the link above and in this case disregard the TextBox aspect.

    private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)  
    {  
       // Determine if text has changed in the textbox by comparing to original text.  
       if (textBox1.Text != strMyOriginalText)  
       {  
          // Display a MsgBox asking the user to save changes or abort.  
          if(MessageBox.Show("Do you want to save changes to your text?", "My Application",  
             MessageBoxButtons.YesNo) ==  DialogResult.Yes)  
          {  
             // Cancel the Closing event from closing the form.  
             e.Cancel = true;  
             // Call method to save file...  
          }  
       }  
    }  
    
    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.