-1

Hi Ive got a label on my form that i want to press for 2.5 seconds before it does a function like display a message box I tried Using mouse down and mouse up but without success it didn't wait for the time i told it to. Anything would help.Thanks.

 private void Ltitelpress(object sender, EventArgs e)
    {
        lTitel.MouseDown+=delegate(object o, MouseEventArgs args) {  };
       Timer timer = new Timer();
        timer.Start();
        timer.Interval = 2500;
        if (timer.Interval == 2500)
        {
        lTitel.MouseUp+= delegate(object a, MouseEventArgs args)
        {
            timer.Stop();
            MessageBox.Show("Good Job");
        };

        }
    }

the problem is i don't even no if this code is even close to accurrite

2 Answers2

2

Declare a Stopwatch at the class level (form Level) so you can access it from 2 different event procedures.

private Stopwatch sw = new Stopwatch();
        private void label1_MouseDown(object sender, MouseEventArgs e)
        {
            sw.Start();
        }
        private void label1_MouseUp(object sender, MouseEventArgs e)
        {
            sw.Stop();
            if (sw.ElapsedMilliseconds > 2500)
                MessageBox.Show("Mouse held down long enough.");
            else
                MessageBox.Show("Not long enough.");
        }
Mary
  • 14,926
  • 3
  • 18
  • 27
0

Just move your codes to MouseUP event of the Label and it will fire only when you release the mouse click from the label

private void label_MouseUP()
///codes here

or if you wanna do it the hard way :)

private void label_MouseDown()
  var watch = System.Diagnostics.Stopwatch.StartNew();
  double elapsedMs = watch.ElapsedMilliseconds;

   if (elapsedMs > 2500)
    { 
     ////codes here
    }
Software Dev
  • 5,368
  • 5
  • 22
  • 45