0

I have created a windows form application in c# in which input from user is taken .I want to calculate time spent by user in between two submissions.How can I do that?

Manuj
  • 253
  • 1
  • 7
  • 14

3 Answers3

4

Use Stopwatch. Create object of the Stopwatch at class level and use that to calculate time.

Something like:

 public partial class Form1 : Form
    {
        Stopwatch stopwatch = new Stopwatch();

        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            stopwatch.Start();

        }
        private void button2_Click(object sender, EventArgs e)
        {

            stopwatch.Stop();
            var milliSeocnds = stopwatch.ElapsedMilliseconds;
            var timeSpan = stopwatch.Elapsed;
        }
    }
Habib
  • 219,104
  • 29
  • 407
  • 436
3

You can use two global DateTime variable and in click twice button diff to variable;

   private DateTime btn1Click ;
   private DateTime btn2click;


        private void btn1_Click(object sender, EventArgs e)
        {
            btn1Click = DateTime.Now;
        }

        private void btn2_Click(object sender, EventArgs e)
        {
            btn2click = DateTime.Now;
        }

and use this code for diff time:

 TimeSpan timespan = btn2click - btn1Click;

In same button :

  private DateTime btnClick1 ;
        private DateTime btnClick2;

  private void btn_Click(object sender, EventArgs e)
        {
            if (btnClick1==null)
            {
                btnClick1 = DateTime.Now;
            }
            else
            {
                btnClick2 = DateTime.Now;
            }
        }
hamid reza mansouri
  • 11,035
  • 2
  • 22
  • 32
  • 1
    http://stackoverflow.com/questions/28637/is-datetime-now-the-best-way-to-measure-a-functions-performance – Habib Oct 24 '12 at 12:25
  • I want to calculate duration between two clicks for same button in same form – Manuj Oct 24 '12 at 12:45
0

Using System.Threading you can use the stopwatch function. Just start the function on the first click and stop it on the second.

Using System.Threading

//main etc ignored

//declare

Stopwatch s = new Stopwatch();

//start
s.start();
//stop
s.stop()
//get the time
s.Elapsed;
LukeJenx
  • 63
  • 1
  • 10