我如何才能获得在代码块中按下的键?

问题描述 投票:-1回答:2

如何显示按下了哪个键?

我的意思是,就像你按A一样,屏幕上会显示:你按了A.

cin>>keypress;
cout<<"You pressed:"<<keypress;

我想直接显示我要按的是什么键。无需等待按下输入并完成执行。

c++ codeblocks
2个回答
0
投票

我想你想要显示你正在按压的角色(就像在你的例子中一样)。所以,它非常简单。这是代码:

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


int main()
{
    char keyPress;
    while(1)
        {
            keyPress=_getch();
            if((keyPress==27)||(keyPress==32))
            {
                printf("You decided to stop the execution of this code.");
                return 0;
            }
            printf("You pressed:%c\n",keyPress);
        }
}

如果您让代码如何,程序将在esc或空格按下完成执行。如果要更改此设置,可以使用按钮的其他ascii代码替换:if((keyPress==27)||(keyPress==32))中的数字。这是所有的ascii代码:https://ascii.cl/。如果你想只在一个按钮上结束程序,只需从if((keyPress==27)||(keyPress==32))修改为if(keyPress==27),现在程序将仅在ESC上停止。


1
投票

我不知道是否有可能,但你可能想要一个更好的头衔。看起来你乍看之下就是在寻找一些非常基本的东西,但这根本不是它。除此之外,我有一个使用Windows api的Windows解决方案。 #include <wInDoWs.h>

你可以使用GetAsyncKeyState()并将密钥的ASCII值传递给它。它将返回一个指示按钮状态的短消息。据我所知,按下按钮时返回值-32767。将其包裹在一个函数中,您可以判断按钮是否被按下。 (以下将与复制/粘贴一起运行。)

#include <windows.h>
#include <iostream>

bool pressed(const short& _key)
{
 short state = 0;
 short pressed= -32767;
 state = GetAsyncKeyState( _key);

 return ( state == pressed );
}

int main()
{
 //see if J is pressed
 while(1)
 {
   if(pressed( 0x4a ) )// 'J'
    std::cout << "J";
 }
}

为了使所有角色能够工作,恐怕我想不出比存储所有ASCII值更简单的方法,以及在按下按键时要打印出来的内容,在容器中检查它们的按下状态frame。(下面只是伪代码。)

//the container         this short is the 'key'
std::vector< std::pair< short , std::string > > chars;

//to check the status
for(auto& c : chars)
   if( pressed( c.first ) ) std::cout << c.second;

我会把它放在某种循环中。

通过这种方式添加“你按下的空间”并不困难。做就是了

chars.push_back( std::pair<int,std::string>(0x20 , "Spacebar") );

© www.soinside.com 2019 - 2024. All rights reserved.