To confine the mouse cursor within a rectangle on macOS, we can use Python with PyObjC (Python Objective-C bridge) to interact with macOS APIs, or alternatively write in Swift/Objective-C directly.
Here’s a Python script using PyObjC that lets you define a rectangle and confines the mouse cursor within it:
✅ Requirements
Install pyobjc if not already installed:
pip install pyobjc
🐍 Python Script: Confine Mouse to Rectangle (macOS)
from AppKit import NSScreen, NSCursor
from Quartz import (
CGWarpMouseCursorPosition,
CGDisplayBounds,
CGMainDisplayID,
)
import time
import threading
import sys
# Define the rectangle boundaries (in screen coordinates)
RECTANGLE_BOUNDS = {
"x": 100,
"y": 100,
"width": 400,
"height": 300
}
def get_mouse_position():
from Quartz import CGEventCreateMouseEvent, kCGEventMouseMoved
from Quartz import CGEventGetLocation
from Foundation import NSEvent
# Create a dummy moved event to get current location
dummy_event = CGEventCreateMouseEvent(None, kCGEventMouseMoved, (0, 0), 0)
return CGEventGetLocation(dummy_event)
def confine_mouse():
display_id = CGMainDisplayID()
bounds = CGDisplayBounds(display_id)
rect = RECTANGLE_BOUNDS
min_x = rect["x"]
max_x = rect["x"] + rect["width"]
min_y = rect["y"]
max_y = rect["y"] + rect["height"]
print(f"Confining mouse to rectangle: ({min_x}, {min_y}) - ({max_x}, {max_y})")
print("Press Ctrl+C to stop.")
try:
while True:
pos = get_mouse_position()
x, y = pos.x, pos.y
# Constrain position
new_x = max(min_x, min(x, max_x))
new_y = max(min_y, min(y, max_y))
if new_x != x or new_y != y:
CGWarpMouseCursorPosition((new_x, new_y))
time.sleep(0.01) # Polling interval
except KeyboardInterrupt:
print("\nMouse confinement stopped.")
🔧 Run the script:
if __name__ == "__main__":
thread = threading.Thread(target=confine_mouse)
thread.daemon = True
thread.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("Exiting...")
sys.exit(0)
📝 Notes
- This script uses Quartz Event Services via PyObjC.
- It polls the mouse position every 10ms and warps it back into the defined rectangle.
- You can change
RECTANGLE_BOUNDS to any area of your screen.
- This does not block user input, but keeps pulling the cursor back — similar to how games often trap the mouse.
⚠️ Limitations
- macOS has limited support for true mouse capture compared to Windows/Linux.
- The cursor may briefly escape during fast movements, but will be pulled back.
- Works best when the app is active or system-wide accessibility permissions are granted.
✅ Optional Enhancements
- Add GUI to select the rectangle with mouse clicks.
- Use Swift for better integration with native APIs.
Would you like a Swift version or one that captures mouse events globally?