write a python script that confines the mouse cursor in a user defined rectangle on the…
- User
write a python script that confines the mouse cursor in a user defined rectangle on the screen on macos (not windows). if you want you can also use other languages like c or javascript.
Assistant
I'll create a Python script that confines the mouse cursor to a rectangle on macOS using the Quartz (Core Graphics) framework through PyObjC.
#!/usr/bin/env python3 """ Mouse cursor confinement script for macOS Confines the mouse cursor within a user-defined rectangle """ import time import sys from Quartz import ( CGEventCreateMouseEvent, CGEventPost, kCGEventMouseMoved, kCGMouseEventSource, CGEventGetLocation, CGEventCreate, kCGHIDEventTap ) from AppKit import NSEvent, NSApplication, NSApp import threading class MouseConfinement: def __init__(self, x, y, width, height): """ Initialize the confinement rectangle Args: x: Left edge of rectangle y: Top edge of rectangle width: Width of rectangle height: Height of rectangle """ self.rect_x = x self.rect_y = y self.rect_width = width self.rect_height = height self.active = False # Calculate boundaries self.min_x = x self.max_x = x + width self.min_y = y self.max_y = y + height def get_mouse_position(self): """Get current mouse position""" event = CGEventCreate(None) location = CGEventGetLocation(event) return location.x, location.y def set_mouse_position(self, x, y): """Set mouse position to specific coordinates""" move_event = CGEventCreateMouseEvent( kCGMouseEventSource, kCGEventMouseMoved, (x, y), 0 ) CGEventPost(kCGHIDEventTap, move_event) def confine_cursor(self): """Main loop to confine cursor within rectangle""" print(f"Confining mouse to rectangle: ({self.rect_x}, {self.rect_y}) " f"with size {self.rect_width}x{self.rect_height}") print("Press Ctrl+C to stop...") while self.active: try: x, y = self.get_mouse_position() # Check if cursor is outside boundaries and adjust new_x, new_y = x, y if x < self.min_x: new_x = self.min_x elif x > self.max_x: new_x = self.max_x if y < self.min_y: new_y = self.min_y elif y > self.max_y: new_y = self.max_y # Only move if position changed if new_x != x or new_y != y: self.set_mouse_position(new_x, new_y) # Small delay to prevent excessive CPU usage time.sleep(0.01) except KeyboardInterrupt: break except Exception as e: print(f"Error: {e}") break def start(self): """Start confining the cursor""" self.active = True self.confine_cursor() def stop(self): """Stop confining the cursor""" self.active = False def main(): # Example usage with different preset rectangles print("Mouse Confinement Tool for macOS") print("================================") print("\nSelect a confinement area:") print("1. Top-left quarter of screen (0, 0, 960, 540)") print("2. Center box (500, 300, 600, 400)") print("3. Full left half (0, 0, 960, 1080)") print("4. Custom rectangle") choice = input("\nEnter your choice (1-4): ").strip() if choice == '1': x, y, width, height = 0, 0, 960, 540 elif choice == '2': x, y, width, height = 500, 300, 600, 400 elif choice == '3': x, y, width, height = 0, 0, 960, 1080 elif choice == '4': print("\nEnter custom rectangle parameters:") x = int(input("X position (left edge): ")) y = int(input("Y position (top edge): ")) width = int(input("Width: ")) height = int(input("Height: ")) else: print("Invalid choice!") return # Create and start confinement confinement = MouseConfinement(x, y, width, height) try: confinement.start() except KeyboardInterrupt: print("\nStopping mouse confinement...") finally: confinement.stop() print("Mouse confinement ended.") if __name__ == "__main__": # Check if running on macOS import platform if platform.system() != 'Darwin': print("This script only works on macOS!") sys.exit(1) # Check for required permissions print("Note: This script requires accessibility permissions.") print("You may need to grant Terminal/Python access in:") print("System Preferences > Security & Privacy > Privacy > Accessibility") print() main()To use this script:
- Install PyObjC (if not already installed):
pip install pyobjc-framework-Quartz pyobjc-framework-AppKit-
Grant accessibility permissions:
- Go to System Preferences → Security & Privacy → Privacy → Accessibility
- Add Terminal (or your Python interpreter) to the allowed apps
-
Run the script:
python mouse_confine.pyThe script provides several features:
- Preset confinement areas (quarter screen, center box, left half)
- Custom rectangle definition
- Smooth cursor movement restriction
- Low CPU usage with efficient polling
- Clean exit with Ctrl+C
How it works:
- Continuously monitors the mouse position using Core Graphics
- When the cursor moves outside the defined rectangle, it immediately moves it back to the nearest valid position
- Uses a small sleep interval to prevent excessive CPU usage while maintaining responsiveness
Alternative approach using Swift (if you prefer a compiled solution):
// MouseConfine.swift import Cocoa import CoreGraphics class MouseConfinement { var confinementRect: CGRect var isActive = false var timer: Timer? init(rect: CGRect) { self.confinementRect = rect } func start() { isActive = true timer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true) { _ in self.confineMouseCursor() } } func stop() { isActive = false timer?.invalidate() } private func confineMouseCursor() { let mouseLocation = NSEvent.mouseLocation var newLocation = mouseLocation // Adjust coordinates (NSEvent uses bottom-left origin) let screenHeight = NSScreen.main?.frame.height ?? 0 let currentY = screenHeight - mouseLocation.y if mouseLocation.x < confinementRect.minX { newLocation.x = confinementRect.minX } else if mouseLocation.x > confinementRect.maxX { newLocation.x = confinementRect.maxX } if currentY < confinementRect.minY { newLocation.y = screenHeight - confinementRect.minY } else if currentY > confinementRect.maxY { newLocation.y = screenHeight - confinementRect.maxY } if newLocation != mouseLocation { CGWarpMouseCursorPosition(CGPoint(x: newLocation.x, y: screenHeight - newLocation.y)) } } } // Usage example let rect = CGRect(x: 100, y: 100, width: 800, height: 600) let confinement = MouseConfinement(rect: rect) confinement.start()The Python solution is easier to get started with and modify, while the Swift version would be better for a production application that needs optimal performance.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.