Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set mouse cursor position in C on linux?

how can I set the mouse cursor position in an X window using a C program under Linux? thanks :) (like setcursorpos() in WIN)

EDIT: I've tried this code, but doesn't work:

#include <curses.h>

main(){
 move(100, 100);
 refresh();
}
like image 211
frx08 Avatar asked Mar 12 '10 14:03

frx08


People also ask

How will you find the position of mouse in C?

The given task is to get the current position of the cursor from the output screen in C. Approach: There is a predefined function wherex() in C language that returns the x coordinate of the cursor in the current output screen. And wherey() function that returns the y coordinate of the cursor in current output screen.

How do I get cursor position in terminal?

At ANSI compatible terminals, printing the sequence ESC[6n will report the cursor position to the application as (as though typed at the keyboard) ESC[n;mR , where n is the row and m is the column.


2 Answers

12.4 - Moving the Pointer

Although movement of the pointer normally should be left to the control of the end user, sometimes it is necessary to move the pointer to a new position under program control.

To move the pointer to an arbitrary point in a window, use XWarpPointer().


Example:

Display *dpy; Window root_window;  dpy = XOpenDisplay(0); root_window = XRootWindow(dpy, 0); XSelectInput(dpy, root_window, KeyReleaseMask); XWarpPointer(dpy, None, root_window, 0, 0, 0, 0, 100, 100); XFlush(dpy); // Flushes the output buffer, therefore updates the cursor's position. Thanks to Achernar. 
like image 54
Bertrand Marron Avatar answered Sep 17 '22 19:09

Bertrand Marron


This is old, but in case someone else comes across this issue. The answer provided by tusbar was correct but the command XFlush(dpy) must be added at the end to update the cursor's position. The libraries needed are: X11/X.h, X11/Xlib.h, X11/Xutil.h.

int main(int argc, char *argv[]){
         //Get system window
         Display *dpy;
         Window root_window;

         dpy = XOpenDisplay(0);
         root_window = XRootWindow(dpy, 0);
         XSelectInput(dpy, root_window, KeyReleaseMask);

         XWarpPointer(dpy, None, root_window, 0, 0, 0, 0, 100, 100);

         XFlush(dpy);

         return 0;}

PS: You can use this command to build the code gcc main.c -lX11

like image 34
Achernar Avatar answered Sep 18 '22 19:09

Achernar