domingo, 7 de abril de 2013

Usar el mouse con C/C++ en linux

La forma más fácil para usar las funcionalidades del mouse es usando xdotool (necesita tenerlo instalado).

Ejemplo 1:
Mover el cursor a la coordenada 1,1
system("xdotool mousemove 1 1");



Ejemplo 2:
Este es otro ejemplo de una clase "Mouse" que hice para probar 



#include <inttypes.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
using namespace std;

#define SIZE_OF_SCRIPT_CLICK 20 // Size script that will run the click

class Mouse{
public:

 /** Mouse buttons **/
 enum MouseButton{
  Left=1,
  Middle=2,
  Right=3
 };

 /** Perform click's
  *
  * @param nClicks Number of clicks to perform
  * @param button Button of the click
  * @param delay Delay time in microseconds
  *
  */
 void click(int nClicks=1, MouseButton button=Left,int delay=0){
  static char script[SIZE_OF_SCRIPT_CLICK];
  memset(script,0,sizeof(char)*SIZE_OF_SCRIPT_CLICK);

  sprintf (script,"xdotool click %d",int(button));

  while (nClicks--){
   system(script);
   if (nClicks)
    usleep(delay);
  }
 }

 /** Type of mouse move **/
 enum TypeOfMove{
  Relative, // Move the cursor with respect to the current position
  Absolute  // Places the cursor at a given position
 };

 /** Change the cursor position
  *
  * @param x Abscissa
  * @param y Ordinate
  * @param typeOfMove Type of move
  */
 void move(int x,int y,TypeOfMove typeOfMove=Absolute){
  static char script[SIZE_OF_SCRIPT_CLICK];
  memset(script,0,sizeof(char)*SIZE_OF_SCRIPT_CLICK);
  sprintf (script,"xdotool mousemove%s %d %d",
    typeOfMove==Relative?"_relative":"",x,y);
  system(script);
 }
};


int main() {
 Mouse m;
 usleep(500000);
 m.click(1,Mouse::Right);
 usleep(500000);
 m.move(0,200,Mouse::Relative);
 m.click(1,Mouse::Left);
 m.move(0,200,Mouse::Absolute);
 m.click(1,Mouse::Left);
 return 0;
}


No hay comentarios:

Publicar un comentario