WPF 限制或释放鼠标在窗体内移动
123
public class User32 { public struct RECT { public int LeftTopX; public int LeftTopY; public int RightBottomX; public int RightBottomY; public RECT(int ltx, int lty, int rbx, int rby) { LeftTopX = ltx; LeftTopY = lty; RightBottomX = rbx; RightBottomY = rby; } } [System.Runtime.InteropServices.DllImport("user32.dll")] static extern bool GetClipCursor(IntPtr lpRect); [System.Runtime.InteropServices.DllImport("user32.dll")] static extern bool ClipCursor(IntPtr lpRect); [System.Runtime.InteropServices.DllImport("User32.dll")] static extern bool ClipCursor(ref RECT lpRect); /// <summary> /// 限制 /// </summary> /// <param name="ltx"></param> /// <param name="lty"></param> /// <param name="rbx"></param> /// <param name="rby"></param> public static void ClipCursor(int ltx, int lty, int rbx, int rby) { RECT rect = new RECT(ltx, lty, rbx, rby); ClipCursor(ref rect); } /// <summary> /// 释放 /// </summary> public static void ClearCursor() { ClipCursor(IntPtr.Zero); } }
调用方式:
User32.ClipCursor( (int)(Left + SystemParameters.WindowNonClientFrameThickness.Left + SystemParameters.WindowResizeBorderThickness.Left), (int)(Top + SystemParameters.WindowNonClientFrameThickness.Left + SystemParameters.WindowNonClientFrameThickness.Top), (int)(Left + Width - SystemParameters.WindowResizeBorderThickness.Left * 2), (int)(Top + Height - SystemParameters.WindowResizeBorderThickness.Left * 2));
这里的坐标需要考虑窗体边框的宽度。
释放:
User32.ClearCursor();