很多游戲都是用鼠標控制的,所以說處理鼠標事件也是非常重要的,鼠標事件和鍵盤事件處理方式差的不太多,所以我就直接給出了一個小程序,該程序把窗口一分為二,當在左半部分移動時,左面部分就變綠色,右面部分變黑色,在右半部分移動時,該部分就變藍色,左半部分就變成了黑色,當鼠標左擊時,對應的部分將會變紅色。
#include?
"
SDL.h
"
#include?
"
SDL_ttf.h
"
SDL_Surface?
*
screen
=
NULL;

TTF_Font?
*
font
=
NULL;
//
screen?to?show?on?window
const
?
int
?SCREEN_BPP
=
32
;



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

{
????
//
Start?SDL
????
bool
?quit
=
false
;
????SDL_Rect?rectLeft;
????SDL_Rect?rectRight;
????rectLeft.x
=
0
;
????rectLeft.y
=
0
;
????rectLeft.w
=
320
;
????rectLeft.h
=
480
;
????rectRight.x
=
320
;
????rectRight.y
=
0
;
????rectRight.w
=
640
;
????rectRight.h
=
480
;
????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
;

????Uint32?colorBlue
=
SDL_MapRGB(screen
->
format,
0
,
0
,
255
);
????Uint32?colorGreen
=
SDL_MapRGB(screen
->
format,
0
,
255
,
0
);
????Uint32?colorRed
=
SDL_MapRGB(screen
->
format,
255
,
0
,
0
);
????Uint32?colorBlack
=
SDL_MapRGB(screen
->
format,
0
,
0
,
0
);
????SDL_Event?
event
;
????
while
(
!
quit)

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

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

????????????
{
????????????????Uint16?x
=
event
.motion.x;
????????????????Uint16?y
=
event
.motion.y;


????????????????
if
(x
>
0
?
&&
?x
<
320
?
&&
?y
>
0
?
&&
?y
<
480
?)

????????????????
{
????????????????????SDL_FillRect(screen,
&
rectLeft,colorBlue);
????????????????????SDL_FillRect(screen,
&
rectRight,colorBlack);
????????????????}
????????????????
if
(x
>
320
?
&&
?x
<
640
?
&&
?y
>
0
?
&&
?y
<
480
?)

????????????????
{
????????????????????SDL_FillRect(screen,
&
rectRight,colorGreen);
????????????????????SDL_FillRect(screen,
&
rectLeft,colorBlack);
????????????????}
????????????}
????????????
if
(
event
.type?
==
SDL_MOUSEBUTTONDOWN)

????????????
{
????????????????Uint16?x
=
event
.motion.x;
????????????????Uint16?y
=
event
.motion.y;
????????????????
if
(
event
.button.button?
==
?SDL_BUTTON_LEFT)

????????????????
{
????????????????????
if
(x
>
0
?
&&
?x
<
320
?
&&
?y
>
0
?
&&
?y
<
480
?)

????????????????????
{
????????????????????????SDL_FillRect(screen,
&
rectLeft,colorRed);
????????????????????}
????????????????????
if
(x
>
320
?
&&
?x
<
640
?
&&
?y
>
0
?
&&
?y
<
480
?)

????????????????????
{
????????????????????????SDL_FillRect(screen,
&
rectRight,colorRed);
????????????????????}
????????????????}
????????????}
????????????
if
(
event
.type?
==
?SDL_QUIT)
????????????????quit
=
true
;
????????}
????????
if
(SDL_Flip(screen)?
==
?
-
1
)

????????
{
????????????
return
?
false
;
????????}
????}
????SDL_FreeSurface(screen);
????SDL_Quit();

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