Click here to Skip to main content
15,949,686 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i have a button that does many different functions with one click. and a textbox. when the button is clicked i want those functions to be repeated every x minutes. and x minutes represents the value of the textbox. and if the texbox is blank. to not repeat. also another button that will stop the timer. how do i do this? i dont know timers and im guessing this is a good way to learn..
Posted

public partial class Form1 : Form
{
   Timer theTimer = new Timer();
   public int countdown { get; set; }
   
   public Form1()
   {
      InitializeComponent();
      theTimer.Tick += new EventHandler(theTimer_Tick);
   }

   void theTimer_Tick(object sender, EventArgs e)
   {
      //Work the Functions
   }

   private void btn_StopTimer_Click(object sender, EventArgs e)
   {
      if (theTimer.Enabled)
         theTimer.Stop();
   }

   private void btn_StartTimer_Click(object sender, EventArgs e)
   {
      if (this.txt_TimerInterval.Text != "")
      {
         int theInterval = 0;
         if (Int32.TryParse(this.txt_TimerInterval.Text, out theInterval))
         {
            if (theInterval != 0)
            {
               theTimer.Interval = theInterval * 1000;
               theTimer.Start();
            }
         }
       }
       else
       {
          btn_StopTimer_Click(null, null);
       }
   }
}


Just a dummy form I created. It contains 2 buttons, btn_StartTimer starts the timer, btn_StopTimer stops the timer. txt_TimerInterval is the textbox where you want to set the minutes to run the timer
 
Share this answer
 
Comments
johannesnestler 30-Jun-11 8:15am    
oh yes you are right! It seems I have read the OPs requirements too fast...
vlad781 30-Jun-11 12:49pm    
amzing. i even understood all of it thanks a lot. 5/5
Hi vlad781,

I created an executable example based on your requirements for you.
(I wouldn't recommend using a textbox for repetition input, have a look at NumericUpDown). Feel free to ask if anything is unclear...

using System;
using System.Windows.Forms;

namespace Repeat
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            // Create a test Form with Buttons and a Textbox to enter the repetition count
            Form form = new Form();
            Button buttonStart = new Button();
            buttonStart.Text = "Start";
            buttonStart.Dock = DockStyle.Top;
            Button buttonStop = new Button();
            buttonStop.Text = "Stop";
            buttonStop.Dock = DockStyle.Top;
            TextBox textbox = new TextBox();
            textbox.Dock = DockStyle.Top;
            form.Controls.Add(buttonStop);
            form.Controls.Add(buttonStart);
            form.Controls.Add(textbox);

            // Create a timer
            Timer timer = new Timer();
            timer.Interval = 60000; // set the timer interval to one minute
 
            int iRepetitionCount = 0; // Number of remainig repetitions

            // Add event handlers for the button Click-Events

            buttonStart.Click += delegate(object sender, EventArgs e)
            {
                // Restarting also stops the timer
                timer.Stop();

                if (String.IsNullOrWhiteSpace(textbox.Text)) // Textbox empty?
                {
                    // Just call the function once
                    TheFunction();
                }
                else
                {
                    // Try to get the entered repetition value
                    iRepetitionCount = 0; // reset
                    if (!Int32.TryParse(textbox.Text, out iRepetitionCount))
                    {
                        MessageBox.Show("Invalid repetition count");// The entered text could not be converted to an integer
                        return;
                    }

                    // Call the function now 
                    TheFunction();
                    iRepetitionCount--;  // Decrement the repetition counter
                    // ... and start the timer (on timer.Tick the Function will be called again)
                    timer.Start();
                }
            };

            buttonStop.Click += delegate(object sender, EventArgs e)
            {
                // Stop the repetition timer
                timer.Stop();
            };

            // Add event handlers for the timer Tick-Events

            timer.Tick += delegate(object sender, EventArgs e)
            {
                if (iRepetitionCount <= 0) // no more repetitions?
                {
                    timer.Stop(); // stop the timer now
                }
                else
                {
                    iRepetitionCount--; // Decrement the repetition counter
                    TheFunction(); // Call the function
                }
            };

            // Run the form
            Application.Run(form);
        }

        static void TheFunction()
        {
            MessageBox.Show("I was called at " + DateTime.Now.ToString());
        }
    }
}
 
Share this answer
 
Comments
johannesnestler 30-Jun-11 8:16am    
Sorry, I mis-read the requirements - UJimbo's solution is correct. Anyway I leave my code unchanged.
UJimbo 30-Jun-11 8:41am    
Wicked coding non the less. Nice work there mate
vlad781 30-Jun-11 12:48pm    
looks, awesome. but i didnt want the static main thread. i give you a 3/5
You better should use threads.
http://msdn.microsoft.com/en-us/library/7a2f3ay4(v=vs.80).aspx[^]

To elapse the time, you can use Thread.Sleep within thread loop.
 
Share this answer
 
Comments
Pete O'Hanlon 30-Jun-11 6:05am    
Thread.Sleep is not a good practice to pause threads, as it blocks everything on that thread - which means you can't selectively poke it to cancel it. You have to abort those threads.
Sergey Alexandrovich Kryukov 1-Jul-11 2:05am    
This is correct solution, my 5. Nothing else on the thread should run, that's it. Sleep does not block thread forever: abort is perfectly robust and safe.
--SA
Pete O'Hanlon 1-Jul-11 3:49am    
Sorry mate, you know I have a lot of time for you, but in this case you can't state that this is the correct solution. You can only state that it might be correct. We don't know whether the OP has any operations that must be disposed of cleanly, so it is dangerous to state that Abort is perfectly robust and safe - it isn't; it terminates the thread instantly, so any freeing up of resources will not take place. Trust me on this, it's dangerous to rely on this behaviour, and other, better methods exist.

The bottom line is - not everybody is as aware of the intricacies and subtleties of threading as you are, so it is hard for them to know when it is acceptable to cross the line. Hence my recommendation not to rely on Thread.Abort.
Sergey Alexandrovich Kryukov 3-Jul-11 1:43am    
Well, I have to agree with you; in general case it may or may not be the applicable solution.

Nevertheless I think this is a good valuable advice which ***very well might*** be a good solution in many cases.

(Prerak, you see: I defended your solution as hard as I can. :-))
--SA
Prerak Patel 4-Jul-11 1:23am    
Thanks SA... But OP was interested in timer only.

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