限制鼠标活动区域

1.首先是获取鼠标的绝对位置的类

class CursorPositionHelper
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            public int X;
            public int Y;
        }
        [DllImport("user32.dll", EntryPoint = "GetCursorPos", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool GetCursorPos(out POINT pt);
    }

2. 限制鼠标区域的类

    class ClipCursorHelper
    {

        [DllImport("user32.dll",EntryPoint = "ClipCursor",CharSet = CharSet.Auto,SetLastError = true)]
        static extern bool ClipCursor(ref RECT lpRect);

        public struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
            public RECT(Int32 left, Int32 top, Int32 right, Int32 bottom)
            {
                Left = left;
                Top = top;
                Right = right;
                Bottom = bottom;
            }
        }
    
        ///
        /// 限制鼠标光标的位置
        ///

        /// 限制矩形的左上角X坐标
        /// 限制矩形的左上角Y坐标
        /// 限制矩形的宽
        /// 限制矩形的高
        ///
        public static bool SetCursorPosition(int startX, int startY, int width, int height)
        {
            RECT rect = new RECT(startX, startY, startX + width, startY + height);
            return ClipCursor(ref rect);
        }
}

调用示例:

//获取鼠标的绝对坐标
CursorPositionHelper.POINT mouseAbsPoint = new CursorPositionHelper.POINT();
CursorPositionHelper.GetCursorPos(out mouseAbsPoint);
//限制鼠标的活动区域
ClipCursorHelper.SetCursorPosition(mouseAbsPoint.X, mouseAbsPoint.Y, 1, 1);

注:标红的部分,如果为1,则鼠标按下后,不可移动


你可能感兴趣的:(C#,WPF)