c++ - 确定是否应同时使用 shift 和 caps lock 将键大写
问题描述
我想根据 shift 键和 Caps-Lock 的状态来确定一个字母是大写还是小写。例如:如果两者都关闭或都打开,则字母为小写。但是如果按下 shift 并且 Caps-Lock 关闭,或者如果没有按下 shift 并且 Caps-Lock 开启,那么字母应该是大写的。
我尝试简单地查看 shift 键的高位来确定它是否被按下,以及确定 Caps-Lock 是否被切换GetKeyState()
的低位,但它并没有完美地工作。GetKeyState()
现在我只是将数据输出到一个文本文件,看看我得到了什么值。我GetKeyState()
从这里得到信息
这是我用来确定字母大小写的函数:
bool Capitalize(short int shift, short int caps){
bool s = shift<0;
bool c = (caps&1)!=0;
return s!=c;
}
这里是我调用函数的地方:
ofstream write("test.txt", ios::app);
void main(){
char c;
for(;;){
for(c=1;c<=222;c++){
if(GetAsyncKeyState(c)==-32767){
short int shift = GetKeyState(VK_SHIFT);
short int caps = GetKeyState(VK_CAPITAL);
switch(c){
case 65:{
if(Capitalize(shift,caps))
write<<"A";
else
write<<"a";
}break;
}
write<<"\r\n";
}
}
}
}
因此,当我关闭 Caps-Lock 并且没有按住 shift 键时,输出如下:
A
a
a
a
如果您注意到,第一个字母是大写的,我希望它是小写的。当我在 Caps-Lock 打开时按住 shift 时发生了同样的事情,这应该会产生小写字母。如果按下任一班次,或大写锁定,但不是两者兼而有之,那么它似乎工作正常并且所有字母都输出为大写“A”。我不完全确定为什么会这样,但任何帮助/解释将不胜感激:)
解决方案
这段代码对我来说适用于您期望的输出:
#include <Windows.h>
#include <iostream>
bool Capitalize(short int shift, short int caps)
{
bool s = shift < 0;
bool c = (caps & 1) != 0;
return s != c;
}
void main()
{
unsigned char c;
while (true)
{
for (c = 1; c <= 222; c++)
{
if (GetAsyncKeyState(c) &1)
{
short int shift = GetKeyState(VK_SHIFT);
short int caps = GetKeyState(VK_CAPITAL);
switch (c)
{
case 65:
{
if (Capitalize(shift, caps))
{
std::cout << "A\n";
}
else
{
std::cout << "a\n";
}
}
}
}
}
}
}
推荐阅读
- apache-spark - 无法使用 PySpark 从 Elasticsearch 读取
- c# - c#不能在代码中的资源中使用图片?
- python - 任务调度程序未运行 Selenium 脚本
- angular - 错误:mat-table 上的 FormArray --> 找不到路径控件(Angular 6)
- encoding - 你能用不是 utf8 的编码来编写 Perl 6 脚本吗?
- oracle - ora-01722 更新记录时数字无效
- sql - SQL Server 数据库中的表具有互斥外键的最佳实践
- neo4j - 加载数据库命令后 Neo4j 不启动
- javascript - WAI 的轮播示例滑块具有不同的行为,带有 < > 箭头与底部的 123 个链接
- python - 还需要使用 lxml getpath 函数深入文本的绝对 xpath