Events VB.NET

From SDL.NET

Introduction

One of the primary strengths of SDL.NET is input handling. SDL.NET provides a simple API for handling many different kind of input events. The most common of these are keyboard, mouse and tick events. This tutorial will demo the basics of using these input events.

Basic Event Processing

The Events class contains many different events that an application can use. Most applications will want to capture keyboard and mouse input by a user. Many apps will also want to have a ticker running to perform timed actions such as blitting a Surface to the screen.

The Events class contains these relevant events:

KeyboardUp
KeyboardDown
MouseMotion
MouseButtonDown
MouseButtonUp
Tick
Quit

An application can attach an EventHandler to each of these events to process mouse or keyboard input. The EventHandlers should be instantiated when the application is initialized.

To use these event handlers, remember to include

Imports SdlDotNet.Input

VB code:

AddHandler Events.KeyboardDown, AddressOf OnKeyboardDown
AddHandler Events.MouseMotion, AddressOf OnMouseMotion
AddHandler Events.MouseButtonDown, AddressOf OnMouseButtonDown
AddHandler Events.Tick, AddressOf OnTick
AddHandler Events.Quit, AddressOf OnQuit

Start the event processing loop in main part of the program

Events.Run()

Create private methods that will process the events.

'Handles keyboard events. The 'Escape' and 'Q'keys will cause the app to exit
Sub OnKeyboardDown(sender as Object, e as KeyboardEventArgs)
    If (e.Key == Key.Escape || e.Key == Key.Q)
        Events.QuitApplication()
    End If
End Sub

'This will set the position of a custom cursor to blit to the screen
Sub OnMouseMotion(sender as Object, e as MouseMotionEventArgs)
    position.X = e.X
    position.Y = e.Y
End Sub

'This changes the rendering of an OpenGL heightmap when the mouse button is pressed.
Sub OnMouseButtonDown(sender as Object, e as MouseButtonEventArgs)
    bRender = Not bRender
End Sub

'A ticker is running to update the screen constantly.
'This method will fill the screen with black to clear it out.
'Then it will Blit the surface to the screen.
'Then it will refresh the screen and display it.
Sub OnTick(sender as Object, args as TickEventArgs)
    screen.Fill(Color.Black)
    screen.Blit(surface)
    screen.Flip()
End Sub

Conclusion

Events are often used in the main program, but they are often used by Sprites as well. Consult the Sprites demo to see how Sprites and SpriteCollections consume events to create motion and react to use input.