2
Contributors
2
Replies
5
Views
5 Years
Discussion Span
Last Post by Gonbe
0

What kind of keyboard hits? Do you want to detect any form of keypress? Does it have to happen while another activity is going on? Be more specific.

It's likely (it depends on what you want exactly) that it's not possible in a platform independent way. Assuming you develop on Windows you could for example have something like the following:

#include <stdio.h>
#include <windows.h>

int main (void)
{
    HANDLE            handle       = GetStdHandle(STD_INPUT_HANDLE);
    KEY_EVENT_RECORD *currentEvent = NULL;
    DWORD             eventCount;
    INPUT_RECORD      inputRecord;

    // Run this example endlessly.
    for (;;)
    {
        // Determine if anything can be read
        PeekConsoleInput(handle, &inputRecord, 1, &eventCount);

        // See if there was an event
        if(eventCount > 0)
        {
            // Read it.
            ReadConsoleInput(handle, &inputRecord, 1, &eventCount);

            currentEvent = &(inputRecord.Event.KeyEvent);

            // Filter for key events and only display it for the key being down.
            // Option for filtering the holding of a key are limited so omitted here.
            if (inputRecord.EventType == KEY_EVENT && currentEvent->bKeyDown)
            {
                printf("Detected key-press: %d. (%c)\n", currentEvent->wVirtualKeyCode,
                                                         currentEvent->uChar.AsciiChar);
            }
        }
    }

    return 0;
}

Using this, I assume you could extend it so it records timestamps and calculates the difference between them? (And if not, ask here and mentioned specifically what isn't working)

Edited by Gonbe

0

To show how important it is you specify clearly what you want, another partial solution (which is less flexible and can't detect everything but might fit your needs) would be the following:

#include <stdio.h>
#include <conio.h>

int main (void)
{
    for (;;)
    {
        // A key has been pressed, but not yet read.
        if (kbhit())
        {
            // Read it and show us something.
            printf("Key pressed: %d.\n", _getch());
        }
    }

    return 0;
}

I'll leave it up to you to take what you need and modify it to include timestamps.

Edited by Gonbe

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.