Search code examples
c#labellong-press

A Label in C# That has a long press


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


Solution

  • 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.");
            }