一个简化的鼠标状态机示例
#include <stdbool.h>
#include <stdint.h>
typedef enum {
MOUSE_UP,
MOUSE_DOWN,
MOUSE_FIRST_CLICK,
MOUSE_SECOND_CLICK,
} MouseState;
typedef enum {
MOUSE_PRESS,
MOUSE_RELEASE,
} MouseEventType;
typedef struct {
MouseEventType type;
uint8_t button;
} MouseEvent;
MouseState mouse_state = MOUSE_UP;
uint32_t last_click_time = 0;
void process_mouse_event(MouseEvent *event) {
uint32_t current_time = get_current_time(); // 获取当前时间,单位:毫秒
switch (mouse_state) {
case MOUSE_UP:
if (event->type == MOUSE_PRESS) {
mouse_state = MOUSE_DOWN;
// 生成鼠标按下消息
}
break;
case MOUSE_DOWN:
if (event->type == MOUSE_RELEASE) {
mouse_state = MOUSE_FIRST_CLICK;
// 生成鼠标抬起消息
}
break;
case MOUSE_FIRST_CLICK:
if (event->type == MOUSE_PRESS) {
mouse_state = MOUSE_SECOND_CLICK;
// 生成鼠标单击消息
} else if (current_time - last_click_time > DOUBLE_CLICK_DELAY) {
mouse_state = MOUSE_UP;
}
break;
case MOUSE_SECOND_CLICK:
if (event->type == MOUSE_RELEASE) {
mouse_state = MOUSE_UP;
// 生成鼠标双击消息
}
break;
}
if (event->type == MOUSE_PRESS || event->type == MOUSE_RELEASE) {
last_click_time = current_time;
}
}
在这个示例中,我们定义了一个鼠标状态机,用于处理鼠标按下、抬起、单击和双击等事件。状态机包括四个状态:MOUSE_UP、MOUSE_DOWN、MOUSE_FIRST_CLICK和MOUSE_SECOND_CLICK。在process_mouse_event函数中,我们根据当前状态和事件类型来更新状态机的状态,并生成相应的鼠标消息。
需要注意的是,这个示例仅用于演示如何实现鼠标状态机,实际应用中需要根据具体的单片机硬件和需求进行调整和优化。