Mouse position

From Rosetta Code
Jump to: navigation, search
Mouse position
You are encouraged to solve this task according to the task description, using any language you may know.
Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.


[edit] ActionScript

This shows the mouse position in a text field at the bottom-right corner and updates when the mouse is moved.

package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
public class MousePosition extends Sprite {
private var _textField:TextField = new TextField();
public function MousePosition() {
if ( stage ) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
private function init(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
_textField.autoSize = TextFieldAutoSize.RIGHT;
_textField.x = stage.stageWidth - 10;
_textField.defaultTextFormat = new TextFormat(null, 15);
_textField.text = "Mouse position: X = 0, Y = 0";
_textField.y = stage.stageHeight - _textField.textHeight - 14;
addEventListener(Event.ENTER_FRAME, _onEnterFrame);
private function _onEnterFrame(e:Event):void {
_textField.text = "Mouse position: X = " + stage.mouseX + ", Y = " + stage.mouseY;

[edit] Ada

Library: GTK version GtkAda
Library: GtkAda
Library: GLib

The GTK procedure is Get_Pointer. It returns mouse coordinates relatively to a window (internally created). The following program shows a button, which when pressed indicates coordinates of the mouse pointer relatively to the main window:

with GLib;        use GLib;
with Gtk.Button; use Gtk.Button;
with Gtk.Label; use Gtk.Label;
with Gtk.Window; use Gtk.Window;
with Gtk.Widget; use Gtk.Widget;
with Gtk.Table; use Gtk.Table;
with Gtk.Handlers;
with Gtk.Main;
procedure Tell_Mouse is
Window : Gtk_Window;
Grid  : Gtk_Table;
Button : Gtk_Button;
Label  : Gtk_Label;
package Handlers is new Gtk.Handlers.Callback (Gtk_Widget_Record);
package Return_Handlers is
new Gtk.Handlers.Return_Callback (Gtk_Widget_Record, Boolean);
function Delete_Event (Widget : access Gtk_Widget_Record'Class)
return Boolean is
return False;
end Delete_Event;
procedure Destroy (Widget : access Gtk_Widget_Record'Class) is
end Destroy;
procedure Clicked (Widget : access Gtk_Widget_Record'Class) is
X, Y : GInt;
Get_Pointer (Window, X, Y);
Set_Text (Label, "At" & GInt'Image (X) & GInt'Image (Y));
end Clicked;
Gtk.Window.Gtk_New (Window);
Gtk_New (Grid, 1, 2, False);
Add (Window, Grid);
Gtk_New (Label);
Attach (Grid, Label, 0, 1, 0, 1);
Gtk_New (Button, "Click me");
Attach (Grid, Button, 0, 1, 1, 2);
( Window,
Return_Handlers.To_Marshaller (Delete_Event'Access)
( Window,
Handlers.To_Marshaller (Destroy'Access)
( Button,
Handlers.To_Marshaller (Clicked'Access)
Show_All (Grid);
Show (Window);
end Tell_Mouse;

[edit] AutoHotkey

Window may be an externally created window.

#i:: ; (Optional) Assigns a hotkey to display window info, Windows+i
MouseGetPos, x, y ; Gets x/y pos relative to active window
WinGetActiveTitle, WinTitle ; Gets active window title
Traytip, Mouse position, x: %x%`ny: %y%`rWindow: %WinTitle%, 4 ; Displays the info as a Traytip for 4 seconds

[edit] with DllCall

Source: GetCursorPos @github by jNizM

static POINT, init := VarSetCapacity(POINT, 8, 0) && NumPut(8, POINT, "Int")
if (DllCall("User32.dll\GetCursorPos", "Ptr", &POINT))
return, { 0 : NumGet(POINT, 0, "Int"), 1 : NumGet(POINT, 4, "Int") }
GetCursorPos := GetCursorPos()
MsgBox, % "GetCursorPos function`n"
. "POINT structure`n`n"
. "x-coordinate:`t`t" GetCursorPos[0] "`n"
. "y-coordinate:`t`t" GetCursorPos[1]

Source: GetPhysicalCursorPos @github by jNizM

static POINT, init := VarSetCapacity(POINT, 8, 0) && NumPut(8, POINT, "Int")
if (DllCall("User32.dll\GetPhysicalCursorPos", "Ptr", &POINT))
return, { 0 : NumGet(POINT, 0, "Int"), 1 : NumGet(POINT, 4, "Int") }
GetPhysicalCursorPos := GetPhysicalCursorPos()
MsgBox, % "GetPhysicalCursorPos function`n"
. "POINT structure`n`n"
. "x-coordinate:`t`t" GetPhysicalCursorPos[0] "`n"
. "y-coordinate:`t`t" GetPhysicalCursorPos[1]

[edit] BBC BASIC

The mouse coordinates are relative to the bottom-left corner of the BBC BASIC main output window:

      MOUSE xmouse%, ymouse%, buttons%
PRINT xmouse%, ymouse%

[edit] C

Library: Xlib
#include <stdio.h>
#include <X11/Xlib.h>
int main()
Display *d;
Window inwin; /* root window the pointer is in */
Window inchildwin; /* child win the pointer is in */
int rootx, rooty; /* relative to the "root" window; we are not interested in these,
but we can't pass NULL */

int childx, childy; /* the values we are interested in */
Atom atom_type_prop; /* not interested */
int actual_format; /* should be 32 after the call */
unsigned int mask; /* status of the buttons */
unsigned long n_items, bytes_after_ret;
Window *props; /* since we are interested just in the first value, which is
a Window id */

/* default DISPLAY */
d = XOpenDisplay(NULL);
/* ask for active window (no error check); the client must be freedesktop
compliant */

(void)XGetWindowProperty(d, DefaultRootWindow(d),
XInternAtom(d, "_NET_ACTIVE_WINDOW", True),
0, 1, False, AnyPropertyType,
&atom_type_prop, &actual_format,
&n_items, &bytes_after_ret, (unsigned char**)&props);
XQueryPointer(d, props[0], &inwin, &inchildwin,
&rootx, &rooty, &childx, &childy, &mask);
printf("relative to active window: %d,%d\n", childx, childy);
XFree(props); /* free mem */
(void)XCloseDisplay(d); /* and close the display */
return 0;

[edit] C#

Writes the absolute Mouse Position of the Screen into the Console

using System;
using System.Windows.Forms;
static class Program
static void Main()

[edit] Clojure

(let [point (.. java.awt.MouseInfo getPointerInfo getLocation)] [(.getX point) (.getY point)])

[edit] Delphi

Shows Mouse Position on a label on the form

procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
lblMousePosition.Caption := ('X:' + IntToStr(X) + ', Y:' + IntToStr(Y));

Delphi Console Program

The following program will help capture mouse position with the help of Windows and classes units.

program Project1;
SysUtils, Controls, Windows;
MyMouse : TMouse;
MyMouse := TMouse.Create;
While True do
WriteLn('(X, y) = (' + inttostr(TPoint(MyMouse.CursorPos).x) + ',' + inttostr(TPoint(MyMouse.CursorPos).y) + ')');

--Neo.abhinav 17:00, 6 May 2011 (UTC)

[edit] Emacs Lisp

For Emacs' own frames (which is what Emacs calls its window system windows), the frame the mouse is over and where the mouse is within that frame can be obtained with

(FRAME . (X . Y))

Or mouse-position for characters instead of pixels. Works when the mouse is over any Emacs frame, not just when that frame is the active focused window.

There's no particularly easy way to inquire about a non-Emacs focused window, only generic X11 or similar approaches run externally.

[edit] Factor

Works only in the graphical listener. Replaces the text in the button with the relative and absolute coordinates of the mouse

: replace-text ( button text -- )
[ drop children>> pop drop ] [ >label add-gadget drop ] 2bi;
: present-locations ( loc1 loc2 -- string )
first2 [ number>string ] bi@ "," glue
] bi@ ";" glue ;
: example ( -- ) "click me"
dup hand-rel ! location relative to the button
hand-loc get ! location relative to the window
present-locations replace-text
<border-button> gadget. ;

[edit] F#

Have to do a lot of interop here. Primarily because the active window may not be a .NET form/control. If the question was for the point relative to the current window, life would be much simpler.

open System.Windows.Forms
open System.Runtime.InteropServices
#nowarn "9"
[<Struct; StructLayout(LayoutKind.Sequential)>]
type POINT =
new (x, y) = { X = x; Y = y }
val X : int
val Y : int
extern nativeint GetForegroundWindow();
[<DllImport("user32.dll", CharSet=CharSet.Auto, SetLastError=true, ExactSpelling=true)>]
extern int ScreenToClient(nativeint hWnd, POINT &pt);
let GetMousePosition() =
let hwnd = GetForegroundWindow()
let pt = Cursor.Position
let mutable ptFs = new POINT(pt.X, pt.Y)
ScreenToClient(hwnd, &ptFs) |> ignore

[edit] Gambas

In gambas, the position of the pointer can only be determined when the click button is held down. A window with a drawing area is required, because this is the only widget that can track pointer movement within gambas.

PUBLIC SUB Form1_MouseMove()
PRINT mouse.X

[edit] Groovy

Based on Java solution:

1.upto(5) {
def p = java.awt.MouseInfo.pointerInfo.location
println "${it}: x=${p.@x} y=${p.@y}"

Sample output:

1: x=857 y=0
2: x=765 y=447
3: x=0 y=535
4: x=715 y=283
5: x=1335 y=83

[edit] HicEst

Mouse click positions for windows created internally. X and Y are in units of current xy axes (optional: invisible).

AXIS(WINdowhandle=handle, MouSeCall=Mouse_Callback, MouSeX=X, MouSeY=Y)
SUBROUTINE Mouse_Callback()
WRITE(Messagebox, Name) X, Y

[edit] Icon and Unicon

In Icon/Unicon the mouse position may be tracked between button presses for any window created by the program. The following code snippet taken from the Icon Graphics Book on page 197-198 shows how to track the mouse.

until *Pending() > 0 & Event() == "q" do { # loop until there is something to do
px := WAttrib("pointerx")
py := WAttrib("pointery")
# do whatever is needed
WDelay(5) # wait and share processor

[edit] Java

Works with: Java version 1.5+

The mouse position can be checked at any time by calling

Point mouseLocation = MouseInfo.getPointerInfo().getLocation();

This returns a point on the entire screen, rather than relative to a particular window. This call can be combined with getLocation() from any Component (including a Frame, which is a window) to get the location relative to that Component.

[edit] JavaScript

In a browser environment, it's impossible to actually get the cursor position at the specific moment. You must wait for user input (movement, click, etc). One of many ways to add an event listener:

document.addEventListener('mousemove', function(e){
var position = { x: e.clientX, y: e.clientY }

In the above example, the window may not be external. It must in fact be a web browser window, which runs the script.

[edit] Liberty BASIC

This example gets the mouse position based on the active window. Click on other windows to get relative mouse position based on those windows.

UpperLeftX = DisplayWidth-WindowWidth
UpperLeftY = DisplayHeight-WindowHeight
struct point, x as long, y as long
stylebits ,0,0,_WS_EX_STATICEDGE,0
statictext "",16,16,100,26
stylebits #main ,0,0,_WS_EX_TOPMOST,0
open "move your mouse" for window_nf as #main
#main "trapclose [quit]"
timer 100, [mm]
CallDll #user32, "GetForegroundWindow", WndHandle as uLong CursorPos$(WndHandle)
close #main
function CursorPos$(handle)
Calldll #user32, "GetCursorPos",_
point as struct,_
result as long
Calldll #user32, "ScreenToClient",_
handle As Ulong,_
point As struct,_
result as long
x = point.x.struct
y = point.y.struct
CursorPos$=x; ",";y
end function


show mousepos   ; [-250 250]

[edit] Mathematica


[edit] MATLAB


[edit] OCaml

equivalent to the C example, uses the Xlib binding ocaml-xlib

open Xlib
let () =
let d = xOpenDisplay "" in
(* ask for active window (no error check);
the client must be freedesktop compliant *)

let _, _, _, _, props =
xGetWindowProperty_window d
(xDefaultRootWindow d)
(xInternAtom d "_NET_ACTIVE_WINDOW" true)
0 1 false AnyPropertyType
let _, _, _, child, _ = xQueryPointer d props in
begin match child with
| Some(_, childx, childy) ->
Printf.printf "relative to active window: %d,%d\n%!" childx childy;
| None ->
print_endline "the pointer is not on the same screen as the specified window"
xCloseDisplay d;

[edit] Octave

To get the X,Y coordinates of N mouse clicks in the current figure, one can use this:

[X, Y, BUTTONS] = ginput(N);


>>  [X, Y, BUTTONS] = ginput(4)
X =


Y =




[edit] Oz

Repeatedly shows the mouse coordinates relative to the foremost window of the application.

[QTk] = { ['x-oz://system/wp/QTk.ozf']}
WindowClosed = {NewCell false}
Window = {
td(action:proc {$} WindowClosed := true {Window close} end
label(text:"" handle:Label))}
{Window show}
for while:{Not @WindowClosed} do
TopmostWindow = {List.last {String.tokens {Tk.return wm(stackorder '.')} & }}
Winfo = {Record.mapInd winfo(rootx:_ rooty:_ pointerx:_ pointery:_)
fun {$ I _}
{Tk.returnInt winfo(I TopmostWindow)}
{Label set(text:"x: "#(Winfo.pointerx - Winfo.rootx)
#", y: "#(Winfo.pointery - Winfo.rooty))}
{Delay 250}

[edit] Perl

The following code will use the SDL module, a wrapper for the libSDL C-library. When you move the mouse over the created window, the mouse position get printed and the program terminates.

use SDL;
use SDL::Events;
use SDLx::App;
my $app = SDLx::App->new;
$app->add_event_handler( sub {
my $event = shift;
if( $event->type == SDL_MOUSEMOTION ) {
printf( "x=%d y=%d\n", $event->motion_x, $event->motion_y );
} );


x=15 y=304

[edit] Perl 6

Works with: rakudo/jvm version 2013-12-03
use java::awt::MouseInfo:from<java>;
given MouseInfo.getPointerInfo.getLocation {
say .getX, 'x', .getY;

[edit] PicoLisp

The following works in an XTerm window. After calling (mousePosition), click into the current terminal window. The returned value is (X . Y), where X is the column and Y the line number.

(de mousePosition ()
(prin "^[[?9h") # Mouse reporting on
(= "^[" (key))
(key 200)
(key 200)
(- (char (key)) 32)
(- (char (key)) 32) ) )
(prin "^[[?9l") ) ) # Mouse reporting off


: (mousePosition)
-> (7 . 3)

[edit] PureBasic

The mouse position can be obtained by these two commands.

x = WindowMouseX(#MyWindow)
y = WindowMouseY(#MyWindow)

This example repeatedly shows the mouse coordinates relative to the window created in the application.

#MyWindow = 0
#Label_txt = 0
#MousePos_txt = 1
If OpenWindow(#MyWindow,0,0,200,200,"Test",#PB_Window_SystemMenu)
TextGadget(#Label_txt,0,0,100,20,"Mouse Position (x,y):",#PB_Text_Right)
event = WaitWindowEvent(10)
If event = #PB_Event_CloseWindow
Break 2 ;exit program
Until event = 0
x = WindowMouseX(#MyWindow)
y = WindowMouseY(#MyWindow)
SetGadgetText(#MousePos_txt,"(" + Str(x) + "," + Str(y) + ")")

[edit] Python

Mouse position using Tkinter graphics library nearly universally included in installations of Python. There is other alternatives but they are platform specific. Shows position of mouse while it is over the program windows and changes color of window when mouse is near (<10) hot spot 100,100.

Code is based on post in Daniweb: by ZZucker

import Tkinter as tk
def showxy(event):
xm, ym = event.x, event.y
str1 = "mouse at x=%d y=%d" % (xm, ym)
# show cordinates in title
# switch color to red if mouse enters a set location range
x,y, delta = 100, 100, 10
if abs(xm - x) < delta and abs(ym - y) < delta
else 'yellow')
root = tk.Tk()
frame = tk.Frame(root, bg= 'yellow', width=300, height=200)
frame.bind("<Motion>", showxy)
#simple way of ,get cursor xy data
[email protected]
from Tkinter import *
def xy(event):
xm, ym = event.x, event.y
xy_data = "x=%d y=%d" % (xm, ym)

[edit] Scala

Library: Scala
import java.awt.MouseInfo
object MousePosition extends App {
val mouseLocation = MouseInfo.getPointerInfo().getLocation()
println (mouseLocation)

[edit] Racket

The mouse position can be queried at any time with a function in a GUI context.

#lang racket/gui
(define-values [point _] (get-current-mouse-state))
(send point get-x)
(send point get-y)

[edit] Retro

This requires running Retro on a VM with support for the canvas device.

needs canvas'

[edit] Ruby

Library: Shoes => "Mouse Position", :width => 400, :height => 400) do
@position = para "Position : ?, ?", :size => 12, :margin => 10
motion do |x, y|
@position.text = "Position : #{x}, #{y}"

[edit] Rust

Prints current location of the mouse cursor relative to any active window. This example relies on the Windows API.

// rustc 0.9 (7613b15 2014-01-08 18:04:43 -0800)
use std::libc::{BOOL, HANDLE, LONG};
use std::ptr::mut_null;
struct POINT {
x: LONG,
#[link_name = "user32"]
extern "system" {
fn GetCursorPos(lpPoint:&mut POINT) -> BOOL;
fn GetForegroundWindow() -> HWND;
fn ScreenToClient(hWnd:HWND, lpPoint:&mut POINT);
fn main() {
let mut pt = POINT{x:0, y:0};
loop {
std::io::timer::sleep(100); // sleep duration in milliseconds
let pt_prev = pt;
unsafe { GetCursorPos(&mut pt) };
if pt != pt_prev {
let h = unsafe { GetForegroundWindow() };
if h == mut_null() { continue }
let mut pt_client = pt;
unsafe { ScreenToClient(h, &mut pt_client) };
println!("x: {}, y: {}", pt_client.x, pt_client.y);

Sample output:

x: 550, y: 614
x: 650, y: 248
x: 612, y: 0
x: 620, y: 0
x: 405, y: 0
x: 0, y: 0

[edit] Seed7

The functions pointerXPos and pointerYPos from the graph.s7i library determine the actual X and Y position of the mouse pointer, relative to the given window:

xPos := pointerXPos(curr_win);
yPos := pointerYPos(curr_win);

[edit] Tcl

Library: Tk
package require Tk 8.5
set curWindow [lindex [wm stackorder .] end]
# Everything below will work with anything from Tk 8.0 onwards
set x [expr {[winfo pointerx .] - [winfo rootx $curWindow]}]
set y [expr {[winfo pointery .] - [winfo rooty $curWindow]}]
tk_messageBox -message "the mouse is at ($x,$y) in window $curWindow"

[edit] Visual Basic

There are two methods for determining where the mouse pointer is. The first only works when the pointer is actually over the window containing the code. This actually works for any control that has a MouseMove event, but it doesn't work if the pointer is over anything else, including controls on the form (so if the pointer is over a button on the current form, the event will only fire for the button, not the form).

Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
'X and Y are in "twips" -- 15 twips per pixel
Me.Print "X:" & X
Me.Print "Y:" & Y
End Sub

The second method uses the Windows API, and can be easily translated to any language that can make API calls. This example uses a Timer control to check the mouse position.

Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Private Type POINTAPI
'X and Y are in pixels, with (0,0) being the top left corner of the primary display
X As Long
Y As Long
End Type
Private Pt As POINTAPI
Private Sub Timer1_Timer()
GetCursorPos Pt
Me.Print "X:" & Pt.X
Me.Print "Y:" & Pt.Y
End Sub

[edit] XPL0

GetMousePosition(0) = X coordinate; 1 = Y coordinate. For video modes $0..$E and $13 the maximum coordinates are 639x199, minus the size of the pointer. For modes $F..$12 the coordinates are the same as the pixels. VESA graphic modes are (usually) 639x479 regardless of the resolution. For 80-column text modes divide the mouse coordinates by 8 to get the character cursor position.

The mouse cursor location is always relative to the upper-left corner of the screen. A window may be externally created ... using a fair amount of code because the version of XPL0 used with these Rosetta Code examples does not make Windows applications (however see "Simple windowed application").

include c:\cxpl\stdlib;
if not OpenMouse then Text(0, "A mouse is required")
else [ShowMouse(true);
IntOut(0, GetMousePosition(0)); ChOut(0, ^,);
IntOut(0, GetMousePosition(1)); CrLf(0);

Example output:

Personal tools