簡単な 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;
}
}