我制作了一个程序,允许我读取键盘上的所有独立功能键(至少我想测试一下)。我对其进行了设计,以便我可以将任何单个键输入称为单个值。它处理Return、F1-F12、delete、backspace、箭头等
我只是想测试输入的修改。我已经确定 shift 有效,但现在我决定测试 Ctrl 和 Alt。
问题 1 为什么 Alt 不修改任何输入的键码?
问题 2 为什么我无法捕获某些 Ctrl + 组合? 例如。 Ctrl + s; Ctrl + 1-9;
Ctrl + 2 有效,但我认为这可能是因为我的键盘设置为英国。
这是我正在使用的代码。
请注意,我不一定要问如何捕获这些组合键(除非是一两个简单的修改)。我只想知道为什么我做不到。
#include <iostream>
#include <conio.h>
#include <cwchar>
union wide_char
{
short Result;
char C[2];
};
int main()
{
wchar_t R;
int N;
wide_char user_input;
//Loops forever, this is only a proof of concept program proving this is possible to incorporate into a larger program
while(true)
{
user_input.C[0] = 0;
user_input.C[1] = 0;
//Loop twice, or until code causes the loop to exit
//Two times are neccessary for function keys unfortunately
for(int i = 0; i < 2; ++i)
{
//While there isn't a key pressed, loop doing nothing
while(!kbhit()){}
//Grab the next key from the buffer
//Since the loop is done, there must be at least one
user_input.C[i] = getch();
switch(user_input.C[i])
{
case 0:
case -32:
//The key pressed is a Function key because it matches one of these two cases
//This means getch() must be called twice
//Break switch, run the for loop again ++i
break;
default:
//The character obtained from getch() is from a regular key
//Or this is the second char from getch() because the for loop is on run #2
//Either way we need a wide char (16 bits / 2 Bytes)
if(user_input.C[1] != 0)
//Function keys {Arrows, F1-12, Esc}
//We now combine the bits of both chars obtained
//They must be combined Second+First else the F1-12 will be duplicate
//This is because on F1-12 getch() returns 0 thus won't affect the combination
R = user_input.Result;
else
//Regular key press
R = user_input.C[0];
//Display our unique results from each key press
N = R;
std::cout << R << " R = N " << N << std::endl;
if( R == 'a' )
std::cout << "a = " << N << std::endl;
//Manually break for loop
i = 3;
break;
}
}
//We need to reset the array in this situation
//Else regular key presses will be affected by the last function key press
}
}
最佳答案
这非常适合您的环境。您正在使用特定于 DOS/Windows 的 conio
。
大多数 Ctrl + alpha 键值绑定(bind)到字符 1 - 26,某些其他绑定(bind)到 31 以下的其他值,以映射到 ASCII 控制字符。但是有些,比如 Ctrl + S 有特殊的含义(Ctrl + S 在 ASCII 中是 XOFF),所以可能会被您的环境“吞噬”。
从根本上说,您面临的问题是 getch
类似于老式串行终端接口(interface)。它们仅在“最小公分母”级别公开键盘事件,而不是允许您区分修改键等的较低级别,并为您提供更好的方式来处理特殊键,例如功能键。
(正如您所注意到的,功能键具有特殊的多字节序列。同样,这是由于模拟老式串行终端,键盘可能位于远程链接的另一端。)
要获得较低级别(因此更直接和灵活的界面),您需要使用更特定于平台的库,或更丰富的库,例如 SDL。两者都会为您提供键盘输入的较低级别 View 。
关于c++ - 为什么我不能读取所有 Ctrl + 'letters',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20086959/