Getting started with ClanLib - Part IV

(1/1)

Richard Marks:
Getting started with ClanLib - Part IV

In this article I am going to show you how the work with the keyboard.
Whats that? I already did that? Well sort of. What I did before was ok to get started, but its more useful to have our input handled separately from the main method. That is what we are doing now.

Go duplicate the previous code-base and make your edits like I told you to before. ...I'll wait.....

Done? Ok. Lets continue. :D

We are going to add a couple more private methods to our class:
Code:

/// handles key press events
void KeyDownEventHandler(const CL_InputEvent& event);

/// handles key release events
void KeyUpEventHandler(const CL_InputEvent& event);



Now, after we get the graphics context, we will grab the input context of the window:
Code:

// get the input context of the window
CL_InputContext* inputContext = mainWindow.get_ic();


Lets get the keyboard device next:
Code:

// get the keyboard device
CL_InputDevice keyboardDevice = inputContext->get_keyboard();


Now, we attach our keyboard event handlers:
Code:

// attach our signal handlers for the keyboard input events
CL_Slot windowKeyDownEventSlot = keyboardDevice.sig_key_down().connect(this, &CLTest4Application::KeyDownEventHandler);
CL_Slot windowKeyUpEventSlot = keyboardDevice.sig_key_down().connect(this, &CLTest4Application::KeyUpEventHandler);


remove this code from the main loop since we are handling input via signals now:
Code:

// if the ESC key is pressed then
if (CL_Keyboard::get_keycode(CL_KEY_ESCAPE))
{
// stop the main loop
running_ = false;
}


Now we get our event handler method for when a key is pressed:
Code:

void CLTest4Application::KeyDownEventHandler(const CL_InputEvent& event)
{
switch(event.id)
{
case CL_KEY_ESCAPE:
{
// stop the main loop
running_ = false;
} break;

default: break;
}
}


And the event handler method for when a key is released:
Code:

void CLTest4Application::KeyUpEventHandler(const CL_InputEvent& event)
{
switch(event.id)
{
default: break;
}
}


You are right. it doesn't do anything...yet. It just exists now to be complete. ;D

We're done!
Build and run and you should see nothing different from the Test3 executable..but we know better. 8)
Stay tuned for the next article!


Navigation

[0] Message Index