用于WPF的窗体移动很好用

点击事件

     public bool beginMove = false;//初始化鼠标位置
        public int currentXPosition;
        public int currentYPosition;

        private void _MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                beginMove = true;
                MouseHelper.POINT ponint;
                MouseHelper.GetCursorPos(out ponint);
                currentXPosition = ponint.X;//鼠标的x坐标为当前窗体左上角x坐标
                currentYPosition = ponint.Y;//鼠标的y坐标为当前窗体左上角y坐标
            }
        }

        private void _MouseMove(object sender, MouseEventArgs e)
        {
            if (beginMove)
            {
                MouseHelper.POINT ponint;
                MouseHelper.GetCursorPos(out ponint);
                this.Left += ponint.X - currentXPosition;//根据鼠标x坐标确定窗体的左边坐标x
                this.Top += ponint.Y - currentYPosition;//根据鼠标的y坐标窗体的顶部,即Y坐标
                currentXPosition = ponint.X;
                currentYPosition = ponint.Y;
            }
        }

        private void _MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                currentXPosition = 0; //设置初始状态
                currentYPosition = 0;
                beginMove = false;
            }
        }

鼠标位置帮助类

  public class MouseHelper
    {
        /// <summary>
        /// 设置鼠标的坐标
        /// </summary>
        /// <param name="x">横坐标</param>
        /// <param name="y">纵坐标</param>          

        [DllImport("User32")]

        public extern static void SetCursorPos(int x, int y);
        public struct POINT
        {
            public int X;
            public int Y;
            public POINT(int x, int y)
            {
                this.X = x;
                this.Y = y;
            }
        }

        /// <summary>
        /// 获取鼠标的坐标
        /// </summary>
        /// <param name="lpPoint">传址参数,坐标point类型</param>
        /// <returns>获取成功返回真</returns>   

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern bool GetCursorPos(out POINT pt);
    }

 

posted @ 2020-07-24 11:00  Sorry名米  阅读(381)  评论(0编辑  收藏  举报