這次我們看看如何在SDL中處理鍵盤事件,每次事件發生以后,有關事件的所有信息都存儲在SDL_Event類型的變量當中,查查手冊我們可以知道,實際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_SywWMEvent syswm;
} SDL_Event;
當發生鍵盤事件時,key變量就是有效的。
typedef struct{
? Uint8 type;
? Uint8 state;
? SDL_keysym keysym;
} SDL_KeyboardEvent;
key變量是一個結構體,其中keysym成員包含了按鍵信息。
typedef struct{
? Uint8 scancode;
? SDLKey sym;
? SDLMod mod;
? Uint16 unicode;
} SDL_keysym;
在keysym的成員當中,sym記錄按鍵所對應的虛擬鍵。
比如說向上就是SDLK_UP;向下就是SDLK_DOWN;大家可以自己去查手冊。
下面就看一個處理鍵盤消息的實例吧。
該例子中,我們一旦發現有上下左右四個鍵被按下,就馬上在屏幕上顯示相對應的消息,這里用到了擴展類庫SDL_TTF,如有不清楚的,參考一下前面的幾篇文章。
#include?"SDL.h"
#include?"SDL_ttf.h"
SDL_Surface?*screen=NULL;
SDL_Surface?*up=NULL;
SDL_Surface?*down=NULL;
SDL_Surface?*left=NULL;
SDL_Surface?*right=NULL;
SDL_Surface?*message=NULL;
TTF_Font?*font=NULL;
//screen?to?show?on?window
const?int?SCREEN_BPP=32;

SDL_Color?textColor=
{255,255,255};


int?main(?int?argc,?char*?args[]?)


{
????//Start?SDL
????bool?quit=false;
????SDL_Init(?SDL_INIT_EVERYTHING?);
????if(TTF_Init()==-1)
????????return?false;

????screen?=?SDL_SetVideoMode(?600,?480,?SCREEN_BPP,?SDL_SWSURFACE?);
????if(screen==NULL)
????????return?false;
????font=TTF_OpenFont("tahoma.ttf",28);
????up?=?TTF_RenderText_Solid(?font,?"Up?was?pressed.",?textColor?);
????down?=?TTF_RenderText_Solid(?font,?"Down?was?pressed.",?textColor?);
????left?=?TTF_RenderText_Solid(?font,?"Left?was?pressed",?textColor?);
????right?=?TTF_RenderText_Solid(?font,?"Right?was?pressed",?textColor?);
????SDL_Event?event;
????while(!quit)

????
{
????????if(SDL_PollEvent(&event))

????????
{
????????????if(event.type?==?SDL_KEYDOWN)

????????????
{
????????????????switch(event.key.keysym.sym)

????????????????
{
????????????????????case?SDLK_UP:?message=up;break;
????????????????????case?SDLK_DOWN:?message=down;break;
????????????????????case?SDLK_LEFT:?message=left;break;
????????????????????case?SDLK_RIGHT:?message=right;break;
????????????????}
????????????}
????????????if(event.type?==?SDL_QUIT)
????????????????quit=true;
????????}
????????if(message?!=?NULL)

????????
{
????????????Uint32?colorVal=SDL_MapRGB(screen->format,0,0,0);
????????????SDL_FillRect(screen,?&screen->clip_rect,colorVal);
????????????SDL_BlitSurface(message,NULL,screen,NULL);

????????????message=NULL;
????????}
????????if(SDL_Flip(screen)?==?-1)

????????
{
????????????return?false;
????????}
????}
????//Quit?SDL
????SDL_Quit();

????return?0;????
}
