In a C++ console program, I've found how to detect and arrow key on Windows, and I've found a lot of other stuff that had nothing to do with the question (despite what I thought were good search terms), but I want to know if there is a platform-indep开发者_如何学Cendent way to detect an arrow key press. A decent second place for this would be how to detect arrow key press in unix and mac. Code fragments would be appreciated.
There's no cross platform way to do it because it's not defined by either C or C++ standards (though there may be libraries which abstract away the differences when compiled on different platforms).
I believe the library you are looking for on POSIX boxes is curses, but I've never used it myself -- I could be wrong.
Keep in mind that it's entirely possible the console program (i.e. gnome-terminal
or konsole
or xterm
) has monopolized the use of those keys for other functions.
As Billy said, there is no standard cross-platform way to do it.
Personally I use this (game-oriented) library for all inputs, cross-platform win/linux/mac : http://sourceforge.net/projects/wgois/
You can do this cross-platform by using SDL2.
Example code:
#include <SDL2/SDL.h>
int main()
{
SDL_Event event;
SDL_PollEvent(&event);
if(event.type == SDL_KEYDOWN)
{
// Move centerpoint of rotation for one of the trees:
switch(event.key.keysym.sym)
{
case SDLK_UP:
// do something
break;
case SDLK_DOWN:
// do something
break;
case SDLK_LEFT:
// do something
break;
case SDLK_RIGHT:
// do something
break;
case SDLK_ESCAPE:
// do something
return 0;
default:
break;
}
}
return 0;
}
精彩评论