SDL提供了下面几个结构体用于实现鼠标移动、点触等事件。
一个主要的共同体SDL_Event,原型如下:
typedef union{
Uint8 type;
SDL_ActiveEvent active;
SDL_KeyboardEvent key;
SDL_MouseMotionEvent motion;
SDL_MouseButtonEvent button;
SDL_JoyAxisEvent jaxis;
SDL_JoyBallEvent jball;
SDL_JoyHatEvent jhat;
SDL_JoyButtonEvent jbutton;
SDL_ResizeEvent resize;
SDL_ExposeEvent expose;
SDL_QuitEvent quit;
SDL_UserEvent user;
SDL_SysWMEvent syswm;
} SDL_Event;
SDL_Event是所有SDL事件处理的核心,它是SDL_Surface之后最重要的结构。它通过判断事件类型(type)来决定选择使用哪一个结构体,它们的对应使用关系如下:
Event type |
Event Structure |
SDL_ACTIVEEVENT |
|
SDL_KEYDOWN/UP |
|
SDL_MOUSEMOTION |
|
SDL_MOUSEBUTTONDOWN/UP |
|
SDL_JOYAXISMOTION |
|
SDL_JOYBALLMOTION |
|
SDL_JOYHATMOTION |
|
SDL_JOYBUTTONDOWN/UP |
|
SDL_VIDEORESIZE |
|
SDL_VIDEOEXPOSE |
|
SDL_QUIT |
|
SDL_USEREVENT |
|
SDL_SYSWMEVENT |
SDL_Event中有两个用于模拟鼠标设备的动作的结构体SDL_MouseMotionEvent与SDL_MouseButtonEvent,原型如下:
typedef struct{
Uint8 type; //被使用时,为SDL_MOUSEMOTION
Uint8 state; //鼠标按键状态
Uint16 x, y; //绝对坐标
Sint16 xrel, yrel; //相对坐标
} SDL_MouseMotionEvent;
当SDL_Event.type为SDL_MOUSEMOTION时,SDL_MouseMotionEvent结构体被选择。SDL_MouseMotionEvent在SDL_MOUSEMOTION(鼠标移动)事件触发时被使用。简单地说,当用户移动应用程序的窗口内的鼠标或SDL_WarpMouse被引用,SDL_MOUSEMOTION类型的事件就发生。
typedef struct{
Uint8 type; //SDL_MOUSEBUTTONDOWN或SDL_MOUSEBUTTONUP
Uint8 which; //输入设备索引
Uint8 button; //鼠标按键索引(SDL_BUTTON_LEFT, SDL_BUTTON_MIDDLE, SDL_BUTTON_RIGHT, SDL_BUTTON_WHEELUP, SDL_BUTTON_WHEELDOWN)
Uint8 state; //按键状态(SDL_PRESSED或SDL_RELEASED)
Uint16 x, y; //按键当前坐标
} SDL_MouseButtonEvent;
当SDL_Event.type为SDL_MOUSEBUTTONDOWN或SDL_MOUSEBUTTONUP时,SDL_MouseButtonEvent结构体被选择。同样地,SDL_MouseButtonEvent在检测到鼠标按钮按下或释放时使用,鼠标时间发生时鼠标的位置存储在X和Y字段。
根据触屏数据模拟鼠标点击事件
从触屏获取校正后的点触坐标X、Y与点触状态pressure,将这些信息相应地填充到SDL_MouseMotionEvent与SDL_MouseButtonEvent中,再使用SDL_PushEvent装载填充好的结构体,实现鼠标的移动或点击事件。
(注:SDL实现触屏模拟鼠标点击的一个重要的函数:int SDL_PushEvent(SDL_Event *event),该函数用于装载结构体)