c - 事件处理程序?

标签 c event-handling

我正在使用给定的代码来处理鼠标点击。但是,这是行不通的。我已经通过 input.h 弄明白了,但我做不到。达到if条件时字节为1,但我的代码仍然不允许执行if条件。这里做错了什么:

const char *mfile = "/dev/input/mice";

int main()
{
int fd, bytes;
struct input_event data;

fd = open(mfile, O_RDWR | O_NONBLOCK);
if(fd == -1)
{
    printf("ERROR Opening associated device file: /dev/input/mice \n");
    return -1;
}

while(1)
{ 
    bytes = read(fd, &data, sizeof(struct input_event));

    if(bytes > 0)
    {
     if((data.code == BTN_LEFT) && (data.value == 0))
                printf("Left pressed. \n");                    
         else if((data.code == BTN_RIGHT) && (data.value == 0))
        printf("Right presseed. \n");
    }   
}
close(fd);
return 0; 
}

最佳答案

在处理其中的数据之前,您必须等到 read 读取了 input_event 结构的大小的输入。

但目前的代码只检查是否有任何字节被读取。此检查应更改为检查读取的字节数是否等于 input_event 结构。

请参阅 read 的文档:.

Return Value.

On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal. On error, -1 is returned, and errno is set appropriately. In this case it is left unspecified whether the file position (if any) changes.

关于c - 事件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52341251/

相关文章:

C scanf 有空格问题

.net - 为什么子不能同时实现接口(interface)和处理事件?

Java 事件绑定(bind)

c++ - matPutVariable: error (matrix::serialize::WrongSize) 试图输出数据到mat文件

c - 为什么fread()函数读取后,光标会跳转到随机位置?

c - C 编程中 "&"%f", &variableName);"中的 "scanf("是什么?

c++ - 通过 switch 和 static_cast 访问多态对象的运行时类型

c - sizeof (int) == sizeof (void*)?

Javascript:删除相关 HTML 时是否应该删除事件处理程序?

javascript - 在 VueJS 中,你在哪里监听发出的事件?