gpt4 book ai didi

c - 在鼠标事件后重新启动无限循环?

转载 作者:太空宇宙 更新时间:2023-11-04 07:53:08 25 4
gpt4 key购买 nike

我的目标是一个看起来像这样的简单代码:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <poll.h>
#include <linux/input.h>

int main()
{
int fd, bytes;
unsigned char data[3];
fd = open("/dev/input/mice", O_RDWR);
int left;

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

if(bytes > 0)
{
left = data[0] & 0x1;
right = data[0] & 0x2;

if(left==1){
goto reset_EVENT;
}
}

reset_EVENT:

printf("hey 1");
sleep(1);
printf("hey 2");
sleep(1);
printf("hey 3");
sleep(1);
}
return 0;
}

我的目标是在单击鼠标左键时立即从“hey 1”重新开始打印序列。但是,如果不在每次 sleep 前使用“if”条件,我将无法实现这一点。 “goto”也不适用于不同的功能。有人可以为此提出最佳解决方案吗?

最佳答案

你可以用某种状态机来实现这个:一个函数有一个内部静态知道 which 是最后打印的 hey

void print_event(int reset)
{
/* by default, print nothing */
static int state = 4;

/* if reset, restart counting */
if (reset)
state = 1;

/* if state under 4, display `hey` */
if (state <= 3)
printf("hey %d\n", state++);
}

int main()
{
int fd, bytes;
unsigned char data[3];
fd = open("/dev/input/mice", O_RDWR);
int left, right;

while(1)
{
/* by default, event is not reset */
int reset = 0;
bytes = read(fd, data, sizeof(data));

if(bytes > 0)
{
left = data[0] & 0x1;
right = data[0] & 0x2;

if(left==1){
/* left click: reset event*/
reset = 1;
}
}

/* ask function to print if needed */
print_event(reset);

sleep(1);
}
return 0;
}

编辑

循环中的一个问题是您将等待很长时间才能阅读新内容来自 fd 的值。

您可以使用信号来实现这一点:

  • 不 sleep 不间断地读取鼠标的输入
  • 当检测到左键单击时,发出警报信号以显示事件:

因此,您的代码可以是:

/* print event function: can be called from alarm signal handler
or directly from main function */
void print_event(int reset)
{
/* by default, print nothing */
static int state = 4;

/* if reset, restart counting */
if (reset)
state = 1;

/* if state under 4, display `hey` */
if (state <= 3)
{
printf("hey %d", state++);

/* if all `hey` have not been printed, prepare the next */
alarm(1);
}
}

/* alarm signal receiver*/
void handle(int sig) {
/* print event without reset */
print_event(0);
}

int main()
{
int fd, bytes;
unsigned char data[3];
fd = open("/dev/input/mice", O_RDWR);
int left;

/* tell what function is to be called when alarm signal is raised */
signal(SIGALRM, handle);

/* if you want to display one sequence before the first click, uncomment the following line */
/* print_event(1); */

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

if(bytes > 0)
{
left = data[0] & 0x1;

if(left==1){
/* left click: reset event*/
print_event(1);
}
}
}
return 0;
}

关于c - 在鼠标事件后重新启动无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52512703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com