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.

AutoHotkey

<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>

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>