Kuronekonova
Kuronekonova

Reputation: 13

How do I make my program do a specific thing after I press a certain key on my keyboard?

#include <stdlib.h>
#include <stdio.h>


int main()
{
    char ch;
    
    printf("Enter any character: \n");
    ch = fgetc(stdin);
    
    if(ch == 'A')
    {
        printf("A was inputed.\n");
    }
    else
    {
        printf("%c was inputed.\n", ch);
    }
    
    return 0;
}

So this is a simple program: When you input A and press enter, "A was inputed" gets printed. If you input any other character it will print " was inputed."

But I want to make it like this: When the right arrow key is pressed, it will print "Right Arrow Key", but when the left arrow key is pressed, it will print "Left Arrow Key".

How do I do this?

I can do this with the enter key by doing this.

if(ch == 0x0A)
{
printf("ENTER KEY was pressed\n");
}
else
{

}

I learned that 0x0A is the hexadecimal ASCII value of the enter key. So I thought I could do the same with other keys after I get their hexadecimal ASCII value. But I don't know the ones for the right arrow and left arrow keys.

EDIT: I should have mentioned that I use Windows 10.

Upvotes: 0

Views: 328

Answers (1)

ryyker
ryyker

Reputation: 23218

You have not specified OS...

This this answer will address the question from a Windows perspective.

Two items that can simplify your task in a Windows environment:

Which, along with every other keyboard definition, does include the arrow keys:

  • VK_LEFT 0x25 LEFT ARROW key

  • VK_UP 0x26 UP ARROW key

  • VK_RIGHT 0x27 RIGHT ARROW key

  • VK_DOWN 0x28 DOWN ARROW key

Together, these can be used to enable your code to capture single keystrokes as well as combinations of keystrokes, detect both instantaneous and held states all helping to determine the state of the keyboard. Using these, your code example could be implemented like this:

void GetAppState(void)
{
    short state=0;
    short state1=0;
    
    state = GetAsyncKeyState(VK_RETURN);
    if (0x80000000 & state) //check instantaineous state of key
    {
       printf("ENTER KEY was pressed\n");
    }
    else
    {
        ...
    } 
    ...... and so on

To capture multiple simultaneous keystrokes, you can do something similar to this for example (capturing <ctrl><shift><h>)

state = GetAsyncKeyState(VK_CONTROL);
    if (0x80000000 & state) //check instantaineous state of key
    {
        state = GetAsyncKeyState(VK_SHIFT); 
        if (0x80000000 & state) //check instantaineous state of key
        {
            state = GetAsyncKeyState('h'); 
            state1 = GetAsyncKeyState('H'); 
            if ((0x80000000 & state) || 
                (0x80000000 & state1))
            {    
 

Upvotes: 1

Related Questions