很多游戏都是用鼠标控制的,所以说处理鼠标事件也是非常重要的,鼠标事件和键盘事件处理方式差的不太多,所以我就直接给出了一个小程序,该程序把窗口一分为二,当在左半部分移动时,左面部分就变绿色,右面部分变黑色,在右半部分移动时,该部分就变蓝色,左半部分就变成了黑色,当鼠标左击时,对应的部分将会变红色。
#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
;
}