如何检测用户是否从 c# 中摇晃(检测摇晃),

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

我制作了一个绘画克隆,想在摇动表格时清除边框(因此,按住顶部栏上的 mouse1 并快速左右移动)。 我试图比较 x 轴上的两个点,这些点是根据鼠标位置设置的,并针对阈值进行了测试。我添加了一个组合,所以你需要多次克服阈值以避免意外激活,为了帮助解决这个问题,还有一个计时器可以重置组合。 问题是它把向一侧的快速移动看作是摇晃我仍然希望用户能够在不清除 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

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.

shakecounter 超过所需的某个值时接受。

不要忘记在鼠标按钮抬起时重置所有内容。