利用api 函数 ClipCursor和GetWindowRect可以实现限定鼠标移动范围的功能。
[System.Runtime.InteropServices.DllImport("user32", EntryPoint = "ClipCursor")]
public extern static int ClipCursor(ref RECT lpRect);
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "GetWindowRect")]
public extern static int GetWindowRect(int hwnd, ref RECT lpRect);
public struct RECT//声明参数的值
{
public int left;
public int top;
public int right;
public int bottom;
}
public void Lock(System.Windows.Forms.Form ObjectForm)
{
RECT _FormRect = new RECT();
GetWindowRect(ObjectForm.Handle.ToInt32(), ref _FormRect);
ClipCursor(ref _FormRect);
}
public void UnLock()
{
RECT _ScreenRect = new RECT();
_ScreenRect.top = 0;
_ScreenRect.left = 0;
_ScreenRect.bottom = int.MaxValue; ;
_ScreenRect.right = int.MaxValue;
ClipCursor(ref _ScreenRect);
}
private void bntKong_Click(object sender, EventArgs e)
{
this.Lock(this);
}
private void bntMove_Click(object sender, EventArgs e)
{
this.UnLock();
}