Reputation: 410
i am writing a c console application (for windows platform, using msc++ compiler) which requires reading state of some keyboard keys in very short time intervals (of the order of a couple of milliseconds). The read state is then fed into a FSM which provides rich key events (KEY_UP, KEY_RELEASED, KEY_DOWN, KEY_HELD_FOR_LONG_PERIOD, etc.) to rest of the application logic. (basically porting an embedded application to windows platform).
i don't know how to read key states, hence i googled and came across this answer. From what i understand, it basically scans the console events for any key (or mouse) events.
Although, the provided answer is a good starting point but the problem i face is that between successive 'reads' of keyboard state (and when time lag between successive reads is less than 50 ms), i get different answers (at times pressed, at times released) even when the key remains physically pressed. This messes up the FSM logic. But this is probably accepted behavior considering the console might not have new keyboard events in such short time duration. Unfortunately, this doesn't solve my problem.
So how can i
i have a limited understanding of available windows API to solve the task at hand. i am mainly a Embedded/C# guy who either works bare-metal (when developing firmware) or uses .net framework (when developing for windows).
Upvotes: 3
Views: 345
Reputation: 410
After the suggestion of arx i looked back at the API and the keyboard events and figured out that it was my design of dealing with events which was giving me a problem.. i was polling the events as if they are 'signals' for the current state of keys. Rather events represent 'change' in the signal.
The original design was something like:
if ( there_is_an_event_for (KEY_A) ) // i assumed that events represents a key high state
Update_fsm_for_KEY_A (with_high_signal);
else
Update_fsm_for_KEY_A (with_low_signal);
Since the console gets events upon key_pressed and key_released, this design was inappropriate. This is a new design:
static bool last_key_state = false;
if ( there_is_a_key_pressed_event_for (KEY_A) )
last_key_state = true;
else if (there_is_a_key_released_event_for (KEY_B) )
last_key_state = false;
Update_fsm_for_KEY_A (last_key_state)
Thank You everyone for Your efforts and Help. i am posting and accepting this as an answer. Who knows this might help someone who is struggling with same problem.
Upvotes: 0
Reputation: 10415
You can read the raw keyboard state with GetAsyncKeyState or GetKeyboardState APIs.
Upvotes: 1