Event Examples

Filtering and Handling Events

uses
SDL;

// This function may run in a separate event thread
function FilterEvents( const event : PSDL_Event ) : integer;
var
boycott : integer;
begin
boycott := 1;

// This quit event signals the closing of the window
if ( ( event.type_ = SDL_QUITEV ) and boycott ) then
begin
MessageBox( 0, 'Quit Event filtered out -- try again', 'Information', MB_OK or MB_ICONHAND );
boycott := 0;
result := 0;
exit;
end;

if ( event.type_ = SDL_MOUSEMOTION ) then
begin
MessageBox( 0, PChar( Format( 'Mouse moved to ( x : %d, y : %d )', [ event.motion.x, event.motion.y ] ) ), 'Information', MB_OK or MB_ICONHAND );
result := 0; // Drop it, we've handled it
exit;
end;
result := 1;
end;

var
event : TSDL_Event;
keys : PKeyStateArr;
begin

// Initialize the SDL library (starts the event loop)
if ( SDL_Init( SDL_INIT_VIDEO ) < 0 ) then
begin
MessageBox(0, PChar( Format( 'Couldn''t initialize SDL : %s', [SDL_GetError] ) ), 'Error', MB_OK or MB_ICONHAND );
SQL_Quit;
halt(1);
end;

// Ignore key events
SDL_EventState( SDL_KEYDOWN, SDL_IGNORE );
SDL_EventState( SDL_KEYUP, SDL_IGNORE );

// Filter quit and mouse motion events
SDL_SetEventFilter( FilterEvents );

// The mouse isn't much use unless we have a display for reference
if ( SDL_SetVideoMode(640, 480, 8, 0) = nil ) then
begin
MessageBox(0, PChar( Format( 'Couldn't set 640x480x8 video mode : %s', [SDL_GetError])), 'Error', MB_OK or MB_ICONHAND);
halt(1);
end;

// Loop waiting for ESC+Mouse_Button
while ( SDL_WaitEvent( @event ) >= 0 ) do
begin
case event.type_ of
SDL_ACTIVEEVENT:
begin
if ( event.active.state and SDL_APPACTIVE ) then
begin
if ( event.active.gain ) then
begin
MessageBox( 0, 'App Activated', 'Information', MB_OK or MB_ICONHAND );
end
else
begin
MessageBox( 0, 'App Iconified', 'Information', MB_OK or MB_ICONHAND );
end;
end;
end;

SDL_MOUSEBUTTONDOWN:
begin
keys := PKeyStrateArr( SDL_GetKeyState( nil ) );
if ( keys[SDLK_ESCAPE] = SDL_PRESSED ) then
begin
MessageBox( 0, 'Bye bye...', 'Information', MB_OK or MB_ICONHAND );S
halt(0);
end;
MessageBox( 0, 'Moused Button Pressed', 'Information', MB_OK or MB_ICONHAND );
end;

SDL_QUITEV:
begin
MessageBox( 0, 'Quit Requested, quitting.', 'Information', MB_OK or MB_ICONHAND );
halt(0);
end;
end;
end;
// This should never happen
MessageBox( 0, PChar( Format( 'SDL_WaitEvent error : %s', [SDL_GetError] ) ), 'Error', MB_OK or MB_ICONHAND );
halt(1);
end;