Saturday, October 1, 2022

#1 2019-10-24 11:27:56 am

From:: Greece
Registered: 2019-03-03
Posts: 2524

Getting Mouse Location

For such a simple task as obtaining mouse coordinates, there is no need to use third-party solutions. I decided to write this short article, as I often come across articles like this: Mouse Location with OS 10.2.
Here is one fine solution with AsObjC:


use framework "AppKit"

-- Get coordinates from bottom left corner
set |mouseLocation| to current application's NSEvent's mouseLocation()
----> {176.671875, 690.0234375}

-- Get current screen resolution
tell application "Finder" to set theDesctopBounds to bounds of window of desktop
----> {0, 0, 1280, 800}

-- Get coordinates from top left corner
set |mouseLocation| to {|mouseLocation|'s x, (item 4 of theDesctopBounds) - (|mouseLocation|'s y)}
----> {176.671875, 109.9765625}

Last edited by KniazidisR (2019-10-24 11:45:30 am)

Model: MacBook Pro
OS X: Catalina 10.15.7
Web Browser: Safari 14.1
Ram: 4 GB



#2 2022-08-27 10:30:19 am

From:: Prescott, Arizona
Registered: 2018-09-04
Posts: 1465

Re: Getting Mouse Location

Thanks KniazidisR--this is exactly what I was looking for.

FWIW, I modified the script slightly to eliminate Finder and to place everything in a handler. The cursor position is rounded down to the nearest whole number, although that's easily changed. I tested this script on Monterey, and it may not work on earlier macOS versions.


use framework "AppKit"
use framework "Foundation"
use scripting additions

set cursorPosition to getCursorPosition()

on getCursorPosition()
   set cursorPosition to current application's NSEvent's mouseLocation()
   set {{x1, y1}, {x2, y2}} to (current application's NSScreen's mainScreen())'s frame()
   return {(cursorPosition's x as integer), (y2 as integer) - (cursorPosition's y as integer)}
end getCursorPosition

Last edited by peavine (2022-08-27 03:57:41 pm)

2018 Mac mini - macOS Monterey - Script Debugger 8



Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)