Linux Keyboard Events

Hi All,

I am building a small game engine for the Raspberry Pi using OpenVG.

The graphics side of things is perfect now adding a library to detect keyboard inputs.

This is my code so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <fstream>
#include <cstring>
#include <linux/input.h>

using namespace std;

//structure to hold event info
struct input_event event;

int main(int argc, char *argv[]) {
    
    cout << "Receiving Keyboard Presses!" << endl;
    
    //open the file for reading
    ifstream file("/dev/input/event1");
    
    //temp storage for event
    char data[sizeof(event)];
    
    //check if file opened!
    if(file.is_open()) {
        
        //lets loop until esc key
        bool session = true;
        while(session) {
            
            //lets get to work
            file.read(data, sizeof(event));
            
            //now copy the data to the struct
            memcpy(&event, data, sizeof(event));
            
            //now lets read the event
            //event type
            if(event.type == EV_KEY) {
                
                //its a keyboard event
                //was it the esc key?
                if(event.code == KEY_ESC) {
                    
                    cout << "The Escape Key Was Pushed!" << endl;
                    session = false;
                }
                else {
                    
                    cout << "Key Press " << event.code << endl;
                }
            }
        }
        
        //dont forget to close the file
        file.close();
    }
    else {
        
        cout << "Unable to open file!" << endl;
        return 1;
    }
    
    return 0;
}


It works but still needs improvements. I need to detect the keyboard automatically and I will need to find I believe a non blocking read for this to be efficient.

What my main concern is, is that when I type a key after compiling this the program reads the event but so does the terminal it is running in. Generally this is fine but when lots of keys get pushed I am worried that something unexpected may happen in the terminal.

I am reading directly from the device but what I want to know is when I capture the event can I remove it so that only my application uses it???

Thanks!
Last edited on
Topic archived. No new replies allowed.