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();
}
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With