2024年4月3日发(作者:)

一.事件循环

------------------------------------------------------

一个完整的GUI程序,需要处理各种事件,如按键,鼠标,窗口操作等。一般这种程序会设计成一个与

底层交互的事件驱动模型。即底层不断发送事件,而在程序用一个循环不断处理各种事件

各个GUI都是采用这样模型来实现,SDL抽象这个模型,采用SDL_event来抽象表示具体的事件,它有如

下几种类型。

/** Event enumerations */

typedef enum {

SDL_NOEVENT = 0, /**< Unused (do not remove) */

SDL_ACTIVEEVENT, /**< Application loses/gains visibility

*/

SDL_KEYDOWN, /**< Keys pressed */

SDL_KEYUP, /**< Keys released */

SDL_MOUSEMOTION, /**< Mouse moved */

SDL_MOUSEBUTTONDOWN, /**< Mouse button pressed */

SDL_MOUSEBUTTONUP, /**< Mouse button released */

SDL_JOYAXISMOTION, /**< Joystick axis motion */

SDL_JOYBALLMOTION, /**< Joystick trackball motion */

SDL_JOYHATMOTION, /**< Joystick hat position change */

SDL_JOYBUTTONDOWN, /**< Joystick button pressed */

SDL_JOYBUTTONUP, /**< Joystick button released */

SDL_QUIT, /**< User-requested quit */

SDL_SYSWMEVENT, /**< System specific event */

SDL_EVENT_RESERVEDA, /**< Reserved for future use.. */

SDL_EVENT_RESERVEDB, /**< Reserved for future use.. */

SDL_VIDEORESIZE, /**< User resized video mode */

SDL_VIDEOEXPOSE, /**< Screen needs to be redrawn */

SDL_EVENT_RESERVED2, /**< Reserved for future use.. */

SDL_EVENT_RESERVED3, /**< Reserved for future use.. */

SDL_EVENT_RESERVED4, /**< Reserved for future use.. */

SDL_EVENT_RESERVED5, /**< Reserved for future use.. */

SDL_EVENT_RESERVED6, /**< Reserved for future use.. */

SDL_EVENT_RESERVED7, /**< Reserved for future use.. */

/** Events SDL_USEREVENT through SDL_MAXEVENTS-1 are for your use */

SDL_USEREVENT = 24,

/** This last event is only for bounding internal arrays

* It is the number of bits in the event mask datatype -- Uint32

*/

SDL_NUMEVENTS = 32

} SDL_EventType;

SDL采用 int SDL_PollEvent(SDL_Event *event); 来从底层提取事件。

每一个事件都有一个独立数据结构来定义,但是第一个成员必是一个int type,

SDL_Event就是一个各种事件定义的联合

/** General event structure */

typedef union SDL_Event {

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;

而象常用的事件有,退出事件(当你点击窗口关闭键,就会触发此事件)

typedef struct SDL_QuitEvent {

Uint8 type; /**< SDL_QUIT */

} SDL_QuitEvent;

按键处理事件

/** Keyboard event structure */

typedef struct SDL_KeyboardEvent {

Uint8 type; /**< SDL_KEYDOWN or SDL_KEYUP */

Uint8 which; /**< The keyboard device index */

Uint8 state; /**< SDL_PRESSED or SDL_RELEASED */

SDL_keysym keysym;

} SDL_KeyboardEvent;