下面是一些您可以尝试的简单 Windows 窗体代码。它使用 SetWindowsHookEx 函数设置全局鼠标挂钩。在钩子方法中,它检查鼠标坐标是否在主屏幕的范围内,并在必要时调整坐标。当您运行此代码时,只要您只是移动鼠标,鼠标光标仍然能够离开主屏幕区域,但是一旦发生单击事件,它就会跳回来。您可能希望将我的代码与您的 ClipCursor 技术结合起来以防止这种情况发生。
public partial class Form1 : Form
{
private const int WH_MOUSE_LL = 14;
private delegate int HookProc(int code, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", EntryPoint = "SetWindowsHookEx", SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
Rectangle _ScreenBounds;
HookProc _HookProc;
public Form1()
{
InitializeComponent();
_ScreenBounds = Screen.PrimaryScreen.Bounds;
_HookProc = HookMethod;
IntPtr hook = SetWindowsHookEx(WH_MOUSE_LL, _HookProc, GetModuleHandle("user32"), 0);
if (hook == IntPtr.Zero) throw new System.ComponentModel.Win32Exception();
}
private int HookMethod(int code, IntPtr wParam, IntPtr lParam)
{
if (Cursor.Position.X < _ScreenBounds.Left)
{
Cursor.Position = new Point(_ScreenBounds.Left, Cursor.Position.Y);
}
else if (Cursor.Position.X > _ScreenBounds.Right)
{
Cursor.Position = new Point(_ScreenBounds.Right - 1, Cursor.Position.Y);
}
if (Cursor.Position.Y < _ScreenBounds.Top)
{
Cursor.Position = new Point(Cursor.Position.X, _ScreenBounds.Top);
}
else if (Cursor.Position.Y > _ScreenBounds.Bottom)
{
Cursor.Position = new Point(Cursor.Position.X, _ScreenBounds.Bottom - 1);
}
return 0;
}
}