How to detect if user is shaking form c# (detect shake),

Viewed 97

I've made a paint clone and want to clear the bord when you shake the form, (so by holding mouse1 down on the top bar and moving it right and left fast). I tried to compare two points on the x-axis, the points are set based on the mouse position and tested against a treshold. And I added a combo so you need to overcome the treshold multiple times to avoid accidental activation, to help with this there is also a timer that resets the combo. The problem is that it sees fast movement to one side as a shake I still want the user to be able to move the form without clearing the canvas.

        int firstpos = 0;
        int secondpos = 0;
        bool isfirst = true;
        int combo = 0;
        int threshold = 50;
        Point lastPoint;

        private void TopBar_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)//to move the form
            {
                this.Left += e.X - lastPoint.X;
                this.Top += e.Y - lastPoint.Y;
            }
            if (isfirst)
            {
                firstpos = e.X;
                isfirst = false;
            }
            else
            {
                secondpos = e.X;
                int diff = secondpos - firstpos;
                if (diff < 0) diff *= -1;//make positive
                if (diff >= threshold)
                {
                    combo++;
                    Thread t = new Thread(startdecay);
                    t.Start();
                }
                if (combo == 4)
                {
                    canvas.Invalidate();//clear the canvas
                    combo = 0;
                }
                isfirst = true;
            }
        }

        void startdecay()
        {
            Thread.Sleep(1000);
            combo = 0;
        }

        private void TopBar_MouseDown(object sender, MouseEventArgs e)
        {
            lastPoint = new Point(e.X, e.Y);
        }

the form

1 Answers
isfirst == true: Save firstpos.
                 Set isfirst = false.

isfirst == false: Get secondpos.
                  Get diff.
                  if Math.Sign(diff) != saveddiff {
                      increment shakecounter.
                      Set saveddiff = Math.Sign(diff).
                  }
                  Set firstpos = secondpos.

Accept when shakecounter over some value desired.

Don't forget to reset everything when Mouse Button goes up.

Related