Mouse position

From Rosetta Code
Task
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.

Ada

Library: GTK version GtkAda
Library: GtkAda

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: <lang Ada>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
  begin
     return False;
  end Delete_Event;

  procedure Destroy (Widget : access Gtk_Widget_Record'Class) is
  begin
     Gtk.Main.Main_Quit;
  end Destroy;

  procedure Clicked (Widget : access Gtk_Widget_Record'Class) is
     X, Y : GInt;
  begin
     Get_Pointer (Window, X, Y);
     Set_Text (Label, "At" & GInt'Image (X) & GInt'Image (Y));
  end Clicked;

begin

  Gtk.Main.Init;
  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);
  Return_Handlers.Connect
  (  Window,
     "delete_event",
     Return_Handlers.To_Marshaller (Delete_Event'Access)
  );
  Handlers.Connect
  (  Window,
     "destroy",
     Handlers.To_Marshaller (Destroy'Access)
  );
  Handlers.Connect
  (  Button,
     "clicked",
     Handlers.To_Marshaller (Clicked'Access)
  );
  Show_All (Grid);
  Show (Window);

  Gtk.Main.Main;

end Tell_Mouse;</lang>

AutoHotkey

Window may be externally created. <lang AutoHotkey>WinGetTitle, window, A MouseGetPos, x, y Msgbox, the mouse is at xpos %x% ypos %y% in window %window%</lang>

C

Library: Xlib

<lang c>#include <stdio.h>

  1. 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;

}</lang>

Clojure

<lang lisp>(let [point (.. java.awt.MouseInfo getPointerInfo getLocation)] [(.getX point) (.getY point)])</lang>

Factor

Works only in the graphical listener. Replaces the text in the button with the relative and absolute coordinates of the mouse <lang factor>: 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. ; </lang>

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. <lang fsharp>open System.Windows.Forms open System.Runtime.InteropServices

  1. nowarn "9"

[<Struct; StructLayout(LayoutKind.Sequential)>] type POINT =

   new (x, y) = { X = x; Y = y }
   val X : int
   val Y : int

[<DllImport("user32.dll")>] 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
   ptFs

</lang>

HicEst

Mouse click positions for windows created internally. X and Y are in units of current xy axes (optional: invisible). <lang hicest> WINDOW(WINdowhandle=handle)

  AXIS(WINdowhandle=handle, MouSeCall=Mouse_Callback, MouSeX=X, MouSeY=Y) 
END

SUBROUTINE Mouse_Callback()

  WRITE(Messagebox, Name) X, Y
END</lang>

Java

Works with: Java version 1.5+

The mouse position can be checked at any time by calling <lang java5>Point mouseLocation = MouseInfo.getPointerInfo().getLocation();</lang> 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.

JavaScript

One of many ways to add an event listener:

<lang javascript>document.onmousemove = function(ev) {

 var mouse = {x: ev.clientX, y: ev.clientY};

}</lang>

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

<lang logo>show mousepos  ; [-250 250]</lang>

Mathematica

<lang Mathematica>MousePosition["WindowAbsolute"]</lang>

OCaml

equivalent to the C example, uses the Xlib binding ocaml-xlib <lang OCaml>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
 in
 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"
 end;
 xCloseDisplay d;
</lang>


Oz

Repeatedly shows the mouse coordinates relative to the foremost window of the application. <lang oz>declare

 [QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']}
 WindowClosed = {NewCell false}
 Label
 Window = {QTk.build

td(action:proc {$} WindowClosed := true {Window close} end label(text:"" handle:Label))} in

 {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)} end}

 in
    {Label set(text:"x: "#(Winfo.pointerx - Winfo.rootx)

#", y: "#(Winfo.pointery - Winfo.rooty))}

    {Delay 250}
 end</lang>

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. <lang PicoLisp>(de mousePosition ()

  (prog2
     (prin "^[[?9h")  # Mouse reporting on
     (and
        (= "^[" (key))
        (key 200)
        (key 200)
        (key)
        (cons
           (- (char (key)) 32)
           (- (char (key)) 32) ) )
     (prin "^[[?9l") ) )  # Mouse reporting off</lang>

Output:

: (mousePosition)
-> (7 . 3)

PureBasic

The mouse position can be obtained by these two commands. <lang PureBasic>x = WindowMouseX(#MyWindow) y = WindowMouseY(#MyWindow)</lang> This example repeatedly shows the mouse coordinates relative to the window created in the application. <lang PureBasic>#MyWindow = 0

  1. Label_txt = 0
  2. 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)
 TextGadget(#MousePos_txt,120,0,60,20,"()")
 
 Repeat 
   Repeat
     event = WaitWindowEvent(10)
     If event = #PB_Event_CloseWindow
       Break 2 ;exit program
     EndIf 
   Until event = 0
   
   x = WindowMouseX(#MyWindow)
   y = WindowMouseY(#MyWindow)
   SetGadgetText(#MousePos_txt,"(" + Str(x) + "," + Str(y) + ")")
 ForEver

EndIf</lang>

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: http://www.daniweb.com/forums/post616327.html#post616327 by ZZucker <lang python> 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
   root.title(str1)
   # switch color to red if mouse enters a set location range
   x,y, delta = 100, 100, 10
   frame.config(bg='red'
                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) frame.pack()

root.mainloop() </lang>



Ruby

Library: Shoes

<lang Ruby> Shoes.app(:title => "Mouse Position", :width => 400, :height => 400) do

 @position = para "Position : ?,?", :size => 12, :margin => 10
 
 motion do |x,y|
   @position.text = "Position : " + x.to_s + "," + y.to_s 
 end

end </lang>

Tcl

Library: Tk

8.5

<lang tcl>set curWindow [lindex [wm stackorder .] end]

  1. 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"</lang>