Search code examples
ckeyboardcodeblocksarrow-keys

Why getch() is throwing an error in C


I am running a C program in Code :: Blocks in windows XP. I am getting an error as

"drawing operation is attempeted when there was no current window"

What might cause this and how can I solve it? My code is as follows:

#include <stdio.h>
#include <conio.h>
static int get_code(void);
// System dependent key codes
enum
{
    KEY_ESC     = 27,
    ARROW_UP    = 256 + 72,
    ARROW_DOWN  = 256 + 80,
    ARROW_LEFT  = 256 + 75,
    ARROW_RIGHT = 256 + 77
};
int main(void)
{
    int ch;
    puts("Press arrow keys, escape key + enter to exit:");
    while (( ch = get_code()) != KEY_ESC )
    {
        switch (ch)
        {
        case ARROW_UP:
            printf("UP\n");
            break;
        case ARROW_DOWN:
            printf("DOWN\n");
            break;
        case ARROW_LEFT:
            printf("LEFT\n");
            break;
        case ARROW_RIGHT:
            printf("RIGHT\n");
            break;
        }
    }
    getchar();   // wait
    return 0;
}
static int get_code(void)
{
    int ch = getch();    // Error happens here
    if (ch == 0 || ch == 224)
        ch = 256 + getch();
    return ch;
}

Solution

  • the α came from the getche() input, it prompts the user for input and when the user press a key then enter it echos that key on the standard output "screen" and since the arrows are non-printable keys that's what happened you can do something like like this:

    switch (ch)
            {
            case ARROW_UP:
                printf("\bUP\n");
                break;
            case ARROW_DOWN:
                printf("\bDOWN\n");
                break;
            case ARROW_LEFT:
                printf("\bLEFT\n");
                break;
            case ARROW_RIGHT:
                printf("\bRIGHT\n");
                break;
            }