首页 > 解决方案 > 确定是否应同时使用 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”。我不完全确定为什么会这样,但任何帮助/解释将不胜感激:)

标签: c++bitwise-operators

解决方案


这段代码对我来说适用于您期望的输出:

#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";
                        }
                    }
                }
            }
        }
    }
}

推荐阅读