Linux字符界面下的鼠标操作

来源:互联网 发布:matlab高级编程 pdf 编辑:程序博客网 时间:2024/05/01 10:07

本文是关于如何在字符界面下获取鼠标信息的。
在阅读linux1.0源码中关于鼠标驱动的代码时,希望在linux下写一个测试程序,读取一下鼠标的数据,看与内核代码是否一致。
鼠标图片
linux下操作设备一般都是通过打开设备文件,对设备文件进行读取或写入。鼠标在linux下也被抽象为设备文件,一样是通过open read close的接口操作。但在linux发现有许多鼠标的设备文件,在字符界面下有些鼠标文件无法打开,有些打开后读取的话会陷入等待。
通过不断测试,终于找到一个可以获取鼠标信息的文件—/dev/psaux文件。
在打开文件前执行命令service gpm stop,将gpm服务关闭,不然gpm会影响鼠标文件的读取。

以下是操作代码

#include <stdio.h>#include <sys/select.h> #include <unistd.h>#include <sys/types.h>#include <fcntl.h>int main(void){    int fd, retval;    char buf[6];    fd_set readfds;    struct timeval tv;    fd = open("/dev/psaux", O_RDONLY);    if(fd==-1)    {        printf("Failed to open/dev/psaux");        return -1;    }    while(1)    {        FD_ZERO(&readfds);        FD_SET(fd, &readfds);        tv.tv_sec = 5;        tv.tv_usec = 0;        if((retval = select(fd+1, &readfds, NULL, NULL, &tv)) == 1)        {            if(read(fd, buf, 6) <= 0)            {                continue;             }            printf("Button type = %d, X = %d, Y = %d\n", (buf[0] & 0x07), buf[1], buf[2]);        }    }    close(fd);    return 0;}

gpm是linux console下的鼠标操作服务。用它可以实现copy和paste操作。你也可以用gpm提供的API得到鼠标的坐标。但这些API的原理也是跟上面讲的一样,都是操作mice文件。

0 0
原创粉丝点击